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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c3af9ac5c2ff1f8b520da46244e16eb2556bdb15 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/analysis/normed_space/basic.lean | bbbfb7e9c34fcba1d1e2ba33776711519c75cea8 | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 52,389 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
-/
import topology.instances.nnreal
import topology.instances.complex
import topology.algebra.module
import topology.metric_space.antilipschitz
/-!
# Normed spaces
-/
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*}
noncomputable theory
open filter metric
open_locale topological_space big_operators
localized "notation f `→_{`:50 a `}`:0 b := filter.tendsto f (_root_.nhds a) (_root_.nhds b)" in filter
/-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to
be extended in more interesting classes specifying the properties of the norm. -/
class has_norm (α : Type*) := (norm : α → ℝ)
export has_norm (norm)
notation `∥`:1024 e:1 `∥`:1 := norm e
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines
a metric space structure. -/
class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
end prio
/-- Construct a normed group from a translation invariant distance -/
def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α]
(H1 : ∀ x:α, ∥x∥ = dist x 0)
(H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α :=
{ dist_eq := λ x y, begin
rw H1, apply le_antisymm,
{ rw [sub_eq_add_neg, ← add_right_neg y], apply H2 },
{ have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }
end }
/-- Construct a normed group from a translation invariant distance -/
def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α]
(H1 : ∀ x:α, ∥x∥ = dist x 0)
(H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α :=
{ dist_eq := λ x y, begin
rw H1, apply le_antisymm,
{ have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this },
{ rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }
end }
/-- A normed group can be built from a norm that satisfies algebraic properties. This is
formalised in this structure. -/
structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop :=
(norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0)
(triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥)
(norm_neg : ∀ x : α, ∥-x∥ = ∥x∥)
/-- Constructing a normed group from core properties of a norm, i.e., registering the distance and
the metric space structure from the norm properties. -/
noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α]
(C : normed_group.core α) : normed_group α :=
{ dist := λ x y, ∥x - y∥,
dist_eq := assume x y, by refl,
dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp),
eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h,
dist_triangle := assume x y z,
calc ∥x - z∥ = ∥x - y + (y - z)∥ : by rw sub_add_sub_cancel
... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _,
dist_comm := assume x y,
calc ∥x - y∥ = ∥ -(y - x)∥ : by simp
... = ∥y - x∥ : by { rw [C.norm_neg] } }
section normed_group
variables [normed_group α] [normed_group β]
lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ :=
normed_group.dist_eq _ _
@[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ :=
by rw [dist_eq_norm, sub_zero]
lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ :=
by simpa only [dist_eq_norm] using dist_comm g h
@[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ :=
by simpa using norm_sub_rev 0 g
@[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ :=
by simp [dist_eq_norm]
@[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ :=
by simp [dist_eq_norm]
@[simp] lemma dist_neg_neg (g h : α) : dist (-g) (-h) = dist g h :=
by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev]
@[simp] lemma dist_sub_left (g h₁ h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ :=
by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg]
@[simp] lemma dist_sub_right (g₁ g₂ h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ :=
dist_add_right _ _ _
/-- Triangle inequality for the norm. -/
lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ :=
by simpa [dist_eq_norm] using dist_triangle g 0 (-h)
lemma norm_add_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) :
∥g₁ + g₂∥ ≤ n₁ + n₂ :=
le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂)
lemma dist_add_add_le (g₁ g₂ h₁ h₂ : α) :
dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ :=
by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂)
lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ}
(H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) :
dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ :=
le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂)
lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : α) :
dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ :=
dist_neg_neg g₂ h₂ ▸ dist_add_add_le _ _ _ _
lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ}
(H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) :
dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ :=
le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂)
lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : α) :
abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) :=
by simpa only [dist_add_left, dist_add_right, dist_comm h₂]
using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂)
@[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ :=
by { rw[←dist_zero_right], exact dist_nonneg }
@[simp] lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 :=
dist_zero_right g ▸ dist_eq_zero
@[simp] lemma norm_zero : ∥(0:α)∥ = 0 := norm_eq_zero.2 rfl
lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥∑ a in s, f a∥ ≤ ∑ a in s, ∥ f a ∥ :=
finset.le_sum_of_subadditive norm norm_zero norm_add_le
lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) :
∥∑ b in s, f b∥ ≤ ∑ b in s, n b :=
le_trans (norm_sum_le s f) (finset.sum_le_sum h)
lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 :=
dist_zero_right g ▸ dist_pos
lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 :=
by { rw[←dist_zero_right], exact dist_le_zero }
lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ :=
by simpa [dist_eq_norm] using dist_triangle g 0 h
lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) :
∥g₁ - g₂∥ ≤ n₁ + n₂ :=
le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂)
lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ :=
by { rw dist_eq_norm, apply norm_sub_le }
lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ :=
by simpa [dist_eq_norm] using abs_dist_sub_le g h 0
lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ :=
le_trans (le_abs_self _) (abs_norm_sub_norm_le g h)
lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ :=
abs_norm_sub_norm_le g h
lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} :=
set.ext $ assume a, by simp
lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) :
∥h∥ ≤ ∥g∥ + r :=
calc
∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right]
... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _
... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H }
lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) :
∥h∥ < ∥g∥ + r :=
calc
∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right]
... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _
... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H }
theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} :
tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε :=
metric.tendsto_nhds.trans $ by simp only [dist_zero_right]
/-- A homomorphism `f` of normed groups is Lipschitz, if there exists a constant `C` such that for
all `x`, one has `∥f x∥ ≤ C * ∥x∥`.
The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/
lemma add_monoid_hom.lipschitz_of_bound (f :α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) :
lipschitz_with (nnreal.of_real C) f :=
lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y)
/-- A homomorphism `f` of normed groups is continuous, if there exists a constant `C` such that for
all `x`, one has `∥f x∥ ≤ C * ∥x∥`.
The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/
lemma add_monoid_hom.continuous_of_bound (f :α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) :
continuous f :=
(f.lipschitz_of_bound C h).continuous
section nnnorm
/-- Version of the norm taking values in nonnegative reals. -/
def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩
@[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl
lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _
@[simp] lemma nnnorm_eq_zero {a : α} : nnnorm a = 0 ↔ a = 0 :=
by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero]
@[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 :=
nnreal.eq norm_zero
lemma nnnorm_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h :=
nnreal.coe_le_coe.2 $ norm_add_le g h
@[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g :=
nnreal.eq $ norm_neg g
lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) :=
nnreal.coe_le_coe.2 $ dist_norm_norm_le g h
lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ennreal) :=
ennreal.of_real_eq_coe_nnreal _
lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (nnnorm (x - y) : ennreal) :=
by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm]
lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ennreal) :=
by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero]
lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) :
nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ :=
nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂
lemma edist_add_add_le (g₁ g₂ h₁ h₂ : α) :
edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ :=
by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le }
lemma nnnorm_sum_le {β} : ∀(s : finset β) (f : β → α), nnnorm (∑ a in s, f a) ≤ ∑ a in s, nnnorm (f a) :=
finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le
end nnnorm
lemma lipschitz_with.neg {α : Type*} [emetric_space α] {K : nnreal} {f : α → β}
(hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) :=
λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y
lemma lipschitz_with.add {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β}
(hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) :
lipschitz_with (Kf + Kg) (λ x, f x + g x) :=
λ x y,
calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) :
edist_add_add_le _ _ _ _
... ≤ Kf * edist x y + Kg * edist x y :
add_le_add (hf x y) (hg x y)
... = (Kf + Kg) * edist x y :
(add_mul _ _ _).symm
lemma lipschitz_with.sub {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β}
(hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) :
lipschitz_with (Kf + Kg) (λ x, f x - g x) :=
hf.add hg.neg
lemma antilipschitz_with.add_lipschitz_with {α : Type*} [metric_space α] {Kf : nnreal} {f : α → β}
(hf : antilipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g)
(hK : Kg < Kf⁻¹) :
antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) :=
begin
refine antilipschitz_with.of_le_mul_dist (λ x y, _),
rw [nnreal.coe_inv, ← div_eq_inv_mul],
rw le_div_iff (nnreal.coe_pos.2 $ nnreal.sub_pos.2 hK),
rw [mul_comm, nnreal.coe_sub (le_of_lt hK), sub_mul],
calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) :
sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y)
... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _)
end
/-- A submodule of a normed group is also a normed group, with the restriction of the norm.
As all instances can be inferred from the submodule `s`, they are put as implicit instead of
typeclasses. -/
instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜}
{E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s :=
{ norm := λx, norm (x : E),
dist_eq := λx y, dist_eq_norm (x : E) (y : E) }
/-- normed group instance on the product of two normed groups, using the sup norm. -/
instance prod.normed_group : normed_group (α × β) :=
{ norm := λx, max ∥x.1∥ ∥x.2∥,
dist_eq := assume (x y : α × β),
show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] }
lemma prod.norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl
lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ :=
le_max_left _ _
lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ :=
le_max_right _ _
lemma norm_prod_le_iff {x : α × β} {r : ℝ} :
∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r :=
max_le_iff
/-- normed group instance on the product of finitely many normed groups, using the sup norm. -/
instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] :
normed_group (Πi, π i) :=
{ norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ),
dist_eq := assume x y,
congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a,
show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ }
/-- The norm of an element in a product space is `≤ r` if and only if the norm of each
component is. -/
lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r)
{x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r :=
by { simp only [(dist_zero_right _).symm, dist_pi_le_iff hr], refl }
lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) :
∥x i∥ ≤ ∥x∥ :=
(pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i
lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} :
tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥ f e - b ∥) a (𝓝 0) :=
by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm]
lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} :
tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e ∥) a (𝓝 0) :=
have tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (𝓝 0) :=
tendsto_iff_norm_tendsto_zero,
by simpa
/-- Special case of the sandwich theorem: if the norm of `f` is eventually bounded by a real
function `g` which tends to `0`, then `f` tends to `0`.
In this pair of lemmas (`squeeze_zero_norm'` and `squeeze_zero_norm`), following a convention of
similar lemmas in `topology.metric_space.basic` and `topology.algebra.ordered`, the `'` version is
phrased using "eventually" and the non-`'` version is phrased absolutely. -/
lemma squeeze_zero_norm' {f : γ → α} {g : γ → ℝ} {t₀ : filter γ}
(h : ∀ᶠ n in t₀, ∥f n∥ ≤ g n)
(h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) :=
tendsto_zero_iff_norm_tendsto_zero.mpr
(squeeze_zero' (eventually_of_forall (λ n, norm_nonneg _)) h h')
/-- Special case of the sandwich theorem: if the norm of `f` is bounded by a real function `g` which
tends to `0`, then `f` tends to `0`. -/
lemma squeeze_zero_norm {f : γ → α} {g : γ → ℝ} {t₀ : filter γ}
(h : ∀ (n:γ), ∥f n∥ ≤ g n)
(h' : tendsto g t₀ (𝓝 0)) :
tendsto f t₀ (𝓝 0) :=
squeeze_zero_norm' (eventually_of_forall h) h'
lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 :=
tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x)
lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 :=
by simpa using lim_norm (0:α)
lemma continuous_norm : continuous (λg:α, ∥g∥) :=
begin
rw continuous_iff_continuous_at,
intro x,
rw [continuous_at, tendsto_iff_dist_tendsto_zero],
exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x)
end
lemma filter.tendsto.norm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) :
tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) :=
tendsto.comp continuous_norm.continuous_at h
lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) :=
continuous_subtype_mk _ continuous_norm
lemma filter.tendsto.nnnorm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) :
tendsto (λ x, nnnorm (f x)) l (𝓝 (nnnorm a)) :=
tendsto.comp continuous_nnnorm.continuous_at h
/-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/
lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α}
(h : tendsto (λ y, ∥f y∥) l at_top) (x : α) :
∀ᶠ y in l, f y ≠ x :=
begin
have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)),
refine this.mono (λ y hy hxy, _),
subst x,
exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy)
end
/-- A normed group is a uniform additive group, i.e., addition and subtraction are uniformly
continuous. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_uniform_group : uniform_add_group α :=
begin
refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩,
rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h,
calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ :
by simp [dist_eq_norm, sub_eq_add_neg]; abel
... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_sub_le _ _
... < ε / 2 + ε / 2 : add_lt_add h.1 h.2
... = ε : add_halves _
end
@[priority 100] -- see Note [lower instance priority]
instance normed_top_monoid : has_continuous_add α := by apply_instance -- short-circuit type class inference
@[priority 100] -- see Note [lower instance priority]
instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference
end normed_group
section normed_ring
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b)
end prio
@[priority 100] -- see Note [lower instance priority]
instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β }
lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) :=
normed_ring.norm_mul _ _
lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n
| 1 h := by simp
| (n+2) h :=
le_trans (norm_mul_le a (a^(n+1)))
(mul_le_mul (le_refl _)
(norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _))
lemma eventually_norm_pow_le {α : Type*} [normed_ring α] (a : α) :
∀ᶠ (n:ℕ) in at_top, ∥a ^ n∥ ≤ ∥a∥ ^ n :=
begin
refine eventually_at_top.mpr ⟨1, _⟩,
intros b h,
exact norm_pow_le a (nat.succ_le_iff.mp h),
end
lemma units.norm_pos {α : Type*} [normed_ring α] [nontrivial α] (x : units α) : 0 < ∥(x:α)∥ :=
norm_pos_iff.mpr (units.ne_zero x)
/-- In a normed ring, the left-multiplication `add_monoid_hom` is bounded. -/
lemma mul_left_bound {α : Type*} [normed_ring α] (x : α) :
∀ (y:α), ∥add_monoid_hom.mul_left x y∥ ≤ ∥x∥ * ∥y∥ :=
norm_mul_le x
/-- In a normed ring, the right-multiplication `add_monoid_hom` is bounded. -/
lemma mul_right_bound {α : Type*} [normed_ring α] (x : α) :
∀ (y:α), ∥add_monoid_hom.mul_right x y∥ ≤ ∥x∥ * ∥y∥ :=
λ y, by {rw mul_comm, convert norm_mul_le y x}
/-- Normed ring structure on the product of two normed rings, using the sup norm. -/
instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) :=
{ norm_mul := assume x y,
calc
∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl
... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl
... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) :
max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2))
... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm]
... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] }
... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm]
... = (∥x∥*∥y∥) : rfl,
..prod.normed_group }
end normed_ring
@[priority 100] -- see Note [lower instance priority]
instance normed_ring_top_monoid [normed_ring α] : has_continuous_mul α :=
⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd =
e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel,
begin
apply squeeze_zero,
{ intro, apply norm_nonneg },
{ simp only [this], intro, apply norm_add_le },
{ rw ←zero_add (0 : ℝ), apply tendsto.add,
{ apply squeeze_zero,
{ intro, apply norm_nonneg },
{ intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥,
rw ←mul_sub, apply norm_mul_le },
{ rw ←mul_zero (∥x.fst∥), apply tendsto.mul,
{ apply continuous_iff_continuous_at.1,
apply continuous_norm.comp continuous_fst },
{ apply tendsto_iff_norm_tendsto_zero.1,
apply continuous_iff_continuous_at.1,
apply continuous_snd }}},
{ apply squeeze_zero,
{ intro, apply norm_nonneg },
{ intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥,
rw ←sub_mul, apply norm_mul_le },
{ rw ←zero_mul (∥x.snd∥), apply tendsto.mul,
{ apply tendsto_iff_norm_tendsto_zero.1,
apply continuous_iff_continuous_at.1,
apply continuous_fst },
{ apply tendsto_const_nhds }}}}
end ⟩
/-- A normed ring is a topological ring. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_top_ring [normed_ring α] : topological_ring α :=
⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
have ∀ e : α, -e - -x = -(e - x), by intro; simp,
by simp only [this, norm_neg]; apply lim_norm ⟩
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/
class normed_field (α : Type*) extends has_norm α, field α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul' : ∀ a b, norm (a * b) = norm a * norm b)
/-- A nondiscrete normed field is a normed field in which there is an element of norm different from
`0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication
by the powers of any element, and thus to relate algebra and topology. -/
class nondiscrete_normed_field (α : Type*) extends normed_field α :=
(non_trivial : ∃x:α, 1<∥x∥)
end prio
@[priority 100] -- see Note [lower instance priority]
instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α :=
{ norm_mul := by finish [i.norm_mul'], ..i }
namespace normed_field
@[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 :=
have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc
∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul'
... = ∥(1 : α)∥ * 1 : by simp,
mul_left_cancel' (ne_of_gt (norm_pos_iff.2 (by simp))) this
@[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ :=
normed_field.norm_mul' a b
@[simp] lemma nnnorm_one [normed_field α] : nnnorm (1:α) = 1 := nnreal.eq $ by simp
instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) :=
{ map_one := norm_one, map_mul := norm_mul }
@[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n :=
is_monoid_hom.map_pow norm a
@[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) :
∥∏ b in s, f b∥ = ∏ b in s, ∥f b∥ :=
eq.symm (s.prod_hom norm)
@[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ :=
begin
classical,
by_cases hb : b = 0, {simp [hb]},
apply eq_div_of_mul_eq,
{ apply ne_of_gt, apply norm_pos_iff.mpr hb },
{ rw [←normed_field.norm_mul, div_mul_cancel _ hb] }
end
@[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ :=
by simp only [inv_eq_one_div, norm_div, norm_one]
@[simp] lemma nnnorm_inv {α : Type*} [normed_field α] (a : α) : nnnorm (a⁻¹) = (nnnorm a)⁻¹ :=
nnreal.eq $ by simp
@[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ,
∥a^n∥ = ∥a∥^n
| (n : ℕ) := norm_pow a n
| -[1+ n] := by simp [fpow_neg_succ_of_nat]
lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ :=
i.non_trivial
lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 :=
begin
rcases exists_one_lt_norm α with ⟨y, hy⟩,
refine ⟨y⁻¹, _, _⟩,
{ simp only [inv_eq_zero, ne.def, norm_pos_iff],
assume h,
rw ← norm_eq_zero at h,
rw h at hy,
exact lt_irrefl _ (lt_trans zero_lt_one hy) },
{ simp [inv_lt_one hy] }
end
lemma exists_lt_norm (α : Type*) [nondiscrete_normed_field α]
(r : ℝ) : ∃ x : α, r < ∥x∥ :=
let ⟨w, hw⟩ := exists_one_lt_norm α in
let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in
⟨w^n, by rwa norm_pow⟩
lemma exists_norm_lt (α : Type*) [nondiscrete_normed_field α]
{r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r :=
let ⟨w, hw⟩ := exists_one_lt_norm α in
let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in
⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _},
by rwa norm_fpow⟩
@[instance]
lemma punctured_nhds_ne_bot {α : Type*} [nondiscrete_normed_field α] (x : α) :
ne_bot (𝓝[{x}ᶜ] x) :=
begin
rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff],
rintros ε ε0,
rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩,
refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩,
rwa [dist_comm, dist_eq_norm, add_sub_cancel'],
end
@[instance]
lemma nhds_within_is_unit_ne_bot {α : Type*} [nondiscrete_normed_field α] :
ne_bot (𝓝[{x : α | is_unit x}] 0) :=
by simpa only [is_unit_iff_ne_zero] using punctured_nhds_ne_bot (0:α)
lemma tendsto_inv [normed_field α] {r : α} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) :=
begin
refine (nhds_basis_closed_ball.tendsto_iff nhds_basis_closed_ball).2 (λε εpos, _),
let δ := min (ε/2 * ∥r∥^2) (∥r∥/2),
have norm_r_pos : 0 < ∥r∥ := norm_pos_iff.mpr r0,
have A : 0 < ε / 2 * ∥r∥ ^ 2 := mul_pos (half_pos εpos) (pow_pos norm_r_pos 2),
have δpos : 0 < δ, by simp [half_pos norm_r_pos, A],
refine ⟨δ, δpos, λ x hx, _⟩,
have rx : ∥r∥/2 ≤ ∥x∥ := calc
∥r∥/2 = ∥r∥ - ∥r∥/2 : by ring
... ≤ ∥r∥ - ∥r - x∥ :
begin
apply sub_le_sub (le_refl _),
rw [← dist_eq_norm, dist_comm],
exact le_trans hx (min_le_right _ _)
end
... ≤ ∥r - (r - x)∥ : norm_sub_norm_le r (r - x)
... = ∥x∥ : by simp [sub_sub_cancel],
have norm_x_pos : 0 < ∥x∥ := lt_of_lt_of_le (half_pos norm_r_pos) rx,
have : x⁻¹ - r⁻¹ = (r - x) * x⁻¹ * r⁻¹,
by rw [sub_mul, sub_mul, mul_inv_cancel (norm_pos_iff.mp norm_x_pos), one_mul, mul_comm,
← mul_assoc, inv_mul_cancel r0, one_mul],
calc dist x⁻¹ r⁻¹ = ∥x⁻¹ - r⁻¹∥ : dist_eq_norm _ _
... ≤ ∥r-x∥ * ∥x∥⁻¹ * ∥r∥⁻¹ : by rw [this, norm_mul, norm_mul, norm_inv, norm_inv]
... ≤ (ε/2 * ∥r∥^2) * (2 * ∥r∥⁻¹) * (∥r∥⁻¹) : begin
apply_rules [mul_le_mul, inv_nonneg.2, le_of_lt A, norm_nonneg, mul_nonneg,
(inv_le_inv norm_x_pos norm_r_pos).2, le_refl],
show ∥r - x∥ ≤ ε / 2 * ∥r∥ ^ 2,
by { rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_left _ _) },
show ∥x∥⁻¹ ≤ 2 * ∥r∥⁻¹,
{ convert (inv_le_inv norm_x_pos (half_pos norm_r_pos)).2 rx,
rw [inv_div, div_eq_inv_mul, mul_comm] },
show (0 : ℝ) ≤ 2, by norm_num
end
... = ε * (∥r∥ * ∥r∥⁻¹)^2 : by { generalize : ∥r∥⁻¹ = u, ring }
... = ε : by { rw [mul_inv_cancel (ne.symm (ne_of_lt norm_r_pos))], simp }
end
lemma continuous_on_inv [normed_field α] : continuous_on (λ(x:α), x⁻¹) {x | x ≠ 0} :=
begin
assume x hx,
apply continuous_at.continuous_within_at,
exact (tendsto_inv hx)
end
end normed_field
instance : normed_field ℝ :=
{ norm := λ x, abs x,
dist_eq := assume x y, rfl,
norm_mul' := abs_mul }
instance : nondiscrete_normed_field ℝ :=
{ non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ }
/-- If a function converges to a nonzero value, its inverse converges to the inverse of this value.
We use the name `tendsto.inv'` as `tendsto.inv` is already used in multiplicative topological
groups. -/
lemma filter.tendsto.inv' [normed_field α] {l : filter β} {f : β → α} {y : α}
(hy : y ≠ 0) (h : tendsto f l (𝓝 y)) :
tendsto (λx, (f x)⁻¹) l (𝓝 y⁻¹) :=
(normed_field.tendsto_inv hy).comp h
lemma filter.tendsto.div [normed_field α] {l : filter β} {f g : β → α} {x y : α}
(hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) (hy : y ≠ 0) :
tendsto (λa, f a / g a) l (𝓝 (x / y)) :=
hf.mul (hg.inv' hy)
lemma filter.tendsto.div_const [normed_field α] {l : filter β} {f : β → α} {x y : α}
(hf : tendsto f l (𝓝 x)) : tendsto (λa, f a / y) l (𝓝 (x / y)) :=
by { simp only [div_eq_inv_mul], exact tendsto_const_nhds.mul hf }
/-- Continuity at a point of the result of dividing two functions
continuous at that point, where the denominator is nonzero. -/
lemma continuous_at.div [topological_space α] [normed_field β] {f : α → β} {g : α → β} {x : α}
(hf : continuous_at f x) (hg : continuous_at g x) (hnz : g x ≠ 0) :
continuous_at (λ x, f x / g x) x :=
hf.div hg hnz
namespace real
lemma norm_eq_abs (r : ℝ) : ∥r∥ = abs r := rfl
@[simp] lemma norm_coe_nat (n : ℕ) : ∥(n : ℝ)∥ = n := abs_of_nonneg n.cast_nonneg
@[simp] lemma nnnorm_coe_nat (n : ℕ) : nnnorm (n : ℝ) = n := nnreal.eq $ by simp
@[simp] lemma norm_two : ∥(2:ℝ)∥ = 2 := abs_of_pos (@two_pos ℝ _)
@[simp] lemma nnnorm_two : nnnorm (2:ℝ) = 2 := nnreal.eq $ by simp
end real
@[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ :=
by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)]
@[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a :=
by simp only [nnnorm, norm_norm]
instance : normed_ring ℤ :=
{ norm := λ n, ∥(n : ℝ)∥,
norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul],
dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub] }
@[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl
instance : normed_field ℚ :=
{ norm := λ r, ∥(r : ℝ)∥,
norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul],
dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] }
instance : nondiscrete_normed_field ℚ :=
{ non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ }
@[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl
@[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ :=
by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast
section normed_space
section prio
set_option default_priority 920 -- see Note [default priority]. Here, we set a rather high priority,
-- to take precedence over `semiring.to_semimodule` as this leads to instance paths with better
-- unification properties.
-- see Note[vector space definition] for why we extend `semimodule`.
/-- A normed space over a normed field is a vector space endowed with a norm which satisfies the
equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove
`∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/
class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β]
extends semimodule α β :=
(norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥)
end prio
variables [normed_field α] [normed_group β]
instance normed_field.to_normed_space : normed_space α α :=
{ norm_smul_le := λ a b, le_of_eq (normed_field.norm_mul a b) }
lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ :=
begin
classical,
by_cases h : s = 0,
{ simp [h] },
{ refine le_antisymm (normed_space.norm_smul_le s x) _,
calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul' h]
... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : _
... = ∥s • x∥ : _,
exact mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _),
rw [normed_field.norm_inv, ← mul_assoc, mul_inv_cancel, one_mul],
rwa [ne.def, norm_eq_zero] }
end
lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y :=
by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub]
lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x :=
nnreal.eq $ norm_smul s x
lemma nndist_smul [normed_space α β] (s : α) (x y : β) :
nndist (s • x) (s • y) = nnnorm s * nndist x y :=
nnreal.eq $ dist_smul s x y
variables {E : Type*} {F : Type*}
[normed_group E] [normed_space α E] [normed_group F] [normed_space α F]
@[priority 100] -- see Note [lower instance priority]
instance normed_space.topological_vector_space : topological_vector_space α E :=
begin
refine { continuous_smul := continuous_iff_continuous_at.2 $
λ p, tendsto_iff_norm_tendsto_zero.2 _ },
refine squeeze_zero (λ _, norm_nonneg _) _ _,
{ exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ },
{ intro q,
rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul],
exact norm_add_le _ _ },
{ conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr,
rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] },
exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul
(continuous_snd.tendsto p).norm).add
(tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) }
end
theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
closure (ball x r) = closed_ball x r :=
begin
refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _),
have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 :=
((continuous_id.smul continuous_const).add continuous_const).continuous_within_at,
convert this.mem_closure _ _,
{ rw [one_smul, sub_add_cancel] },
{ simp [closure_Ico (@zero_lt_one ℝ _), zero_le_one] },
{ rintros c ⟨hc0, hc1⟩,
rw [set.mem_preimage, mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs,
abs_of_nonneg hc0, mul_comm, ← mul_one r],
rw [mem_closed_ball, dist_eq_norm] at hy,
apply mul_lt_mul'; assumption }
end
theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
frontier (ball x r) = sphere x r :=
begin
rw [frontier, closure_ball x hr, is_open_ball.interior_eq],
ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm
end
theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
interior (closed_ball x r) = ball x r :=
begin
refine set.subset.antisymm _ ball_subset_interior_closed_ball,
intros y hy,
rcases le_iff_lt_or_eq.1 (mem_closed_ball.1 $ interior_subset hy) with hr|rfl, { exact hr },
set f : ℝ → E := λ c : ℝ, c • (y - x) + x,
suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1,
{ have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const,
have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f],
have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) :=
interior_mono this (preimage_interior_subset_interior_preimage hfc hf1),
contrapose h1,
simp },
intros c hc,
rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr],
simpa [f, dist_eq_norm, norm_smul] using hc
end
theorem interior_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) :
interior (closed_ball x r) = ball x r :=
begin
rcases lt_trichotomy r 0 with hr|rfl|hr,
{ simp [closed_ball_eq_empty_iff_neg.2 hr, ball_eq_empty_iff_nonpos.2 (le_of_lt hr)] },
{ suffices : x ∉ interior {x},
{ rw [ball_zero, closed_ball_zero, ← set.subset_empty_iff],
intros y hy,
obtain rfl : y = x := set.mem_singleton_iff.1 (interior_subset hy),
exact this hy },
rw [← set.mem_compl_iff, ← closure_compl],
rcases exists_ne (0 : E) with ⟨z, hz⟩,
suffices : (λ c : ℝ, x + c • z) 0 ∈ closure ({x}ᶜ : set E),
by simpa only [zero_smul, add_zero] using this,
have : (0:ℝ) ∈ closure (set.Ioi (0:ℝ)), by simp [closure_Ioi],
refine (continuous_const.add (continuous_id.smul
continuous_const)).continuous_within_at.mem_closure this _,
intros c hc,
simp [smul_eq_zero, hz, ne_of_gt hc] },
{ exact interior_closed_ball x hr }
end
theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
frontier (closed_ball x r) = sphere x r :=
by rw [frontier, closure_closed_ball, interior_closed_ball x hr,
closed_ball_diff_ball]
theorem frontier_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) :
frontier (closed_ball x r) = sphere x r :=
by rw [frontier, closure_closed_ball, interior_closed_ball' x r, closed_ball_diff_ball]
open normed_field
/-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to
any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows
up in applications. -/
lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) :
∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) :=
begin
have xεpos : 0 < ∥x∥/ε := div_pos (norm_pos_iff.2 hx) εpos,
rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩,
have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc,
have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 },
refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩,
show (c ^ (n + 1))⁻¹ ≠ 0,
by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff],
show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε,
{ rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_le_iff cnpos, mul_comm, norm_fpow],
exact (div_le_iff εpos).1 (le_of_lt (hn.2)) },
show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥,
{ rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos),
fpow_one, mul_inv_rev', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos),
one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm],
exact (le_div_iff εpos).1 hn.1 },
show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥,
{ have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring,
rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul],
exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) }
end
/-- The product of two normed spaces is a normed space, with the sup norm. -/
instance : normed_space α (E × F) :=
{ norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg],
-- TODO: without the next two lines Lean unfolds `≤` to `real.le`
add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _),
smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _),
..prod.normed_group,
..prod.semimodule }
/-- The product of finitely many normed spaces is a normed space, with the sup norm. -/
instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)]
[∀i, normed_space α (E i)] : normed_space α (Πi, E i) :=
{ norm_smul_le := λ a f, le_of_eq $
show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) =
nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))),
by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] }
/-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/
instance submodule.normed_space {𝕜 : Type*} [normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 s :=
{ norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) }
end normed_space
section normed_algebra
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of
`𝕜` in `𝕜'` is an isometry. -/
class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
extends algebra 𝕜 𝕜' :=
(norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥)
end prio
@[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
[h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ :=
normed_algebra.norm_algebra_map_eq _
variables (𝕜 : Type*) [normed_field 𝕜]
variables (𝕜' : Type*) [normed_ring 𝕜']
@[priority 100]
instance normed_algebra.to_normed_space [h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' :=
{ norm_smul_le := λ s x, calc
∥s • x∥ = ∥((algebra_map 𝕜 𝕜') s) * x∥ : by { rw h.smul_def', refl }
... ≤ ∥algebra_map 𝕜 𝕜' s∥ * ∥x∥ : normed_ring.norm_mul _ _
... = ∥s∥ * ∥x∥ : by rw norm_algebra_map_eq,
..h }
instance normed_algebra.id : normed_algebra 𝕜 𝕜 :=
{ norm_algebra_map_eq := by simp,
.. algebra.id 𝕜}
variables {𝕜'} [normed_algebra 𝕜 𝕜']
include 𝕜
@[simp] lemma normed_algebra.norm_one : ∥(1:𝕜')∥ = 1 :=
by simpa using (norm_algebra_map_eq 𝕜' (1:𝕜))
lemma normed_algebra.zero_ne_one : (0:𝕜') ≠ 1 :=
begin
refine (norm_pos_iff.mp _).symm,
rw @normed_algebra.norm_one 𝕜, norm_num,
end
lemma normed_algebra.to_nonzero : nontrivial 𝕜' :=
⟨⟨0, 1, normed_algebra.zero_ne_one 𝕜⟩⟩
end normed_algebra
section restrict_scalars
variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
(E : Type*) [normed_group E] [normed_space 𝕜' E]
/-- `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a
normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred.
The type synonym `semimodule.restrict_scalars 𝕜 𝕜' E` will be endowed with this instance by default.
-/
def normed_space.restrict_scalars' : normed_space 𝕜 E :=
{ norm_smul_le := λc x, le_of_eq $ begin
change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥,
simp [norm_smul]
end,
..semimodule.restrict_scalars' 𝕜 𝕜' E }
instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : normed_group E] :
normed_group (semimodule.restrict_scalars 𝕜 𝕜' E) := I
instance semimodule.restrict_scalars.normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {E : Type*}
[normed_field 𝕜'] [normed_group E] [I : normed_space 𝕜' E] :
normed_space 𝕜' (semimodule.restrict_scalars 𝕜 𝕜' E) := I
instance : normed_space 𝕜 (semimodule.restrict_scalars 𝕜 𝕜' E) :=
(normed_space.restrict_scalars' 𝕜 𝕜' E : normed_space 𝕜 E)
end restrict_scalars
section summable
open_locale classical
open finset filter
variables [normed_group α] [normed_group β]
-- Applying a bounded homomorphism commutes with taking an (infinite) sum.
lemma has_sum_of_bounded_monoid_hom_of_has_sum
{f : ι → α} {φ : α →+ β} {x : α} (hf : has_sum f x) (C : ℝ) (hφ : ∀x, ∥φ x∥ ≤ C * ∥x∥) :
has_sum (λ (b:ι), φ (f b)) (φ x) :=
begin
unfold has_sum,
convert (φ.continuous_of_bound C hφ).continuous_at.tendsto.comp hf,
ext s, rw [function.comp_app, finset.sum_hom s φ],
end
lemma has_sum_of_bounded_monoid_hom_of_summable
{f : ι → α} {φ : α →+ β} (hf : summable f) (C : ℝ) (hφ : ∀x, ∥φ x∥ ≤ C * ∥x∥) :
has_sum (λ (b:ι), φ (f b)) (φ (∑'b, f b)) :=
has_sum_of_bounded_monoid_hom_of_has_sum hf.has_sum C hφ
lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} :
cauchy_seq (λ s : finset ι, ∑ i in s, f i) ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε :=
begin
simp only [cauchy_seq_finset_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib],
split,
{ assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] },
{ assume h s ε hε hs,
rcases h ε hε with ⟨t, ht⟩,
refine ⟨t, assume u hu, hs _⟩,
rw [ball_0_eq],
exact ht u hu }
end
lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} :
summable f ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε :=
by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm]
lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g)
(h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, ∑ i in s, f i) :=
cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε,
let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in
⟨s, assume t ht,
have ∥∑ i in t, g i∥ < ε := hs t ht,
have nn : 0 ≤ ∑ i in t, g i := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)),
lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $
by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩
lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) :
cauchy_seq (λ s : finset ι, ∑ a in s, f a) :=
cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _)
/-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space
its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable
with sum `a`. -/
lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥))
{s : γ → finset ι} {p : filter γ} [ne_bot p]
(hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) :
has_sum f a :=
tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hs ha
/-- If `∑' i, ∥f i∥` is summable, then `∥(∑' i, f i)∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume
that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/
lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) :
∥(∑'i, f i)∥ ≤ (∑' i, ∥f i∥) :=
begin
by_cases h : summable f,
{ have h₁ : tendsto (λs:finset ι, ∥∑ i in s, f i∥) at_top (𝓝 ∥(∑' i, f i)∥) :=
(continuous_norm.tendsto _).comp h.has_sum,
have h₂ : tendsto (λs:finset ι, ∑ i in s, ∥f i∥) at_top (𝓝 (∑' i, ∥f i∥)) :=
hf.has_sum,
exact le_of_tendsto_of_tendsto' h₁ h₂ (assume s, norm_sum_le _ _) },
{ rw tsum_eq_zero_of_not_summable h,
simp [tsum_nonneg] }
end
lemma has_sum_iff_tendsto_nat_of_summable_norm {f : ℕ → α} {a : α} (hf : summable (λi, ∥f i∥)) :
has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) :=
⟨λ h, h.tendsto_sum_nat,
λ h, has_sum_of_subseq_of_summable hf tendsto_finset_range h⟩
/-- The direct comparison test for series: if the norm of `f` is bounded by a real function `g`
which is summable, then `f` is summable. -/
lemma summable_of_norm_bounded
[complete_space α] {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) :
summable f :=
by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h }
/-- Quantitative result associated to the direct comparison test for series: If `∑' i, g i` is
summable, and for all `i`, `∥f i∥ ≤ g i`, then `∥(∑' i, f i)∥ ≤ (∑' i, g i)`. Note that we do not
assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/
lemma tsum_of_norm_bounded {f : ι → α} {g : ι → ℝ} {a : ℝ} (hg : has_sum g a) (h : ∀i, ∥f i∥ ≤ g i) :
∥(∑' (i:ι), f i)∥ ≤ a :=
begin
have h' : summable (λ (i : ι), ∥f i∥),
{ let f' : ι → ℝ := λ i, ∥f i∥,
have h'' : ∀ i, ∥f' i∥ ≤ g i,
{ intros i,
convert h i,
simp },
simpa [f'] using summable_of_norm_bounded g hg.summable h'' },
have h1 : ∥(∑' (i:ι), f i)∥ ≤ ∑' (i:ι), ∥f i∥ := by simpa using norm_tsum_le_tsum_norm h',
have h2 := tsum_le_tsum h h' hg.summable,
have h3 : a = ∑' (i:ι), g i := (has_sum.tsum_eq hg).symm,
linarith
end
variable [complete_space α]
/-- Variant of the direct comparison test for series: if the norm of `f` is eventually bounded by a
real function `g` which is summable, then `f` is summable. -/
lemma summable_of_norm_bounded_eventually {f : ι → α} (g : ι → ℝ) (hg : summable g)
(h : ∀ᶠ i in cofinite, ∥f i∥ ≤ g i) : summable f :=
begin
replace h := mem_cofinite.1 h,
refine h.summable_compl_iff.mp _,
refine summable_of_norm_bounded _ (h.summable_compl_iff.mpr hg) _,
rintros ⟨a, h'⟩,
simpa using h'
end
lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → nnreal) (hg : summable g)
(h : ∀i, nnnorm (f i) ≤ g i) : summable f :=
summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i)
lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f :=
summable_of_norm_bounded _ hf (assume i, le_refl _)
lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λa, nnnorm (f a))) : summable f :=
summable_of_nnnorm_bounded _ hf (assume i, le_refl _)
end summable
|
d0b9c20a8d91a9378b830a2e5d9e09d988296ea2 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/field_theory/adjoin.lean | dc974321910eeb5fd7737dc8464bff5498cbec69 | [
"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 | 15,453 | lean | /-
Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning and Patrick Lutz
-/
import field_theory.tower
import field_theory.intermediate_field
/-!
# Adjoining Elements to Fields
In this file we introduce the notion of adjoining elements to fields.
This isn't quite the same as adjoining elements to rings.
For example, `algebra.adjoin K {x}` might not include `x⁻¹`.
## Main results
- `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining S ∪ T.
- `bot_eq_top_of_dim_adjoin_eq_one`: if `F⟮x⟯` has dimension `1` over `F` for every `x`
in `E` then `F = E`
## Notation
- `F⟮α⟯`: adjoin a single element `α` to `F`.
-/
namespace intermediate_field
section adjoin_def
variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E)
/-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/
def adjoin : intermediate_field F E :=
{ algebra_map_mem' := λ x, subfield.subset_closure (or.inl (set.mem_range_self x)),
..subfield.closure (set.range (algebra_map F E) ∪ S) }
end adjoin_def
section lattice
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
@[simp] lemma adjoin_le_iff {S : set E} {T : intermediate_field F E} : adjoin F S ≤ T ↔ S ≤ T :=
⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subfield.subset_closure) H,
λ H, (@subfield.closure_le E _ (set.range (algebra_map F E) ∪ S) T.to_subfield).mpr
(set.union_subset (intermediate_field.set_range_subset T) H)⟩
lemma gc : galois_connection (adjoin F : set E → intermediate_field F E) coe := λ _ _, adjoin_le_iff
/-- Galois insertion between `adjoin` and `coe`. -/
def gi : galois_insertion (adjoin F : set E → intermediate_field F E) coe :=
{ choice := λ S _, adjoin F S,
gc := intermediate_field.gc,
le_l_u := λ S, (intermediate_field.gc (S : set E) (adjoin F S)).1 $ le_refl _,
choice_eq := λ _ _, rfl }
instance : complete_lattice (intermediate_field F E) :=
galois_insertion.lift_complete_lattice intermediate_field.gi
instance : inhabited (intermediate_field F E) := ⟨⊤⟩
lemma mem_bot {x : E} : x ∈ (⊥ : intermediate_field F E) ↔ x ∈ set.range (algebra_map F E) :=
begin
suffices : set.range (algebra_map F E) = (⊥ : intermediate_field F E),
{ rw this, refl },
{ change set.range (algebra_map F E) = subfield.closure (set.range (algebra_map F E) ∪ ∅),
simp [←set.image_univ, ←ring_hom.map_field_closure] }
end
lemma mem_top {x : E} : x ∈ (⊤ : intermediate_field F E) :=
subfield.subset_closure $ or.inr trivial
@[simp] lemma bot_to_subalgebra : (⊥ : intermediate_field F E).to_subalgebra = ⊥ :=
by { ext, rw [mem_to_subalgebra, algebra.mem_bot, mem_bot] }
@[simp] lemma top_to_subalgebra : (⊤ : intermediate_field F E).to_subalgebra = ⊤ :=
by { ext, rw [mem_to_subalgebra, iff_true_right algebra.mem_top], exact mem_top }
@[simp] lemma coe_bot_eq_self (K : intermediate_field F E) : ↑(⊥ : intermediate_field K E) = K :=
by { ext, rw [mem_lift2, mem_bot], exact set.ext_iff.mp subtype.range_coe x }
@[simp] lemma coe_top_eq_top (K : intermediate_field F E) :
↑(⊤ : intermediate_field K E) = (⊤ : intermediate_field F E) :=
intermediate_field.ext'_iff.mpr (set.ext_iff.mpr (λ _, iff_of_true mem_top mem_top))
end lattice
section adjoin_def
variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E)
lemma adjoin_eq_range_algebra_map_adjoin :
(adjoin F S : set E) = set.range (algebra_map (adjoin F S) E) := (subtype.range_coe).symm
lemma adjoin.algebra_map_mem (x : F) : algebra_map F E x ∈ adjoin F S :=
intermediate_field.algebra_map_mem (adjoin F S) x
lemma adjoin.range_algebra_map_subset : set.range (algebra_map F E) ⊆ adjoin F S :=
begin
intros x hx,
cases hx with f hf,
rw ← hf,
exact adjoin.algebra_map_mem F S f,
end
instance adjoin.field_coe : has_coe_t F (adjoin F S) :=
{coe := λ x, ⟨algebra_map F E x, adjoin.algebra_map_mem F S x⟩}
lemma subset_adjoin : S ⊆ adjoin F S :=
λ x hx, subfield.subset_closure (or.inr hx)
instance adjoin.set_coe : has_coe_t S (adjoin F S) :=
{coe := λ x, ⟨x,subset_adjoin F S (subtype.mem x)⟩}
@[mono] lemma adjoin.mono (T : set E) (h : S ⊆ T) : adjoin F S ≤ adjoin F T :=
galois_connection.monotone_l gc h
lemma adjoin_contains_field_as_subfield (F : subfield E) : (F : set E) ⊆ adjoin F S :=
λ x hx, adjoin.algebra_map_mem F S ⟨x, hx⟩
lemma subset_adjoin_of_subset_left {F : subfield E} {T : set E} (HT : T ⊆ F) : T ⊆ adjoin F S :=
λ x hx, (adjoin F S).algebra_map_mem ⟨x, HT hx⟩
lemma subset_adjoin_of_subset_right {T : set E} (H : T ⊆ S) : T ⊆ adjoin F S :=
λ x hx, subset_adjoin F S (H hx)
@[simp] lemma adjoin_empty (F E : Type*) [field F] [field E] [algebra F E] :
adjoin F (∅ : set E) = ⊥ :=
eq_bot_iff.mpr (adjoin_le_iff.mpr (set.empty_subset _))
/-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ≤ K`. -/
lemma adjoin_le_subfield {K : subfield E} (HF : set.range (algebra_map F E) ⊆ K)
(HS : S ⊆ K) : (adjoin F S).to_subfield ≤ K :=
begin
apply subfield.closure_le.mpr,
rw set.union_subset_iff,
exact ⟨HF, HS⟩,
end
lemma adjoin_subset_adjoin_iff {F' : Type*} [field F'] [algebra F' E]
{S S' : set E} : (adjoin F S : set E) ⊆ adjoin F' S' ↔
set.range (algebra_map F E) ⊆ adjoin F' S' ∧ S ⊆ adjoin F' S' :=
⟨λ h, ⟨trans (adjoin.range_algebra_map_subset _ _) h, trans (subset_adjoin _ _) h⟩,
λ ⟨hF, hS⟩, subfield.closure_le.mpr (set.union_subset hF hS)⟩
/-- `F[S][T] = F[S ∪ T]` -/
lemma adjoin_adjoin_left (T : set E) : ↑(adjoin (adjoin F S) T) = adjoin F (S ∪ T) :=
begin
rw intermediate_field.ext'_iff,
change ↑(adjoin (adjoin F S) T) = _,
apply set.eq_of_subset_of_subset; rw adjoin_subset_adjoin_iff; split,
{ rintros _ ⟨⟨x, hx⟩, rfl⟩, exact adjoin.mono _ _ _ (set.subset_union_left _ _) hx },
{ exact subset_adjoin_of_subset_right _ _ (set.subset_union_right _ _) },
{ exact subset_adjoin_of_subset_left _ (adjoin.range_algebra_map_subset _ _) },
{ exact set.union_subset
(subset_adjoin_of_subset_left _ (subset_adjoin _ _))
(subset_adjoin _ _) },
end
@[simp] lemma adjoin_insert_adjoin (x : E) :
adjoin F (insert x (adjoin F S : set E)) = adjoin F (insert x S) :=
le_antisymm
(adjoin_le_iff.mpr (set.insert_subset.mpr ⟨subset_adjoin _ _ (set.mem_insert _ _),
adjoin_le_iff.mpr (subset_adjoin_of_subset_right _ _ (set.subset_insert _ _))⟩))
(adjoin.mono _ _ _ (set.insert_subset_insert (subset_adjoin _ _)))
/-- `F[S][T] = F[T][S]` -/
lemma adjoin_adjoin_comm (T : set E) :
↑(adjoin (adjoin F S) T) = (↑(adjoin (adjoin F T) S) : (intermediate_field F E)) :=
by rw [adjoin_adjoin_left, adjoin_adjoin_left, set.union_comm]
lemma adjoin_map {E' : Type*} [field E'] [algebra F E'] (f : E →ₐ[F] E') :
(adjoin F S).map f = adjoin F (f '' S) :=
begin
ext x,
show x ∈ (subfield.closure (set.range (algebra_map F E) ∪ S)).map (f : E →+* E') ↔
x ∈ subfield.closure (set.range (algebra_map F E') ∪ f '' S),
rw [ring_hom.map_field_closure, set.image_union, ← set.range_comp, ← ring_hom.coe_comp,
f.comp_algebra_map],
refl,
end
lemma algebra_adjoin_le_adjoin : algebra.adjoin F S ≤ (adjoin F S).to_subalgebra :=
algebra.adjoin_le (subset_adjoin _ _)
lemma adjoin_eq_algebra_adjoin (inv_mem : ∀ x ∈ algebra.adjoin F S, x⁻¹ ∈ algebra.adjoin F S) :
(adjoin F S).to_subalgebra = algebra.adjoin F S :=
le_antisymm
(show adjoin F S ≤
{ neg_mem' := λ x, (algebra.adjoin F S).neg_mem, inv_mem' := inv_mem, .. algebra.adjoin F S},
from adjoin_le_iff.mpr (algebra.subset_adjoin))
(algebra_adjoin_le_adjoin _ _)
lemma eq_adjoin_of_eq_algebra_adjoin (K : intermediate_field F E)
(h : K.to_subalgebra = algebra.adjoin F S) : K = adjoin F S :=
begin
apply to_subalgebra_injective,
rw h,
refine (adjoin_eq_algebra_adjoin _ _ _).symm,
intros x,
convert K.inv_mem,
rw ← h,
refl
end
@[elab_as_eliminator]
lemma adjoin_induction {s : set E} {p : E → Prop} {x} (h : x ∈ adjoin F s)
(Hs : ∀ x ∈ s, p x) (Hmap : ∀ x, p (algebra_map F E x))
(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 :=
subfield.closure_induction h (λ x hx, or.cases_on hx (λ ⟨x, hx⟩, hx ▸ Hmap x) (Hs x))
((algebra_map F E).map_one ▸ Hmap 1)
Hadd Hneg Hinv Hmul
/--
Variation on `set.insert` to enable good notation for adjoining elements to fields.
Used to preferentially use `singleton` rather than `insert` when adjoining one element.
-/
--this definition of notation is courtesy of Kyle Miller on zulip
class insert {α : Type*} (s : set α) :=
(insert : α → set α)
@[priority 1000]
instance insert_empty {α : Type*} : insert (∅ : set α) :=
{ insert := λ x, @singleton _ _ set.has_singleton x }
@[priority 900]
instance insert_nonempty {α : Type*} (s : set α) : insert s :=
{ insert := λ x, set.insert x s }
notation K`⟮`:std.prec.max_plus l:(foldr `, ` (h t, insert.insert t h) ∅) `⟯` := adjoin K l
section adjoin_simple
variables (α : E)
lemma mem_adjoin_simple_self : α ∈ F⟮α⟯ :=
subset_adjoin F {α} (set.mem_singleton α)
/-- generator of `F⟮α⟯` -/
def adjoin_simple.gen : F⟮α⟯ := ⟨α, mem_adjoin_simple_self F α⟩
@[simp] lemma adjoin_simple.algebra_map_gen : algebra_map F⟮α⟯ E (adjoin_simple.gen F α) = α := rfl
lemma adjoin_simple_adjoin_simple (β : E) : ↑F⟮α⟯⟮β⟯ = F⟮α, β⟯ :=
adjoin_adjoin_left _ _ _
lemma adjoin_simple_comm (β : E) : ↑F⟮α⟯⟮β⟯ = (↑F⟮β⟯⟮α⟯ : intermediate_field F E) :=
adjoin_adjoin_comm _ _ _
end adjoin_simple
end adjoin_def
section adjoin_subalgebra_lattice
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} {S : set E}
@[simp] lemma adjoin_eq_bot_iff : adjoin F S = ⊥ ↔ S ⊆ (⊥ : intermediate_field F E) :=
by { rw [eq_bot_iff, adjoin_le_iff], refl, }
@[simp] lemma adjoin_simple_eq_bot_iff : F⟮α⟯ = ⊥ ↔ α ∈ (⊥ : intermediate_field F E) :=
by { rw adjoin_eq_bot_iff, exact set.singleton_subset_iff }
@[simp] lemma adjoin_zero : F⟮(0 : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (zero_mem ⊥)
@[simp] lemma adjoin_one : F⟮(1 : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (one_mem ⊥)
@[simp] lemma adjoin_int (n : ℤ) : F⟮(n : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n)
@[simp] lemma adjoin_nat (n : ℕ) : F⟮(n : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n)
section adjoin_dim
open finite_dimensional vector_space
@[simp] lemma dim_intermediate_field_eq_dim_subalgebra :
dim F (adjoin F S).to_subalgebra = dim F (adjoin F S) := rfl
@[simp] lemma findim_intermediate_field_eq_findim_subalgebra :
findim F (adjoin F S).to_subalgebra = findim F (adjoin F S) := rfl
@[simp] lemma to_subalgebra_eq_iff {K L : intermediate_field F E} :
K.to_subalgebra = L.to_subalgebra ↔ K = L :=
by { rw [subalgebra.ext_iff, intermediate_field.ext'_iff, set.ext_iff], refl }
lemma dim_adjoin_eq_one_iff : dim F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) :=
by rw [←dim_intermediate_field_eq_dim_subalgebra, subalgebra.dim_eq_one_iff,
←bot_to_subalgebra, to_subalgebra_eq_iff, adjoin_eq_bot_iff]
lemma dim_adjoin_simple_eq_one_iff : dim F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) :=
by { rw [dim_adjoin_eq_one_iff], exact set.singleton_subset_iff }
lemma findim_adjoin_eq_one_iff : findim F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) :=
by rw [←findim_intermediate_field_eq_findim_subalgebra, subalgebra.findim_eq_one_iff,
←bot_to_subalgebra, to_subalgebra_eq_iff, adjoin_eq_bot_iff]
lemma findim_adjoin_simple_eq_one_iff : findim F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) :=
by { rw [findim_adjoin_eq_one_iff], exact set.singleton_subset_iff }
/-- If `F⟮x⟯` has dimension `1` over `F` for every `x ∈ E` then `F = E`. -/
lemma bot_eq_top_of_dim_adjoin_eq_one (h : ∀ x : E, dim F F⟮x⟯ = 1) :
(⊥ : intermediate_field F E) = ⊤ :=
begin
ext,
rw iff_true_right intermediate_field.mem_top,
exact dim_adjoin_simple_eq_one_iff.mp (h x),
end
lemma bot_eq_top_of_findim_adjoin_eq_one (h : ∀ x : E, findim F F⟮x⟯ = 1) :
(⊥ : intermediate_field F E) = ⊤ :=
begin
ext,
rw iff_true_right intermediate_field.mem_top,
exact findim_adjoin_simple_eq_one_iff.mp (h x),
end
lemma subsingleton_of_dim_adjoin_eq_one (h : ∀ x : E, dim F F⟮x⟯ = 1) :
subsingleton (intermediate_field F E) :=
subsingleton_of_bot_eq_top (bot_eq_top_of_dim_adjoin_eq_one h)
lemma subsingleton_of_findim_adjoin_eq_one (h : ∀ x : E, findim F F⟮x⟯ = 1) :
subsingleton (intermediate_field F E) :=
subsingleton_of_bot_eq_top (bot_eq_top_of_findim_adjoin_eq_one h)
instance [finite_dimensional F E] (K : intermediate_field F E) : finite_dimensional F K :=
finite_dimensional.finite_dimensional_submodule (K.to_subalgebra.to_submodule)
/-- If `F⟮x⟯` has dimension `≤1` over `F` for every `x ∈ E` then `F = E`. -/
lemma bot_eq_top_of_findim_adjoin_le_one [finite_dimensional F E]
(h : ∀ x : E, findim F F⟮x⟯ ≤ 1) : (⊥ : intermediate_field F E) = ⊤ :=
begin
apply bot_eq_top_of_findim_adjoin_eq_one,
exact λ x, by linarith [h x, show 0 < findim F F⟮x⟯, from findim_pos],
end
lemma subsingleton_of_findim_adjoin_le_one [finite_dimensional F E]
(h : ∀ x : E, findim F F⟮x⟯ ≤ 1) : subsingleton (intermediate_field F E) :=
subsingleton_of_bot_eq_top (bot_eq_top_of_findim_adjoin_le_one h)
end adjoin_dim
end adjoin_subalgebra_lattice
section induction
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
/-- An intermediate field `S` is finitely generated if there exists `t : finset E` such that
`intermediate_field.adjoin F t = S`. -/
def fg (S : intermediate_field F E) : Prop := ∃ (t : finset E), adjoin F ↑t = S
lemma fg_adjoin_finset (t : finset E) : (adjoin F (↑t : set E)).fg :=
⟨t, rfl⟩
theorem fg_def {S : intermediate_field F E} : S.fg ↔ ∃ t : set E, set.finite t ∧ adjoin F t = S :=
⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩,
λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩
theorem fg_bot : (⊥ : intermediate_field F E).fg :=
⟨∅, adjoin_empty F E⟩
lemma fg_of_fg_to_subalgebra (S : intermediate_field F E)
(h : S.to_subalgebra.fg) : S.fg :=
begin
cases h with t ht,
exact ⟨t, (eq_adjoin_of_eq_algebra_adjoin _ _ _ ht.symm).symm⟩
end
lemma fg_of_noetherian (S : intermediate_field F E)
[is_noetherian F E] : S.fg :=
S.fg_of_fg_to_subalgebra S.to_subalgebra.fg_of_noetherian
lemma induction_on_adjoin [fd : finite_dimensional F E] (P : intermediate_field F E → Prop)
(base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯)
(K : intermediate_field F E) : P K :=
begin
haveI := classical.prop_decidable,
obtain ⟨s, rfl⟩ := fg_of_noetherian K,
apply @finset.induction_on E (λ s, P (adjoin F ↑s)) _ s base,
intros a t _ h,
rw [finset.coe_insert, ←set.union_singleton, ←adjoin_adjoin_left],
exact ih (adjoin F ↑t) a h
end
end induction
end intermediate_field
|
93ced58f2ffa2b3e30cd189c4dc7a9694a9e9c8c | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/elab1.lean | 5d356af7d5fbfb1e70af50fc5034b4e04c5d23ca | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 405 | lean | definition foo.subst := @eq.subst
definition boo.subst := @eq.subst
definition foo.add := @has_add.add
definition boo.add := @has_add.add
set_option pp.all true
open foo boo has_add
#print raw subst -- subst is overloaded
#print raw add -- add is overloaded
#check @subst
#check @@subst
open eq
#check subst
constants a b : nat
constant H1 : a = b
constant H2 : a + b > 0
#check eq.subst H1 H2
|
c356682eae7ec0101e824688172456b7886a8e79 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/control/traversable/equiv.lean | 9733ecf04da08acabad9cffd35c20ff2c3be1e1f | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,202 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
Transferring `traversable` instances using isomorphisms.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.equiv.basic
import Mathlib.control.traversable.lemmas
import Mathlib.PostPort
universes u
namespace Mathlib
namespace equiv
/-- Given a functor `t`, a function `t' : Type u → Type u`, and
equivalences `t α ≃ t' α` for all `α`, then every function `α → β` can
be mapped to a function `t' α → t' β` functorially (see
`equiv.functor`). -/
protected def map {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [Functor t] {α : Type u} {β : Type u} (f : α → β) (x : t' α) : t' β :=
coe_fn (eqv β) (f <$> coe_fn (equiv.symm (eqv α)) x)
/-- The function `equiv.map` transfers the functoriality of `t` to
`t'` using the equivalences `eqv`. -/
protected def functor {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [Functor t] : Functor t' :=
{ map := equiv.map eqv, mapConst := fun (α β : Type u) => equiv.map eqv ∘ function.const β }
protected theorem id_map {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [Functor t] [is_lawful_functor t] {α : Type u} (x : t' α) : equiv.map eqv id x = x := sorry
protected theorem comp_map {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [Functor t] [is_lawful_functor t] {α : Type u} {β : Type u} {γ : Type u} (g : α → β) (h : β → γ) (x : t' α) : equiv.map eqv (h ∘ g) x = equiv.map eqv h (equiv.map eqv g x) := sorry
protected theorem is_lawful_functor {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [Functor t] [is_lawful_functor t] : is_lawful_functor t' :=
is_lawful_functor.mk (equiv.id_map eqv) (equiv.comp_map eqv)
protected theorem is_lawful_functor' {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [Functor t] [is_lawful_functor t] [F : Functor t'] (h₀ : ∀ {α β : Type u} (f : α → β), Functor.map f = equiv.map eqv f) (h₁ : ∀ {α β : Type u} (f : β), Functor.mapConst f = function.comp (equiv.map eqv) (function.const α) f) : is_lawful_functor t' := sorry
/-- Like `equiv.map`, a function `t' : Type u → Type u` can be given
the structure of a traversable functor using a traversable functor
`t'` and equivalences `t α ≃ t' α` for all α. See `equiv.traversable`. -/
protected def traverse {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [traversable t] {m : Type u → Type u} [Applicative m] {α : Type u} {β : Type u} (f : α → m β) (x : t' α) : m (t' β) :=
⇑(eqv β) <$> traverse f (coe_fn (equiv.symm (eqv α)) x)
/-- The function `equiv.tranverse` transfers a traversable functor
instance across the equivalences `eqv`. -/
protected def traversable {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [traversable t] : traversable t' :=
traversable.mk (equiv.traverse eqv)
protected theorem id_traverse {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [traversable t] [is_lawful_traversable t] {α : Type u} (x : t' α) : equiv.traverse eqv id.mk x = x := sorry
protected theorem traverse_eq_map_id {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [traversable t] [is_lawful_traversable t] {α : Type u} {β : Type u} (f : α → β) (x : t' α) : equiv.traverse eqv (id.mk ∘ f) x = id.mk (equiv.map eqv f x) := sorry
protected theorem comp_traverse {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [traversable t] [is_lawful_traversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {α : Type u} {β : Type u} {γ : Type u} (f : β → F γ) (g : α → G β) (x : t' α) : equiv.traverse eqv (functor.comp.mk ∘ Functor.map f ∘ g) x =
functor.comp.mk (equiv.traverse eqv f <$> equiv.traverse eqv g x) := sorry
protected theorem naturality {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [traversable t] [is_lawful_traversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G] (η : applicative_transformation F G) {α : Type u} {β : Type u} (f : α → F β) (x : t' α) : coe_fn η (t' β) (equiv.traverse eqv f x) = equiv.traverse eqv (coe_fn η β ∘ f) x := sorry
/-- The fact that `t` is a lawful traversable functor carries over the
equivalences to `t'`, with the traversable functor structure given by
`equiv.traversable`. -/
protected def is_lawful_traversable {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [traversable t] [is_lawful_traversable t] : is_lawful_traversable t' :=
is_lawful_traversable.mk (equiv.id_traverse eqv) (equiv.comp_traverse eqv) (equiv.traverse_eq_map_id eqv)
(equiv.naturality eqv)
/-- If the `traversable t'` instance has the properties that `map`,
`map_const`, and `traverse` are equal to the ones that come from
carrying the traversable functor structure from `t` over the
equivalences, then the the fact `t` is a lawful traversable functor
carries over as well. -/
protected def is_lawful_traversable' {t : Type u → Type u} {t' : Type u → Type u} (eqv : (α : Type u) → t α ≃ t' α) [traversable t] [is_lawful_traversable t] [traversable t'] (h₀ : ∀ {α β : Type u} (f : α → β), Functor.map f = equiv.map eqv f) (h₁ : ∀ {α β : Type u} (f : β), Functor.mapConst f = function.comp (equiv.map eqv) (function.const α) f) (h₂ : ∀ {F : Type u → Type u} [_inst_7 : Applicative F] [_inst_8 : is_lawful_applicative F] {α β : Type u} (f : α → F β),
traverse f = equiv.traverse eqv f) : is_lawful_traversable t' :=
is_lawful_traversable.mk sorry sorry sorry sorry
|
034066cc8648bcd016b125afb21a605775f103c2 | 93b17e1ec33b7fd9fb0d8f958cdc9f2214b131a2 | /src/sep/basic.lean | 1bc36359a5f6a712b2331d793b1677a8bb788161 | [] | no_license | intoverflow/timesink | 93f8535cd504bc128ba1b57ce1eda4efc74e5136 | c25be4a2edb866ad0a9a87ee79e209afad6ab303 | refs/heads/master | 1,620,033,920,087 | 1,524,995,105,000 | 1,524,995,105,000 | 120,576,102 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,471 | lean | /- Separation algebras
-
-/
namespace Sep
universes ℓ ℓ₁ ℓ₂ ℓ₃ ℓ₄
-- Separation algebras
structure Alg.Assoc {A' : Type ℓ} (join : A' → A' → set A')
{x₁ x₂ x₃ x₁x₂ x₁x₂x₃}
(H₁ : join x₁ x₂ x₁x₂) (H₂ : join x₁x₂ x₃ x₁x₂x₃)
:= (x : A')
(J₁ : join x₂ x₃ x)
(J₂ : join x₁ x x₁x₂x₃)
def IsAssoc {A' : Type ℓ} (join : A' → A' → set A') : Prop
:= ∀ {x₁ x₂ x₃ x₁x₂ x₁x₂x₃}
(H₁ : join x₁ x₂ x₁x₂) (H₂ : join x₁x₂ x₃ x₁x₂x₃)
{P : Prop}
(C : Alg.Assoc join H₁ H₂ → P)
, P
structure Alg
:= (τ : Type ℓ)
(join : τ → τ → set τ)
(comm : ∀ {x₁ x₂ x₃}, join x₁ x₂ x₃ → join x₂ x₁ x₃)
(assoc : IsAssoc join)
-- Subsets of separation algebras
def Set (A : Alg.{ℓ}) := set A.τ
class has_sepmul (α : Type ℓ) := (sepmul : α → α → α)
infix <*> := has_sepmul.sepmul
instance Set_has_emptyc (A : Alg.{ℓ}) : has_emptyc (Set A) := set.has_emptyc
instance Set_has_subset (A : Alg.{ℓ}) : has_subset (Set A) := set.has_subset
instance Set_has_inter (A : Alg.{ℓ}) : has_inter (Set A) := set.has_inter
instance Set_has_union (A : Alg.{ℓ}) : has_union (Set A) := set.has_union
instance Set_has_mem (A : Alg.{ℓ}) : has_mem A.τ (Set A) := set.has_mem
def Set.Cover.Subset {A : Alg.{ℓ}}
{S : Set A} {SS : set (Set A)}
(Scover : S = set.sUnion SS)
{T : Set A} (SST : T ∈ SS)
: T ⊆ S
:= begin
intros x H,
rw Scover,
existsi T,
exact exists.intro SST H
end
def Set.Subset.trans {A : Alg.{ℓ}}
{S₁ S₂ S₃ : Set A}
(H₁₂ : S₁ ⊆ S₂) (H₂₃ : S₂ ⊆ S₃)
: S₁ ⊆ S₃
:= λ s H, H₂₃ (H₁₂ H)
def Set.nonempty {A : Alg.{ℓ}} (S : Set A) : Prop
:= ∃ x, x ∈ S
def Alg.EmptySet (A : Alg.{ℓ}) : Set A := λ a, false
def Alg.WholeSet (A : Alg.{ℓ}) : Set A := λ a, true
def Set.Compl {A : Alg.{ℓ}} (S : Set A) : Set A
:= set.compl S
def Set.ComplCompl {A : Alg.{ℓ}} (S : Set A)
: S.Compl.Compl = S
:= begin
apply funext, intro s,
apply iff.to_eq,
apply iff.intro,
{ intro H₁,
apply classical.by_contradiction,
intro H₂,
exact H₁ H₂
},
{ intros H₁ H₂,
exact H₂ H₁
}
end
def Set.mem_nonempty {A : Alg.{ℓ}} {S : Set A}
{x} (H : x ∈ S)
: S ≠ ∅
:= λ Q, cast (congr_fun Q x) H
-- An equivalence relation on sets; happens to imply equality but is easier to prove
def SetEq {A : Alg.{ℓ}} (S₁ S₂ : Set A) : Prop
:= ∀ x, x ∈ S₁ ↔ x ∈ S₂
def SetEq.refl {A : Alg.{ℓ}} (S : Set A)
: SetEq S S
:= λ x, iff.refl _
def SetEq.symm {A : Alg.{ℓ}} {S₁ S₂ : Set A}
: SetEq S₁ S₂ → SetEq S₂ S₁
:= λ H x, iff.symm (H x)
def SetEq.trans {A : Alg.{ℓ}} {S₁ S₂ S₃ : Set A}
: SetEq S₁ S₂ → SetEq S₂ S₃ → SetEq S₁ S₃
:= λ H₁₂ H₂₃ x, iff.trans (H₁₂ x) (H₂₃ x)
def SetEq.to_eq {A : Alg.{ℓ}} {S₁ S₂ : Set A}
: SetEq S₁ S₂ → S₁ = S₂
:= λ H, funext (λ x, iff.to_eq (H x))
-- Identity elements
structure Alg.Ident (A : Alg.{ℓ})
:= (one : A.τ)
(join_one_r : ∀ x, A.join x one x)
(join_one_uniq_r : ∀ {x y}, A.join x one y → y = x)
def Alg.Ident.join_one_l {A : Alg.{ℓ}} (A₁ : A.Ident)
: ∀ x, A.join A₁.one x x
:= λ x, A.comm (A₁.join_one_r x)
def Alg.Ident.join_one_uniq_l {A : Alg.{ℓ}} (A₁ : A.Ident)
: ∀ {x y}, A.join A₁.one x y → y = x
:= λ x y H, A₁.join_one_uniq_r (A.comm H)
-- Identity elements are unique
def Ident.uniq (A : Alg.{ℓ}) (Ae₁ Ae₂ : A.Ident)
: Ae₁ = Ae₂
:= let H := Ae₁.join_one_uniq_r (A.comm (Ae₂.join_one_r Ae₁.one))
in begin cases Ae₁, cases Ae₂, simp * at * end
/- The Join function
-
-/
def Alg.Join (A : Alg.{ℓ})
: Set A → Set A → Set A
:= λ X₁ X₂ x₃, ∃ x₁ x₂, X₁ x₁ ∧ X₂ x₂ ∧ A.join x₁ x₂ x₃
instance Set_has_sepmul (A : Alg.{ℓ}) : has_sepmul (Set A)
:= { sepmul := A.Join
}
def Alg.Join.show {A : Alg.{ℓ}} {X₁ X₂ : Set A}
{x₁ x₂ x₃} (H₁ : X₁ x₁) (H₂ : X₂ x₂) (Hx : A.join x₁ x₂ x₃)
: A.Join X₁ X₂ x₃
:= ⟨ x₁, x₂, H₁, H₂, Hx ⟩
def Alg.Join.elim {A : Alg.{ℓ}} {X₁ X₂ : Set A} {x₃}
(H : A.Join X₁ X₂ x₃)
{P : Prop}
: (∀ {x₁ x₂}, X₁ x₁ → X₂ x₂ → A.join x₁ x₂ x₃ → P) → P
:= λ C, begin
cases H with x₁ H, cases H with x₂ H,
exact C H.1 H.2.1 H.2.2
end
-- The join relation is a special case of the Join function
def Alg.join_Join (A : Alg.{ℓ}) {x₁ x₂ x₃}
: A.join x₁ x₂ x₃ ↔ A.Join (eq x₁) (eq x₂) x₃
:= iff.intro
(λ H, Alg.Join.show rfl rfl H)
(λ H, Alg.Join.elim H (λ x₁' x₂' H₁ H₂ Hx, begin rw [H₁, H₂], exact Hx end))
-- The Join function is commutative
def Alg.Join.comm (A : Alg.{ℓ}) {X₁ X₂ : Set A}
: X₁ <*> X₂ = X₂ <*> X₁
:= begin
apply funext, intro x,
refine iff.to_eq (iff.intro _ _),
repeat
{ intro H, apply Alg.Join.elim H,
intros x₁' x₂' H₁ H₂ Hx,
exact Alg.Join.show H₂ H₁ (A.comm Hx)
}
end
-- The Join function is associative
def Alg.Join.assoc (A : Alg.{ℓ}) {X₁ X₂ X₃ : Set A}
: (X₁ <*> X₂) <*> X₃ = X₁ <*> (X₂ <*> X₃)
:= begin
apply funext, intro z,
refine iff.to_eq (iff.intro _ _),
{ intro H, cases H with x₁ H, cases H with x₂ H,
cases H with H' H, cases H' with y₁ H', cases H' with y₂ H',
apply A.assoc H'.2.2 H.2,
intro a,
existsi y₁, existsi a.x,
refine and.intro H'.1 (and.intro _ a.J₂),
existsi y₂, existsi x₂,
refine and.intro H'.2.1 (and.intro H.1 a.J₁)
},
{ intro H, cases H with x₁ H, cases H with x₂ H,
cases H with X₁x₁ H, cases H with H' H, cases H' with y₁ H', cases H' with y₂ H',
apply A.assoc (A.comm H'.2.2) (A.comm H),
intro a,
existsi a.x, existsi y₂,
refine and.intro _ (and.intro H'.2.1 (A.comm a.J₂)),
existsi x₁, existsi y₁,
exact and.intro X₁x₁ (and.intro H'.1 (A.comm a.J₁))
},
end
/- The "divides" relation
-
-/
def Alg.Divides (A : Alg.{ℓ}) (x₁ x₃ : A.τ)
: Prop
:= ∀ (P : Prop)
(C₁ : ∀ {x}, A.join x₁ x x₃ → P)
(C₂ : x₁ = x₃ → P)
, P
-- Divides is transitive
def Divides.trans {A : Alg.{ℓ}} {x₁ x₂ x₃}
: A.Divides x₁ x₂ → A.Divides x₂ x₃ → A.Divides x₁ x₃
:= λ d₁₂ d₂₃ P C₁ C₂
, begin
apply d₁₂,
{ intros x'₁ Jx'₁,
apply d₂₃,
{ intros x'₂ Jx'₂,
apply A.assoc Jx'₁ Jx'₂, intro a,
exact C₁ a.J₂
},
{ intro E, subst E, exact C₁ Jx'₁ }
},
{ intro E, subst E,
apply d₂₃,
{ intros x'₂ Jx'₂,
exact C₁ Jx'₂
},
{ apply C₂ }
}
end
-- Divides is reflective
def Divides.refl (A : Alg.{ℓ}) (x : A.τ)
: A.Divides x x
:= λ P C₁ C₂ , C₂ rfl
/- Parts
-
-/
def Alg.Part (A : Alg.{ℓ}) (m : A.τ) : Prop
:= ∃ m₂ m₃, A.join m m₂ m₃
/- Units
-
-/
def Alg.Unit (A : Alg.{ℓ}) : Set A
:= λ u, ∀ x, A.Divides u x
-- If w divides a unit, then w is also a unit
def Unit.Divides {A : Alg.{ℓ}} {u} (uUnit : A.Unit u) (v : A.τ)
: A.Divides v u → A.Unit v
:= begin
intro H,
intro x,
apply Divides.trans H,
apply uUnit
end
-- Distinct units join with each other to form new units
def Unit.Join {A : Alg.{ℓ}}
{u₁} (Uu₁ : A.Unit u₁)
{u₂} (Uu₂ : A.Unit u₂)
{P : Prop}
(C : ∀ u₃, u₃ ∈ A.join u₁ u₂ → A.Unit u₃ → P)
(E : u₁ = u₂ → P)
: P
:= begin
apply Uu₁ u₂,
{ intros w Jw,
apply Uu₂ w,
{ intros v Jv,
apply A.assoc (A.comm Jv) (A.comm Jw),
intro a,
apply C a.x (A.comm a.J₁),
apply Unit.Divides Uu₂,
intros P C₁ C₂,
exact C₁ (A.comm a.J₂)
},
{ intro E', subst E', apply C, repeat { assumption } }
},
{ exact E }
end
def Alg.ProperUnit (A : Alg.{ℓ}) : Set A
:= λ u, ∀ x, ∃ xu, A.join u xu x
def ProperUnit.Unit {A : Alg.{ℓ}} {u : A.τ}
(uU : u ∈ A.ProperUnit)
: u ∈ A.Unit
:= begin
intro x,
cases uU x with xu Hxu,
intros P C₁ C₂,
exact C₁ Hxu
end
def Alg.StrongUnit (A : Alg.{ℓ}) : Set A
:= λ u, u ∈ A.Unit ∧ (∀ v, v ∈ A.Unit → A.join u v ⊆ A.Unit)
-- If w divides a proper unit, then w is also a unit
def ProperUnit.Divides {A : Alg.{ℓ}} {u}
(uUnit : A.ProperUnit u)
(v : A.τ)
: A.Divides v u → A.ProperUnit v
:= begin
intro H,
intro x,
apply H; clear H,
{ intros w Jvwu,
cases uUnit x with xu Ju,
apply A.assoc Jvwu Ju,
intro a,
existsi a.x,
exact a.J₂
},
{ intro E, subst E,
exact uUnit x
}
end
-- Proper units join with each other to form new proper units
def ProperUnit.Join {A : Alg.{ℓ}}
{u₁} (Uu₁ : A.ProperUnit u₁)
{u₂} (Uu₂ : A.ProperUnit u₂)
: ∃ u₃, u₃ ∈ A.join u₁ u₂ ∧ A.ProperUnit u₃
:= begin
cases Uu₁ u₂ with w Jw,
cases Uu₂ w with v Jv,
apply A.assoc (A.comm Jv) (A.comm Jw),
intro a,
existsi a.x,
apply and.intro (A.comm a.J₁),
apply ProperUnit.Divides Uu₂,
intros P C₁ C₂,
exact C₁ (A.comm a.J₂)
end
/- Linear elements
-
-/
def Alg.Linear (A : Alg.{ℓ}) : Set A
:= λ u
, (∀ x, ∃! y, A.join u x y)
∧ (∀ x₁ x₂, A.join u x₁ = A.join u x₂ → x₁ = x₂)
def Linear.injective {A : Alg.{ℓ}} {l : A.τ} (lLinear : A.Linear l)
{x₁ x₂ y : A.τ}
(J₁ : A.join l x₁ y) (J₂ : A.join l x₂ y)
: x₁ = x₂
:= begin
apply lLinear.2,
apply funext, intro y₁,
apply iff.to_eq, apply iff.intro,
{ intro J₁',
have Q₁ := lLinear.1 x₁,
cases Q₁ with y₁ Q₁,
cases Q₁ with Jy₁ Q₁,
have P := Q₁ _ J₁',
subst P,
have P := Q₁ _ J₁,
subst P,
exact J₂
},
{ intro J₂',
have Q₁ := lLinear.1 x₂,
cases Q₁ with y₁ Q₁,
cases Q₁ with Jy₁ Q₁,
have P := Q₁ _ J₂',
subst P,
have P := Q₁ _ J₂,
subst P,
exact J₁
}
end
def Linear.well_defined {A : Alg.{ℓ}} {l : A.τ} (lLinear : A.Linear l)
{x y₁ y₂ : A.τ}
(J₁ : A.join l x y₁) (J₂ : A.join l x y₂)
: y₁ = y₂
:= begin
have Q := lLinear.1 x,
cases Q with y Q,
cases Q with Jy Q,
refine eq.trans (Q _ J₁) (Q _ J₂).symm,
end
/- Linear units
-
-/
def Alg.LinearUnit (A : Alg.{ℓ}) : Set A
:= A.ProperUnit ∩ A.Linear
def LinearUnit.Ident (A : Alg.{ℓ})
(H : ∃ u, u ∈ A.LinearUnit)
: ∃ i, (∀ x, A.join i x = eq x)
:= begin
cases H with u Hu,
cases Hu.1 u with i Hi,
existsi i,
intro x₁, apply funext, intro x₂,
apply iff.to_eq, apply iff.intro,
{ intro J,
have Q₁ := Hu.2.1 x₁,
cases Q₁ with y₁ Q₁,
cases Q₁ with Jy₁ Q₁,
have Q₂ := Hu.2.1 x₂,
cases Q₂ with y₂ Q₂,
cases Q₂ with Jy₂ Q₂,
apply A.assoc J (A.comm Jy₂),
intro a, cases a with a J₁ J₂,
have E : a = y₁ := Q₁ _ (A.comm J₁),
subst E, clear Q₁ J₁,
refine Linear.injective Hu.2 Jy₁ _,
apply A.assoc (A.comm Jy₁) (A.comm J₂),
intro a', cases a' with a' J₁' J₂',
have E : u = a' := Linear.well_defined Hu.2 Hi J₁',
subst E,
have E : y₂ = a := Linear.well_defined Hu.2 (A.comm J₂') Jy₁,
subst E,
exact Jy₂
},
{ intro E, subst E,
have Q := Hu.2.1 x₁,
cases Q with y Q,
cases Q with Jy Q,
apply A.assoc Hi Jy,
intro a, cases a with a J₁ J₂,
have E : x₁ = a := Linear.injective Hu.2 Jy J₂,
subst E,
exact J₁
}
end
def LinearUnit.GroupIdent (A : Alg.{ℓ})
(H : ∃ u, u ∈ A.LinearUnit)
: ∃ i, (i ∈ A.LinearUnit ∧ ∀ x, A.join i x = eq x)
:= begin
cases LinearUnit.Ident A H with i Hi,
cases H with u Hu,
existsi i,
refine and.intro _ Hi,
apply and.intro,
{ apply ProperUnit.Divides Hu.1,
intros P C₁ C₂,
apply @C₁ u,
rw Hi
},
apply and.intro,
{ intro x, existsi x,
apply and.intro,
{ simp, rw Hi },
{ intros y Hy, rw Hi at Hy, exact Hy.symm }
},
{ intros x₁ x₂ J,
repeat { rw Hi at J },
rw J
}
end
/- Weak identities
-
-/
def Alg.WeakIdentity (A : Alg.{ℓ}) (w : A.τ) : Prop
:= ∀ (x), A.join w x x
def WeakIdentity.Unit {A : Alg.{ℓ}} {w : A.τ} (wWeak : A.WeakIdentity w)
: A.Unit w
:= λ x P C₁ C₂, C₁ (wWeak x)
/- Rational and integral sets
-
-/
-- A set is Rational if it contains all of the linear units.
def Set.Rational {A : Alg.{ℓ}} (R : Set A) : Prop
:= A.LinearUnit ⊆ R
-- A set is Integral if it contains no units.
def Set.Integral {A : Alg.{ℓ}} (I : Set A) : Prop
:= ∀ x, x ∈ I → ¬ (A.LinearUnit x)
-- Arbitrary unions of integral sets are again integral
def Integral.Union {A : Alg.{ℓ}}
(PP : set (Set A))
(H : ∀ (p : Set A), p ∈ PP → p.Integral)
: Set.Integral (set.sUnion PP)
:= begin
intros x Hx F,
cases Hx with p HS,
cases HS with HPP Hxp,
exact H p HPP x Hxp F
end
/- Primes
-
-/
structure Alg.Prime (A : Alg.{ℓ}) (p : A.τ)
:= (u : A.τ)
(proper : A.Divides p u → false)
(prime : ∀ {x₁ x₂ x₃}
, A.join x₁ x₂ x₃ → A.Divides p x₃
→ A.Divides p x₁ ∨ A.Divides p x₂)
/- Important kinds of sets
-
-/
def Set.Ideal {A : Alg.{ℓ}} (I : Set A) : Prop
:= ∀ {x₁ x₂ x₃}, x₁ ∈ I → A.join x₁ x₂ x₃ → x₃ ∈ I
def Ideal.Overlap {A : Alg.{ℓ}} (I S : Set A)
: Set A
:= λ x, x ∈ I ∧ (∃ y, (y ∈ S) ∧ (∀ {z}, ¬ A.join x y z))
infix <-> := Ideal.Overlap
def Overlap.Ideal {A : Alg.{ℓ}} {I₁ I₂ : Set A}
(I₁ideal : I₁.Ideal)
: (I₁ <-> I₂).Ideal
:= begin
intros x₁ x₂ x₃ Ix₁ Jx,
apply and.intro (I₁ideal Ix₁.1 Jx),
cases Ix₁ with Ix₁ Hy,
cases Hy with y Hy,
existsi y,
apply and.intro Hy.1,
intros z Jz,
apply A.assoc (A.comm Jx) Jz, intro a,
apply Hy.2 a.J₁
end
def Set.WeakIdeal {A : Alg.{ℓ}} (I : Set A) : Prop
:= ∀ {x₁ x₂ x₃}, x₁ ∈ I → A.join x₁ x₂ x₃ → ∃ x₃', A.join x₁ x₂ x₃' ∧ x₃' ∈ I
def Ideal.WeakIdeal {A : Alg.{ℓ}} (I : Set A)
: I.Ideal → I.WeakIdeal
:= λ IIdeal x₁ x₂ x₃ Ix₁ Jx
, exists.intro x₃ (and.intro Jx (IIdeal Ix₁ Jx))
def Set.Proper {A : Alg.{ℓ}} (I : Set A)
: Prop
:= ∀ {P : Prop} (C : ∀ z, ¬ z ∈ I → P), P
def Proper.one_not_elem {A : Alg.{ℓ}} (A₁ : A.Ident) {I : Set A} (Iideal : I.Ideal) (Iproper : I.Proper)
: ¬ A₁.one ∈ I
:= begin
intro H',
apply Iproper,
intros z Hz,
apply Hz,
exact Iideal H' (A₁.join_one_l z)
end
-- A set S is a sub-algebra if it associates
def Set.SubAlg {A : Alg.{ℓ}} (S : Set A) : Prop
:= ∀ (x₁ x₂ x₃ x₁₂ x₁₂₃ : {x // S x})
(H₁ : A.join x₁ x₂ x₁₂) (H₂ : A.join x₁₂ x₃ x₁₂₃)
{P : Prop}
(C : ∀ (a : Alg.Assoc A.join H₁ H₂), a.x ∈ S → P)
, P
-- Subalgebras are, of course, algebras
def Set.SubAlg.Alg {A : Alg.{ℓ}} {S : Set A}
(SSA : S.SubAlg)
: Alg.{ℓ}
:= { τ := { x // S x}
, join := λ x₁ x₂ x₃, A.join x₁.val x₂.val x₃.val
, comm := λ x₁ x₂ x₃ J, A.comm J
, assoc := λ x₁ x₂ x₃ x₁₂ x₁₂₃ J₁₂ J₁₂₃ P C
, begin
apply SSA _ _ _ _ _ J₁₂ J₁₂₃,
intros a Sa,
apply C,
exact { x := { val := a.x, property := Sa }
, J₁ := a.J₁
, J₂ := a.J₂
}
end
}
-- A set S is join-closed if: S <*> S ⊆ S
def Set.JoinClosed {A : Alg.{ℓ}} (S : Set A) : Prop
:= ∀ (b₁ b₂ b₃)
, b₃ ∈ A.join b₁ b₂
→ b₁ ∈ S → b₂ ∈ S
→ b₃ ∈ S
-- Join-closed sets are subalgebras in a very strong way
def Set.JoinClosed.assoc {A : Alg.{ℓ}} {S : Set A} (SJC : S.JoinClosed)
{s₁ s₂ s₃ s₁₂ s₁₂₃}
{J₁₂ : s₁₂ ∈ A.join s₁ s₂}
{J₁₂₃ : s₁₂₃ ∈ A.join s₁₂ s₃}
(a : Alg.Assoc A.join J₁₂ J₁₂₃)
(S₁ : s₁ ∈ S) (S₂ : s₂ ∈ S) (S₃ : s₃ ∈ S)
: a.x ∈ S
:= begin
apply SJC _ _ _ a.J₁,
repeat { assumption }
end
def Set.JoinClosed.SubAlg {A : Alg.{ℓ}} {S : Set A} (SJC : S.JoinClosed)
: S.SubAlg
:= begin
intros x₁ x₂ x₃ x₁₂ x₁₂₃ J₁₂ J₁₂₃ P C,
apply A.assoc J₁₂ J₁₂₃,
intro a,
have Ha := Set.JoinClosed.assoc SJC a x₁.property x₂.property x₃.property,
exact C a Ha
end
def Set.JoinClosed.Alg {A : Alg.{ℓ}} {S : Set A} (SJC : S.JoinClosed)
: Alg.{ℓ}
:= SJC.SubAlg.Alg
-- The join-closure of a set of elements
inductive JoinClosure {A : Alg.{ℓ}} (S : Set A)
: Set A
| gen : ∀ {x}, x ∈ S → JoinClosure x
| mul : ∀ {x₁ x₂ x₃}
, x₃ ∈ A.join x₁ x₂
→ JoinClosure x₁
→ JoinClosure x₂
→ JoinClosure x₃
def JoinClosure.JoinClosed {A : Alg.{ℓ}} (S : Set A)
: (JoinClosure S).JoinClosed
:= begin
intros x₁ x₂ x₃ Jx Gx₁ Gx₂,
exact JoinClosure.mul Jx Gx₁ Gx₂
end
def JoinClosed.JoinClosure {A : Alg.{ℓ}} {S : Set A}
(SJC : S.JoinClosed)
: JoinClosure S = S
:= begin
apply funext, intro x,
apply iff.to_eq, apply iff.intro,
{ intro H,
induction H with x' Hx' x₁ x₂ x₃ J Hx₁ Hx₂,
{ assumption },
{ apply SJC _ _ _ J,
repeat { assumption }
}
},
{ intro Hx, apply JoinClosure.gen, assumption }
end
def Alg.JoinClosure₁ (A : Alg.{ℓ}) (x : A.τ) : Set A
:= JoinClosure (eq x)
def JoinClosure₁.JoinClosed {A : Alg.{ℓ}} (x : A.τ)
: (A.JoinClosure₁ x).JoinClosed
:= JoinClosure.JoinClosed _
-- A set S is prime if: a <*> b ∩ S ≠ ∅ implies a ∈ S or b ∈ S
def Set.Prime {A : Alg.{ℓ}} (I : Set A) : Prop
:= ∀ (x₁ x₂ x₃)
, x₃ ∈ A.join x₁ x₂
→ x₃ ∈ I
→ x₁ ∈ I ∨ x₂ ∈ I
def Set.StrongPrime {A : Alg.{ℓ}} (I : Set A) : Prop
:= ∀ (x₁ x₂ x₃)
, x₃ ∈ A.join x₁ x₂
→ x₃ ∈ I
→ x₁ ∈ I ∧ x₂ ∈ I
def Set.StrongPrime.Prime {A : Alg.{ℓ}} {I : Set A}
(ISP : I.StrongPrime)
: I.Prime
:= begin
intros x₁ x₂ x₃ Jx Ix₃,
exact or.inl (ISP _ _ _ Jx Ix₃).1
end
-- Arbitrary unions of primes are again prime
def Prime.Union {A : Alg.{ℓ}}
(PP : set (Set A))
(H : ∀ (p : Set A), p ∈ PP → p.Prime)
: Set.Prime (set.sUnion PP)
:= begin
intros x₁ x₂ x₃ Jx H,
cases H with p H,
cases H with pPrime' px₃,
have pPrime : Set.Prime p := H p pPrime',
have Q := pPrime _ _ _ Jx px₃,
cases Q with Q Q,
{ apply or.inl,
existsi p,
exact exists.intro pPrime' Q
},
{ apply or.inr,
existsi p,
exact exists.intro pPrime' Q
}
end
-- The set of units is prime
def Alg.Unit.Prime (A : Alg.{ℓ})
: A.Unit.Prime
:= begin
intros x₁ x₂ x₃ Jx Hx₃,
apply or.inl,
have Dx : A.Divides x₁ x₃ := λ P C₁ C₂, C₁ Jx,
exact Unit.Divides Hx₃ _ Dx
end
-- The set of proper units is prime
def Alg.ProperUnit.StrongPrime (A : Alg.{ℓ})
: A.ProperUnit.StrongPrime
:= begin
intros x₁ x₂ u Jx Hu,
apply and.intro,
{ intro x,
cases Hu x with xu Ju,
apply A.assoc Jx Ju,
intro a,
existsi a.x,
exact a.J₂
},
{ intro x,
cases Hu x with xu Ju,
apply A.assoc (A.comm Jx) Ju,
intro a,
existsi a.x,
exact a.J₂
}
end
-- A set S is full if: a <*> b ∩ S ≠ ∅ implies a <*> b ⊆ S
def Set.Full {A : Alg.{ℓ}} (p : Set A) : Prop
:= ∀ {x₁ x₂ x₃}
, x₃ ∈ A.join x₁ x₂
→ x₃ ∈ p
→ A.join x₁ x₂ ⊆ p
-- Prime ideals are full
def PrimeIdeal.Full {A : Alg.{ℓ}} {p : Set A}
(pPrime : p.Prime)
(pIdeal : p.Ideal)
: p.Full
:= begin
intros x₁ x₂ x₃ Jx Px x₃' Jx',
cases pPrime _ _ _ Jx Px with H₁ H₂,
{ exact pIdeal H₁ Jx' },
{ exact pIdeal H₂ (A.comm Jx') }
end
-- The complement of a prime set is join-closed
def Set.Prime.Complement_JoinClosed {A : Alg.{ℓ}} {p : Set A}
(pPrime : p.Prime)
: p.Compl.JoinClosed
:= begin
intros x₁ x₂ x₃ Jx Px₁ Px₂,
intro Px₃,
cases pPrime _ _ _ Jx Px₃ with Px₁' Px₂',
{ exact Px₁ Px₁' },
{ exact Px₂ Px₂' }
end
-- The complement of a join-closed set is a prime set
def Set.JoinClosed.Complement_Prime {A : Alg.{ℓ}} {S : Set A}
(SJC : S.JoinClosed)
: S.Compl.Prime
:= begin
intros x₁ x₂ x₃ Jx Sx₃,
cases classical.em (x₁ ∈ S) with Sx₁ Sx₁,
{ cases classical.em (x₂ ∈ S) with Sx₂ Sx₂,
{ apply false.elim, apply Sx₃,
exact SJC _ _ _ Jx Sx₁ Sx₂
},
{ exact or.inr Sx₂ }
},
{ exact or.inl Sx₁ }
end
-- The whole set is an ideal
def WholeIdeal (A : Alg.{ℓ}) : (A.WholeSet).Ideal
:= λ x₁ x₂ x₃ Ix₁ H, Ix₁
-- The whole set is join-closed
def WholeJoinClosed (A : Alg.{ℓ}) : (A.WholeSet).JoinClosed
:= λ x₁ x₂ x₃ Jx H₁ H₂, true.intro
-- The whole set is a prime set
def WholePrime (A : Alg.{ℓ}) : (A.WholeSet).Prime
:= λ x₁ x₂ x₃ Jx H, or.inl true.intro
-- The empty set is an ideal
def EmptyIdeal (A : Alg.{ℓ}) : (A.EmptySet).Ideal
:= λ x₁ x₂ x₃ Ix₁ H, Ix₁
-- In a separation algebra with identity, the empty set is a proper set
def EmptyProper.Proper {A : Alg.{ℓ}} (A₁ : A.Ident) : (A.EmptySet).Proper
:= λ P C, C A₁.one false.elim
-- The empty set is join-closed
def EmptyJoinClosed (A : Alg.{ℓ}) : (A.EmptySet).JoinClosed
:= λ x₁ x₂ x₃ Jx H₁ H₂, false.elim H₁
-- The empty set is a prime set
def EmptyPrime (A : Alg.{ℓ}) : (A.EmptySet).Prime
:= λ x₁ x₂ x₃ H, false.elim
-- Ideal generated by a set of elements
def GenIdeal {A : Alg.{ℓ}} (gen : Set A) : Set A
:= λ y, (∃ x, A.Divides x y ∧ gen x)
def GenIdeal.Ideal {A : Alg.{ℓ}} (gen : Set A) : (GenIdeal gen).Ideal
:= λ a₁ a₂ a₃ Ia₁ H
, begin
cases Ia₁ with x Hx,
cases Hx with Dxa₁ Gx,
existsi x,
refine and.intro _ Gx,
apply Divides.trans @Dxa₁,
intros P C₁ C₂,
exact C₁ H
end
def GenIdeal.mem {A : Alg.{ℓ}} (gen : Set A)
: gen ⊆ (GenIdeal gen)
:= begin
intros x Gx,
existsi x,
refine and.intro _ Gx,
apply Divides.refl
end
def GenIdeal.nonempty {A : Alg.{ℓ}} {gen : Set A} (gen_notempty : gen ≠ ∅)
: GenIdeal gen ≠ ∅
:= begin
intro H,
apply gen_notempty,
apply funext, intro x,
apply iff.to_eq,
apply iff.intro,
{ intro G,
rw H.symm,
apply GenIdeal.mem,
assumption
},
{ exact false.elim }
end
-- Ideal generated by an element
def Alg.GenIdeal₁ (A : Alg.{ℓ}) (x : A.τ) : Set A
:= GenIdeal (eq x)
def GenIdeal₁.Ideal {A : Alg.{ℓ}} (x : A.τ)
: (A.GenIdeal₁ x).Ideal
:= @GenIdeal.Ideal A (eq x)
def GenIdeal₁.nonempty {A : Alg.{ℓ}} (x : A.τ)
: A.GenIdeal₁ x ≠ ∅
:= GenIdeal.nonempty (λ H, cast (congr_fun H x) rfl)
def GenIdeal₁.mem {A : Alg.{ℓ}} (x : A.τ)
: x ∈ (A.GenIdeal₁ x)
:= GenIdeal.mem (eq x) rfl
-- Generating sets
def Set.Generating {A : Alg.{ℓ}} (G : Set A) : Prop
:= ∀ x, ∃ g, A.Divides g x ∧ g ∈ G
def Set.NonGenerating {A : Alg.{ℓ}} (G : Set A) : Prop
:= ∃ x, ∀ g, ¬ (A.Divides g x ∧ g ∈ G)
def NonGenerating_iff {A : Alg.{ℓ}} (G : Set A)
: G.NonGenerating ↔ ¬ G.Generating
:= begin
apply iff.intro,
{ intros HG F,
cases HG with x Hx,
cases F x with g Hg,
exact Hx g Hg
},
{ intros HG,
simp [Set.Generating, Set.NonGenerating] at *,
apply classical.by_contradiction, intro F,
apply HG,
intro x,
apply classical.by_contradiction, intro F',
apply F,
existsi x,
intros g Hg,
apply F',
existsi g,
exact Hg
}
end
-- Prime set generated by a set of elements
def GenPrime {A : Alg.{ℓ}} (gen : Set A) : Set A
:= λ y, ∃ x, A.Divides y x ∧ gen x
def GenPrime.Prime {A : Alg.{ℓ}} (gen : Set A)
: (GenPrime gen).Prime
:= begin
intros x₁ x₂ x₃ Jx Px₃,
{ cases Px₃ with x Hx,
cases Hx with Dx₃x Gx,
apply Dx₃x,
{ intros x₂' Jx',
apply or.inr,
apply A.assoc Jx Jx', intro a₁,
apply A.assoc a₁.J₁ (A.comm a₁.J₂), intro a₂,
existsi x,
refine and.intro _ Gx,
intros P C₁ C₂, exact C₁ a₂.J₂,
},
{ intro E, subst E,
apply or.inl,
existsi x₃,
exact and.intro (λ P C₁ C₂, C₁ Jx) Gx
}
}
end
def GenPrime.mem {A : Alg.{ℓ}} (gen : Set A)
: gen ⊆ (GenPrime gen)
:= begin
intros x Gx,
existsi x,
exact and.intro (λ P C₁ C₂, C₂ rfl) Gx,
end
def GenPrime.nonempty {A : Alg.{ℓ}} {gen : Set A} (gen_notempty : gen ≠ ∅)
: GenPrime gen ≠ ∅
:= begin
intro H,
apply gen_notempty,
apply funext, intro x,
apply iff.to_eq,
apply iff.intro,
{ intro G,
rw H.symm,
apply GenPrime.mem,
assumption
},
{ exact false.elim }
end
-- Prime set generated by an element
def Alg.GenPrime₁ (A : Alg.{ℓ}) (x : A.τ) : Set A
:= GenPrime (eq x)
def GenPrime₁.Prime {A : Alg.{ℓ}} (x : A.τ)
: (A.GenPrime₁ x).Prime
:= @GenPrime.Prime A (eq x)
def GenPrime₁.nonempty {A : Alg.{ℓ}} (x : A.τ)
: A.GenPrime₁ x ≠ ∅
:= GenPrime.nonempty (λ H, cast (congr_fun H x) rfl)
def GenPrime₁.mem {A : Alg.{ℓ}} (x : A.τ)
: x ∈ (A.GenPrime₁ x)
:= GenPrime.mem (eq x) rfl
/- Operations on ideals
-
-/
-- -- Unions
-- def UnionIdeal {A : Alg.{ℓ}} (I₁ I₂ : A.Ideal) : A.Ideal
-- := { elem := λ y, I₁.elem y ∨ I₂.elem y
-- , ideal_l := λ x₁ x₂ x₃ Ix₁ H
-- , or.elim Ix₁
-- (λ ω, or.inl (I₁.ideal_l ω H))
-- (λ ω, or.inr (I₂.ideal_l ω H))
-- }
-- -- Unions are commutative
-- def UnionIdeal.comm {A : Alg.{ℓ}} {I₁ I₂ : A.Ideal}
-- : IdealEq (UnionIdeal I₁ I₂) (UnionIdeal I₂ I₁)
-- := λ x, by simp [UnionIdeal]
-- -- Unions are associative
-- def UnionIdeal.assoc {A : Alg.{ℓ}} {I₁ I₂ I₃ : A.Ideal}
-- : IdealEq (UnionIdeal (UnionIdeal I₁ I₂) I₃) (UnionIdeal I₁ (UnionIdeal I₂ I₃))
-- := λ x, by simp [UnionIdeal]
-- -- The EmptyIdeal is an identity for UnionIdeal
-- def UnionIdeal.empty {A : Alg.{ℓ}} (I : A.Ideal)
-- : IdealEq (UnionIdeal (EmptyIdeal A) I) I
-- := λ x, by simp [UnionIdeal, EmptyIdeal]
-- -- The TrivialIdeal is an annihilator for UnionIdeal
-- def UnionIdeal.trivial {A : Alg.{ℓ}} (I : A.Ideal)
-- : IdealEq (UnionIdeal (TrivialIdeal A) I) (TrivialIdeal A)
-- := λ x, by simp [UnionIdeal, TrivialIdeal]
-- -- Intersections
def IntersectionIdeal {A : Alg.{ℓ}} {I₁ I₂ : Set A}
(I₁Ideal : I₁.Ideal)
(I₂Ideal : I₂.Ideal)
: (I₁ ∩ I₂).Ideal
:= λ x₁ x₂ x₃ Ix Jx
, and.intro (I₁Ideal Ix.1 Jx) (I₂Ideal Ix.2 Jx)
-- -- Intersections are commutative
-- def IntersectionIdeal.comm {A : Alg.{ℓ}} {I₁ I₂ : A.Ideal}
-- : IdealEq (IntersectionIdeal I₁ I₂)
-- (IntersectionIdeal I₂ I₁)
-- := λ x, by simp [IntersectionIdeal]
-- -- Intersections are associative
-- def IntersectionIdeal.assoc {A : Alg.{ℓ}} {I₁ I₂ I₃ : A.Ideal}
-- : IdealEq (IntersectionIdeal (IntersectionIdeal I₁ I₂) I₃)
-- (IntersectionIdeal I₁ (IntersectionIdeal I₂ I₃))
-- := λ x, by simp [IntersectionIdeal]
-- -- Intersections distribute over unions
-- def IntersectionIdeal.union {A : Alg.{ℓ}} {I₁ I₂ I₃ : A.Ideal}
-- : IdealEq (IntersectionIdeal I₁ (UnionIdeal I₂ I₃))
-- (UnionIdeal (IntersectionIdeal I₁ I₂) (IntersectionIdeal I₁ I₃))
-- := λ x, begin
-- simp [IntersectionIdeal, UnionIdeal],
-- apply iff.intro,
-- { intro H, cases H with H₁ H₂₃, cases H₂₃ with H₂ H₃,
-- { exact or.inl (and.intro H₁ H₂) },
-- { exact or.inr (and.intro H₁ H₃) }
-- },
-- { intro H, cases H with H₁ H₂,
-- { exact and.intro H₁.1 (or.inl H₁.2) },
-- { exact and.intro H₂.1 (or.inr H₂.2) }
-- }
-- end
-- -- The EmptyIdeal is an annihilator for IntersectionIdeal
-- def IntersectionIdeal.empty {A : Alg.{ℓ}} (I : A.Ideal)
-- : IdealEq (IntersectionIdeal (EmptyIdeal A) I) (EmptyIdeal A)
-- := λ x, by simp [IntersectionIdeal, EmptyIdeal]
-- -- The TrivialIdeal is an identity for IntersectionIdeal
-- def IntersectionIdeal.trivial {A : Alg.{ℓ}} (I : A.Ideal)
-- : IdealEq (IntersectionIdeal (TrivialIdeal A) I) I
-- := λ x, by simp [IntersectionIdeal, TrivialIdeal]
-- -- Joins
-- def JoinIdeal {A : Alg.{ℓ}} (I₁ I₂ : A.Ideal) : A.Ideal
-- := { elem := I₁.elem <*> I₂.elem
-- , ideal_l := λ x₁ x₂ x₃ Ix₁ H
-- , begin
-- apply Alg.Join.elim Ix₁,
-- intros y₁ y₂ H₁ H₂ H',
-- cases (A.assoc₁ H' H) with y₂x₂ ω₂₁ ω₂₂,
-- exact Alg.Join.show H₁ (I₂.ideal_l H₂ ω₂₁) ω₂₂
-- end
-- }
-- -- Joins are commutative
-- def JoinIdeal.comm {A : Alg.{ℓ}} {I₁ I₂ : A.Ideal}
-- : IdealEq (JoinIdeal I₁ I₂) (JoinIdeal I₂ I₁)
-- := λ x, begin simp [JoinIdeal], rw [Alg.Join.comm] end
-- -- Joins are associative
-- def JoinIdeal.assoc {A : Alg.{ℓ}} {I₁ I₂ I₃ : A.Ideal}
-- : IdealEq (JoinIdeal (JoinIdeal I₁ I₂) I₃) (JoinIdeal I₁ (JoinIdeal I₂ I₃))
-- := λ x, begin simp [JoinIdeal], rw [Alg.Join.assoc] end
-- -- The EmptyIdeal is an annihilator for JoinIdeal
-- def JoinIdeal.empty {A : Alg.{ℓ}} (I : A.Ideal)
-- : IdealEq (JoinIdeal (EmptyIdeal A) I) (EmptyIdeal A)
-- := λ x, begin
-- simp [JoinIdeal, Alg.Join, EmptyIdeal],
-- intro H, cases H with x₁ H, cases H with x₂ H,
-- apply H.1
-- end
-- -- In a sep alg with identity, the TrivialIdeal is an identity for JoinIdeal
-- def JoinIdeal.trivial {A : Alg.{ℓ}} (A₁ : A.Ident) (I : A.Ideal)
-- : IdealEq (JoinIdeal (TrivialIdeal A) I) I
-- := λ x, iff.intro
-- begin
-- simp [JoinIdeal, Alg.Join, TrivialIdeal],
-- intro H, cases H with x₁ H, cases H with x₂ H,
-- exact I.ideal_r H.2.1 H.2.2
-- end
-- begin
-- intro H,
-- existsi A₁.one, existsi x,
-- refine and.intro _ (and.intro H (A₁.join_one_l x)),
-- trivial
-- end
end Sep
|
0cc1c0a79213e8f155f18c80577e76c2fa58c593 | b00eb947a9c4141624aa8919e94ce6dcd249ed70 | /stage0/src/Lean/Elab/Tactic/Basic.lean | 8f4fdeac408a5bf2f2d902339831d5d10dd2f2ae | [
"Apache-2.0"
] | permissive | gebner/lean4-old | a4129a041af2d4d12afb3a8d4deedabde727719b | ee51cdfaf63ee313c914d83264f91f414a0e3b6e | refs/heads/master | 1,683,628,606,745 | 1,622,651,300,000 | 1,622,654,405,000 | 142,608,821 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 23,476 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Util.CollectMVars
import Lean.Parser.Command
import Lean.Meta.PPGoal
import Lean.Meta.Tactic.Assumption
import Lean.Meta.Tactic.Contradiction
import Lean.Meta.Tactic.Intro
import Lean.Meta.Tactic.Clear
import Lean.Meta.Tactic.Revert
import Lean.Meta.Tactic.Subst
import Lean.Elab.Util
import Lean.Elab.Term
import Lean.Elab.Binders
namespace Lean.Elab
open Meta
/- Assign `mvarId := sorry` -/
def admitGoal (mvarId : MVarId) : MetaM Unit :=
withMVarContext mvarId do
let mvarType ← inferType (mkMVar mvarId)
assignExprMVar mvarId (← mkSorry mvarType (synthetic := true))
def goalsToMessageData (goals : List MVarId) : MessageData :=
MessageData.joinSep (goals.map $ MessageData.ofGoal) m!"\n\n"
def Term.reportUnsolvedGoals (goals : List MVarId) : TermElabM Unit :=
withPPInaccessibleNames do
logError <| MessageData.tagged `Tactic.unsolvedGoals <| m!"unsolved goals\n{goalsToMessageData goals}"
goals.forM fun mvarId => admitGoal mvarId
namespace Tactic
structure Context where
main : MVarId
structure State where
goals : List MVarId
deriving Inhabited
structure SavedState where
term : Term.SavedState
tactic : State
abbrev TacticM := ReaderT Context $ StateRefT State TermElabM
abbrev Tactic := Syntax → TacticM Unit
def getGoals : TacticM (List MVarId) :=
return (← get).goals
def setGoals (mvarIds : List MVarId) : TacticM Unit :=
modify fun s => { s with goals := mvarIds }
def pruneSolvedGoals : TacticM Unit := do
let gs ← getGoals
let gs ← gs.filterM fun g => not <$> isExprMVarAssigned g
setGoals gs
def getUnsolvedGoals : TacticM (List MVarId) := do
pruneSolvedGoals
getGoals
@[inline] private def TacticM.runCore (x : TacticM α) (ctx : Context) (s : State) : TermElabM (α × State) :=
x ctx |>.run s
@[inline] private def TacticM.runCore' (x : TacticM α) (ctx : Context) (s : State) : TermElabM α :=
Prod.fst <$> x.runCore ctx s
def run (mvarId : MVarId) (x : TacticM Unit) : TermElabM (List MVarId) :=
withMVarContext mvarId do
let savedSyntheticMVars := (← get).syntheticMVars
modify fun s => { s with syntheticMVars := [] }
let aux : TacticM (List MVarId) :=
/- Important: the following `try` does not backtrack the state.
This is intentional because we don't want to backtrack the error messages when we catch the "abort internal exception"
We must define `run` here because we define `MonadExcept` instance for `TacticM` -/
try
x; getUnsolvedGoals
catch ex =>
if isAbortTacticException ex then
getUnsolvedGoals
else
throw ex
try
aux.runCore' { main := mvarId } { goals := [mvarId] }
finally
modify fun s => { s with syntheticMVars := savedSyntheticMVars }
protected def saveState : TacticM SavedState :=
return { term := (← Term.saveState), tactic := (← get) }
def SavedState.restore (b : SavedState) : TacticM Unit := do
b.term.restore
set b.tactic
protected def getCurrMacroScope : TacticM MacroScope := do pure (← readThe Term.Context).currMacroScope
protected def getMainModule : TacticM Name := do pure (← getEnv).mainModule
unsafe def mkTacticAttribute : IO (KeyedDeclsAttribute Tactic) :=
mkElabAttribute Tactic `Lean.Elab.Tactic.tacticElabAttribute `builtinTactic `tactic `Lean.Parser.Tactic `Lean.Elab.Tactic.Tactic "tactic"
@[builtinInit mkTacticAttribute] constant tacticElabAttribute : KeyedDeclsAttribute Tactic
/-
Important: we must define `evalTacticUsing` and `expandTacticMacroFns` before we define
the instance `MonadExcept` for `TacticM` since it backtracks the state including error messages,
and this is bad when rethrowing the exception at the `catch` block in these methods.
We marked these places with a `(*)` in these methods.
-/
private def evalTacticUsing (s : SavedState) (stx : Syntax) (tactics : List Tactic) : TacticM Unit := do
let rec loop : List Tactic → TacticM Unit
| [] => throwErrorAt stx "unexpected syntax {indentD stx}"
| evalFn::evalFns => do
try
evalFn stx
catch
| ex@(Exception.error _ _) =>
match evalFns with
| [] => throw ex -- (*)
| evalFns => s.restore; loop evalFns
| ex@(Exception.internal id _) =>
if id == unsupportedSyntaxExceptionId then
s.restore; loop evalFns
else
throw ex
loop tactics
def mkTacticInfo (mctxBefore : MetavarContext) (goalsBefore : List MVarId) (stx : Syntax) : TacticM Info :=
return Info.ofTacticInfo {
mctxBefore := mctxBefore
goalsBefore := goalsBefore
stx := stx
mctxAfter := (← getMCtx)
goalsAfter := (← getUnsolvedGoals)
}
def mkInitialTacticInfo (stx : Syntax) : TacticM (TacticM Info) := do
let mctxBefore ← getMCtx
let goalsBefore ← getUnsolvedGoals
return mkTacticInfo mctxBefore goalsBefore stx
@[inline] def withTacticInfoContext (stx : Syntax) (x : TacticM α) : TacticM α := do
withInfoContext x (← mkInitialTacticInfo stx)
mutual
partial def expandTacticMacroFns (stx : Syntax) (macros : List Macro) : TacticM Unit :=
let rec loop : List Macro → TacticM Unit
| [] => throwErrorAt stx "tactic '{stx.getKind}' has not been implemented"
| m::ms => do
let scp ← getCurrMacroScope
try
let stx' ← adaptMacro m stx
evalTactic stx'
catch ex =>
if ms.isEmpty then throw ex -- (*)
loop ms
loop macros
partial def expandTacticMacro (stx : Syntax) : TacticM Unit := do
let k := stx.getKind
let table := (macroAttribute.ext.getState (← getEnv)).table
let macroFns := (table.find? k).getD []
expandTacticMacroFns stx macroFns
partial def evalTacticAux (stx : Syntax) : TacticM Unit :=
withRef stx $ withIncRecDepth $ withFreshMacroScope $ match stx with
| Syntax.node k args =>
if k == nullKind then
-- Macro writers create a sequence of tactics `t₁ ... tₙ` using `mkNullNode #[t₁, ..., tₙ]`
stx.getArgs.forM evalTactic
else do
trace[Elab.step] "{stx}"
let s ← Tactic.saveState
let table := (tacticElabAttribute.ext.getState (← getEnv)).table
let k := stx.getKind
match table.find? k with
| some evalFns => evalTacticUsing s stx evalFns
| none => expandTacticMacro stx
| _ => throwError m!"unexpected tactic{indentD stx}"
partial def evalTactic (stx : Syntax) : TacticM Unit :=
withTacticInfoContext stx (evalTacticAux stx)
end
def throwNoGoalsToBeSolved : TacticM α :=
throwError "no goals to be solved"
def done : TacticM Unit := do
let gs ← getUnsolvedGoals
unless gs.isEmpty do
Term.reportUnsolvedGoals gs
throwAbortTactic
def focus (x : TacticM α) : TacticM α := do
let mvarId :: mvarIds ← getUnsolvedGoals | throwNoGoalsToBeSolved
setGoals [mvarId]
let a ← x
let mvarIds' ← getUnsolvedGoals
setGoals (mvarIds' ++ mvarIds)
pure a
def focusAndDone (tactic : TacticM α) : TacticM α :=
focus do
let a ← tactic
done
pure a
/- Close the main goal using the given tactic. If it fails, log the error and `admit` -/
def closeUsingOrAdmit (tac : TacticM Unit) : TacticM Unit := do
/- Important: we must define `closeUsingOrAdmit` before we define
the instance `MonadExcept` for `TacticM` since it backtracks the state including error messages. -/
let mvarId :: mvarIds ← getUnsolvedGoals | throwNoGoalsToBeSolved
try
focusAndDone tac
catch ex =>
logException ex
admitGoal mvarId
setGoals mvarIds
instance : MonadBacktrack SavedState TacticM where
saveState := Tactic.saveState
restoreState b := b.restore
@[inline] protected def tryCatch {α} (x : TacticM α) (h : Exception → TacticM α) : TacticM α := do
let b ← saveState
try x catch ex => b.restore; h ex
instance : MonadExcept Exception TacticM where
throw := throw
tryCatch := Tactic.tryCatch
@[inline] protected def orElse {α} (x y : TacticM α) : TacticM α := do
try x catch _ => y
instance {α} : OrElse (TacticM α) where
orElse := Tactic.orElse
/-
Save the current tactic state for a token `stx`.
This method is a no-op if `stx` has no position information.
We use this method to save the tactic state at punctuation such as `;`
-/
def saveTacticInfoForToken (stx : Syntax) : TacticM Unit := do
unless stx.getPos?.isNone do
withTacticInfoContext stx (pure ())
/- Elaborate `x` with `stx` on the macro stack -/
@[inline]
def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : TacticM α) : TacticM α :=
withMacroExpansionInfo beforeStx afterStx do
withTheReader Term.Context (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x
/-- Adapt a syntax transformation to a regular tactic evaluator. -/
def adaptExpander (exp : Syntax → TacticM Syntax) : Tactic := fun stx => do
let stx' ← exp stx
withMacroExpansion stx stx' $ evalTactic stx'
def appendGoals (mvarIds : List MVarId) : TacticM Unit :=
modify fun s => { s with goals := s.goals ++ mvarIds }
def replaceMainGoal (mvarIds : List MVarId) : TacticM Unit := do
let (mvarId :: mvarIds') ← getGoals | throwNoGoalsToBeSolved
modify fun s => { s with goals := mvarIds ++ mvarIds' }
/-- Return the first goal. -/
def getMainGoal : TacticM MVarId := do
loop (← getGoals)
where
loop : List MVarId → TacticM MVarId
| [] => throwNoGoalsToBeSolved
| mvarId :: mvarIds => do
if (← isExprMVarAssigned mvarId) then
loop mvarIds
else
setGoals (mvarId :: mvarIds)
return mvarId
/-- Return the main goal metavariable declaration. -/
def getMainDecl : TacticM MetavarDecl := do
getMVarDecl (← getMainGoal)
/-- Return the main goal tag. -/
def getMainTag : TacticM Name :=
return (← getMainDecl).userName
/-- Return expected type for the main goal. -/
def getMainTarget : TacticM Expr := do
instantiateMVars (← getMainDecl).type
/-- Execute `x` using the main goal local context and instances -/
def withMainContext (x : TacticM α) : TacticM α := do
withMVarContext (← getMainGoal) x
/-- Evaluate `tac` at `mvarId`, and return the list of resulting subgoals. -/
def evalTacticAt (tac : Syntax) (mvarId : MVarId) : TacticM (List MVarId) := do
let gs ← getGoals
try
setGoals [mvarId]
evalTactic tac
pruneSolvedGoals
getGoals
finally
setGoals gs
def ensureHasNoMVars (e : Expr) : TacticM Unit := do
let e ← instantiateMVars e
let pendingMVars ← getMVars e
discard <| Term.logUnassignedUsingErrorInfos pendingMVars
if e.hasExprMVar then
throwError "tactic failed, resulting expression contains metavariables{indentExpr e}"
/-- Close main goal using the given expression. If `checkUnassigned == true`, then `val` must not contain unassinged metavariables. -/
def closeMainGoal (val : Expr) (checkUnassigned := true): TacticM Unit := do
if checkUnassigned then
ensureHasNoMVars val
assignExprMVar (← getMainGoal) val
replaceMainGoal []
@[inline] def liftMetaMAtMain (x : MVarId → MetaM α) : TacticM α := do
withMainContext do x (← getMainGoal)
@[inline] def liftMetaTacticAux (tac : MVarId → MetaM (α × List MVarId)) : TacticM α := do
withMainContext do
let (a, mvarIds) ← tac (← getMainGoal)
replaceMainGoal mvarIds
pure a
@[inline] def liftMetaTactic (tactic : MVarId → MetaM (List MVarId)) : TacticM Unit :=
liftMetaTacticAux fun mvarId => do
let gs ← tactic mvarId
pure ((), gs)
@[builtinTactic Lean.Parser.Tactic.«done»] def evalDone : Tactic := fun _ =>
done
def tryTactic? (tactic : TacticM α) : TacticM (Option α) := do
try
pure (some (← tactic))
catch _ =>
pure none
def tryTactic (tactic : TacticM α) : TacticM Bool := do
try
discard tactic
pure true
catch _ =>
pure false
/--
Use `parentTag` to tag untagged goals at `newGoals`.
If there are multiple new untagged goals, they are named using `<parentTag>.<newSuffix>_<idx>` where `idx > 0`.
If there is only one new untagged goal, then we just use `parentTag` -/
def tagUntaggedGoals (parentTag : Name) (newSuffix : Name) (newGoals : List MVarId) : TacticM Unit := do
let mctx ← getMCtx
let mut numAnonymous := 0
for g in newGoals do
if mctx.isAnonymousMVar g then
numAnonymous := numAnonymous + 1
modifyMCtx fun mctx => do
let mut mctx := mctx
let mut idx := 1
for g in newGoals do
if mctx.isAnonymousMVar g then
if numAnonymous == 1 then
mctx := mctx.renameMVar g parentTag
else
mctx := mctx.renameMVar g (parentTag ++ newSuffix.appendIndexAfter idx)
idx := idx + 1
pure mctx
@[builtinTactic seq1] def evalSeq1 : Tactic := fun stx => do
let args := stx[0].getArgs
for i in [:args.size] do
if i % 2 == 0 then
evalTactic args[i]
else
saveTacticInfoForToken args[i] -- add `TacticInfo` node for `;`
@[builtinTactic paren] def evalParen : Tactic := fun stx =>
evalTactic stx[1]
/- Evaluate `many (group (tactic >> optional ";")) -/
private def evalManyTacticOptSemi (stx : Syntax) : TacticM Unit := do
stx.forArgsM fun seqElem => do
evalTactic seqElem[0]
saveTacticInfoForToken seqElem[1] -- add TacticInfo node for `;`
@[builtinTactic tacticSeq1Indented] def evalTacticSeq1Indented : Tactic := fun stx =>
evalManyTacticOptSemi stx[0]
@[builtinTactic tacticSeqBracketed] def evalTacticSeqBracketed : Tactic := fun stx => do
let initInfo ← mkInitialTacticInfo stx[0]
withRef stx[2] <| closeUsingOrAdmit do
-- save state before/after entering focus on `{`
withInfoContext (pure ()) initInfo
evalManyTacticOptSemi stx[1]
@[builtinTactic Parser.Tactic.focus] def evalFocus : Tactic := fun stx => do
let mkInfo ← mkInitialTacticInfo stx[0]
focus do
-- show focused state on `focus`
withInfoContext (pure ()) mkInfo
evalTactic stx[1]
private def getOptRotation (stx : Syntax) : Nat :=
if stx.isNone then 1 else stx[0].toNat
@[builtinTactic Parser.Tactic.rotateLeft] def evalRotateLeft : Tactic := fun stx => do
let n := getOptRotation stx[1]
setGoals <| (← getGoals).rotateLeft n
@[builtinTactic Parser.Tactic.rotateRight] def evalRotateRight : Tactic := fun stx => do
let n := getOptRotation stx[1]
setGoals <| (← getGoals).rotateRight n
@[builtinTactic Parser.Tactic.open] def evalOpen : Tactic := fun stx => do
try
pushScope
let openDecls ← elabOpenDecl stx[1]
withTheReader Core.Context (fun ctx => { ctx with openDecls := openDecls }) do
evalTactic stx[3]
finally
popScope
@[builtinTactic Parser.Tactic.set_option] def elabSetOption : Tactic := fun stx => do
let options ← Elab.elabSetOption stx[1] stx[2]
withTheReader Core.Context (fun ctx => { ctx with maxRecDepth := maxRecDepth.get options, options := options }) do
evalTactic stx[4]
@[builtinTactic Parser.Tactic.allGoals] def evalAllGoals : Tactic := fun stx => do
let mvarIds ← getGoals
let mut mvarIdsNew := #[]
for mvarId in mvarIds do
unless (← isExprMVarAssigned mvarId) do
setGoals [mvarId]
try
evalTactic stx[1]
mvarIdsNew := mvarIdsNew ++ (← getUnsolvedGoals)
catch ex =>
logException ex
mvarIdsNew := mvarIdsNew.push mvarId
setGoals mvarIdsNew.toList
@[builtinTactic tacticSeq] def evalTacticSeq : Tactic := fun stx =>
evalTactic stx[0]
partial def evalChoiceAux (tactics : Array Syntax) (i : Nat) : TacticM Unit :=
if h : i < tactics.size then
let tactic := tactics.get ⟨i, h⟩
catchInternalId unsupportedSyntaxExceptionId
(evalTactic tactic)
(fun _ => evalChoiceAux tactics (i+1))
else
throwUnsupportedSyntax
@[builtinTactic choice] def evalChoice : Tactic := fun stx =>
evalChoiceAux stx.getArgs 0
@[builtinTactic skip] def evalSkip : Tactic := fun stx => pure ()
@[builtinTactic unknown] def evalUnknown : Tactic := fun stx => do
addCompletionInfo <| CompletionInfo.tactic stx (← getGoals)
@[builtinTactic failIfSuccess] def evalFailIfSuccess : Tactic := fun stx => do
let tactic := stx[1]
if (← try evalTactic tactic; pure true catch _ => pure false) then
throwError "tactic succeeded"
@[builtinTactic traceState] def evalTraceState : Tactic := fun stx => do
let gs ← getUnsolvedGoals
logInfo (goalsToMessageData gs)
@[builtinTactic Lean.Parser.Tactic.assumption] def evalAssumption : Tactic := fun stx =>
liftMetaTactic fun mvarId => do Meta.assumption mvarId; pure []
@[builtinTactic Lean.Parser.Tactic.contradiction] def evalContradiction : Tactic := fun stx =>
liftMetaTactic fun mvarId => do Meta.contradiction mvarId; pure []
@[builtinTactic Lean.Parser.Tactic.intro] def evalIntro : Tactic := fun stx => do
match stx with
| `(tactic| intro) => introStep `_
| `(tactic| intro $h:ident) => introStep h.getId
| `(tactic| intro _) => introStep `_
| `(tactic| intro $pat:term) => evalTactic (← `(tactic| intro h; match h with | $pat:term => ?_; try clear h))
| `(tactic| intro $h:term $hs:term*) => evalTactic (← `(tactic| intro $h:term; intro $hs:term*))
| _ => throwUnsupportedSyntax
where
introStep (n : Name) : TacticM Unit :=
liftMetaTactic fun mvarId => do
let (_, mvarId) ← Meta.intro mvarId n
pure [mvarId]
@[builtinTactic Lean.Parser.Tactic.introMatch] def evalIntroMatch : Tactic := fun stx => do
let matchAlts := stx[1]
let stxNew ← liftMacroM <| Term.expandMatchAltsIntoMatchTactic stx matchAlts
withMacroExpansion stx stxNew <| evalTactic stxNew
private def getIntrosSize : Expr → Nat
| Expr.forallE _ _ b _ => getIntrosSize b + 1
| Expr.letE _ _ _ b _ => getIntrosSize b + 1
| Expr.mdata _ b _ => getIntrosSize b
| _ => 0
/- Recall that `ident' := ident <|> Term.hole` -/
def getNameOfIdent' (id : Syntax) : Name :=
if id.isIdent then id.getId else `_
@[builtinTactic «intros»] def evalIntros : Tactic := fun stx =>
match stx with
| `(tactic| intros) => liftMetaTactic fun mvarId => do
let type ← Meta.getMVarType mvarId
let type ← instantiateMVars type
let n := getIntrosSize type
let (_, mvarId) ← Meta.introN mvarId n
pure [mvarId]
| `(tactic| intros $ids*) => liftMetaTactic fun mvarId => do
let (_, mvarId) ← Meta.introN mvarId ids.size (ids.map getNameOfIdent').toList
pure [mvarId]
| _ => throwUnsupportedSyntax
def getFVarId (id : Syntax) : TacticM FVarId := withRef id do
let fvar? ← Term.isLocalIdent? id;
match fvar? with
| some fvar => pure fvar.fvarId!
| none => throwError "unknown variable '{id.getId}'"
def getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) := do
withMainContext do ids.mapM getFVarId
@[builtinTactic Lean.Parser.Tactic.revert] def evalRevert : Tactic := fun stx =>
match stx with
| `(tactic| revert $hs*) => do
let (_, mvarId) ← Meta.revert (← getMainGoal) (← getFVarIds hs)
replaceMainGoal [mvarId]
| _ => throwUnsupportedSyntax
/- Sort free variables using an order `x < y` iff `x` was defined after `y` -/
private def sortFVarIds (fvarIds : Array FVarId) : TacticM (Array FVarId) :=
withMainContext do
let lctx ← getLCtx
return fvarIds.qsort fun fvarId₁ fvarId₂ =>
match lctx.find? fvarId₁, lctx.find? fvarId₂ with
| some d₁, some d₂ => d₁.index > d₂.index
| some _, none => false
| none, some _ => true
| none, none => Name.quickLt fvarId₁ fvarId₂
@[builtinTactic Lean.Parser.Tactic.clear] def evalClear : Tactic := fun stx =>
match stx with
| `(tactic| clear $hs*) => do
let fvarIds ← getFVarIds hs
let fvarIds ← sortFVarIds fvarIds
for fvarId in fvarIds do
withMainContext do
let mvarId ← clear (← getMainGoal) fvarId
replaceMainGoal [mvarId]
| _ => throwUnsupportedSyntax
def forEachVar (hs : Array Syntax) (tac : MVarId → FVarId → MetaM MVarId) : TacticM Unit := do
for h in hs do
withMainContext do
let fvarId ← getFVarId h
let mvarId ← tac (← getMainGoal) (← getFVarId h)
replaceMainGoal [mvarId]
@[builtinTactic Lean.Parser.Tactic.subst] def evalSubst : Tactic := fun stx =>
match stx with
| `(tactic| subst $hs*) => forEachVar hs Meta.subst
| _ => throwUnsupportedSyntax
/--
First method searches for a metavariable `g` s.t. `tag` is a suffix of its name.
If none is found, then it searches for a metavariable `g` s.t. `tag` is a prefix of its name. -/
private def findTag? (mvarIds : List MVarId) (tag : Name) : TacticM (Option MVarId) := do
let mvarId? ← mvarIds.findM? fun mvarId => return tag.isSuffixOf (← getMVarDecl mvarId).userName
match mvarId? with
| some mvarId => return mvarId
| none => mvarIds.findM? fun mvarId => return tag.isPrefixOf (← getMVarDecl mvarId).userName
/--
Use position of `=> $body` for error messages.
If there is a line break before `body`, the message will be displayed on `=>` only,
but the "full range" for the info view will still include `body`. -/
def withCaseRef [Monad m] [MonadRef m] (arrow body : Syntax) (x : m α) : m α :=
withRef (mkNullNode #[arrow, body]) x
@[builtinTactic «case»] def evalCase : Tactic
| stx@`(tactic| case $tag $hs* =>%$arr $tac:tacticSeq) => do
let tag := tag.getId
let gs ← getUnsolvedGoals
let some g ← findTag? gs tag | throwError "tag not found"
let gs := gs.erase g
let mut g := g
unless hs.isEmpty do
let mvarDecl ← getMVarDecl g
let mut lctx := mvarDecl.lctx
let mut hs := hs
let n := lctx.numIndices
for i in [:n] do
let j := n - i - 1
match lctx.getAt? j with
| none => pure ()
| some localDecl =>
if localDecl.userName.hasMacroScopes then
let h := hs.back
if h.isIdent then
let newName := h.getId
lctx := lctx.setUserName localDecl.fvarId newName
hs := hs.pop
if hs.isEmpty then
break
unless hs.isEmpty do
logError m!"too many variable names provided at 'case'"
let mvarNew ← mkFreshExprMVarAt lctx mvarDecl.localInstances mvarDecl.type MetavarKind.syntheticOpaque mvarDecl.userName
assignExprMVar g mvarNew
g := mvarNew.mvarId!
setGoals [g]
let savedTag ← getMVarTag g
setMVarTag g Name.anonymous
try
withCaseRef arr tac do
closeUsingOrAdmit (withTacticInfoContext stx (evalTactic tac))
finally
setMVarTag g savedTag
done
setGoals gs
| _ => throwUnsupportedSyntax
@[builtinTactic «first»] partial def evalFirst : Tactic := fun stx => do
let tacs := stx[1].getArgs
if tacs.isEmpty then throwUnsupportedSyntax
loop tacs 0
where
loop (tacs : Array Syntax) (i : Nat) :=
if i == tacs.size - 1 then
evalTactic tacs[i][1]
else
evalTactic tacs[i][1] <|> loop tacs (i+1)
builtin_initialize registerTraceClass `Elab.tactic
end Lean.Elab.Tactic
|
6a3ea58de9d1119f467cc530ba683bb5bef7a5da | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /src/Lean/Data/Lsp/Diagnostics.lean | c33a12740cea7270bf27e56f583aeecf32e14359 | [
"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 | 3,819 | lean | /-
Copyright (c) 2020 Marc Huisinga. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Marc Huisinga, Wojciech Nawrocki
-/
import Lean.Data.Json
import Lean.Data.Lsp.Basic
import Lean.Data.Lsp.Utf16
import Lean.Message
/-! Definitions and functionality for emitting diagnostic information
such as errors, warnings and #command outputs from the LSP server. -/
namespace Lean
namespace Lsp
open Json
inductive DiagnosticSeverity where
| error | warning | information | hint
deriving Inhabited, BEq
instance : FromJson DiagnosticSeverity := ⟨fun j =>
match j.getNat? with
| some 1 => DiagnosticSeverity.error
| some 2 => DiagnosticSeverity.warning
| some 3 => DiagnosticSeverity.information
| some 4 => DiagnosticSeverity.hint
| _ => none⟩
instance : ToJson DiagnosticSeverity := ⟨fun
| DiagnosticSeverity.error => 1
| DiagnosticSeverity.warning => 2
| DiagnosticSeverity.information => 3
| DiagnosticSeverity.hint => 4⟩
inductive DiagnosticCode where
| int (i : Int)
| string (s : String)
deriving Inhabited, BEq
instance : FromJson DiagnosticCode := ⟨fun
| num (i : Int) => DiagnosticCode.int i
| str s => DiagnosticCode.string s
| _ => none⟩
instance : ToJson DiagnosticCode := ⟨fun
| DiagnosticCode.int i => i
| DiagnosticCode.string s => s⟩
inductive DiagnosticTag where
| unnecessary
| deprecated
deriving Inhabited, BEq
instance : FromJson DiagnosticTag := ⟨fun j =>
match j.getNat? with
| some 1 => DiagnosticTag.unnecessary
| some 2 => DiagnosticTag.deprecated
| _ => none⟩
instance : ToJson DiagnosticTag := ⟨fun
| DiagnosticTag.unnecessary => (1 : Nat)
| DiagnosticTag.deprecated => (2 : Nat)⟩
structure DiagnosticRelatedInformation where
location : Location
message : String
deriving Inhabited, BEq, ToJson, FromJson
structure Diagnostic where
range : Range
/-- extension: preserve semantic range of errors when truncating them for display purposes -/
fullRange : Range := range
severity? : Option DiagnosticSeverity := none
code? : Option DiagnosticCode := none
source? : Option String := none
message : String
tags? : Option (Array DiagnosticTag) := none
relatedInformation? : Option (Array DiagnosticRelatedInformation) := none
deriving Inhabited, BEq, ToJson, FromJson
structure PublishDiagnosticsParams where
uri : DocumentUri
version? : Option Int := none
diagnostics: Array Diagnostic
deriving Inhabited, BEq, ToJson, FromJson
/-- Transform a Lean Message concerning the given text into an LSP Diagnostic. -/
def msgToDiagnostic (text : FileMap) (m : Message) : IO Diagnostic := do
let low : Lsp.Position := text.leanPosToLspPos m.pos
let fullHigh := text.leanPosToLspPos <| m.endPos.getD m.pos
let high : Lsp.Position := match m.endPos with
| some endPos =>
/-
Truncate messages that are more than one line long.
This is a workaround to avoid big blocks of "red squiggly lines" on VS Code.
TODO: should it be a parameter?
-/
let endPos := if endPos.line > m.pos.line then { line := m.pos.line + 1, column := 0 } else endPos
text.leanPosToLspPos endPos
| none => low
let range : Range := ⟨low, high⟩
let fullRange : Range := ⟨low, fullHigh⟩
let severity := match m.severity with
| MessageSeverity.information => DiagnosticSeverity.information
| MessageSeverity.warning => DiagnosticSeverity.warning
| MessageSeverity.error => DiagnosticSeverity.error
let source := "Lean 4 server"
let message ← m.data.toString
pure {
range := range
fullRange := fullRange
severity? := severity
source? := source
message := message
}
end Lsp
end Lean
|
6709c85c96d9c520cc06e70e8839691555fa8e4e | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/io_state.lean | 2566b8ca21f49e8d03cddf89dfe1d0a6cbf64bc5 | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 292 | lean | import system.io
open io state_t
@[reducible] def my_io := state_t nat io
instance lift_io {α} : has_coe (io α) (my_io α) :=
⟨state_t.lift⟩
def tst : my_io unit :=
do x ← get,
print_ln x,
put (x+10),
y ← get,
print_ln y,
put_str "end of program"
#eval tst.run 5
|
7d0e2c717653e7f7dd3017689a6ed247fcec2a17 | bb31430994044506fa42fd667e2d556327e18dfe | /src/order/chain.lean | 9c0087af103890093625fb783bb973038f5972f7 | [
"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 | 12,615 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import data.set.pairwise
import data.set_like.basic
/-!
# Chains and flags
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines chains for an arbitrary relation and flags for an order and proves Hausdorff's
Maximality Principle.
## Main declarations
* `is_chain s`: A chain `s` is a set of comparable elements.
* `max_chain_spec`: Hausdorff's Maximality Principle.
* `flag`: The type of flags, aka maximal chains, of an order.
## Notes
Originally ported from Isabelle/HOL. The
[original file](https://isabelle.in.tum.de/dist/library/HOL/HOL/Zorn.html) was written by Jacques D.
Fleuriot, Tobias Nipkow, Christian Sternagel.
-/
open classical set
variables {α β : Type*}
/-! ### Chains -/
section chain
variables (r : α → α → Prop)
local infix ` ≺ `:50 := r
/-- A chain is a set `s` satisfying `x ≺ y ∨ x = y ∨ y ≺ x` for all `x y ∈ s`. -/
def is_chain (s : set α) : Prop := s.pairwise (λ x y, x ≺ y ∨ y ≺ x)
/-- `super_chain s t` means that `t` is a chain that strictly includes `s`. -/
def super_chain (s t : set α) : Prop := is_chain r t ∧ s ⊂ t
/-- A chain `s` is a maximal chain if there does not exists a chain strictly including `s`. -/
def is_max_chain (s : set α) : Prop := is_chain r s ∧ ∀ ⦃t⦄, is_chain r t → s ⊆ t → s = t
variables {r} {c c₁ c₂ c₃ s t : set α} {a b x y : α}
lemma is_chain_empty : is_chain r ∅ := set.pairwise_empty _
lemma set.subsingleton.is_chain (hs : s.subsingleton) : is_chain r s := hs.pairwise _
lemma is_chain.mono : s ⊆ t → is_chain r t → is_chain r s := set.pairwise.mono
lemma is_chain.mono_rel {r' : α → α → Prop} (h : is_chain r s)
(h_imp : ∀ x y, r x y → r' x y) : is_chain r' s :=
h.mono' $ λ x y, or.imp (h_imp x y) (h_imp y x)
/-- This can be used to turn `is_chain (≥)` into `is_chain (≤)` and vice-versa. -/
lemma is_chain.symm (h : is_chain r s) : is_chain (flip r) s := h.mono' $ λ _ _, or.symm
lemma is_chain_of_trichotomous [is_trichotomous α r] (s : set α) : is_chain r s :=
λ a _ b _ hab, (trichotomous_of r a b).imp_right $ λ h, h.resolve_left hab
lemma is_chain.insert (hs : is_chain r s) (ha : ∀ b ∈ s, a ≠ b → a ≺ b ∨ b ≺ a) :
is_chain r (insert a s) :=
hs.insert_of_symmetric (λ _ _, or.symm) ha
lemma is_chain_univ_iff : is_chain r (univ : set α) ↔ is_trichotomous α r :=
begin
refine ⟨λ h, ⟨λ a b , _⟩, λ h, @is_chain_of_trichotomous _ _ h univ⟩,
rw [or.left_comm, or_iff_not_imp_left],
exact h trivial trivial,
end
lemma is_chain.image (r : α → α → Prop) (s : β → β → Prop) (f : α → β)
(h : ∀ x y, r x y → s (f x) (f y)) {c : set α} (hrc : is_chain r c) :
is_chain s (f '' c) :=
λ x ⟨a, ha₁, ha₂⟩ y ⟨b, hb₁, hb₂⟩, ha₂ ▸ hb₂ ▸ λ hxy,
(hrc ha₁ hb₁ $ ne_of_apply_ne f hxy).imp (h _ _) (h _ _)
section total
variables [is_refl α r]
lemma is_chain.total (h : is_chain r s) (hx : x ∈ s) (hy : y ∈ s) : x ≺ y ∨ y ≺ x :=
(eq_or_ne x y).elim (λ e, or.inl $ e ▸ refl _) (h hx hy)
lemma is_chain.directed_on (H : is_chain r s) : directed_on r s :=
λ x hx y hy, (H.total hx hy).elim (λ h, ⟨y, hy, h, refl _⟩) $ λ h, ⟨x, hx, refl _, h⟩
protected lemma is_chain.directed {f : β → α} {c : set β} (h : is_chain (f ⁻¹'o r) c) :
directed r (λ x : {a : β // a ∈ c}, f x) :=
λ ⟨a, ha⟩ ⟨b, hb⟩, by_cases
(λ hab : a = b, by simp only [hab, exists_prop, and_self, subtype.exists];
exact ⟨b, hb, refl _⟩) $
λ hab, (h ha hb hab).elim (λ h, ⟨⟨b, hb⟩, h, refl _⟩) $ λ h, ⟨⟨a, ha⟩, refl _, h⟩
lemma is_chain.exists3 (hchain : is_chain r s) [is_trans α r] {a b c}
(mem1 : a ∈ s) (mem2 : b ∈ s) (mem3 : c ∈ s) :
∃ (z) (mem4 : z ∈ s), r a z ∧ r b z ∧ r c z :=
begin
rcases directed_on_iff_directed.mpr (is_chain.directed hchain) a mem1 b mem2 with
⟨z, mem4, H1, H2⟩,
rcases directed_on_iff_directed.mpr (is_chain.directed hchain) z mem4 c mem3 with
⟨z', mem5, H3, H4⟩,
exact ⟨z', mem5, trans H1 H3, trans H2 H3, H4⟩,
end
end total
lemma is_max_chain.is_chain (h : is_max_chain r s) : is_chain r s := h.1
lemma is_max_chain.not_super_chain (h : is_max_chain r s) : ¬super_chain r s t :=
λ ht, ht.2.ne $ h.2 ht.1 ht.2.1
lemma is_max_chain.bot_mem [has_le α] [order_bot α] (h : is_max_chain (≤) s) : ⊥ ∈ s :=
(h.2 (h.1.insert $ λ a _ _, or.inl bot_le) $ subset_insert _ _).symm ▸ mem_insert _ _
lemma is_max_chain.top_mem [has_le α] [order_top α] (h : is_max_chain (≤) s) : ⊤ ∈ s :=
(h.2 (h.1.insert $ λ a _ _, or.inr le_top) $ subset_insert _ _).symm ▸ mem_insert _ _
open_locale classical
/-- Given a set `s`, if there exists a chain `t` strictly including `s`, then `succ_chain s`
is one of these chains. Otherwise it is `s`. -/
def succ_chain (r : α → α → Prop) (s : set α) : set α :=
if h : ∃ t, is_chain r s ∧ super_chain r s t then some h else s
lemma succ_chain_spec (h : ∃ t, is_chain r s ∧ super_chain r s t) :
super_chain r s (succ_chain r s) :=
let ⟨t, hc'⟩ := h in
have is_chain r s ∧ super_chain r s (some h),
from @some_spec _ (λ t, is_chain r s ∧ super_chain r s t) _,
by simp [succ_chain, dif_pos, h, this.right]
lemma is_chain.succ (hs : is_chain r s) : is_chain r (succ_chain r s) :=
if h : ∃ t, is_chain r s ∧ super_chain r s t then (succ_chain_spec h).1
else by { simp [succ_chain, dif_neg, h], exact hs }
lemma is_chain.super_chain_succ_chain (hs₁ : is_chain r s) (hs₂ : ¬ is_max_chain r s) :
super_chain r s (succ_chain r s) :=
begin
simp [is_max_chain, not_and_distrib, not_forall_not] at hs₂,
obtain ⟨t, ht, hst⟩ := hs₂.neg_resolve_left hs₁,
exact succ_chain_spec ⟨t, hs₁, ht, ssubset_iff_subset_ne.2 hst⟩,
end
lemma subset_succ_chain : s ⊆ succ_chain r s :=
if h : ∃ t, is_chain r s ∧ super_chain r s t then (succ_chain_spec h).2.1
else by simp [succ_chain, dif_neg, h, subset.rfl]
/-- Predicate for whether a set is reachable from `∅` using `succ_chain` and `⋃₀`. -/
inductive chain_closure (r : α → α → Prop) : set α → Prop
| succ : ∀ {s}, chain_closure s → chain_closure (succ_chain r s)
| union : ∀ {s}, (∀ a ∈ s, chain_closure a) → chain_closure (⋃₀ s)
/-- An explicit maximal chain. `max_chain` is taken to be the union of all sets in `chain_closure`.
-/
def max_chain (r : α → α → Prop) := ⋃₀ set_of (chain_closure r)
lemma chain_closure_empty : chain_closure r ∅ :=
have chain_closure r (⋃₀ ∅),
from chain_closure.union $ λ a h, h.rec _,
by simpa using this
lemma chain_closure_max_chain : chain_closure r (max_chain r) := chain_closure.union $ λ s, id
private lemma chain_closure_succ_total_aux (hc₁ : chain_closure r c₁) (hc₂ : chain_closure r c₂)
(h : ∀ ⦃c₃⦄, chain_closure r c₃ → c₃ ⊆ c₂ → c₂ = c₃ ∨ succ_chain r c₃ ⊆ c₂) :
succ_chain r c₂ ⊆ c₁ ∨ c₁ ⊆ c₂ :=
begin
induction hc₁,
case succ : c₃ hc₃ ih
{ cases ih with ih ih,
{ exact or.inl (ih.trans subset_succ_chain) },
{ exact (h hc₃ ih).imp_left (λ h, h ▸ subset.rfl) } },
case union : s hs ih
{ refine (or_iff_not_imp_left.2 $ λ hn, sUnion_subset $ λ a ha, _),
exact (ih a ha).resolve_left (λ h, hn $ h.trans $ subset_sUnion_of_mem ha) }
end
private lemma chain_closure_succ_total (hc₁ : chain_closure r c₁) (hc₂ : chain_closure r c₂)
(h : c₁ ⊆ c₂) :
c₂ = c₁ ∨ succ_chain r c₁ ⊆ c₂ :=
begin
induction hc₂ generalizing c₁ hc₁ h,
case succ : c₂ hc₂ ih
{ refine (chain_closure_succ_total_aux hc₁ hc₂ $ λ c₁, ih).imp h.antisymm' (λ h₁, _),
obtain rfl | h₂ := ih hc₁ h₁,
{ exact subset.rfl },
{ exact h₂.trans subset_succ_chain } },
case union : s hs ih
{ apply or.imp_left h.antisymm',
apply classical.by_contradiction,
simp [not_or_distrib, sUnion_subset_iff, not_forall],
intros c₃ hc₃ h₁ h₂,
obtain h | h := chain_closure_succ_total_aux hc₁ (hs c₃ hc₃) (λ c₄, ih _ hc₃),
{ exact h₁ (subset_succ_chain.trans h) },
obtain h' | h' := ih c₃ hc₃ hc₁ h,
{ exact h₁ h'.subset },
{ exact h₂ (h'.trans $ subset_sUnion_of_mem hc₃) } }
end
lemma chain_closure.total (hc₁ : chain_closure r c₁) (hc₂ : chain_closure r c₂) :
c₁ ⊆ c₂ ∨ c₂ ⊆ c₁ :=
(chain_closure_succ_total_aux hc₂ hc₁ $ λ c₃ hc₃, chain_closure_succ_total hc₃ hc₁).imp_left
subset_succ_chain.trans
lemma chain_closure.succ_fixpoint (hc₁ : chain_closure r c₁) (hc₂ : chain_closure r c₂)
(hc : succ_chain r c₂ = c₂) :
c₁ ⊆ c₂ :=
begin
induction hc₁,
case succ : s₁ hc₁ h
{ exact (chain_closure_succ_total hc₁ hc₂ h).elim (λ h, h ▸ hc.subset) id },
case union : s hs ih
{ exact sUnion_subset ih }
end
lemma chain_closure.succ_fixpoint_iff (hc : chain_closure r c) :
succ_chain r c = c ↔ c = max_chain r :=
⟨λ h, (subset_sUnion_of_mem hc).antisymm $ chain_closure_max_chain.succ_fixpoint hc h,
λ h, subset_succ_chain.antisymm' $ (subset_sUnion_of_mem hc.succ).trans h.symm.subset⟩
lemma chain_closure.is_chain (hc : chain_closure r c) : is_chain r c :=
begin
induction hc,
case succ : c hc h
{ exact h.succ },
case union : s hs h
{ change ∀ c ∈ s, is_chain r c at h,
exact λ c₁ ⟨t₁, ht₁, (hc₁ : c₁ ∈ t₁)⟩ c₂ ⟨t₂, ht₂, (hc₂ : c₂ ∈ t₂)⟩ hneq,
((hs _ ht₁).total $ hs _ ht₂).elim
(λ ht, h t₂ ht₂ (ht hc₁) hc₂ hneq)
(λ ht, h t₁ ht₁ hc₁ (ht hc₂) hneq) }
end
/-- **Hausdorff's maximality principle**
There exists a maximal totally ordered set of `α`.
Note that we do not require `α` to be partially ordered by `r`. -/
lemma max_chain_spec : is_max_chain r (max_chain r) :=
classical.by_contradiction $ λ h,
let ⟨h₁, H⟩ := chain_closure_max_chain.is_chain.super_chain_succ_chain h in
H.ne (chain_closure_max_chain.succ_fixpoint_iff.mpr rfl).symm
end chain
/-! ### Flags -/
/-- The type of flags, aka maximal chains, of an order. -/
structure flag (α : Type*) [has_le α] :=
(carrier : set α)
(chain' : is_chain (≤) carrier)
(max_chain' : ∀ ⦃s⦄, is_chain (≤) s → carrier ⊆ s → carrier = s)
namespace flag
section has_le
variables [has_le α] {s t : flag α} {a : α}
instance : set_like (flag α) α :=
{ coe := carrier,
coe_injective' := λ s t h, by { cases s, cases t, congr' } }
@[ext] lemma ext : (s : set α) = t → s = t := set_like.ext'
@[simp] lemma mem_coe_iff : a ∈ (s : set α) ↔ a ∈ s := iff.rfl
@[simp] lemma coe_mk (s : set α) (h₁ h₂) : (mk s h₁ h₂ : set α) = s := rfl
@[simp] lemma mk_coe (s : flag α) : mk (s : set α) s.chain' s.max_chain' = s := ext rfl
lemma chain_le (s : flag α) : is_chain (≤) (s : set α) := s.chain'
protected lemma max_chain (s : flag α) : is_max_chain (≤) (s : set α) := ⟨s.chain_le, s.max_chain'⟩
lemma top_mem [order_top α] (s : flag α) : (⊤ : α) ∈ s := s.max_chain.top_mem
lemma bot_mem [order_bot α] (s : flag α) : (⊥ : α) ∈ s := s.max_chain.bot_mem
end has_le
section preorder
variables [preorder α] {a b : α}
protected lemma le_or_le (s : flag α) (ha : a ∈ s) (hb : b ∈ s) : a ≤ b ∨ b ≤ a :=
s.chain_le.total ha hb
instance [order_top α] (s : flag α) : order_top s := subtype.order_top s.top_mem
instance [order_bot α] (s : flag α) : order_bot s := subtype.order_bot s.bot_mem
instance [bounded_order α] (s : flag α) : bounded_order s :=
subtype.bounded_order s.bot_mem s.top_mem
end preorder
section partial_order
variables [partial_order α]
lemma chain_lt (s : flag α) : is_chain (<) (s : set α) :=
λ a ha b hb h, (s.le_or_le ha hb).imp h.lt_of_le h.lt_of_le'
instance [decidable_eq α] [@decidable_rel α (≤)] [@decidable_rel α (<)] (s : flag α) :
linear_order s :=
{ le_total := λ a b, s.le_or_le a.2 b.2,
decidable_eq := subtype.decidable_eq,
decidable_le := subtype.decidable_le,
decidable_lt := subtype.decidable_lt,
..subtype.partial_order _ }
end partial_order
instance [linear_order α] : unique (flag α) :=
{ default := ⟨univ, is_chain_of_trichotomous _, λ s _, s.subset_univ.antisymm'⟩,
uniq := λ s, set_like.coe_injective $ s.3 (is_chain_of_trichotomous _) $ subset_univ _ }
end flag
|
e3896574312ab981193fd3f1179a83db3e0d3eab | 5fbbd711f9bfc21ee168f46a4be146603ece8835 | /lean/natural_number_game/advanced_proposition/03.lean | 293edd90aa5687de24afb06e3151cd369704811e | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | goedel-gang/maths | 22596f71e3fde9c088e59931f128a3b5efb73a2c | a20a6f6a8ce800427afd595c598a5ad43da1408d | refs/heads/master | 1,623,055,941,960 | 1,621,599,441,000 | 1,621,599,441,000 | 169,335,840 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 158 | lean | lemma and_trans (P Q R : Prop) : P ∧ Q → Q ∧ R → P ∧ R :=
begin
intros h1 h2,
cases h1 with p q,
cases h2 with q' r,
split,
cc,
cc,
end
|
614f402376453fc6157edcf7b743e7b3db66cef2 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/topology/metric_space/completion.lean | 25d7a0e955545b7b4895f18ffaf085b7cb603bb1 | [
"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 | 8,651 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.uniform_space.completion
import topology.metric_space.isometry
import topology.instances.real
/-!
# The completion of a metric space
Completion of uniform spaces are already defined in `topology.uniform_space.completion`. We show
here that the uniform space completion of a metric space inherits a metric space structure,
by extending the distance to the completion and checking that it is indeed a distance, and that
it defines the same uniformity as the already defined uniform structure on the completion
-/
open set filter uniform_space uniform_space.completion
open_locale filter
noncomputable theory
universes u
variables {α : Type u} [pseudo_metric_space α]
namespace metric
/-- The distance on the completion is obtained by extending the distance on the original space,
by uniform continuity. -/
instance : has_dist (completion α) :=
⟨completion.extension₂ dist⟩
/-- The new distance is uniformly continuous. -/
protected lemma completion.uniform_continuous_dist :
uniform_continuous (λp:completion α × completion α, dist p.1 p.2) :=
uniform_continuous_extension₂ dist
/-- The new distance is an extension of the original distance. -/
protected lemma completion.dist_eq (x y : α) : dist (x : completion α) y = dist x y :=
completion.extension₂_coe_coe uniform_continuous_dist _ _
/- Let us check that the new distance satisfies the axioms of a distance, by starting from the
properties on α and extending them to `completion α` by continuity. -/
protected lemma completion.dist_self (x : completion α) : dist x x = 0 :=
begin
apply induction_on x,
{ refine is_closed_eq _ continuous_const,
exact (completion.uniform_continuous_dist.continuous.comp
(continuous.prod_mk continuous_id continuous_id : _) : _) },
{ assume a,
rw [completion.dist_eq, dist_self] }
end
protected lemma completion.dist_comm (x y : completion α) : dist x y = dist y x :=
begin
apply induction_on₂ x y,
{ refine is_closed_eq completion.uniform_continuous_dist.continuous _,
exact completion.uniform_continuous_dist.continuous.comp
(@continuous_swap (completion α) (completion α) _ _) },
{ assume a b,
rw [completion.dist_eq, completion.dist_eq, dist_comm] }
end
protected lemma completion.dist_triangle (x y z : completion α) : dist x z ≤ dist x y + dist y z :=
begin
apply induction_on₃ x y z,
{ refine is_closed_le _ (continuous.add _ _),
{ have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.2)) :=
continuous.prod_mk continuous_fst (continuous.comp continuous_snd continuous_snd),
exact (completion.uniform_continuous_dist.continuous.comp this : _) },
{ have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.1)) :=
continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd),
exact (completion.uniform_continuous_dist.continuous.comp this : _) },
{ have : continuous (λp : completion α × completion α × completion α, (p.2.1, p.2.2)) :=
continuous.prod_mk (continuous_fst.comp continuous_snd)
(continuous.comp continuous_snd continuous_snd),
exact (continuous.comp completion.uniform_continuous_dist.continuous this : _) } },
{ assume a b c,
rw [completion.dist_eq, completion.dist_eq, completion.dist_eq],
exact dist_triangle a b c }
end
/-- Elements of the uniformity (defined generally for completions) can be characterized in terms
of the distance. -/
protected lemma completion.mem_uniformity_dist (s : set (completion α × completion α)) :
s ∈ uniformity (completion α) ↔ (∃ε>0, ∀{a b}, dist a b < ε → (a, b) ∈ s) :=
begin
split,
{ /- Start from an entourage `s`. It contains a closed entourage `t`. Its pullback in α is an
entourage, so it contains an ε-neighborhood of the diagonal by definition of the entourages
in metric spaces. Then `t` contains an ε-neighborhood of the diagonal in `completion α`, as
closed properties pass to the completion. -/
assume hs,
rcases mem_uniformity_is_closed hs with ⟨t, ht, ⟨tclosed, ts⟩⟩,
have A : {x : α × α | (coe (x.1), coe (x.2)) ∈ t} ∈ uniformity α :=
uniform_continuous_def.1 (uniform_continuous_coe α) t ht,
rcases mem_uniformity_dist.1 A with ⟨ε, εpos, hε⟩,
refine ⟨ε, εpos, λx y hxy, _⟩,
have : ε ≤ dist x y ∨ (x, y) ∈ t,
{ apply induction_on₂ x y,
{ have : {x : completion α × completion α | ε ≤ dist (x.fst) (x.snd) ∨ (x.fst, x.snd) ∈ t}
= {p : completion α × completion α | ε ≤ dist p.1 p.2} ∪ t, by ext; simp,
rw this,
apply is_closed.union _ tclosed,
exact is_closed_le continuous_const completion.uniform_continuous_dist.continuous },
{ assume x y,
rw completion.dist_eq,
by_cases h : ε ≤ dist x y,
{ exact or.inl h },
{ have Z := hε (not_le.1 h),
simp only [set.mem_set_of_eq] at Z,
exact or.inr Z }}},
simp only [not_le.mpr hxy, false_or, not_le] at this,
exact ts this },
{ /- Start from a set `s` containing an ε-neighborhood of the diagonal in `completion α`. To show
that it is an entourage, we use the fact that `dist` is uniformly continuous on
`completion α × completion α` (this is a general property of the extension of uniformly
continuous functions). Therefore, the preimage of the ε-neighborhood of the diagonal in ℝ
is an entourage in `completion α × completion α`. Massaging this property, it follows that
the ε-neighborhood of the diagonal is an entourage in `completion α`, and therefore this is
also the case of `s`. -/
rintros ⟨ε, εpos, hε⟩,
let r : set (ℝ × ℝ) := {p | dist p.1 p.2 < ε},
have : r ∈ uniformity ℝ := metric.dist_mem_uniformity εpos,
have T := uniform_continuous_def.1 (@completion.uniform_continuous_dist α _) r this,
simp only [uniformity_prod_eq_prod, mem_prod_iff, exists_prop,
filter.mem_map, set.mem_set_of_eq] at T,
rcases T with ⟨t1, ht1, t2, ht2, ht⟩,
refine mem_of_superset ht1 _,
have A : ∀a b : completion α, (a, b) ∈ t1 → dist a b < ε,
{ assume a b hab,
have : ((a, b), (a, a)) ∈ t1 ×ˢ t2 := ⟨hab, refl_mem_uniformity ht2⟩,
have I := ht this,
simp [completion.dist_self, real.dist_eq, completion.dist_comm] at I,
exact lt_of_le_of_lt (le_abs_self _) I },
show t1 ⊆ s,
{ rintros ⟨a, b⟩ hp,
have : dist a b < ε := A a b hp,
exact hε this }}
end
/-- If two points are at distance 0, then they coincide. -/
protected lemma completion.eq_of_dist_eq_zero (x y : completion α) (h : dist x y = 0) : x = y :=
begin
/- This follows from the separation of `completion α` and from the description of
entourages in terms of the distance. -/
have : separated_space (completion α) := by apply_instance,
refine separated_def.1 this x y (λs hs, _),
rcases (completion.mem_uniformity_dist s).1 hs with ⟨ε, εpos, hε⟩,
rw ← h at εpos,
exact hε εpos
end
/-- Reformulate `completion.mem_uniformity_dist` in terms that are suitable for the definition
of the metric space structure. -/
protected lemma completion.uniformity_dist' :
uniformity (completion α) = (⨅ε:{ε : ℝ // 0 < ε}, 𝓟 {p | dist p.1 p.2 < ε.val}) :=
begin
ext s, rw mem_infi_of_directed,
{ simp [completion.mem_uniformity_dist, subset_def] },
{ rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩,
simp [lt_min_iff, (≥)] {contextual := tt} }
end
protected lemma completion.uniformity_dist :
uniformity (completion α) = (⨅ ε>0, 𝓟 {p | dist p.1 p.2 < ε}) :=
by simpa [infi_subtype] using @completion.uniformity_dist' α _
/-- Metric space structure on the completion of a pseudo_metric space. -/
instance completion.metric_space : metric_space (completion α) :=
{ dist_self := completion.dist_self,
eq_of_dist_eq_zero := completion.eq_of_dist_eq_zero,
dist_comm := completion.dist_comm,
dist_triangle := completion.dist_triangle,
to_uniform_space := by apply_instance,
uniformity_dist := completion.uniformity_dist }
/-- The embedding of a metric space in its completion is an isometry. -/
lemma completion.coe_isometry : isometry (coe : α → completion α) :=
isometry_emetric_iff_metric.2 completion.dist_eq
end metric
|
dd1796b79ad51a98b9df79163a955c3ea8c9d84d | 5fbbd711f9bfc21ee168f46a4be146603ece8835 | /lean/natural_number_game/function/4.lean | c37d3a093afa58823b942828e9104c7f85854e52 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | goedel-gang/maths | 22596f71e3fde9c088e59931f128a3b5efb73a2c | a20a6f6a8ce800427afd595c598a5ad43da1408d | refs/heads/master | 1,623,055,941,960 | 1,621,599,441,000 | 1,621,599,441,000 | 169,335,840 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 167 | lean | example (P Q R S T U: Type)
(p : P)
(h : P → Q)
(i : Q → R)
(j : Q → T)
(k : S → T)
(l : T → U)
: U :=
begin
apply l,
apply j,
apply h,
exact p,
end
|
0d5982ed5b59ac8b22687de9f7c0fec0c58844c6 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/coeSort1.lean | 9d083c6efc17040064e06e4d5052912c24e3df2d | [
"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 | 285 | lean | --
universe u
def Below (n : Nat) : Nat → Prop :=
(· < n)
def f {n : Nat} (v : Subtype (Below n)) : Nat :=
↑v + 1
instance pred2subtype {α : Type u} : CoeSort (α → Prop) (Type u) :=
CoeSort.mk (fun p => Subtype p)
def g {n : Nat} (v : Below n) : Nat :=
v.val + 1
|
189809a733e612a1415991516f89cfbcbc51ba8c | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/slim_check.lean | 95f337259e96154ce86f65cf713e108a68c107f7 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 8,215 | 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 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,
tactic.admit }
end tactic.interactive
|
8c16428b3fdd31e28ab390070b683906de0720d0 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/logic/equiv/local_equiv.lean | 9ce17ae02c71f613934b64f369d7cfb5b0dcc2c8 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 35,613 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import data.set.function
import logic.equiv.basic
/-!
# Local equivalences
This files defines equivalences between subsets of given types.
An element `e` of `local_equiv α β` is made of two maps `e.to_fun` and `e.inv_fun` respectively
from α to β and from β to α (just like equivs), which are inverse to each other on the subsets
`e.source` and `e.target` of respectively α and β.
They are designed in particular to define charts on manifolds.
The main functionality is `e.trans f`, which composes the two local equivalences by restricting
the source and target to the maximal set where the composition makes sense.
As for equivs, we register a coercion to functions and use it in our simp normal form: we write
`e x` and `e.symm y` instead of `e.to_fun x` and `e.inv_fun y`.
## Main definitions
`equiv.to_local_equiv`: associating a local equiv to an equiv, with source = target = univ
`local_equiv.symm` : the inverse of a local equiv
`local_equiv.trans` : the composition of two local equivs
`local_equiv.refl` : the identity local equiv
`local_equiv.of_set` : the identity on a set `s`
`eq_on_source` : equivalence relation describing the "right" notion of equality for local
equivs (see below in implementation notes)
## Implementation notes
There are at least three possible implementations of local equivalences:
* equivs on subtypes
* pairs of functions taking values in `option α` and `option β`, equal to none where the local
equivalence is not defined
* pairs of functions defined everywhere, keeping the source and target as additional data
Each of these implementations has pros and cons.
* When dealing with subtypes, one still need to define additional API for composition and
restriction of domains. Checking that one always belongs to the right subtype makes things very
tedious, and leads quickly to DTT hell (as the subtype `u ∩ v` is not the "same" as `v ∩ u`, for
instance).
* With option-valued functions, the composition is very neat (it is just the usual composition, and
the domain is restricted automatically). These are implemented in `pequiv.lean`. For manifolds,
where one wants to discuss thoroughly the smoothness of the maps, this creates however a lot of
overhead as one would need to extend all classes of smoothness to option-valued maps.
* The local_equiv version as explained above is easier to use for manifolds. The drawback is that
there is extra useless data (the values of `to_fun` and `inv_fun` outside of `source` and `target`).
In particular, the equality notion between local equivs is not "the right one", i.e., coinciding
source and target and equality there. Moreover, there are no local equivs in this sense between
an empty type and a nonempty type. Since empty types are not that useful, and since one almost never
needs to talk about equal local equivs, this is not an issue in practice.
Still, we introduce an equivalence relation `eq_on_source` that captures this right notion of
equality, and show that many properties are invariant under this equivalence relation.
### Local coding conventions
If a lemma deals with the intersection of a set with either source or target of a `local_equiv`,
then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`.
-/
mk_simp_attribute mfld_simps "The simpset `mfld_simps` records several simp lemmas that are
especially useful in manifolds. It is a subset of the whole set of simp lemmas, but it makes it
possible to have quicker proofs (when used with `squeeze_simp` or `simp only`) while retaining
readability.
The typical use case is the following, in a file on manifolds:
If `simp [foo, bar]` is slow, replace it with `squeeze_simp [foo, bar] with mfld_simps` and paste
its output. The list of lemmas should be reasonable (contrary to the output of
`squeeze_simp [foo, bar]` which might contain tens of lemmas), and the outcome should be quick
enough.
"
-- register in the simpset `mfld_simps` several lemmas that are often useful when dealing
-- with manifolds
attribute [mfld_simps] id.def function.comp.left_id set.mem_set_of_eq set.image_eq_empty
set.univ_inter set.preimage_univ set.prod_mk_mem_set_prod_eq and_true set.mem_univ
set.mem_image_of_mem true_and set.mem_inter_eq set.mem_preimage function.comp_app
set.inter_subset_left set.mem_prod set.range_id set.range_prod_map and_self set.mem_range_self
eq_self_iff_true forall_const forall_true_iff set.inter_univ set.preimage_id function.comp.right_id
not_false_iff and_imp set.prod_inter_prod set.univ_prod_univ true_or or_true prod.map_mk
set.preimage_inter heq_iff_eq equiv.sigma_equiv_prod_apply equiv.sigma_equiv_prod_symm_apply
subtype.coe_mk equiv.to_fun_as_coe equiv.inv_fun_as_coe
/-- Common `@[simps]` configuration options used for manifold-related declarations. -/
def mfld_cfg : simps_cfg := {attrs := [`simp, `mfld_simps], fully_applied := ff}
namespace tactic.interactive
/-- A very basic tactic to show that sets showing up in manifolds coincide or are included in
one another. -/
meta def mfld_set_tac : tactic unit := do
goal ← tactic.target,
match goal with
| `(%%e₁ = %%e₂) :=
`[ext my_y,
split;
{ assume h_my_y,
try { simp only [*, -h_my_y] with mfld_simps at h_my_y },
simp only [*] with mfld_simps }]
| `(%%e₁ ⊆ %%e₂) :=
`[assume my_y h_my_y,
try { simp only [*, -h_my_y] with mfld_simps at h_my_y },
simp only [*] with mfld_simps]
| _ := tactic.fail "goal should be an equality or an inclusion"
end
end tactic.interactive
open function set
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- Local equivalence between subsets `source` and `target` of α and β respectively. The (global)
maps `to_fun : α → β` and `inv_fun : β → α` map `source` to `target` and conversely, and are inverse
to each other there. The values of `to_fun` outside of `source` and of `inv_fun` outside of `target`
are irrelevant. -/
structure local_equiv (α : Type*) (β : Type*) :=
(to_fun : α → β)
(inv_fun : β → α)
(source : set α)
(target : set β)
(map_source' : ∀{x}, x ∈ source → to_fun x ∈ target)
(map_target' : ∀{x}, x ∈ target → inv_fun x ∈ source)
(left_inv' : ∀{x}, x ∈ source → inv_fun (to_fun x) = x)
(right_inv' : ∀{x}, x ∈ target → to_fun (inv_fun x) = x)
namespace local_equiv
variables (e : local_equiv α β) (e' : local_equiv β γ)
instance [inhabited α] [inhabited β] : inhabited (local_equiv α β) :=
⟨⟨const α default, const β default, ∅, ∅, maps_to_empty _ _, maps_to_empty _ _,
eq_on_empty _ _, eq_on_empty _ _⟩⟩
/-- The inverse of a local equiv -/
protected def symm : local_equiv β α :=
{ to_fun := e.inv_fun,
inv_fun := e.to_fun,
source := e.target,
target := e.source,
map_source' := e.map_target',
map_target' := e.map_source',
left_inv' := e.right_inv',
right_inv' := e.left_inv' }
instance : has_coe_to_fun (local_equiv α β) (λ _, α → β) := ⟨local_equiv.to_fun⟩
/-- See Note [custom simps projection] -/
def simps.symm_apply (e : local_equiv α β) : β → α := e.symm
initialize_simps_projections local_equiv (to_fun → apply, inv_fun → symm_apply)
@[simp, mfld_simps] theorem coe_mk (f : α → β) (g s t ml mr il ir) :
(local_equiv.mk f g s t ml mr il ir : α → β) = f := rfl
@[simp, mfld_simps] theorem coe_symm_mk (f : α → β) (g s t ml mr il ir) :
((local_equiv.mk f g s t ml mr il ir).symm : β → α) = g := rfl
@[simp, mfld_simps] lemma to_fun_as_coe : e.to_fun = e := rfl
@[simp, mfld_simps] lemma inv_fun_as_coe : e.inv_fun = e.symm := rfl
@[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target :=
e.map_source' h
@[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source :=
e.map_target' h
@[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x :=
e.left_inv' h
@[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x :=
e.right_inv' h
lemma eq_symm_apply {x : α} {y : β} (hx : x ∈ e.source) (hy : y ∈ e.target) :
x = e.symm y ↔ e x = y :=
⟨λ h, by rw [← e.right_inv hy, h], λ h, by rw [← e.left_inv hx, h]⟩
protected lemma maps_to : maps_to e e.source e.target := λ x, e.map_source
lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to
protected lemma left_inv_on : left_inv_on e.symm e e.source := λ x, e.left_inv
protected lemma right_inv_on : right_inv_on e.symm e e.target := λ x, e.right_inv
protected lemma inv_on : inv_on e.symm e e.source e.target := ⟨e.left_inv_on, e.right_inv_on⟩
protected lemma inj_on : inj_on e e.source := e.left_inv_on.inj_on
protected lemma bij_on : bij_on e e.source e.target := e.inv_on.bij_on e.maps_to e.symm_maps_to
protected lemma surj_on : surj_on e e.source e.target := e.bij_on.surj_on
/-- Associating a local_equiv to an equiv-/
@[simps (mfld_cfg)] def _root_.equiv.to_local_equiv (e : α ≃ β) : local_equiv α β :=
{ to_fun := e,
inv_fun := e.symm,
source := univ,
target := univ,
map_source' := λx hx, mem_univ _,
map_target' := λy hy, mem_univ _,
left_inv' := λx hx, e.left_inv x,
right_inv' := λx hx, e.right_inv x }
instance inhabited_of_empty [is_empty α] [is_empty β] : inhabited (local_equiv α β) :=
⟨((equiv.equiv_empty α).trans (equiv.equiv_empty β).symm).to_local_equiv⟩
/-- Create a copy of a `local_equiv` providing better definitional equalities. -/
@[simps {fully_applied := ff}]
def copy (e : local_equiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g)
(s : set α) (hs : e.source = s) (t : set β) (ht : e.target = t) :
local_equiv α β :=
{ to_fun := f,
inv_fun := g,
source := s,
target := t,
map_source' := λ x, ht ▸ hs ▸ hf ▸ e.map_source,
map_target' := λ y, hs ▸ ht ▸ hg ▸ e.map_target,
left_inv' := λ x, hs ▸ hf ▸ hg ▸ e.left_inv,
right_inv' := λ x, ht ▸ hf ▸ hg ▸ e.right_inv }
lemma copy_eq_self (e : local_equiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g)
(s : set α) (hs : e.source = s) (t : set β) (ht : e.target = t) :
e.copy f hf g hg s hs t ht = e :=
by { substs f g s t, cases e, refl }
/-- Associating to a local_equiv an equiv between the source and the target -/
protected def to_equiv : equiv (e.source) (e.target) :=
{ to_fun := λ x, ⟨e x, e.map_source x.mem⟩,
inv_fun := λ y, ⟨e.symm y, e.map_target y.mem⟩,
left_inv := λ⟨x, hx⟩, subtype.eq $ e.left_inv hx,
right_inv := λ⟨y, hy⟩, subtype.eq $ e.right_inv hy }
@[simp, mfld_simps] lemma symm_source : e.symm.source = e.target := rfl
@[simp, mfld_simps] lemma symm_target : e.symm.target = e.source := rfl
@[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := by { cases e, refl }
lemma image_source_eq_target : e '' e.source = e.target := e.bij_on.image_eq
lemma forall_mem_target {p : β → Prop} : (∀ y ∈ e.target, p y) ↔ ∀ x ∈ e.source, p (e x) :=
by rw [← image_source_eq_target, ball_image_iff]
lemma exists_mem_target {p : β → Prop} : (∃ y ∈ e.target, p y) ↔ ∃ x ∈ e.source, p (e x) :=
by rw [← image_source_eq_target, bex_image_iff]
/-- We say that `t : set β` is an image of `s : set α` under a local equivalence if
any of the following equivalent conditions hold:
* `e '' (e.source ∩ s) = e.target ∩ t`;
* `e.source ∩ e ⁻¹ t = e.source ∩ s`;
* `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition).
-/
def is_image (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ e.source → (e x ∈ t ↔ x ∈ s)
namespace is_image
variables {e} {s : set α} {t : set β} {x : α} {y : β}
lemma apply_mem_iff (h : e.is_image s t) (hx : x ∈ e.source) : e x ∈ t ↔ x ∈ s := h hx
lemma symm_apply_mem_iff (h : e.is_image s t) : ∀ ⦃y⦄, y ∈ e.target → (e.symm y ∈ s ↔ y ∈ t) :=
e.forall_mem_target.mpr $ λ x hx, by rw [e.left_inv hx, h hx]
protected lemma symm (h : e.is_image s t) : e.symm.is_image t s := h.symm_apply_mem_iff
@[simp] lemma symm_iff : e.symm.is_image t s ↔ e.is_image s t := ⟨λ h, h.symm, λ h, h.symm⟩
protected lemma maps_to (h : e.is_image s t) : maps_to e (e.source ∩ s) (e.target ∩ t) :=
λ x hx, ⟨e.maps_to hx.1, (h hx.1).2 hx.2⟩
lemma symm_maps_to (h : e.is_image s t) : maps_to e.symm (e.target ∩ t) (e.source ∩ s) :=
h.symm.maps_to
/-- Restrict a `local_equiv` to a pair of corresponding sets. -/
@[simps {fully_applied := ff}] def restr (h : e.is_image s t) : local_equiv α β :=
{ to_fun := e,
inv_fun := e.symm,
source := e.source ∩ s,
target := e.target ∩ t,
map_source' := h.maps_to,
map_target' := h.symm_maps_to,
left_inv' := e.left_inv_on.mono (inter_subset_left _ _),
right_inv' := e.right_inv_on.mono (inter_subset_left _ _) }
lemma image_eq (h : e.is_image s t) : e '' (e.source ∩ s) = e.target ∩ t :=
h.restr.image_source_eq_target
lemma symm_image_eq (h : e.is_image s t) : e.symm '' (e.target ∩ t) = e.source ∩ s :=
h.symm.image_eq
lemma iff_preimage_eq : e.is_image s t ↔ e.source ∩ e ⁻¹' t = e.source ∩ s :=
by simp only [is_image, set.ext_iff, mem_inter_eq, and.congr_right_iff, mem_preimage]
alias iff_preimage_eq ↔ preimage_eq of_preimage_eq
lemma iff_symm_preimage_eq : e.is_image s t ↔ e.target ∩ e.symm ⁻¹' s = e.target ∩ t :=
symm_iff.symm.trans iff_preimage_eq
alias iff_symm_preimage_eq ↔ symm_preimage_eq of_symm_preimage_eq
lemma of_image_eq (h : e '' (e.source ∩ s) = e.target ∩ t) : e.is_image s t :=
of_symm_preimage_eq $ eq.trans (of_symm_preimage_eq rfl).image_eq.symm h
lemma of_symm_image_eq (h : e.symm '' (e.target ∩ t) = e.source ∩ s) : e.is_image s t :=
of_preimage_eq $ eq.trans (of_preimage_eq rfl).symm_image_eq.symm h
protected lemma compl (h : e.is_image s t) : e.is_image sᶜ tᶜ :=
λ x hx, not_congr (h hx)
protected lemma inter {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') :
e.is_image (s ∩ s') (t ∩ t') :=
λ x hx, and_congr (h hx) (h' hx)
protected lemma union {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') :
e.is_image (s ∪ s') (t ∪ t') :=
λ x hx, or_congr (h hx) (h' hx)
protected lemma diff {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') :
e.is_image (s \ s') (t \ t') :=
h.inter h'.compl
lemma left_inv_on_piecewise {e' : local_equiv α β} [∀ i, decidable (i ∈ s)] [∀ i, decidable (i ∈ t)]
(h : e.is_image s t) (h' : e'.is_image s t) :
left_inv_on (t.piecewise e.symm e'.symm) (s.piecewise e e') (s.ite e.source e'.source) :=
begin
rintro x (⟨he, hs⟩|⟨he, hs : x ∉ s⟩),
{ rw [piecewise_eq_of_mem _ _ _ hs, piecewise_eq_of_mem _ _ _ ((h he).2 hs), e.left_inv he], },
{ rw [piecewise_eq_of_not_mem _ _ _ hs, piecewise_eq_of_not_mem _ _ _ ((h'.compl he).2 hs),
e'.left_inv he] }
end
lemma inter_eq_of_inter_eq_of_eq_on {e' : local_equiv α β} (h : e.is_image s t)
(h' : e'.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) :
e.target ∩ t = e'.target ∩ t :=
by rw [← h.image_eq, ← h'.image_eq, ← hs, Heq.image_eq]
lemma symm_eq_on_of_inter_eq_of_eq_on {e' : local_equiv α β} (h : e.is_image s t)
(hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) :
eq_on e.symm e'.symm (e.target ∩ t) :=
begin
rw [← h.image_eq],
rintros y ⟨x, hx, rfl⟩,
have hx' := hx, rw hs at hx',
rw [e.left_inv hx.1, Heq hx, e'.left_inv hx'.1]
end
end is_image
lemma is_image_source_target : e.is_image e.source e.target := λ x hx, by simp [hx]
lemma is_image_source_target_of_disjoint (e' : local_equiv α β) (hs : disjoint e.source e'.source)
(ht : disjoint e.target e'.target) :
e.is_image e'.source e'.target :=
is_image.of_image_eq $ by rw [hs.inter_eq, ht.inter_eq, image_empty]
lemma image_source_inter_eq' (s : set α) :
e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' s :=
by rw [inter_comm, e.left_inv_on.image_inter', image_source_eq_target, inter_comm]
lemma image_source_inter_eq (s : set α) :
e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' (e.source ∩ s) :=
by rw [inter_comm, e.left_inv_on.image_inter, image_source_eq_target, inter_comm]
lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) :
e '' s = e.target ∩ e.symm ⁻¹' s :=
by rw [← e.image_source_inter_eq', inter_eq_self_of_subset_right h]
lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) :
e.symm '' s = e.source ∩ e ⁻¹' s :=
e.symm.image_eq_target_inter_inv_preimage h
lemma symm_image_target_inter_eq (s : set β) :
e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' (e.target ∩ s) :=
e.symm.image_source_inter_eq _
lemma symm_image_target_inter_eq' (s : set β) :
e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' s :=
e.symm.image_source_inter_eq' _
lemma source_inter_preimage_inv_preimage (s : set α) :
e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s :=
set.ext $ λ x, and.congr_right_iff.2 $ λ hx, by simp only [mem_preimage, e.left_inv hx]
lemma source_inter_preimage_target_inter (s : set β) :
e.source ∩ (e ⁻¹' (e.target ∩ s)) = e.source ∩ (e ⁻¹' s) :=
ext $ λ x, ⟨λ hx, ⟨hx.1, hx.2.2⟩, λ hx, ⟨hx.1, e.map_source hx.1, hx.2⟩⟩
lemma target_inter_inv_preimage_preimage (s : set β) :
e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s :=
e.symm.source_inter_preimage_inv_preimage _
lemma symm_image_image_of_subset_source {s : set α} (h : s ⊆ e.source) :
e.symm '' (e '' s) = s :=
(e.left_inv_on.mono h).image_image
lemma image_symm_image_of_subset_target {s : set β} (h : s ⊆ e.target) :
e '' (e.symm '' s) = s :=
e.symm.symm_image_image_of_subset_source h
lemma source_subset_preimage_target : e.source ⊆ e ⁻¹' e.target :=
e.maps_to
lemma symm_image_target_eq_source : e.symm '' e.target = e.source :=
e.symm.image_source_eq_target
lemma target_subset_preimage_source : e.target ⊆ e.symm ⁻¹' e.source :=
e.symm_maps_to
/-- Two local equivs that have the same `source`, same `to_fun` and same `inv_fun`, coincide. -/
@[ext]
protected lemma ext {e e' : local_equiv α β} (h : ∀x, e x = e' x)
(hsymm : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' :=
begin
have A : (e : α → β) = e', by { ext x, exact h x },
have B : (e.symm : β → α) = e'.symm, by { ext x, exact hsymm x },
have I : e '' e.source = e.target := e.image_source_eq_target,
have I' : e' '' e'.source = e'.target := e'.image_source_eq_target,
rw [A, hs, I'] at I,
cases e; cases e',
simp * at *
end
/-- Restricting a local equivalence to e.source ∩ s -/
protected def restr (s : set α) : local_equiv α β :=
(@is_image.of_symm_preimage_eq α β e s (e.symm ⁻¹' s) rfl).restr
@[simp, mfld_simps] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl
@[simp, mfld_simps] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl
@[simp, mfld_simps] lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ s := rfl
@[simp, mfld_simps] lemma restr_target (s : set α) :
(e.restr s).target = e.target ∩ e.symm ⁻¹' s := rfl
lemma restr_eq_of_source_subset {e : local_equiv α β} {s : set α} (h : e.source ⊆ s) :
e.restr s = e :=
local_equiv.ext (λ_, rfl) (λ_, rfl) (by simp [inter_eq_self_of_subset_left h])
@[simp, mfld_simps] lemma restr_univ {e : local_equiv α β} : e.restr univ = e :=
restr_eq_of_source_subset (subset_univ _)
/-- The identity local equiv -/
protected def refl (α : Type*) : local_equiv α α := (equiv.refl α).to_local_equiv
@[simp, mfld_simps] lemma refl_source : (local_equiv.refl α).source = univ := rfl
@[simp, mfld_simps] lemma refl_target : (local_equiv.refl α).target = univ := rfl
@[simp, mfld_simps] lemma refl_coe : (local_equiv.refl α : α → α) = id := rfl
@[simp, mfld_simps] lemma refl_symm : (local_equiv.refl α).symm = local_equiv.refl α := rfl
@[simp, mfld_simps] lemma refl_restr_source (s : set α) :
((local_equiv.refl α).restr s).source = s :=
by simp
@[simp, mfld_simps] lemma refl_restr_target (s : set α) :
((local_equiv.refl α).restr s).target = s :=
by { change univ ∩ id⁻¹' s = s, simp }
/-- The identity local equiv on a set `s` -/
def of_set (s : set α) : local_equiv α α :=
{ to_fun := id,
inv_fun := id,
source := s,
target := s,
map_source' := λx hx, hx,
map_target' := λx hx, hx,
left_inv' := λx hx, rfl,
right_inv' := λx hx, rfl }
@[simp, mfld_simps] lemma of_set_source (s : set α) : (local_equiv.of_set s).source = s := rfl
@[simp, mfld_simps] lemma of_set_target (s : set α) : (local_equiv.of_set s).target = s := rfl
@[simp, mfld_simps] lemma of_set_coe (s : set α) : (local_equiv.of_set s : α → α) = id := rfl
@[simp, mfld_simps] lemma of_set_symm (s : set α) :
(local_equiv.of_set s).symm = local_equiv.of_set s := rfl
/-- Composing two local equivs if the target of the first coincides with the source of the
second. -/
protected def trans' (e' : local_equiv β γ) (h : e.target = e'.source) :
local_equiv α γ :=
{ to_fun := e' ∘ e,
inv_fun := e.symm ∘ e'.symm,
source := e.source,
target := e'.target,
map_source' := λx hx, by simp [h.symm, hx],
map_target' := λy hy, by simp [h, hy],
left_inv' := λx hx, by simp [hx, h.symm],
right_inv' := λy hy, by simp [hy, h] }
/-- Composing two local equivs, by restricting to the maximal domain where their composition
is well defined. -/
protected def trans : local_equiv α γ :=
local_equiv.trans' (e.symm.restr (e'.source)).symm (e'.restr (e.target)) (inter_comm _ _)
@[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl
@[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl
lemma trans_apply {x : α} : (e.trans e') x = e' (e x) := rfl
lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm :=
by cases e; cases e'; refl
@[simp, mfld_simps] lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := rfl
lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) :=
by mfld_set_tac
lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) :=
by rw [e.trans_source', e.symm_image_target_inter_eq]
lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source :=
(e.symm.restr e'.source).symm.image_source_eq_target
@[simp, mfld_simps] lemma trans_target :
(e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl
lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) :=
trans_source' e'.symm e.symm
lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) :=
trans_source'' e'.symm e.symm
lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target :=
image_trans_source e'.symm e.symm
lemma trans_assoc (e'' : local_equiv γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') :=
local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, @preimage_comp α β γ, inter_assoc])
@[simp, mfld_simps] lemma trans_refl : e.trans (local_equiv.refl β) = e :=
local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source])
@[simp, mfld_simps] lemma refl_trans : (local_equiv.refl α).trans e = e :=
local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, preimage_id])
lemma trans_refl_restr (s : set β) :
e.trans ((local_equiv.refl β).restr s) = e.restr (e ⁻¹' s) :=
local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source])
lemma trans_refl_restr' (s : set β) :
e.trans ((local_equiv.refl β).restr s) = e.restr (e.source ∩ e ⁻¹' s) :=
local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source], rw [← inter_assoc, inter_self] }
lemma restr_trans (s : set α) :
(e.restr s).trans e' = (e.trans e').restr s :=
local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source, inter_comm], rwa inter_assoc }
/-- A lemma commonly useful when `e` and `e'` are charts of a manifold. -/
lemma mem_symm_trans_source {e' : local_equiv α γ} {x : α} (he : x ∈ e.source)
(he' : x ∈ e'.source) : e x ∈ (e.symm.trans e').source :=
⟨e.maps_to he, by rwa [mem_preimage, local_equiv.symm_symm, e.left_inv he]⟩
/-- Postcompose a local equivalence with an equivalence.
We modify the source and target to have better definitional behavior. -/
@[simps] def trans_equiv (e' : β ≃ γ) : local_equiv α γ :=
(e.trans e'.to_local_equiv).copy _ rfl _ rfl e.source (inter_univ _) (e'.symm ⁻¹' e.target)
(univ_inter _)
lemma trans_equiv_eq_trans (e' : β ≃ γ) : e.trans_equiv e' = e.trans e'.to_local_equiv :=
copy_eq_self _ _ _ _ _ _ _ _ _
/-- Precompose a local equivalence with an equivalence.
We modify the source and target to have better definitional behavior. -/
@[simps] def _root_.equiv.trans_local_equiv (e : α ≃ β) : local_equiv α γ :=
(e.to_local_equiv.trans e').copy _ rfl _ rfl (e ⁻¹' e'.source) (univ_inter _) e'.target
(inter_univ _)
lemma _root_.equiv.trans_local_equiv_eq_trans (e : α ≃ β) :
e.trans_local_equiv e' = e.to_local_equiv.trans e' :=
copy_eq_self _ _ _ _ _ _ _ _ _
/-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. Then `e`
and `e'` should really be considered the same local equiv. -/
def eq_on_source (e e' : local_equiv α β) : Prop :=
e.source = e'.source ∧ (e.source.eq_on e e')
/-- `eq_on_source` is an equivalence relation -/
instance eq_on_source_setoid : setoid (local_equiv α β) :=
{ r := eq_on_source,
iseqv := ⟨
λe, by simp [eq_on_source],
λe e' h, by { simp [eq_on_source, h.1.symm], exact λx hx, (h.2 hx).symm },
λe e' e'' h h', ⟨by rwa [← h'.1, ← h.1], λx hx, by { rw [← h'.2, h.2 hx], rwa ← h.1 }⟩⟩ }
lemma eq_on_source_refl : e ≈ e := setoid.refl _
/-- Two equivalent local equivs have the same source -/
lemma eq_on_source.source_eq {e e' : local_equiv α β} (h : e ≈ e') : e.source = e'.source :=
h.1
/-- Two equivalent local equivs coincide on the source -/
lemma eq_on_source.eq_on {e e' : local_equiv α β} (h : e ≈ e') : e.source.eq_on e e' :=
h.2
/-- Two equivalent local equivs have the same target -/
lemma eq_on_source.target_eq {e e' : local_equiv α β} (h : e ≈ e') : e.target = e'.target :=
by simp only [← image_source_eq_target, ← h.source_eq, h.2.image_eq]
/-- If two local equivs are equivalent, so are their inverses. -/
lemma eq_on_source.symm' {e e' : local_equiv α β} (h : e ≈ e') : e.symm ≈ e'.symm :=
begin
refine ⟨h.target_eq, eq_on_of_left_inv_on_of_right_inv_on e.left_inv_on _ _⟩;
simp only [symm_source, h.target_eq, h.source_eq, e'.symm_maps_to],
exact e'.right_inv_on.congr_right e'.symm_maps_to (h.source_eq ▸ h.eq_on.symm),
end
/-- Two equivalent local equivs have coinciding inverses on the target -/
lemma eq_on_source.symm_eq_on {e e' : local_equiv α β} (h : e ≈ e') :
eq_on e.symm e'.symm e.target :=
h.symm'.eq_on
/-- Composition of local equivs respects equivalence -/
lemma eq_on_source.trans' {e e' : local_equiv α β} {f f' : local_equiv β γ}
(he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' :=
begin
split,
{ rw [trans_source'', trans_source'', ← he.target_eq, ← hf.1],
exact (he.symm'.eq_on.mono $ inter_subset_left _ _).image_eq },
{ assume x hx,
rw trans_source at hx,
simp [(he.2 hx.1).symm, hf.2 hx.2] }
end
/-- Restriction of local equivs respects equivalence -/
lemma eq_on_source.restr {e e' : local_equiv α β} (he : e ≈ e') (s : set α) :
e.restr s ≈ e'.restr s :=
begin
split,
{ simp [he.1] },
{ assume x hx,
simp only [mem_inter_eq, restr_source] at hx,
exact he.2 hx.1 }
end
/-- Preimages are respected by equivalence -/
lemma eq_on_source.source_inter_preimage_eq {e e' : local_equiv α β} (he : e ≈ e') (s : set β) :
e.source ∩ e ⁻¹' s = e'.source ∩ e' ⁻¹' s :=
by rw [he.eq_on.inter_preimage_eq, he.source_eq]
/-- Composition of a local equiv and its inverse is equivalent to the restriction of the identity
to the source -/
lemma trans_self_symm :
e.trans e.symm ≈ local_equiv.of_set e.source :=
begin
have A : (e.trans e.symm).source = e.source, by mfld_set_tac,
refine ⟨by simp [A], λx hx, _⟩,
rw A at hx,
simp only [hx] with mfld_simps
end
/-- Composition of the inverse of a local equiv and this local equiv is equivalent to the
restriction of the identity to the target -/
lemma trans_symm_self :
e.symm.trans e ≈ local_equiv.of_set e.target :=
trans_self_symm (e.symm)
/-- Two equivalent local equivs are equal when the source and target are univ -/
lemma eq_of_eq_on_source_univ (e e' : local_equiv α β) (h : e ≈ e')
(s : e.source = univ) (t : e.target = univ) : e = e' :=
begin
apply local_equiv.ext (λx, _) (λx, _) h.1,
{ apply h.2,
rw s,
exact mem_univ _ },
{ apply h.symm'.2,
rw [symm_source, t],
exact mem_univ _ }
end
section prod
/-- The product of two local equivs, as a local equiv on the product. -/
def prod (e : local_equiv α β) (e' : local_equiv γ δ) : local_equiv (α × γ) (β × δ) :=
{ source := e.source ×ˢ e'.source,
target := e.target ×ˢ e'.target,
to_fun := λp, (e p.1, e' p.2),
inv_fun := λp, (e.symm p.1, e'.symm p.2),
map_source' := λp hp, by { simp at hp, simp [hp] },
map_target' := λp hp, by { simp at hp, simp [map_target, hp] },
left_inv' := λp hp, by { simp at hp, simp [hp] },
right_inv' := λp hp, by { simp at hp, simp [hp] } }
@[simp, mfld_simps] lemma prod_source (e : local_equiv α β) (e' : local_equiv γ δ) :
(e.prod e').source = e.source ×ˢ e'.source := rfl
@[simp, mfld_simps] lemma prod_target (e : local_equiv α β) (e' : local_equiv γ δ) :
(e.prod e').target = e.target ×ˢ e'.target := rfl
@[simp, mfld_simps] lemma prod_coe (e : local_equiv α β) (e' : local_equiv γ δ) :
((e.prod e') : α × γ → β × δ) = (λp, (e p.1, e' p.2)) := rfl
lemma prod_coe_symm (e : local_equiv α β) (e' : local_equiv γ δ) :
((e.prod e').symm : β × δ → α × γ) = (λp, (e.symm p.1, e'.symm p.2)) := rfl
@[simp, mfld_simps] lemma prod_symm (e : local_equiv α β) (e' : local_equiv γ δ) :
(e.prod e').symm = (e.symm.prod e'.symm) :=
by ext x; simp [prod_coe_symm]
@[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*}
(e : local_equiv α β) (f : local_equiv β γ) (e' : local_equiv δ η) (f' : local_equiv η ε) :
(e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') :=
by ext x; simp [ext_iff]; tauto
end prod
/-- Combine two `local_equiv`s using `set.piecewise`. The source of the new `local_equiv` is
`s.ite e.source e'.source = e.source ∩ s ∪ e'.source \ s`, and similarly for target. The function
sends `e.source ∩ s` to `e.target ∩ t` using `e` and `e'.source \ s` to `e'.target \ t` using `e'`,
and similarly for the inverse function. The definition assumes `e.is_image s t` and
`e'.is_image s t`. -/
@[simps {fully_applied := ff}] def piecewise (e e' : local_equiv α β) (s : set α) (t : set β)
[∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) :
local_equiv α β :=
{ to_fun := s.piecewise e e',
inv_fun := t.piecewise e.symm e'.symm,
source := s.ite e.source e'.source,
target := t.ite e.target e'.target,
map_source' := H.maps_to.piecewise_ite H'.compl.maps_to,
map_target' := H.symm.maps_to.piecewise_ite H'.symm.compl.maps_to,
left_inv' := H.left_inv_on_piecewise H',
right_inv' := H.symm.left_inv_on_piecewise H'.symm }
lemma symm_piecewise (e e' : local_equiv α β) {s : set α} {t : set β}
[∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)]
(H : e.is_image s t) (H' : e'.is_image s t) :
(e.piecewise e' s t H H').symm = e.symm.piecewise e'.symm t s H.symm H'.symm :=
rfl
/-- Combine two `local_equiv`s with disjoint sources and disjoint targets. We reuse
`local_equiv.piecewise`, then override `source` and `target` to ensure better definitional
equalities. -/
@[simps {fully_applied := ff}]
def disjoint_union (e e' : local_equiv α β) (hs : disjoint e.source e'.source)
(ht : disjoint e.target e'.target) [∀ x, decidable (x ∈ e.source)]
[∀ y, decidable (y ∈ e.target)] :
local_equiv α β :=
(e.piecewise e' e.source e.target e.is_image_source_target $
e'.is_image_source_target_of_disjoint _ hs.symm ht.symm).copy
_ rfl _ rfl (e.source ∪ e'.source) (ite_left _ _) (e.target ∪ e'.target) (ite_left _ _)
lemma disjoint_union_eq_piecewise (e e' : local_equiv α β) (hs : disjoint e.source e'.source)
(ht : disjoint e.target e'.target) [∀ x, decidable (x ∈ e.source)]
[∀ y, decidable (y ∈ e.target)] :
e.disjoint_union e' hs ht = e.piecewise e' e.source e.target e.is_image_source_target
(e'.is_image_source_target_of_disjoint _ hs.symm ht.symm) :=
copy_eq_self _ _ _ _ _ _ _ _ _
section pi
variables {ι : Type*} {αi βi : ι → Type*} (ei : Π i, local_equiv (αi i) (βi i))
/-- The product of a family of local equivs, as a local equiv on the pi type. -/
@[simps (mfld_cfg)] protected def pi : local_equiv (Π i, αi i) (Π i, βi i) :=
{ to_fun := λ f i, ei i (f i),
inv_fun := λ f i, (ei i).symm (f i),
source := pi univ (λ i, (ei i).source),
target := pi univ (λ i, (ei i).target),
map_source' := λ f hf i hi, (ei i).map_source (hf i hi),
map_target' := λ f hf i hi, (ei i).map_target (hf i hi),
left_inv' := λ f hf, funext $ λ i, (ei i).left_inv (hf i trivial),
right_inv' := λ f hf, funext $ λ i, (ei i).right_inv (hf i trivial) }
end pi
end local_equiv
namespace set
-- All arguments are explicit to avoid missing information in the pretty printer output
/-- A bijection between two sets `s : set α` and `t : set β` provides a local equivalence
between `α` and `β`. -/
@[simps {fully_applied := ff}] noncomputable def bij_on.to_local_equiv [nonempty α] (f : α → β)
(s : set α) (t : set β) (hf : bij_on f s t) :
local_equiv α β :=
{ to_fun := f,
inv_fun := inv_fun_on f s,
source := s,
target := t,
map_source' := hf.maps_to,
map_target' := hf.surj_on.maps_to_inv_fun_on,
left_inv' := hf.inv_on_inv_fun_on.1,
right_inv' := hf.inv_on_inv_fun_on.2 }
/-- A map injective on a subset of its domain provides a local equivalence. -/
@[simp, mfld_simps] noncomputable def inj_on.to_local_equiv [nonempty α] (f : α → β) (s : set α)
(hf : inj_on f s) :
local_equiv α β :=
hf.bij_on_image.to_local_equiv f s (f '' s)
end set
namespace equiv
/- equivs give rise to local_equiv. We set up simp lemmas to reduce most properties of the local
equiv to that of the equiv. -/
variables (e : α ≃ β) (e' : β ≃ γ)
@[simp, mfld_simps] lemma refl_to_local_equiv :
(equiv.refl α).to_local_equiv = local_equiv.refl α := rfl
@[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl
@[simp, mfld_simps] lemma trans_to_local_equiv :
(e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv :=
local_equiv.ext (λx, rfl) (λx, rfl) (by simp [local_equiv.trans_source, equiv.to_local_equiv])
end equiv
|
0e904c463d3076e274ec937e1fcfc2cb0c315cdc | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tmp/new-frontend/parser/declaration.lean | 6cf4322341584a98f4cd8053e16b27b11266f774 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 5,344 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sebastian Ullrich
Parsers for commands that declare things
-/
prelude
import init.lean.parser.term
namespace Lean
namespace Parser
open Combinators MonadParsec
open Parser.HasTokens Parser.HasView
instance termParserCommandParserCoe : HasCoe termParser commandParser :=
⟨λ p, adaptReader coe $ p.run⟩
namespace «command»
local postfix `?`:10000 := optional
local postfix *:10000 := Combinators.many
local postfix +:10000 := Combinators.many1
@[derive HasTokens HasView]
def docComment.Parser : commandParser :=
node! docComment ["/--", doc: raw $ many' (notFollowedBy (str "-/") *> any), "-/"]
@[derive HasTokens HasView]
def attrInstance.Parser : commandParser :=
-- use `rawIdent` because of attribute names such as `instance`
node! attrInstance [Name: rawIdent.Parser, args: (Term.Parser maxPrec)*]
@[derive HasTokens HasView]
def declAttributes.Parser : commandParser :=
-- TODO(Sebastian): custom attribute parsers
node! declAttributes ["@[", attrs: sepBy1 attrInstance.Parser (symbol ","), "]"]
set_option class.instance_max_depth 300
@[derive HasTokens HasView]
def declModifiers.Parser : commandParser :=
node! declModifiers [
docComment: docComment.Parser?,
attrs: declAttributes.Parser?,
visibility: nodeChoice! visibility {"private", "protected"}?,
«noncomputable»: (symbol "noncomputable")?,
«unsafe»: (symbol "unsafe")?,
]
@[derive HasTokens HasView]
def declSig.Parser : commandParser :=
node! declSig [
params: Term.bracketedBinders.Parser,
type: Term.typeSpec.Parser,
]
@[derive HasTokens HasView]
def optDeclSig.Parser : commandParser :=
node! optDeclSig [
params: Term.bracketedBinders.Parser,
type: Term.optType.Parser,
]
@[derive HasTokens HasView]
def equation.Parser : commandParser :=
node! equation ["|", lhs: (Term.Parser maxPrec)+, ":=", rhs: Term.Parser]
@[derive HasTokens HasView]
def declVal.Parser : commandParser :=
nodeChoice! declVal {
simple: node! simpleDeclVal [":=", body: Term.Parser],
emptyMatch: symbol ".",
«match»: equation.Parser+
}
@[derive HasTokens HasView]
def inferModifier.Parser : commandParser :=
nodeChoice! inferModifier {
relaxed: try $ node! relaxedInferModifier ["{", "}"],
strict: try $ node! strictInferModifier ["(", ")"],
}
@[derive HasTokens HasView]
def introRule.Parser : commandParser :=
node! introRule [
"|",
Name: ident.Parser,
inferMod: inferModifier.Parser?,
sig: optDeclSig.Parser,
]
@[derive HasTokens HasView]
def structBinderContent.Parser : commandParser :=
node! structBinderContent [
ids: ident.Parser+,
inferMod: inferModifier.Parser?,
sig: optDeclSig.Parser,
default: Term.binderDefault.Parser?,
]
@[derive HasTokens HasView]
def structureFieldBlock.Parser : commandParser :=
nodeChoice! structureFieldBlock {
explicit: node! structExplicitBinder ["(", content: nodeChoice! structExplicitBinderContent {
«notation»: command.notationLike.Parser,
other: structBinderContent.Parser
}, right: symbol ")"],
implicit: node! structImplicitBinder ["{", content: structBinderContent.Parser, "}"],
strictImplicit: node! strictImplicitBinder ["⦃", content: structBinderContent.Parser, "⦄"],
instImplicit: node! instImplicitBinder ["[", content: structBinderContent.Parser, "]"],
}
@[derive HasTokens HasView]
def oldUnivParams.Parser : commandParser :=
node! oldUnivParams ["{", ids: ident.Parser+, "}"]
@[derive Parser.HasTokens Parser.HasView]
def identUnivParams.Parser : commandParser :=
node! identUnivParams [
id: ident.Parser,
univParams: node! univParams [".{", params: ident.Parser+, "}"]?
]
@[derive HasTokens HasView]
def structure.Parser : commandParser :=
node! «structure» [
keyword: nodeChoice! structureKw {"structure", "class"},
oldUnivParams: oldUnivParams.Parser?,
Name: identUnivParams.Parser,
sig: optDeclSig.Parser,
«extends»: node! «extends» ["extends", parents: sepBy1 Term.Parser (symbol ",")]?,
":=",
ctor: node! structureCtor [Name: ident.Parser, inferMod: inferModifier.Parser?, "::"]?,
fieldBlocks: structureFieldBlock.Parser*,
]
@[derive HasTokens HasView]
def declaration.Parser : commandParser :=
node! declaration [
modifiers: declModifiers.Parser,
inner: nodeChoice! declaration.inner {
«defLike»: node! «defLike» [
kind: nodeChoice! defLike.kind {"def", "abbreviation", "abbrev", "theorem", "constant"},
oldUnivParams: oldUnivParams.Parser?,
Name: identUnivParams.Parser, sig: optDeclSig.Parser, val: declVal.Parser],
«instance»: node! «instance» ["instance", Name: identUnivParams.Parser?, sig: declSig.Parser, val: declVal.Parser],
«example»: node! «example» ["example", sig: declSig.Parser, val: declVal.Parser],
«axiom»: node! «axiom» [
kw: nodeChoice! constantKeyword {"axiom"},
Name: identUnivParams.Parser,
sig: declSig.Parser],
«inductive»: node! «inductive» [try [«class»: (symbol "class")?, "inductive"],
oldUnivParams: oldUnivParams.Parser?,
Name: identUnivParams.Parser,
sig: optDeclSig.Parser,
localNotation: notationLike.Parser?,
introRules: introRule.Parser*],
«structure»: structure.Parser,
}
]
end «command»
end Parser
end Lean
|
6dccedf94132f58a80fe7a1174fd2303ed21f9a6 | 968e2f50b755d3048175f176376eff7139e9df70 | /examples/prop_logic_theory/unnamed_1429.lean | e45169cb833f694afb04b0c47efa2cbda42c16e8 | [] | 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 | 159 | lean | import data.nat.basic
variables x y z : ℕ
-- BEGIN
example : x * (y + z) = x * z + y * x :=
begin
rw mul_add,
rw add_comm,
rw mul_comm x y,
end
-- END |
23ee100fcc56489141d3b28d6049689d924d98a1 | 10c7c971a1902d76057c52ce0529ebb491a69c44 | /ProblemSheet2.lean | 7b44a74582938bb128cb1ab38741903a862108ae | [] | no_license | SzymonKubica/Lean | 5f6122e8dd9171239b36a9ce0515f6acbc49781a | 627bff2f001ba3f009c112c9332093e8de84863c | refs/heads/main | 1,675,563,490,768 | 1,608,538,609,000 | 1,608,538,609,000 | 307,184,347 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,092 | lean | /- Math40001 : Introduction to university mathematics.
Problem Sheet 2, October 2020.
This is a Lean file. It can be read with the Lean theorem prover.
You can work on this file online via the link at
https://github.com/ImperialCollegeLondon/M40001_lean/blob/master/README.md
or you can install Lean and its maths library following the
instructions at
https://leanprover-community.github.io/get_started.html
and then just clone the project onto your own computer
with `leanproject get ImperialCollegeLondon/M40001_lean`.
There are advantages to installing Lean on your own computer
(for example it's faster), but it's more hassle than
just using it online.
In the below, delete "sorry" and replace it with some
tactics which prove the result.
-/
import data.real.basic -- need real numbers for Q5
-- Q1 prove that ∩ is symmetric
lemma question1 (α : Type) (X Y : set α) : X ∩ Y = Y ∩ X :=
begin
end
-- question 2 defs
def A := {x : ℝ | x ^ 2 < 3}
def B := {x : ℝ | ∃ n : ℤ, x = n ∧ x ^ 2 < 3}
def C := {x : ℝ | x ^ 3 < 3}
-- Change _true to _false and put a ¬ in front
-- of the goal if you think it's false.
-- e.g. if you think 2c is false then don't
-- try to prove it's true, try proving
-- lemma question2c_false : ¬ (A ⊆ C) := ...
-- Some of these are tricky for Lean beginners.
lemma question2a_true : (1 : ℝ)/2 ∈ A ∩ B :=
begin
sorry
end
lemma question2b_true : (1 : ℝ)/2 ∈ A ∪ B :=
begin
sorry
end
lemma question2c_true : A ⊆ C :=
begin
sorry
end
lemma question2d_true : B ⊆ C :=
begin
sorry
end
lemma question2e_true : C ⊆ A ∪ B :=
begin
sorry
end
lemma question2f_true : (A ∩ B) ∪ C = (A ∪ B) ∩ C :=
begin
sorry
end
-- Q3 set-up
variables (X Y : Type)
variable (P : X → Prop)
variable (Q : X → Prop)
variable (R : X → Y → Prop)
-- for Q3 you're going to have to change the right hand
-- side of the ↔ in the statement
-- of the lemma to the answer you think is correct.
lemma question3a : ¬ (∀ x : X, P x ∧ ¬ Q x) ↔ true := -- change `true`!
begin
sorry
end
lemma question3b : ¬ (∃ x : X, (¬ P x) ∧ Q x) ↔ true := -- change `true`!
begin
sorry
end
lemma question3c : ¬ (∀ x : X, ∃ y : Y, R x y) ↔ true := -- change `true`!
begin
sorry
end
example (f : ℝ → ℝ) (x : ℝ) :
¬ (∀ ε : ℝ, ε > 0 → ∃ δ : ℝ, δ > 0 ∧ ∀ y : ℝ, abs (y - x) < δ → abs (f y -f x) < ε )
↔ -- change next line to what you think the answer is
true :=
begin
sorry
end
-- change _true to _false in 4a, 4b if you think the opposite is true
-- and stick a `¬` in front of it
lemma question4a_true : ∀ x : ℝ, ∃ y : ℝ, x + y = 2 :=
begin
sorry
end
lemma question4b_true : ∃ y : ℝ, ∀ x : ℝ, x + y = 2 :=
begin
sorry
end
-- similarly for Q5 -- change _true to _false and add in a negation if you
-- want to prove that the proposition in the question is false.
lemma question5a_true : ∃ x ∈ (∅ : set ℕ), 2 + 2 = 5 :=
begin
sorry
end
lemma question5b_true : ∀ x ∈ (∅ : set ℕ), 2 + 2 = 5 :=
begin
sorry
end
|
a984c6f5598dded86d0335809b9984e81b6934ed | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/list/intervals.lean | fa5509e5679f02ffe48fb286b00ce7e46cddbe77 | [
"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 | 6,755 | 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 data.list.range
import data.list.bag_inter
open nat
namespace list
/--
`Ico n m` is the list of natural numbers `n ≤ x < m`.
(Ico stands for "interval, closed-open".)
See also `data/set/intervals.lean` for `set.Ico`, modelling intervals in general preorders, and
`multiset.Ico` and `finset.Ico` for `n ≤ x < m` as a multiset or as a finset.
@TODO (anyone): Define `Ioo` and `Icc`, state basic lemmas about them.
@TODO (anyone): Also do the versions for integers?
@TODO (anyone): One could generalise even further, defining
'locally finite partial orders', for which `set.Ico a b` is `[finite]`, and
'locally finite total orders', for which there is a list model.
-/
def Ico (n m : ℕ) : list ℕ := range' n (m - n)
namespace Ico
theorem zero_bot (n : ℕ) : Ico 0 n = range n :=
by rw [Ico, nat.sub_zero, range_eq_range']
@[simp] theorem length (n m : ℕ) : length (Ico n m) = m - n :=
by dsimp [Ico]; simp only [length_range']
theorem pairwise_lt (n m : ℕ) : pairwise (<) (Ico n m) :=
by dsimp [Ico]; simp only [pairwise_lt_range']
theorem nodup (n m : ℕ) : nodup (Ico n m) :=
by dsimp [Ico]; simp only [nodup_range']
@[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m :=
suffices n ≤ l ∧ l < n + (m - n) ↔ n ≤ l ∧ l < m, by simp [Ico, this],
begin
cases le_total n m with hnm hmn,
{ rw [nat.add_sub_of_le hnm] },
{ rw [nat.sub_eq_zero_of_le hmn, add_zero],
exact and_congr_right (assume hnl, iff.intro
(assume hln, (not_le_of_gt hln hnl).elim)
(assume hlm, lt_of_lt_of_le hlm hmn)) }
end
theorem eq_nil_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = [] :=
by simp [Ico, nat.sub_eq_zero_of_le h]
theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) :=
by rw [Ico, Ico, map_add_range', nat.add_sub_add_right, add_comm n k]
theorem map_sub (n m k : ℕ) (h₁ : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) :=
begin
by_cases h₂ : n < m,
{ rw [Ico, Ico],
rw nat.sub_sub_sub_cancel_right h₁,
rw [map_sub_range' _ _ _ h₁] },
{ simp at h₂,
rw [eq_nil_of_le h₂],
rw [eq_nil_of_le (nat.sub_le_sub_right h₂ _)],
refl }
end
@[simp] theorem self_empty {n : ℕ} : Ico n n = [] :=
eq_nil_of_le (le_refl n)
@[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = [] ↔ m ≤ n :=
iff.intro (assume h, nat.le_of_sub_eq_zero $ by rw [← length, h]; refl) eq_nil_of_le
lemma append_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) :
Ico n m ++ Ico m l = Ico n l :=
begin
dunfold Ico,
convert range'_append _ _ _,
{ exact (nat.add_sub_of_le hnm).symm },
{ rwa [← nat.add_sub_assoc hnm, nat.sub_add_cancel] }
end
@[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = [] :=
begin
apply eq_nil_iff_forall_not_mem.2,
intro a,
simp only [and_imp, not_and, not_lt, list.mem_inter, list.Ico.mem],
intros h₁ h₂ h₃,
exfalso,
exact not_lt_of_ge h₃ h₂
end
@[simp] lemma bag_inter_consecutive (n m l : ℕ) : list.bag_inter (Ico n m) (Ico m l) = [] :=
(bag_inter_nil_iff_inter_nil _ _).2 (inter_consecutive n m l)
@[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = [n] :=
by dsimp [Ico]; simp [nat.add_sub_cancel_left]
theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = Ico n m ++ [m] :=
by rwa [← succ_singleton, append_consecutive]; exact nat.le_succ _
theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m :=
by rw [← append_consecutive (nat.le_succ n) h, succ_singleton]; refl
@[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = [m - 1] :=
by dsimp [Ico]; rw nat.sub_sub_self h; simp
theorem chain'_succ (n m : ℕ) : chain' (λa b, b = succ a) (Ico n m) :=
begin
by_cases n < m,
{ rw [eq_cons h], exact chain_succ_range' _ _ },
{ rw [eq_nil_of_le (le_of_not_gt h)], trivial }
end
@[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m :=
by simp; intros; refl
lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m :=
filter_eq_self.2 $ assume k hk, lt_of_lt_of_le (mem.1 hk).2 hml
lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = [] :=
filter_eq_nil.2 $ assume k hk, not_lt_of_le $ le_trans hln $ (mem.1 hk).1
lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l :=
begin
cases le_total n l with hnl hln,
{ rw [← append_consecutive hnl hlm, filter_append,
filter_lt_of_top_le (le_refl l), filter_lt_of_le_bot (le_refl l), append_nil] },
{ rw [eq_nil_of_le hln, filter_lt_of_le_bot hln] }
end
@[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) :=
begin
cases le_total m l with hml hlm,
{ rw [min_eq_left hml, filter_lt_of_top_le hml] },
{ rw [min_eq_right hlm, filter_lt_of_ge hlm] }
end
lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m :=
filter_eq_self.2 $ assume k hk, le_trans hln (mem.1 hk).1
lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = [] :=
filter_eq_nil.2 $ assume k hk, not_le_of_gt (lt_of_lt_of_le (mem.1 hk).2 hml)
lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m :=
begin
cases le_total l m with hlm hml,
{ rw [← append_consecutive hnl hlm, filter_append,
filter_le_of_top_le (le_refl l), filter_le_of_le_bot (le_refl l), nil_append] },
{ rw [eq_nil_of_le hml, filter_le_of_top_le hml] }
end
@[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (_root_.max n l) m :=
begin
cases le_total n l with hnl hln,
{ rw [max_eq_right hnl, filter_le_of_le hnl] },
{ rw [max_eq_left hln, filter_le_of_le_bot hln] }
end
lemma filter_lt_of_succ_bot {n m : ℕ} (hnm : n < m) : (Ico n m).filter (λ x, x < n + 1) = [n] :=
begin
have r : min m (n + 1) = n + 1 := (@inf_eq_right _ _ m (n + 1)).mpr hnm,
simp [filter_lt n m (n + 1), r],
end
@[simp] lemma filter_le_of_bot {n m : ℕ} (hnm : n < m) : (Ico n m).filter (λ x, x ≤ n) = [n] :=
begin
rw ←filter_lt_of_succ_bot hnm,
exact filter_congr (λ _ _, lt_succ_iff.symm),
end
/--
For any natural numbers n, a, and b, one of the following holds:
1. n < a
2. n ≥ b
3. n ∈ Ico a b
-/
lemma trichotomy (n a b : ℕ) : n < a ∨ b ≤ n ∨ n ∈ Ico a b :=
begin
by_cases h₁ : n < a,
{ left, exact h₁ },
{ right,
by_cases h₂ : n ∈ Ico a b,
{ right, exact h₂ },
{ left, simp only [Ico.mem, not_and, not_lt] at *, exact h₂ h₁ }}
end
end Ico
end list
|
155c0c84c1488da914a7d4ee53b7c51f2667f170 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/combinatorics/simple_graph/coloring.lean | 8aaa57e487a697c2a0e5dee2211ac2a9edd4ec2d | [
"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 | 14,101 | lean | /-
Copyright (c) 2021 Arthur Paulino. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Arthur Paulino, Kyle Miller
-/
import combinatorics.simple_graph.subgraph
import data.nat.lattice
import data.setoid.partition
import order.antichain
/-!
# Graph Coloring
This module defines colorings of simple graphs (also known as proper
colorings in the literature). A graph coloring is the attribution of
"colors" to all of its vertices such that adjacent vertices have
different colors. A coloring can be represented as a homomorphism into
a complete graph, whose vertices represent the colors.
## Main definitions
* `G.coloring α` is the type of `α`-colorings of a simple graph `G`,
with `α` being the set of available colors. The type is defined to
be homomorphisms from `G` into the complete graph on `α`, and
colorings have a coercion to `V → α`.
* `G.colorable n` is the proposition that `G` is `n`-colorable, which
is whether there exists a coloring with at most *n* colors.
* `G.chromatic_number` is the minimal `n` such that `G` is
`n`-colorable, or `0` if it cannot be colored with finitely many
colors.
* `C.color_class c` is the set of vertices colored by `c : α` in the
coloring `C : G.coloring α`.
* `C.color_classes` is the set containing all color classes.
## Todo:
* Gather material from:
* https://github.com/leanprover-community/mathlib/blob/simple_graph_matching/src/combinatorics/simple_graph/coloring.lean
* https://github.com/kmill/lean-graphcoloring/blob/master/src/graph.lean
* Lowerbound for cliques
* Trees
* Planar graphs
* Chromatic polynomials
* develop API for partial colorings, likely as colorings of subgraphs (`H.coe.coloring α`)
-/
universes u v
namespace simple_graph
variables {V : Type u} (G : simple_graph V)
/--
An `α`-coloring of a simple graph `G` is a homomorphism of `G` into the complete graph on `α`.
This is also known as a proper coloring.
-/
abbreviation coloring (α : Type v) := G →g (⊤ : simple_graph α)
variables {G} {α : Type v} (C : G.coloring α)
lemma coloring.valid {v w : V} (h : G.adj v w) : C v ≠ C w :=
C.map_rel h
/--
Construct a term of `simple_graph.coloring` using a function that
assigns vertices to colors and a proof that it is as proper coloring.
(Note: this is a definitionally the constructor for `simple_graph.hom`,
but with a syntactically better proper coloring hypothesis.)
-/
@[pattern] def coloring.mk
(color : V → α)
(valid : ∀ {v w : V}, G.adj v w → color v ≠ color w) :
G.coloring α := ⟨color, @valid⟩
/--
The color class of a given color.
-/
def coloring.color_class (c : α) : set V := {v : V | C v = c}
/-- The set containing all color classes. -/
def coloring.color_classes : set (set V) := (setoid.ker C).classes
lemma coloring.mem_color_class (v : V) :
v ∈ C.color_class (C v) := by exact rfl
lemma coloring.color_classes_is_partition :
setoid.is_partition C.color_classes :=
setoid.is_partition_classes (setoid.ker C)
lemma coloring.mem_color_classes {v : V} : C.color_class (C v) ∈ C.color_classes :=
⟨v, rfl⟩
lemma coloring.color_classes_finite_of_fintype [fintype α] : C.color_classes.finite :=
by { rw set.finite_def, apply setoid.nonempty_fintype_classes_ker, }
lemma coloring.card_color_classes_le [fintype α] [fintype C.color_classes] :
fintype.card C.color_classes ≤ fintype.card α :=
setoid.card_classes_ker_le C
lemma coloring.not_adj_of_mem_color_class {c : α} {v w : V}
(hv : v ∈ C.color_class c) (hw : w ∈ C.color_class c) :
¬G.adj v w :=
λ h, C.valid h (eq.trans hv (eq.symm hw))
lemma coloring.color_classes_independent (c : α) :
is_antichain G.adj (C.color_class c) :=
λ v hv w hw h, C.not_adj_of_mem_color_class hv hw
-- TODO make this computable
noncomputable
instance [fintype V] [fintype α] : fintype (coloring G α) :=
begin
classical,
change fintype (rel_hom G.adj (⊤ : simple_graph α).adj),
apply fintype.of_injective _ rel_hom.coe_fn_injective,
apply_instance,
end
variables (G)
/-- Whether a graph can be colored by at most `n` colors. -/
def colorable (n : ℕ) : Prop := nonempty (G.coloring (fin n))
/-- The coloring of an empty graph. -/
def coloring_of_is_empty [is_empty V] : G.coloring α :=
coloring.mk is_empty_elim (λ v, is_empty_elim)
lemma colorable_of_is_empty [is_empty V] (n : ℕ) : G.colorable n :=
⟨G.coloring_of_is_empty⟩
lemma is_empty_of_colorable_zero (h : G.colorable 0) : is_empty V :=
begin
split,
intro v,
obtain ⟨i, hi⟩ := h.some v,
exact nat.not_lt_zero _ hi,
end
/-- The "tautological" coloring of a graph, using the vertices of the graph as colors. -/
def self_coloring : G.coloring V :=
coloring.mk id (λ v w, G.ne_of_adj)
/-- The chromatic number of a graph is the minimal number of colors needed to color it.
If `G` isn't colorable with finitely many colors, this will be 0. -/
noncomputable def chromatic_number : ℕ :=
Inf { n : ℕ | G.colorable n }
/-- Given an embedding, there is an induced embedding of colorings. -/
def recolor_of_embedding {α β : Type*} (f : α ↪ β) : G.coloring α ↪ G.coloring β :=
{ to_fun := λ C, (embedding.complete_graph.of_embedding f).to_hom.comp C,
inj' := begin -- this was strangely painful; seems like missing lemmas about embeddings
intros C C' h,
dsimp only at h,
ext v,
apply (embedding.complete_graph.of_embedding f).inj',
change ((embedding.complete_graph.of_embedding f).to_hom.comp C) v = _,
rw h,
refl,
end }
/-- Given an equivalence, there is an induced equivalence between colorings. -/
def recolor_of_equiv {α β : Type*} (f : α ≃ β) : G.coloring α ≃ G.coloring β :=
{ to_fun := G.recolor_of_embedding f.to_embedding,
inv_fun := G.recolor_of_embedding f.symm.to_embedding,
left_inv := λ C, by { ext v, apply equiv.symm_apply_apply },
right_inv := λ C, by { ext v, apply equiv.apply_symm_apply } }
/-- There is a noncomputable embedding of `α`-colorings to `β`-colorings if
`β` has at least as large a cardinality as `α`. -/
noncomputable def recolor_of_card_le {α β : Type*} [fintype α] [fintype β]
(hn : fintype.card α ≤ fintype.card β) :
G.coloring α ↪ G.coloring β :=
G.recolor_of_embedding $ (function.embedding.nonempty_of_card_le hn).some
variables {G}
lemma colorable.mono {n m : ℕ} (h : n ≤ m) (hc : G.colorable n) : G.colorable m :=
⟨G.recolor_of_card_le (by simp [h]) hc.some⟩
lemma coloring.to_colorable [fintype α] (C : G.coloring α) :
G.colorable (fintype.card α) :=
⟨G.recolor_of_card_le (by simp) C⟩
lemma colorable_of_fintype (G : simple_graph V) [fintype V] :
G.colorable (fintype.card V) :=
G.self_coloring.to_colorable
/-- Noncomputably get a coloring from colorability. -/
noncomputable def colorable.to_coloring [fintype α] {n : ℕ} (hc : G.colorable n)
(hn : n ≤ fintype.card α) :
G.coloring α :=
begin
rw ←fintype.card_fin n at hn,
exact G.recolor_of_card_le hn hc.some,
end
lemma colorable.of_embedding {V' : Type*} {G' : simple_graph V'}
(f : G ↪g G') {n : ℕ} (h : G'.colorable n) : G.colorable n :=
⟨(h.to_coloring (by simp)).comp f⟩
lemma colorable_iff_exists_bdd_nat_coloring (n : ℕ) :
G.colorable n ↔ ∃ (C : G.coloring ℕ), ∀ v, C v < n :=
begin
split,
{ rintro hc,
have C : G.coloring (fin n) := hc.to_coloring (by simp),
let f := embedding.complete_graph.of_embedding (fin.coe_embedding n).to_embedding,
use f.to_hom.comp C,
intro v,
cases C with color valid,
exact fin.is_lt (color v), },
{ rintro ⟨C, Cf⟩,
refine ⟨coloring.mk _ _⟩,
{ exact λ v, ⟨C v, Cf v⟩, },
{ rintro v w hvw,
simp only [subtype.mk_eq_mk, ne.def],
exact C.valid hvw, } }
end
lemma colorable_set_nonempty_of_colorable {n : ℕ} (hc : G.colorable n) :
{n : ℕ | G.colorable n}.nonempty :=
⟨n, hc⟩
lemma chromatic_number_bdd_below : bdd_below {n : ℕ | G.colorable n} :=
⟨0, λ _ _, zero_le _⟩
lemma chromatic_number_le_of_colorable {n : ℕ} (hc : G.colorable n) :
G.chromatic_number ≤ n :=
begin
rw chromatic_number,
apply cInf_le chromatic_number_bdd_below,
fsplit,
exact classical.choice hc,
end
lemma chromatic_number_le_card [fintype α] (C : G.coloring α) :
G.chromatic_number ≤ fintype.card α :=
cInf_le chromatic_number_bdd_below C.to_colorable
lemma colorable_chromatic_number {m : ℕ} (hc : G.colorable m) :
G.colorable G.chromatic_number :=
begin
dsimp only [chromatic_number],
rw nat.Inf_def,
apply nat.find_spec,
exact colorable_set_nonempty_of_colorable hc,
end
lemma colorable_chromatic_number_of_fintype (G : simple_graph V) [fintype V] :
G.colorable G.chromatic_number :=
colorable_chromatic_number G.colorable_of_fintype
lemma chromatic_number_le_one_of_subsingleton (G : simple_graph V) [subsingleton V] :
G.chromatic_number ≤ 1 :=
begin
rw chromatic_number,
apply cInf_le chromatic_number_bdd_below,
fsplit,
refine coloring.mk (λ _, 0) _,
intros v w,
rw subsingleton.elim v w,
simp,
end
lemma chromatic_number_eq_zero_of_isempty (G : simple_graph V) [is_empty V] :
G.chromatic_number = 0 :=
begin
rw ←nonpos_iff_eq_zero,
apply cInf_le chromatic_number_bdd_below,
apply colorable_of_is_empty,
end
lemma is_empty_of_chromatic_number_eq_zero (G : simple_graph V) [fintype V]
(h : G.chromatic_number = 0) : is_empty V :=
begin
have h' := G.colorable_chromatic_number_of_fintype,
rw h at h',
exact G.is_empty_of_colorable_zero h',
end
lemma chromatic_number_pos [nonempty V] {n : ℕ} (hc : G.colorable n) :
0 < G.chromatic_number :=
begin
apply le_cInf (colorable_set_nonempty_of_colorable hc),
intros m hm,
by_contra h',
simp only [not_le, nat.lt_one_iff] at h',
subst h',
obtain ⟨i, hi⟩ := hm.some (classical.arbitrary V),
exact nat.not_lt_zero _ hi,
end
lemma colorable_of_chromatic_number_pos (h : 0 < G.chromatic_number) :
G.colorable G.chromatic_number :=
begin
obtain ⟨h, hn⟩ := nat.nonempty_of_pos_Inf h,
exact colorable_chromatic_number hn,
end
lemma colorable.mono_left {G' : simple_graph V} (h : G ≤ G') {n : ℕ}
(hc : G'.colorable n) : G.colorable n :=
⟨hc.some.comp (hom.map_spanning_subgraphs h)⟩
lemma colorable.chromatic_number_le_of_forall_imp {V' : Type*} {G' : simple_graph V'}
{m : ℕ} (hc : G'.colorable m)
(h : ∀ n, G'.colorable n → G.colorable n) :
G.chromatic_number ≤ G'.chromatic_number :=
begin
apply cInf_le chromatic_number_bdd_below,
apply h,
apply colorable_chromatic_number hc,
end
lemma colorable.chromatic_number_mono (G' : simple_graph V)
{m : ℕ} (hc : G'.colorable m) (h : G ≤ G') :
G.chromatic_number ≤ G'.chromatic_number :=
hc.chromatic_number_le_of_forall_imp (λ n, colorable.mono_left h)
lemma colorable.chromatic_number_mono_of_embedding {V' : Type*} {G' : simple_graph V'}
{n : ℕ} (h : G'.colorable n) (f : G ↪g G') :
G.chromatic_number ≤ G'.chromatic_number :=
h.chromatic_number_le_of_forall_imp (λ _, colorable.of_embedding f)
lemma chromatic_number_eq_card_of_forall_surj [fintype α] (C : G.coloring α)
(h : ∀ (C' : G.coloring α), function.surjective C') :
G.chromatic_number = fintype.card α :=
begin
apply le_antisymm,
{ apply chromatic_number_le_card C, },
{ by_contra hc,
rw not_le at hc,
obtain ⟨n, cn, hc⟩ := exists_lt_of_cInf_lt
(colorable_set_nonempty_of_colorable C.to_colorable) hc,
rw ←fintype.card_fin n at hc,
have f := (function.embedding.nonempty_of_card_le (le_of_lt hc)).some,
have C' := cn.some,
specialize h (G.recolor_of_embedding f C'),
change function.surjective (f ∘ C') at h,
have h1 : function.surjective f := function.surjective.of_comp h,
have h2 := fintype.card_le_of_surjective _ h1,
exact nat.lt_le_antisymm hc h2, },
end
lemma chromatic_number_bot [nonempty V] :
(⊥ : simple_graph V).chromatic_number = 1 :=
begin
let C : (⊥ : simple_graph V).coloring (fin 1) :=
coloring.mk (λ _, 0) (λ v w h, false.elim h),
apply le_antisymm,
{ exact chromatic_number_le_card C, },
{ exact chromatic_number_pos C.to_colorable, },
end
@[simp] lemma chromatic_number_top [fintype V] :
(⊤ : simple_graph V).chromatic_number = fintype.card V :=
begin
apply chromatic_number_eq_card_of_forall_surj (self_coloring _),
intro C,
rw ←fintype.injective_iff_surjective,
intros v w,
contrapose,
intro h,
exact C.valid h,
end
lemma chromatic_number_top_eq_zero_of_infinite (V : Type*) [infinite V] :
(⊤ : simple_graph V).chromatic_number = 0 :=
begin
let n := (⊤ : simple_graph V).chromatic_number,
by_contra hc,
replace hc := pos_iff_ne_zero.mpr hc,
apply nat.not_succ_le_self n,
convert_to (⊤ : simple_graph {m | m < n + 1}).chromatic_number ≤ _,
{ simp, },
refine (colorable_of_chromatic_number_pos hc).chromatic_number_mono_of_embedding _,
apply embedding.complete_graph.of_embedding,
exact (function.embedding.subtype _).trans (infinite.nat_embedding V),
end
/-- The bicoloring of a complete bipartite graph using whether a vertex
is on the left or on the right. -/
def complete_bipartite_graph.bicoloring (V W : Type*) :
(complete_bipartite_graph V W).coloring bool :=
coloring.mk (λ v, v.is_right) begin
intros v w,
cases v; cases w; simp,
end
lemma complete_bipartite_graph.chromatic_number {V W : Type*} [nonempty V] [nonempty W] :
(complete_bipartite_graph V W).chromatic_number = 2 :=
begin
apply chromatic_number_eq_card_of_forall_surj (complete_bipartite_graph.bicoloring V W),
intros C b,
have v := classical.arbitrary V,
have w := classical.arbitrary W,
have h : (complete_bipartite_graph V W).adj (sum.inl v) (sum.inr w) := by simp,
have hn := C.valid h,
by_cases he : C (sum.inl v) = b,
{ exact ⟨_, he⟩ },
{ by_cases he' : C (sum.inr w) = b,
{ exact ⟨_, he'⟩ },
{ exfalso,
cases b;
simp only [eq_tt_eq_not_eq_ff, eq_ff_eq_not_eq_tt] at he he';
rw [he, he'] at hn;
contradiction }, },
end
end simple_graph
|
7a3f6a2ee8901407f0c2c22bf864106a6757b2e9 | 28be2ab6091504b6ba250b367205fb94d50ab284 | /levels/solutions/world3_le_variant_solutions.lean | eafcd3994797f941265864262c7cfb3c7bfc3338 | [
"Apache-2.0"
] | permissive | postmasters/natural_number_game | 87304ac22e5e1c5ac2382d6e523d6914dd67a92d | 38a7adcdfdb18c49c87b37831736c8f15300d821 | refs/heads/master | 1,649,856,819,031 | 1,586,444,676,000 | 1,586,444,676,000 | 255,006,061 | 0 | 0 | Apache-2.0 | 1,586,664,599,000 | 1,586,664,598,000 | null | UTF-8 | Lean | false | false | 7,383 | lean | import mynat.mul
import solutions.world2_multiplication
import tactic.linarith
-- this is one of *three* routes to
-- canonically_ordered_comm_semiring
namespace mynat
inductive le : mynat → mynat → Prop
| refl (a : mynat) : le a a
| succ (a b : mynat) : le a b → le a (succ b)
-- Other choices:
-- | le 0 _
-- | le (succ a) (succ b) = le ab
-- or
-- le a b := ∃ c : a + c = b
-- That's three routes
-- notation
instance : has_le mynat := ⟨mynat.le⟩
-- this attribute must go
@[_refl_lemma]
theorem le_refl (a : mynat) : a ≤ a :=
begin
exact le.refl a
end
theorem le_succ {a b : mynat} (h : a ≤ b) : a ≤ (succ b) :=
begin
exact le.succ a b h,
end
example : one ≤ one := le_refl one
/-
should I define lt, ge, gt?
-- notation a < b := lt a b
-- notation b > a := lt a b
-/
lemma zero_le (a : mynat) : zero ≤ a :=
begin
induction a with d hd,
{
exact le_refl zero
},
{
exact le_succ hd
}
end
lemma le_zero {a : mynat} : a ≤ zero → a = zero :=
begin
intro h,
cases h, -- induction on le
refl
end
lemma succ_le_succ {a b : mynat} (h : a ≤ b) : succ a ≤ succ b :=
begin
revert a, -- new trick
induction b with d hd,
{
intros a ha,
rw le_zero ha,
-- refl, -- why doesn't this work
apply le_refl,
},
{
intros a ha,
cases ha with _ _ _ hbad, -- le2 leakage and how can I avoid all the _'s?
-- I would just like one tactic `blah ha with hgood`
-- and result hgood : a ≤ d in second goal
{ apply le_refl, -- should be refl
},
{
apply le_succ,
apply hd,
/-
hbad : le a d
⊢ a ≤ d
-/
assumption
}
}
end
-- one of the axioms for ordered semiring or whatever
theorem add_le_add_right (a b : mynat) : a ≤ b → ∀ t, (a + t) ≤ (b + t) :=
begin
intros h t,
induction t with d hd,
{
exact h
},
{
rw add_succ,
rw add_succ,
exact succ_le_succ hd
}
end
-- axiom 2
theorem le_trans' {a b c : mynat} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c :=
begin
revert a b,
induction c with d hd,
{
intros a b hab hb0,
cases hb0,
cases hab,
apply le_refl
},
{
intros a b hab hb,
cases hb with _ _ c hc, -- le leakage
-- rcases leaks too
assumption,
apply le_succ,
apply hd hab,
assumption
}
end
theorem le_trans (a b c : mynat) : a ≤ b → b ≤ c → a ≤ c := le_trans'
-- axiom 3.1
theorem le_symm_thing (a b : mynat) : a ≤ b ∨ b ≤ a :=
begin
revert a,
induction b with c hc,
intro a, right, apply zero_le,
intro a,
induction a with d hd,
left, apply zero_le,
cases hc d with h h,
left, exact succ_le_succ h,
right, exact succ_le_succ h,
end
theorem le_succ_self (a : mynat) : a ≤ succ a :=
begin
apply le_succ,
apply le_refl
end
theorem le_of_succ_le_succ {a b : mynat} : succ a ≤ succ b → a ≤ b :=
begin
intro h,
cases h with _ _ a ha, -- le leakage and annoying _ _'s
apply le_refl,
apply le_trans' _ ha,
apply le_succ,
apply le_refl
end
-- axiom 3.2
theorem le_antisymm : ∀ (a b : mynat), a ≤ b → b ≤ a → a = b :=
begin
intro a,
intro b,
revert a, -- switcheroo
induction b with d hd,
{
intros a ha h,
cases ha,
refl,
},
{ intro a,
cases a with a,
intros h1 h2, cases h2,
intros had hda,
congr,
apply hd,
cases had,
apply le_of_succ_le_succ,
assumption,
refine le_trans' _ had_a_1,
apply le_succ,
apply le_refl,
cases hda,
apply le_refl,
apply le_trans' _ hda_a_1,
apply le_succ_self,
}
end
theorem not_succ_le_self {d : mynat} (h : succ d ≤ d) : false :=
begin
-- induction h, -- wtf?
revert h,
induction d with a ha,
intro h,
cases h,
intro h,
apply ha,
apply le_of_succ_le_succ,
assumption,
end
theorem not_succ_le_self' (d : mynat) (h : succ d ≤ d) : false := not_succ_le_self h
theorem le_antisymm' {b : mynat} : ∀ {a : mynat}, b ≤ a → a ≤ b → a = b :=
begin
induction b with d hd,
{
intros a ha h,
cases ha,
refl,
apply le_zero,
assumption,
},
{ intro a,
induction a with b hb,
{ intros h1 h_irrelevant,
symmetry,
apply le_zero,
assumption,
},
{ intros h1 h2,
cases h2 with _ _ _ sald, -- leakage and _
refl,
exfalso,
apply not_succ_le_self' d,
apply le_trans' h1 sald },
}
end
--def lt : mynat → mynat → Prop := λ a b, a ≤ b ∧ ¬ b ≤ a
--instance : has_lt mynat := ⟨mynat.lt⟩
def bot : mynat := 0
instance : lattice.has_bot mynat := ⟨mynat.bot⟩
def bot_le : ∀ a : mynat, ⊥ ≤ a := zero_le
instance : preorder mynat :=
{ le := mynat.le,
le_refl := mynat.le_refl,
le_trans := mynat.le_trans,
}
theorem add_le_add_left :
∀ (a b : mynat), a ≤ b → ∀ (c : mynat), c + a ≤ c + b :=
begin
intros a b hab c,
rw add_comm,
rw add_comm c,
apply add_le_add_right,
assumption
end
def succ_le_succ_iff (a b : mynat) : succ a ≤ succ b ↔ a ≤ b :=
begin
split,
intro h,
cases h,
refl,
refine le_trans' _ h_a_1,
exact le_succ_self _,
exact succ_le_succ,
end
def succ_lt_succ_iff (a b : mynat) : succ a < succ b ↔ a < b :=
begin
rw lt_iff_le_not_le,
rw lt_iff_le_not_le,
split,
intro h,
cases h,
split,
rwa succ_le_succ_iff at h_left,
intro h, apply h_right,
rwa succ_le_succ_iff,
intro h,
cases h,
split,
rwa succ_le_succ_iff,
intro h, apply h_right,
rwa succ_le_succ_iff at h,
end
theorem lt_of_add_lt_add_left : ∀ (a b c : mynat), a + b < a + c → b < c :=
begin
intros a b c,
intro h,
rw add_comm at h,
rw add_comm a at h,
revert b c,
induction a with d hd,
intros a b h, exact h,
intros b c h,
rw [add_succ, add_succ] at h,
apply hd,
rwa succ_lt_succ_iff at h,
end
theorem le_iff_exists_add : ∀ (a b : mynat), a ≤ b ↔ ∃ (c : mynat), b = a + c :=
begin
intros a b,
split,
intro h,
induction b with d hd,
use 0,
rw add_zero,
symmetry,
apply le_zero,
assumption,
cases h,
use 0,
rw add_zero,
cases hd h_a_1 with c hc,
use (succ c),
rw hc,
rw add_succ,
intro h,
rcases h with ⟨c, rfl⟩,
induction c with d hd,
refl,
apply le_trans' hd,
rw add_succ,
exact le_succ_self _,
end
theorem zero_ne_one : (0 : mynat) ≠ 1 :=
begin
intro h, rw eq_comm at h, revert h,
apply succ_ne_zero,
end
instance : canonically_ordered_comm_semiring mynat := by structure_helper
/-
instance : canonically_ordered_comm_semiring mynat :=
{ add := (+),
add_assoc := add_assoc,
zero := 0,
zero_add := zero_add,
add_zero := add_zero,
add_comm := add_comm,
le := (≤),
le_refl := le_refl,
le_trans := le_trans,
le_antisymm := λ a b, le_antisymm,
add_le_add_left := add_le_add_left,
lt_of_add_lt_add_left := lt_of_add_lt_add_left,
bot := ⊥,
bot_le := bot_le,
le_iff_exists_add := le_iff_exists_add,
mul := (*),
mul_assoc := mul_assoc,
one := 1,
one_mul := one_mul,
mul_one := mul_one,
left_distrib := left_distrib,
right_distrib := right_distrib,
zero_mul := zero_mul,
mul_zero := mul_zero,
mul_comm := mul_comm,
zero_ne_one := zero_ne_one,
mul_eq_zero_iff := mul_eq_zero_iff }
-/
end mynat
|
490955a561ecf8b7fb336de63fc12baede04f9ce | 7cdf3413c097e5d36492d12cdd07030eb991d394 | /world_experiments/world9/level6.lean | 814d651c87f1ac83ddd215ee2f65d267b8630413 | [] | no_license | alreadydone/natural_number_game | 3135b9385a9f43e74cfbf79513fc37e69b99e0b3 | 1a39e693df4f4e871eb449890d3c7715a25c2ec9 | refs/heads/master | 1,599,387,390,105 | 1,573,200,587,000 | 1,573,200,691,000 | 220,397,084 | 0 | 0 | null | 1,573,192,734,000 | 1,573,192,733,000 | null | UTF-8 | Lean | false | false | 2,033 | lean | import game.world5.level4 -- hide
import game.world2.level14
namespace mynat -- hide
/-
# World 5 : Inequality world
## Level 6 : `le_antisymm`
In this level, it would be helpful if you knew about how to create extra
hypotheses in the middle of a proof.
Say you have a hypothesis `h : a + b = a`
and you remember back from world 2 level 12 that you proved
`eq_zero_of_add_right_eq_self {a b : mynat} : a + b = a → b = 0`.
You can think of `eq_zero_of_add_right_eq_self` as a function
which turns proofs of `a + b = a` into proofs of `b = 0`. So you can
use the `have` tactic, and type
`have h2 := eq_zero_of_add_right_eq_self h,`
and now `h2` will be a proof that `b = 0`.
Also don't forget that you can use the `rw` tactic on hypotheses -- `rw h1 at h2`
will replace occurrences of the left hand side of `h1` in `h2`,
with the right hand side.
-/
/- Lemma
≤ is antisymmetric. In other words, if a ≤ b and b ≤ a then a = b.
-/
theorem le_antisymm {{a b : mynat}} (hab : a ≤ b) (hba : b ≤ a) : a = b :=
begin [less_leaky]
cases hab with c hc,
cases hba with d hd,
rw hd at hc,
rw add_assoc at hc,
have h := eq_zero_of_add_right_eq_self hc.symm,
have h2 := add_right_eq_zero h,
rw h2 at hd,
rw add_zero at hd,
assumption,
end
/-
Congratulations -- you just proved that the natural numbers are a partial order!
To come: about 25 more ≤ levels. But that will have to wait for v1.1.
If you got this far, and did the world 2 and 3 extra levels, then you have
beaten v1.0 of the game. Now think of a simple mathematical theorem, and see if you
can formulate and prove it yourself using the Lean Theorem Prover. Download Lean
and its maths library
<a href="https://github.com/leanprover-community/mathlib" target=blank">here</a>
(please follow the installation instructions to the letter)
and if and when you get stuck, come and ask at
<a href="https://leanprover.zulipchat.com" target=blank">the Lean chat</a>.
-/
instance : partial_order mynat := by structure_helper -- hide
end mynat
|
8a10b68b176756485c5ec4aba93adcd047693a26 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/topology/algebra/nonarchimedean/basic.lean | 309f3a7ea437f7b326cefc7bca5a388cf159e2cb | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 5,822 | lean | /-
Copyright (c) 2021 Ashwin Iyengar. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Johan Commelin, Ashwin Iyengar, Patrick Massot
-/
import topology.algebra.ring
import topology.algebra.open_subgroup
import data.set.basic
import group_theory.subgroup
/-!
# Nonarchimedean Topology
In this file we set up the theory of nonarchimedean topological groups and rings.
A nonarchimedean group is a topological group whose topology admits a basis of
open neighborhoods of the identity element in the group consisting of open subgroups.
A nonarchimedean ring is a topological ring whose underlying topological (additive)
group is nonarchimedean.
## Definitions
- `nonarchimedean_add_group`: nonarchimedean additive group.
- `nonarchimedean_group`: nonarchimedean multiplicative group.
- `nonarchimedean_ring`: nonarchimedean ring.
-/
/-- An topological additive group is nonarchimedean if every neighborhood of 0
contains an open subgroup. -/
class nonarchimedean_add_group (G : Type*)
[add_group G] [topological_space G] extends topological_add_group G : Prop :=
(is_nonarchimedean : ∀ U ∈ nhds (0 : G), ∃ V : open_add_subgroup G, (V : set G) ⊆ U)
/-- A topological group is nonarchimedean if every neighborhood of 1 contains an open subgroup. -/
@[to_additive]
class nonarchimedean_group (G : Type*)
[group G] [topological_space G] extends topological_group G : Prop :=
(is_nonarchimedean : ∀ U ∈ nhds (1 : G), ∃ V : open_subgroup G, (V : set G) ⊆ U)
/-- An topological ring is nonarchimedean if its underlying topological additive
group is nonarchimedean. -/
class nonarchimedean_ring (R : Type*)
[ring R] [topological_space R] extends topological_ring R : Prop :=
(is_nonarchimedean : ∀ U ∈ nhds (0 : R), ∃ V : open_add_subgroup R, (V : set R) ⊆ U)
/-- Every nonarchimedean ring is naturally a nonarchimedean additive group. -/
@[priority 100] -- see Note [lower instance priority]
instance nonarchimedean_ring.to_nonarchimedean_add_group
(R : Type*) [ring R] [topological_space R] [t: nonarchimedean_ring R] :
nonarchimedean_add_group R := {..t}
namespace nonarchimedean_group
variables {G : Type*} [group G] [topological_space G] [nonarchimedean_group G]
variables {H : Type*} [group H] [topological_space H] [topological_group H]
variables {K : Type*} [group K] [topological_space K] [nonarchimedean_group K]
/-- If a topological group embeds into a nonarchimedean group, then it
is nonarchimedean. -/
@[to_additive nonarchimedean_add_group.nonarchimedean_of_emb]
lemma nonarchimedean_of_emb (f : G →* H) (emb : open_embedding f) : nonarchimedean_group H :=
{ is_nonarchimedean := λ U hU, have h₁ : (f ⁻¹' U) ∈ nhds (1 : G), from
by {apply emb.continuous.tendsto, rwa f.map_one},
let ⟨V, hV⟩ := is_nonarchimedean (f ⁻¹' U) h₁ in
⟨{is_open' := emb.is_open_map _ V.is_open, ..subgroup.map f V},
set.image_subset_iff.2 hV⟩ }
/-- An open neighborhood of the identity in the cartesian product of two nonarchimedean groups
contains the cartesian product of an open neighborhood in each group. -/
@[to_additive nonarchimedean_add_group.prod_subset]
lemma prod_subset {U} (hU : U ∈ nhds (1 : G × K)) :
∃ (V : open_subgroup G) (W : open_subgroup K), (V : set G).prod (W : set K) ⊆ U :=
begin
erw [nhds_prod_eq, filter.mem_prod_iff] at hU,
rcases hU with ⟨U₁, hU₁, U₂, hU₂, h⟩,
cases is_nonarchimedean _ hU₁ with V hV,
cases is_nonarchimedean _ hU₂ with W hW,
use V, use W,
rw set.prod_subset_iff,
intros x hX y hY,
exact set.subset.trans (set.prod_mono hV hW) h (set.mem_sep hX hY),
end
/-- An open neighborhood of the identity in the cartesian square of a nonarchimedean group
contains the cartesian square of an open neighborhood in the group. -/
@[to_additive nonarchimedean_add_group.prod_self_subset]
lemma prod_self_subset {U} (hU : U ∈ nhds (1 : G × G)) :
∃ (V : open_subgroup G), (V : set G).prod (V : set G) ⊆ U :=
let ⟨V, W, h⟩ := prod_subset hU in
⟨V ⊓ W, by {refine set.subset.trans (set.prod_mono _ _) ‹_›; simp}⟩
/-- The cartesian product of two nonarchimedean groups is nonarchimedean. -/
@[to_additive]
instance : nonarchimedean_group (G × K) :=
{ is_nonarchimedean := λ U hU, let ⟨V, W, h⟩ := prod_subset hU in ⟨V.prod W, ‹_›⟩ }
end nonarchimedean_group
namespace nonarchimedean_ring
open nonarchimedean_ring
open nonarchimedean_add_group
variables {R S : Type*}
variables [ring R] [topological_space R] [nonarchimedean_ring R]
variables [ring S] [topological_space S] [nonarchimedean_ring S]
/-- The cartesian product of two nonarchimedean rings is nonarchimedean. -/
instance : nonarchimedean_ring (R × S) :=
{ is_nonarchimedean := nonarchimedean_add_group.is_nonarchimedean }
/-- Given an open subgroup `U` and an element `r` of a nonarchimedean ring, there is an open
subgroup `V` such that `r • V` is contained in `U`. -/
lemma left_mul_subset (U : open_add_subgroup R) (r : R) :
∃ V : open_add_subgroup R, r • (V : set R) ⊆ U :=
⟨U.comap (add_monoid_hom.mul_left r) (continuous_mul_left r),
(U : set R).image_preimage_subset _⟩
/-- An open subgroup of a nonarchimedean ring contains the square of another one. -/
lemma mul_subset (U : open_add_subgroup R) :
∃ V : open_add_subgroup R, (V : set R) * V ⊆ U :=
let ⟨V, H⟩ := prod_self_subset (is_open.mem_nhds (is_open.preimage continuous_mul U.is_open)
begin
simpa only [set.mem_preimage, open_add_subgroup.mem_coe, prod.snd_zero, mul_zero]
using U.zero_mem,
end) in
begin
use V,
rintros v ⟨a, b, ha, hb, hv⟩,
have hy := H (set.mk_mem_prod ha hb),
simp only [set.mem_preimage, open_add_subgroup.mem_coe] at hy,
rwa hv at hy
end
end nonarchimedean_ring
|
4587afb18e0b84bd429beb06046617ee30333992 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/control/traversable/basic.lean | 27a3e00903ff4b4dc366002f667ca3f08d6c2fc2 | [
"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 | 5,598 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Simon Hudon
-/
import control.functor
/-!
# Traversable type class
Type classes for traversing collections. The concepts and laws are taken from
<http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-Traversable.html>
Traversable collections are a generalization of functors. Whereas
functors (such as `list`) allow us to apply a function to every
element, it does not allow functions which external effects encoded in
a monad. Consider for instance a functor `invite : email → io response`
that takes an email address, sends an email and waits for a
response. If we have a list `guests : list email`, using calling
`invite` using `map` gives us the following: `map invite guests : list
(io response)`. It is not what we need. We need something of type `io
(list response)`. Instead of using `map`, we can use `traverse` to
send all the invites: `traverse invite guests : io (list response)`.
`traverse` applies `invite` to every element of `guests` and combines
all the resulting effects. In the example, the effect is encoded in the
monad `io` but any applicative functor is accepted by `traverse`.
For more on how to use traversable, consider the Haskell tutorial:
<https://en.wikibooks.org/wiki/Haskell/Traversable>
## Main definitions
* `traversable` type class - exposes the `traverse` function
* `sequence` - based on `traverse`, turns a collection of effects into an effect returning a collection
* is_lawful_traversable - laws
## Tags
traversable iterator functor applicative
## References
* "Applicative Programming with Effects", by Conor McBride and Ross Paterson,
Journal of Functional Programming 18:1 (2008) 1-13, online at
<http://www.soi.city.ac.uk/~ross/papers/Applicative.html>
* "The Essence of the Iterator Pattern", by Jeremy Gibbons and Bruno Oliveira,
in Mathematically-Structured Functional Programming, 2006, online at
<http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator>
* "An Investigation of the Laws of Traversals", by Mauro Jaskelioff and Ondrej Rypacek,
in Mathematically-Structured Functional Programming, 2012,
online at <http://arxiv.org/pdf/1202.2919>
-/
open function (hiding comp)
universes u v w
section applicative_transformation
variables (F : Type u → Type v) [applicative F] [is_lawful_applicative F]
variables (G : Type u → Type w) [applicative G] [is_lawful_applicative G]
structure applicative_transformation : Type (max (u+1) v w) :=
(app : ∀ α : Type u, F α → G α)
(preserves_pure' : ∀ {α : Type u} (x : α), app _ (pure x) = pure x)
(preserves_seq' : ∀ {α β : Type u} (x : F (α → β)) (y : F α), app _ (x <*> y) = app _ x <*> app _ y)
end applicative_transformation
namespace applicative_transformation
variables (F : Type u → Type v) [applicative F] [is_lawful_applicative F]
variables (G : Type u → Type w) [applicative G] [is_lawful_applicative G]
instance : has_coe_to_fun (applicative_transformation F G) :=
{ F := λ _, Π {α}, F α → G α,
coe := λ a, a.app }
variables {F G}
variables (η : applicative_transformation F G)
@[functor_norm]
lemma preserves_pure : ∀ {α} (x : α), η (pure x) = pure x := η.preserves_pure'
@[functor_norm]
lemma preserves_seq :
∀ {α β : Type u} (x : F (α → β)) (y : F α), η (x <*> y) = η x <*> η y :=
η.preserves_seq'
@[functor_norm]
lemma preserves_map {α β} (x : α → β) (y : F α) : η (x <$> y) = x <$> η y :=
by rw [← pure_seq_eq_map, η.preserves_seq]; simp with functor_norm
end applicative_transformation
open applicative_transformation
class traversable (t : Type u → Type u) extends functor t :=
(traverse : Π {m : Type u → Type u} [applicative m] {α β},
(α → m β) → t α → m (t β))
open functor
export traversable (traverse)
section functions
variables {t : Type u → Type u}
variables {m : Type u → Type v} [applicative m]
variables {α β : Type u}
variables {f : Type u → Type u} [applicative f]
def sequence [traversable t] : t (f α) → f (t α) := traverse id
end functions
class is_lawful_traversable (t : Type u → Type u) [traversable t]
extends is_lawful_functor t : Type (u+1) :=
(id_traverse : ∀ {α} (x : t α), traverse id.mk x = x )
(comp_traverse : ∀ {F G} [applicative F] [applicative G]
[is_lawful_applicative F] [is_lawful_applicative G]
{α β γ} (f : β → F γ) (g : α → G β) (x : t α),
traverse (comp.mk ∘ map f ∘ g) x =
comp.mk (map (traverse f) (traverse g x)))
(traverse_eq_map_id : ∀ {α β} (f : α → β) (x : t α),
traverse (id.mk ∘ f) x = id.mk (f <$> x))
(naturality : ∀ {F G} [applicative F] [applicative G]
[is_lawful_applicative F] [is_lawful_applicative G]
(η : applicative_transformation F G) {α β} (f : α → F β) (x : t α),
η (traverse f x) = traverse (@η _ ∘ f) x)
instance : traversable id := ⟨λ _ _ _ _, id⟩
instance : is_lawful_traversable id := by refine {..}; intros; refl
section
variables {F : Type u → Type v} [applicative F]
instance : traversable option := ⟨@option.traverse⟩
instance : traversable list := ⟨@list.traverse⟩
end
namespace sum
variables {σ : Type u}
variables {F : Type u → Type u}
variables [applicative F]
protected def traverse {α β} (f : α → F β) : σ ⊕ α → F (σ ⊕ β)
| (sum.inl x) := pure (sum.inl x)
| (sum.inr x) := sum.inr <$> f x
end sum
instance {σ : Type u} : traversable.{u} (sum σ) := ⟨@sum.traverse _⟩
|
abf2251a446f2a154958312ef6109df17ce3a73c | aa2345b30d710f7e75f13157a35845ee6d48c017 | /order/complete_lattice.lean | 4d4b8a7a8d8876c6292c82d4d948918b1e750bd7 | [
"Apache-2.0"
] | permissive | CohenCyril/mathlib | 5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe | a12d5a192f5923016752f638d19fc1a51610f163 | refs/heads/master | 1,586,031,957,957 | 1,541,432,824,000 | 1,541,432,824,000 | 156,246,337 | 0 | 0 | Apache-2.0 | 1,541,434,514,000 | 1,541,434,513,000 | null | UTF-8 | Lean | false | false | 30,857 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Theory of complete lattices.
-/
import order.bounded_lattice data.set.basic tactic.pi_instances
set_option old_structure_cmd true
namespace lattice
universes u v w w₂
variables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂}
/-- class for the `Sup` operator -/
class has_Sup (α : Type u) := (Sup : set α → α)
/-- class for the `Inf` operator -/
class has_Inf (α : Type u) := (Inf : set α → α)
/-- Supremum of a set -/
def Sup [has_Sup α] : set α → α := has_Sup.Sup
/-- Infimum of a set -/
def Inf [has_Inf α] : set α → α := has_Inf.Inf
/-- A complete lattice is a bounded lattice which
has suprema and infima for every subset. -/
class complete_lattice (α : Type u) extends bounded_lattice α, has_Sup α, has_Inf α :=
(le_Sup : ∀s, ∀a∈s, a ≤ Sup s)
(Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a)
(Inf_le : ∀s, ∀a∈s, Inf s ≤ a)
(le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s)
/-- A complete linear order is a linear order whose lattice structure is complete. -/
class complete_linear_order (α : Type u) extends complete_lattice α, linear_order α
/-- Indexed supremum -/
def supr [complete_lattice α] (s : ι → α) : α := Sup {a : α | ∃i : ι, a = s i}
/-- Indexed infimum -/
def infi [complete_lattice α] (s : ι → α) : α := Inf {a : α | ∃i : ι, a = s i}
notation `⨆` binders `, ` r:(scoped f, supr f) := r
notation `⨅` binders `, ` r:(scoped f, infi f) := r
section
open set
variables [complete_lattice α] {s t : set α} {a b : α}
@[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a
theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a
@[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a
theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a
theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_Sup hb)
theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (Inf_le hb) h
theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t :=
Sup_le (assume a, assume ha : a ∈ s, le_Sup $ h ha)
theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s :=
le_Inf (assume a, assume ha : a ∈ s, Inf_le $ h ha)
@[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) :=
⟨assume : Sup s ≤ a, assume b, assume : b ∈ s,
le_trans (le_Sup ‹b ∈ s›) ‹Sup s ≤ a›,
Sup_le⟩
@[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) :=
⟨assume : a ≤ Inf s, assume b, assume : b ∈ s,
le_trans ‹a ≤ Inf s› (Inf_le ‹b ∈ s›),
le_Inf⟩
-- how to state this? instead a parameter `a`, use `∃a, a ∈ s` or `s ≠ ∅`?
theorem Inf_le_Sup (h : a ∈ s) : Inf s ≤ Sup s :=
by have := le_Sup h; finish
--Inf_le_of_le h (le_Sup h)
-- TODO: it is weird that we have to add union_def
theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t :=
le_antisymm
(by finish)
(sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _))
/- old proof:
le_antisymm
(Sup_le $ assume a h, or.rec_on h (le_sup_left_of_le ∘ le_Sup) (le_sup_right_of_le ∘ le_Sup))
(sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _))
-/
theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
by finish
/-
Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t))
-/
theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t :=
le_antisymm
(le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _))
(by finish)
/- old proof:
le_antisymm
(le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _))
(le_Inf $ assume a h, or.rec_on h (inf_le_left_of_le ∘ Inf_le) (inf_le_right_of_le ∘ Inf_le))
-/
theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
by finish
/-
le_Inf (assume a ⟨a_s, a_t⟩, sup_le (Inf_le a_s) (Inf_le a_t))
-/
@[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) :=
le_antisymm (by finish) (by finish)
-- le_antisymm (Sup_le (assume _, false.elim)) bot_le
@[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) :=
le_antisymm (by finish) (by finish)
--le_antisymm le_top (le_Inf (assume _, false.elim))
@[simp] theorem Sup_univ : Sup univ = (⊤ : α) :=
le_antisymm (by finish) (le_Sup ⟨⟩) -- finish fails because ⊤ ≤ a simplifies to a = ⊤
--le_antisymm le_top (le_Sup ⟨⟩)
@[simp] theorem Inf_univ : Inf univ = (⊥ : α) :=
le_antisymm (Inf_le ⟨⟩) bot_le
-- TODO(Jeremy): get this automatically
@[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s :=
have Sup {b | b = a} = a,
from le_antisymm (Sup_le $ assume b b_eq, b_eq ▸ le_refl _) (le_Sup rfl),
calc Sup (insert a s) = Sup {b | b = a} ⊔ Sup s : Sup_union
... = a ⊔ Sup s : by rw [this]
@[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s :=
have Inf {b | b = a} = a,
from le_antisymm (Inf_le rfl) (le_Inf $ assume b b_eq, b_eq ▸ le_refl _),
calc Inf (insert a s) = Inf {b | b = a} ⊓ Inf s : Inf_union
... = a ⊓ Inf s : by rw [this]
@[simp] theorem Sup_singleton {a : α} : Sup {a} = a :=
by finish [singleton_def]
--eq.trans Sup_insert $ by simp
@[simp] theorem Inf_singleton {a : α} : Inf {a} = a :=
by finish [singleton_def]
--eq.trans Inf_insert $ by simp
@[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) :=
iff.intro
(assume h a ha, top_unique $ h ▸ Inf_le ha)
(assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha)
@[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) :=
iff.intro
(assume h a ha, bot_unique $ h ▸ le_Sup ha)
(assume h, bot_unique $ Sup_le $ assume a ha, le_bot_iff.2 $ h a ha)
end
section complete_linear_order
variables [complete_linear_order α] {s t : set α} {a b : α}
lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) :=
iff.intro
(assume : Inf s < b, classical.by_contradiction $ assume : ¬ (∃a∈s, a < b),
have b ≤ Inf s,
from le_Inf $ assume a ha, le_of_not_gt $ assume h, this ⟨a, ha, h⟩,
lt_irrefl b (lt_of_le_of_lt ‹b ≤ Inf s› ‹Inf s < b›))
(assume ⟨a, ha, h⟩, lt_of_le_of_lt (Inf_le ha) h)
lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) :=
iff.intro
(assume : b < Sup s, classical.by_contradiction $ assume : ¬ (∃a∈s, b < a),
have Sup s ≤ b,
from Sup_le $ assume a ha, le_of_not_gt $ assume h, this ⟨a, ha, h⟩,
lt_irrefl b (lt_of_lt_of_le ‹b < Sup s› ‹Sup s ≤ b›))
(assume ⟨a, ha, h⟩, lt_of_lt_of_le h $ le_Sup ha)
lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) :=
iff.intro
(assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb)
(assume h, top_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h)
lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) :=
iff.intro
(assume (h : Inf s = ⊥) b (hb : ⊥ < b), by rwa [←h, Inf_lt_iff] at hb)
(assume h, bot_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_lt_of_le h (Inf_le ha))
lemma lt_supr_iff {ι : Sort*} {f : ι → α} : a < supr f ↔ (∃i, a < f i) :=
iff.trans lt_Sup_iff $ iff.intro
(assume ⟨a', ⟨i, rfl⟩, ha⟩, ⟨i, ha⟩)
(assume ⟨i, hi⟩, ⟨f i, ⟨i, rfl⟩, hi⟩)
lemma infi_lt_iff {ι : Sort*} {f : ι → α} : infi f < a ↔ (∃i, f i < a) :=
iff.trans Inf_lt_iff $ iff.intro
(assume ⟨a', ⟨i, rfl⟩, ha⟩, ⟨i, ha⟩)
(assume ⟨i, hi⟩, ⟨f i, ⟨i, rfl⟩, hi⟩)
end complete_linear_order
/- supr & infi -/
section
open set
variables [complete_lattice α] {s t : ι → α} {a b : α}
-- TODO: this declaration gives error when starting smt state
--@[ematch]
theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s :=
le_Sup ⟨i, rfl⟩
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) :=
le_Sup ⟨i, rfl⟩
/- TODO: this version would be more powerful, but, alas, the pattern matcher
doesn't accept it.
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) :=
le_Sup ⟨i, rfl⟩
-/
theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s :=
le_trans h (le_supr _ i)
theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a :=
Sup_le $ assume b ⟨i, eq⟩, eq.symm ▸ h i
theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t :=
supr_le $ assume i, le_supr_of_le i (h i)
theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t :=
supr_le $ assume j, exists.elim (h j) le_supr_of_le
theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) :=
supr_le $ le_supr _ ∘ h
@[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) :=
⟨assume : supr s ≤ a, assume i, le_trans (le_supr _ _) this, supr_le⟩
-- TODO: finish doesn't do well here.
@[congr] theorem supr_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ :=
le_antisymm
(supr_le_supr2 $ assume j, ⟨pq.mp j, le_of_eq $ f _⟩)
(supr_le_supr2 $ assume j, ⟨pq.mpr j, le_of_eq $ (f j).symm⟩)
theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i :=
Inf_le ⟨i, rfl⟩
@[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) :=
Inf_le ⟨i, rfl⟩
/- I wanted to see if this would help for infi_comm; it doesn't.
@[ematch] theorem infi_le₂' (s : ι → ι₂ → α) (i : ι) (j : ι₂): (: ⨅ i j, s i j :) ≤ (: s i j :) :=
begin
transitivity,
apply (infi_le (λ i, ⨅ j, s i j) i),
apply infi_le
end
-/
theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a :=
le_trans (infi_le _ i) h
theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s :=
le_Inf $ assume b ⟨i, eq⟩, eq.symm ▸ h i
theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t :=
le_infi $ assume i, infi_le_of_le i (h i)
theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t :=
le_infi $ assume j, exists.elim (h j) infi_le_of_le
theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) :=
le_infi $ infi_le _ ∘ h
@[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) :=
⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩
@[congr] theorem infi_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ :=
le_antisymm
(infi_le_infi2 $ assume j, ⟨pq.mpr j, le_of_eq $ f j⟩)
(infi_le_infi2 $ assume j, ⟨pq.mp j, le_of_eq $ (f _).symm⟩)
@[simp] theorem infi_const {a : α} : ∀[nonempty ι], (⨅ b:ι, a) = a
| ⟨i⟩ := le_antisymm (Inf_le ⟨i, rfl⟩) (by finish)
@[simp] theorem supr_const {a : α} : ∀[nonempty ι], (⨆ b:ι, a) = a
| ⟨i⟩ := le_antisymm (by finish) (le_Sup ⟨i, rfl⟩)
@[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ :=
top_unique $ le_infi $ assume i, le_refl _
@[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ :=
bot_unique $ supr_le $ assume i, le_refl _
@[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) :=
iff.intro
(assume eq i, top_unique $ eq ▸ infi_le _ _)
(assume h, top_unique $ le_infi $ assume i, top_le_iff.2 $ h i)
@[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) :=
iff.intro
(assume eq i, bot_unique $ eq ▸ le_supr _ _)
(assume h, bot_unique $ supr_le $ assume i, le_bot_iff.2 $ h i)
@[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp :=
le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _)
@[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ :=
le_antisymm le_top $ le_infi $ assume h, (hp h).elim
@[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp :=
le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _)
@[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ :=
le_antisymm (supr_le $ assume h, (hp h).elim) bot_le
-- TODO: should this be @[simp]?
theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i)
(le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j)
/- TODO: this is strange. In the proof below, we get exactly the desired
among the equalities, but close does not get it.
begin
apply @le_antisymm,
simp, intros,
begin [smt]
ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i),
trace_state, close
end
end
-/
-- TODO: should this be @[simp]?
theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) :=
le_antisymm
(supr_le $ assume i, supr_le $ assume j, le_supr_of_le j $ le_supr _ i)
(supr_le $ assume j, supr_le $ assume i, le_supr_of_le i $ le_supr _ j)
@[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
@[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
attribute [ematch] le_refl
theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) :=
le_antisymm
(le_inf
(le_infi $ assume i, infi_le_of_le i inf_le_left)
(le_infi $ assume i, infi_le_of_le i inf_le_right))
(le_infi $ assume i, le_inf
(inf_le_left_of_le $ infi_le _ _)
(inf_le_right_of_le $ infi_le _ _))
/- TODO: here is another example where more flexible pattern matching
might help.
begin
apply @le_antisymm,
safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end
end
-/
lemma infi_inf {f : ι → α} {a : α} (i : ι) : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) :=
le_antisymm
(le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) inf_le_right)
(le_inf (infi_le_infi $ assume i, inf_le_left) (infi_le_of_le i inf_le_right))
lemma inf_infi {f : ι → α} {a : α} (i : ι) : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) :=
by rw [inf_comm, infi_inf i]; simp [inf_comm]
lemma binfi_inf {ι : Sort*} {p : ι → Prop}
{f : Πi, p i → α} {a : α} {i : ι} (hi : p i) :
(⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume hi,
le_inf (inf_le_left_of_le $ infi_le_of_le i $ infi_le _ _) inf_le_right)
(le_inf (infi_le_infi $ assume i, infi_le_infi $ assume hi, inf_le_left)
(infi_le_of_le i $ infi_le_of_le hi $ inf_le_right))
theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) :=
le_antisymm
(supr_le $ assume i, sup_le
(le_sup_left_of_le $ le_supr _ _)
(le_sup_right_of_le $ le_supr _ _))
(sup_le
(supr_le $ assume i, le_supr_of_le i le_sup_left)
(supr_le $ assume i, le_supr_of_le i le_sup_right))
/- supr and infi under Prop -/
@[simp] theorem infi_false {s : false → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, false.elim i)
@[simp] theorem supr_false {s : false → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, false.elim i) bot_le
@[simp] theorem infi_true {s : true → α} : infi s = s trivial :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_true {s : true → α} : supr s = s trivial :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
@[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
@[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, s ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_or {p q : Prop} {s : p ∨ q → α} :
infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume i, match i with
| or.inl i := inf_le_left_of_le $ infi_le _ _
| or.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_or {p q : Prop} {s : p ∨ q → α} :
(⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| or.inl i := le_sup_left_of_le $ le_supr _ i
| or.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨or.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨or.inr j, le_refl _⟩))
theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) :=
le_antisymm
(le_infi $ assume b, le_infi $ assume h, Inf_le h)
(le_Inf $ assume b h, infi_le_of_le b $ infi_le _ h)
theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) :=
le_antisymm
(Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h)
(supr_le $ assume b, supr_le $ assume h, le_Sup h)
lemma Sup_range {f : ι → α} : Sup (range f) = supr f :=
le_antisymm
(Sup_le $ forall_range_iff.mpr $ assume i, le_supr _ _)
(supr_le $ assume i, le_Sup (mem_range_self _))
lemma Inf_range {f : ι → α} : Inf (range f) = infi f :=
le_antisymm
(le_infi $ assume i, Inf_le (mem_range_self _))
(le_Inf $ forall_range_iff.mpr $ assume i, infi_le _ _)
lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) :=
le_antisymm
(supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i)
(supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _))
lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) :=
le_antisymm
(le_infi $ assume i, infi_le_of_le (f i) $ infi_le (λp, g (f i)) (mem_range_self _))
(le_infi $ assume b, le_infi $ assume ⟨i, (h : f i = b)⟩, h ▸ infi_le _ i)
theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) :=
calc Inf (set.image f s) = (⨅a, ⨅h : ∃b, b ∈ s ∧ f b = a, a) : Inf_eq_infi
... = (⨅a, ⨅b, ⨅h : f b = a ∧ b ∈ s, a) : by simp [and_comm]
... = (⨅a, ⨅b, ⨅h : a = f b, ⨅h : b ∈ s, a) : by simp [infi_and, eq_comm]
... = (⨅b, ⨅a, ⨅h : a = f b, ⨅h : b ∈ s, a) : by rw [infi_comm]
... = (⨅a∈s, f a) : congr_arg infi $ by funext x; rw [infi_infi_eq_left]
theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) :=
calc Sup (set.image f s) = (⨆a, ⨆h : ∃b, b ∈ s ∧ f b = a, a) : Sup_eq_supr
... = (⨆a, ⨆b, ⨆h : f b = a ∧ b ∈ s, a) : by simp [and_comm]
... = (⨆a, ⨆b, ⨆h : a = f b, ⨆h : b ∈ s, a) : by simp [supr_and, eq_comm]
... = (⨆b, ⨆a, ⨆h : a = f b, ⨆h : b ∈ s, a) : by rw [supr_comm]
... = (⨆a∈s, f a) : congr_arg supr $ by funext x; rw [supr_supr_eq_left]
/- supr and infi under set constructions -/
/- should work using the simplifier! -/
@[simp] theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ :=
le_antisymm le_top (le_infi $ assume x, le_infi false.elim)
@[simp] theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ :=
le_antisymm (supr_le $ assume x, supr_le false.elim) bot_le
@[simp] theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) :=
show (⨅ (x : β) (H : true), f x) = ⨅ (x : β), f x,
from congr_arg infi $ funext $ assume x, infi_const
@[simp] theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) :=
show (⨆ (x : β) (H : true), f x) = ⨆ (x : β), f x,
from congr_arg supr $ funext $ assume x, supr_const
@[simp] theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) :=
calc (⨅ x ∈ s ∪ t, f x) = (⨅ x, (⨅h : x∈s, f x) ⊓ (⨅h : x∈t, f x)) : congr_arg infi $ funext $ assume x, infi_or
... = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) : infi_inf_eq
@[simp] theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) :=
calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg supr $ funext $ assume x, supr_or
... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq
@[simp] theorem insert_of_has_insert (x : α) (a : set α) : has_insert.insert x a = insert x a := rfl
@[simp] theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) :=
eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left
@[simp] theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) :=
eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left
@[simp] theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b :=
show (⨅ x ∈ insert b (∅ : set β), f x) = f b,
by simp
@[simp] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b :=
show (⨆ x ∈ insert b (∅ : set β), f x) = f b,
by simp
/- supr and infi under Type -/
@[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, empty.rec_on _ i)
@[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, empty.rec_on _ i) bot_le
@[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff :=
le_antisymm
(supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end)
(sup_le (le_supr _ _) (le_supr _ _))
lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff :=
le_antisymm
(le_inf (infi_le _ _) (infi_le _ _))
(le_infi $ assume b, match b with tt := inf_le_left | ff := inf_le_right end)
theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_sigma {p : β → Type w} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_sigma {p : β → Type w} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_prod {γ : Type w} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_prod {γ : Type w} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, f ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_sum {γ : Type w} {f : β ⊕ γ → α} :
(⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume i, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume s, match s with
| sum.inl i := inf_le_left_of_le $ infi_le _ _
| sum.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_sum {γ : Type w} {f : β ⊕ γ → α} :
(⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| sum.inl i := le_sup_left_of_le $ le_supr _ i
| sum.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨sum.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨sum.inr j, le_refl _⟩))
end
section complete_linear_order
variables [complete_linear_order α]
lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) :=
by rw [← Sup_range, Sup_eq_top];
from forall_congr (assume b, forall_congr (assume hb, set.exists_range_iff))
lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, b > f i) :=
by rw [← Inf_range, Inf_eq_bot];
from forall_congr (assume b, forall_congr (assume hb, set.exists_range_iff))
end complete_linear_order
/- Instances -/
instance complete_lattice_Prop : complete_lattice Prop :=
{ Sup := λs, ∃a∈s, a,
le_Sup := assume s a h p, ⟨a, h, p⟩,
Sup_le := assume s a h ⟨b, h', p⟩, h b h' p,
Inf := λs, ∀a:Prop, a∈s → a,
Inf_le := assume s a h p, p a h,
le_Inf := assume s a h p b hb, h b hb p,
..lattice.bounded_lattice_Prop }
lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl
lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl
lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) :=
le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq.symm ▸ h i)
lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) :=
le_antisymm (assume ⟨q, ⟨i, (eq : q = p i)⟩, hq⟩, ⟨i, eq ▸ hq⟩) (assume ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩)
instance pi.complete_lattice {α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] :
complete_lattice (Π i, β i) :=
by { pi_instance;
{ intros, intro,
apply_field, intros,
simp at H, rcases H with ⟨ x, H₀, H₁ ⟩,
subst b, apply a_1 _ H₀ i, } }
lemma Inf_apply
{α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] {s : set (Πa, β a)} {a : α} :
(Inf s) a = (⨅f∈s, (f : Πa, β a) a) :=
by rw [← Inf_image]; refl
lemma infi_apply {α : Type u} {β : α → Type v} {ι : Sort*} [∀ i, complete_lattice (β i)]
{f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) :=
by rw [← Inf_range, Inf_apply, infi_range]
lemma Sup_apply
{α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] {s : set (Πa, β a)} {a : α} :
(Sup s) a = (⨆f∈s, (f : Πa, β a) a) :=
by rw [← Sup_image]; refl
lemma supr_apply {α : Type u} {β : α → Type v} {ι : Sort*} [∀ i, complete_lattice (β i)]
{f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) :=
by rw [← Sup_range, Sup_apply, supr_range]
section complete_lattice
variables [preorder α] [complete_lattice β]
theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) :=
assume x y h, Sup_le $ assume x' ⟨f, f_in, fx_eq⟩, le_Sup_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h
theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) :=
assume x y h, le_Inf $ assume x' ⟨f, f_in, fx_eq⟩, Inf_le_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h
end complete_lattice
section ord_continuous
open lattice
variables [complete_lattice α] [complete_lattice β]
/-- A function `f` between complete lattices is order-continuous
if it preserves all suprema. -/
def ord_continuous (f : α → β) := ∀s : set α, f (Sup s) = (⨆i∈s, f i)
lemma ord_continuous_sup {f : α → β} {a₁ a₂ : α} (hf : ord_continuous f) : f (a₁ ⊔ a₂) = f a₁ ⊔ f a₂ :=
have h : f (Sup {a₁, a₂}) = (⨆i∈({a₁, a₂} : set α), f i), from hf _,
have h₁ : {a₁, a₂} = (insert a₂ {a₁} : set α), from rfl,
begin
rw [h₁, Sup_insert, Sup_singleton, sup_comm] at h,
rw [h, supr_insert, supr_singleton, sup_comm]
end
lemma ord_continuous_mono {f : α → β} (hf : ord_continuous f) : monotone f :=
assume a₁ a₂ h,
calc f a₁ ≤ f a₁ ⊔ f a₂ : le_sup_left
... = f (a₁ ⊔ a₂) : (ord_continuous_sup hf).symm
... = _ : by rw [sup_of_le_right h]
end ord_continuous
end lattice
namespace order_dual
open lattice
variable (α : Type*)
instance [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩
instance [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩
instance [complete_lattice α] : complete_lattice (order_dual α) :=
{ le_Sup := @complete_lattice.Inf_le α _,
Sup_le := @complete_lattice.le_Inf α _,
Inf_le := @complete_lattice.le_Sup α _,
le_Inf := @complete_lattice.Sup_le α _,
.. order_dual.lattice.bounded_lattice α, ..order_dual.lattice.has_Sup α, ..order_dual.lattice.has_Inf α }
end order_dual
|
6d826c8ed5ab0e34f598c7088b78234e3d4eda23 | fe208a542cea7b2d6d7ff79f94d535f6d11d814a | /src/Logic/gabriel_framework.lean | 2e986330f0b91f8ffe85ef99aa3aac94462eb1e3 | [] | no_license | ImperialCollegeLondon/M1F_room_342_questions | c4b98b14113fe900a7f388762269305faff73e63 | 63de9a6ab9c27a433039dd5530bc9b10b1d227f7 | refs/heads/master | 1,585,807,312,561 | 1,545,232,972,000 | 1,545,232,972,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 676 | lean | inductive fml
| atom (i : ℕ)
| imp (a b : fml)
| not (a : fml)
open fml
infixr ` →' `:50 := imp -- right associative
prefix `¬' `:40 := fml.not
inductive prf : fml → Type
| axk (p q) : prf (p →' q →' p)
| axs (p q r) : prf $ (p →' q →' r) →' (p →' q) →' (p →' r)
| axX (p q) : prf $ ((¬' q) →' (¬' p)) →' p →' q
| mp {p q} : prf (p →' q) → prf p → prf q -- bracket change
open prf
-- example usage:
/-
lemma p_of_p_of_p_of_q (p q : fml) : prf $ (p →' q) →' (p →' p) :=
begin
apply mp (axs p q p),
exact (axk p q)
end
-/
lemma Q6a (p : fml) : prf $ p →' p := sorry
theorem Q6b (p : fml) : prf $ p →' ¬' ¬' p := sorry |
7b147654be2af0dcfd3e4e0688c900bb09ad26bf | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/measure_theory/group.lean | febdb5faa917b261c59e3d302a7d8da2cf3ad90b | [
"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 | 4,371 | 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.borel_space
/-!
# Measures on Groups
We develop some properties of measures on (topological) groups
* We define properties on measures: left and right invariant measures
* We define the conjugate `A ↦ μ (A⁻¹)` of a measure `μ`, and show that it is right invariant iff
`μ` is left invariant
-/
noncomputable theory
open has_inv set function
namespace measure_theory
variables {G : Type*}
section
variables [measurable_space G] [has_mul G]
/-- A measure `μ` on a topological group is left invariant if
for all measurable sets `s` and all `g`, we have `μ (gs) = μ s`,
where `gs` denotes the translate of `s` by left multiplication with `g`. -/
def is_left_invariant (μ : set G → ennreal) : Prop :=
∀ (g : G) {A : set G} (h : is_measurable A), μ ((λ h, g * h) ⁻¹' A) = μ A
/-- A measure `μ` on a topological group is right invariant if
for all measurable sets `s` and all `g`, we have `μ (sg) = μ s`,
where `sg` denotes the translate of `s` by right multiplication with `g`. -/
def is_right_invariant (μ : set G → ennreal) : Prop :=
∀ (g : G) {A : set G} (h : is_measurable A), μ ((λ h, h * g) ⁻¹' A) = μ A
end
namespace measure
variables [measurable_space G]
lemma map_mul_left_eq_self [topological_space G] [has_mul G] [has_continuous_mul G] [borel_space G]
{μ : measure G} : (∀ g, measure.map ((*) g) μ = μ) ↔ is_left_invariant μ :=
begin
apply forall_congr, intro g, rw [measure.ext_iff], apply forall_congr, intro A,
apply forall_congr, intro hA, rw [map_apply (measurable_mul_left g) hA]
end
lemma map_mul_right_eq_self [topological_space G] [has_mul G] [has_continuous_mul G] [borel_space G]
{μ : measure G} : (∀ g, measure.map (λ h, h * g) μ = μ) ↔ is_right_invariant μ :=
begin
apply forall_congr, intro g, rw [measure.ext_iff], apply forall_congr, intro A,
apply forall_congr, intro hA, rw [map_apply (measurable_mul_right g) hA]
end
/-- The conjugate of a measure on a topological group.
Defined to be `A ↦ μ (A⁻¹)`, where `A⁻¹` is the pointwise inverse of `A`. -/
protected def conj [group G] (μ : measure G) : measure G :=
measure.map inv μ
variables [group G] [topological_space G] [topological_group G] [borel_space G]
lemma conj_apply (μ : measure G) {s : set G} (hs : is_measurable s) :
μ.conj s = μ s⁻¹ :=
by { unfold measure.conj, rw [measure.map_apply measurable_inv hs, inv_preimage] }
@[simp] lemma conj_conj (μ : measure G) : μ.conj.conj = μ :=
begin
ext1 s hs, rw [μ.conj.conj_apply hs, μ.conj_apply, set.inv_inv], exact measurable_inv hs
end
variables {μ : measure G}
lemma regular.conj [t2_space G] (hμ : μ.regular) : μ.conj.regular :=
hμ.map (homeomorph.inv G)
end measure
section conj
variables [measurable_space G] [group G] [topological_space G] [topological_group G] [borel_space G]
{μ : measure G}
@[simp] lemma regular_conj_iff [t2_space G] : μ.conj.regular ↔ μ.regular :=
by { refine ⟨λ h, _, measure.regular.conj⟩, rw ←μ.conj_conj, exact measure.regular.conj h }
lemma is_right_invariant_conj' (h : is_left_invariant μ) :
is_right_invariant μ.conj :=
begin
intros g A hA, rw [μ.conj_apply (measurable_mul_right g hA), μ.conj_apply hA],
convert h g⁻¹ (measurable_inv hA) using 2,
simp only [←preimage_comp, ← inv_preimage],
apply preimage_congr, intro h, simp only [mul_inv_rev, comp_app, inv_inv]
end
lemma is_left_invariant_conj' (h : is_right_invariant μ) : is_left_invariant μ.conj :=
begin
intros g A hA, rw [μ.conj_apply (measurable_mul_left g hA), μ.conj_apply hA],
convert h g⁻¹ (measurable_inv hA) using 2,
simp only [←preimage_comp, ← inv_preimage],
apply preimage_congr, intro h, simp only [mul_inv_rev, comp_app, inv_inv]
end
@[simp] lemma is_right_invariant_conj : is_right_invariant μ.conj ↔ is_left_invariant μ :=
by { refine ⟨λ h, _, is_right_invariant_conj'⟩, rw ←μ.conj_conj, exact is_left_invariant_conj' h }
@[simp] lemma is_left_invariant_conj : is_left_invariant μ.conj ↔ is_right_invariant μ :=
by { refine ⟨λ h, _, is_left_invariant_conj'⟩, rw ←μ.conj_conj, exact is_right_invariant_conj' h }
end conj
end measure_theory
|
34fa222164fc59ba68afcba34c527414730126ef | 46125763b4dbf50619e8846a1371029346f4c3db | /src/topology/algebra/uniform_group.lean | 592f0d34e1d2029aa875082e9d6bb0b77f304244 | [
"Apache-2.0"
] | permissive | thjread/mathlib | a9d97612cedc2c3101060737233df15abcdb9eb1 | 7cffe2520a5518bba19227a107078d83fa725ddc | refs/heads/master | 1,615,637,696,376 | 1,583,953,063,000 | 1,583,953,063,000 | 246,680,271 | 0 | 0 | Apache-2.0 | 1,583,960,875,000 | 1,583,960,875,000 | null | UTF-8 | Lean | false | false | 19,570 | 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
Uniform structure on 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.
* extension of ℤ-bilinear maps to complete groups (useful for ring completions)
* `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 topology.uniform_space.uniform_embedding topology.uniform_space.complete_separated
import topology.algebra.group tactic.abel
noncomputable theory
open_locale classical uniformity topological_space
section uniform_add_group
open filter set
variables {α : Type*} {β : Type*}
/-- A uniform (additive) group is a group in which the addition and negation are
uniformly continuous. -/
class uniform_add_group (α : Type*) [uniform_space α] [add_group α] : Prop :=
(uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2))
theorem uniform_add_group.mk' {α} [uniform_space α] [add_group α]
(h₁ : uniform_continuous (λp:α×α, p.1 + p.2))
(h₂ : uniform_continuous (λp:α, -p)) : uniform_add_group α :=
⟨h₁.comp (uniform_continuous_fst.prod_mk (h₂.comp uniform_continuous_snd))⟩
variables [uniform_space α] [add_group α] [uniform_add_group α]
lemma uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2) :=
uniform_add_group.uniform_continuous_sub α
lemma uniform_continuous.sub [uniform_space β] {f : β → α} {g : β → α}
(hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x - g x) :=
uniform_continuous_sub.comp (hf.prod_mk hg)
lemma uniform_continuous.neg [uniform_space β] {f : β → α}
(hf : uniform_continuous f) : uniform_continuous (λx, - f x) :=
have uniform_continuous (λx, 0 - f x),
from uniform_continuous_const.sub hf,
by simp * at *
lemma uniform_continuous_neg : uniform_continuous (λx:α, - x) :=
uniform_continuous_id.neg
lemma uniform_continuous.add [uniform_space β] {f : β → α} {g : β → α}
(hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x + g x) :=
have uniform_continuous (λx, f x - - g x), from hf.sub hg.neg,
by simp [*, sub_eq_add_neg] at *
lemma uniform_continuous_add : uniform_continuous (λp:α×α, p.1 + p.2) :=
uniform_continuous_fst.add uniform_continuous_snd
@[priority 10]
instance uniform_add_group.to_topological_add_group : topological_add_group α :=
{ continuous_add := uniform_continuous_add.continuous,
continuous_neg := uniform_continuous_neg.continuous }
instance [uniform_space β] [add_group β] [uniform_add_group β] : uniform_add_group (α × β) :=
⟨((uniform_continuous_fst.comp uniform_continuous_fst).sub
(uniform_continuous_fst.comp uniform_continuous_snd)).prod_mk
((uniform_continuous_snd.comp uniform_continuous_fst).sub
(uniform_continuous_snd.comp uniform_continuous_snd))⟩
lemma uniformity_translate (a : α) : (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) = 𝓤 α :=
le_antisymm
(uniform_continuous_id.add uniform_continuous_const)
(calc 𝓤 α =
((𝓤 α).map (λx:α×α, (x.1 + -a, x.2 + -a))).map (λx:α×α, (x.1 + a, x.2 + a)) :
by simp [filter.map_map, (∘)]; exact filter.map_id.symm
... ≤ (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) :
filter.map_mono (uniform_continuous_id.add uniform_continuous_const))
lemma uniform_embedding_translate (a : α) : uniform_embedding (λx:α, x + a) :=
{ comap_uniformity := begin
rw [← uniformity_translate a, comap_map] {occs := occurrences.pos [1]},
rintros ⟨p₁, p₂⟩ ⟨q₁, q₂⟩,
simp [prod.eq_iff_fst_eq_snd_eq] {contextual := tt}
end,
inj := assume x y, eq_of_add_eq_add_right }
section
variables (α)
lemma uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λx:α×α, x.2 - x.1) (𝓝 (0:α)) :=
begin
rw [nhds_eq_comap_uniformity, filter.comap_comap_comp],
refine le_antisymm (filter.map_le_iff_le_comap.1 _) _,
{ assume s hs,
rcases mem_uniformity_of_uniform_continuous_invariant uniform_continuous_sub hs with ⟨t, ht, hts⟩,
refine mem_map.2 (mem_sets_of_superset ht _),
rintros ⟨a, b⟩,
simpa [subset_def] using hts a b a },
{ assume s hs,
rcases mem_uniformity_of_uniform_continuous_invariant uniform_continuous_add hs with ⟨t, ht, hts⟩,
refine ⟨_, ht, _⟩,
rintros ⟨a, b⟩, simpa [subset_def] using hts 0 (b - a) a }
end
end
lemma group_separation_rel (x y : α) : (x, y) ∈ separation_rel α ↔ x - y ∈ closure ({0} : set α) :=
have embedding (λa, a + (y - x)), from (uniform_embedding_translate (y - x)).embedding,
show (x, y) ∈ ⋂₀ (𝓤 α).sets ↔ x - y ∈ closure ({0} : set α),
begin
rw [this.closure_eq_preimage_closure_image, uniformity_eq_comap_nhds_zero α, sInter_comap_sets],
simp [mem_closure_iff_nhds, inter_singleton_nonempty, sub_eq_add_neg]
end
lemma uniform_continuous_of_tendsto_zero [uniform_space β] [add_group β] [uniform_add_group β]
{f : α → β} [is_add_group_hom f] (h : tendsto f (𝓝 0) (𝓝 0)) :
uniform_continuous f :=
begin
have : ((λx:β×β, x.2 - x.1) ∘ (λx:α×α, (f x.1, f x.2))) = (λx:α×α, f (x.2 - x.1)),
{ simp only [is_add_group_hom.map_sub f] },
rw [uniform_continuous, uniformity_eq_comap_nhds_zero α, uniformity_eq_comap_nhds_zero β,
tendsto_comap_iff, this],
exact tendsto.comp h tendsto_comap
end
lemma uniform_continuous_of_continuous [uniform_space β] [add_group β] [uniform_add_group β]
{f : α → β} [is_add_group_hom f] (h : continuous f) :
uniform_continuous f :=
uniform_continuous_of_tendsto_zero $
suffices tendsto f (𝓝 0) (𝓝 (f 0)), by rwa [is_add_group_hom.map_zero f] at this,
h.tendsto 0
end uniform_add_group
section topological_add_comm_group
universes u v w x
open filter
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) (𝓝 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) (𝓝 0)) (𝓝 (-0)),
{ simpa [(∘), tendsto_comap_iff] },
exact tendsto.comp (tendsto.neg tendsto_id) tendsto_comap
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) (𝓝 (0 : G)),
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 [sub_eq_add_neg, add_comm, add_left_comm] 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) (𝓝 (0 : G)),
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' : 𝓤 G = comap (λp:G×G, p.2 - p.1) (𝓝 (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)) ((𝓝 0).prod (𝓝 0)))
(𝓝 (0 - 0)) :=
(tendsto_fst.sub tendsto_snd).comp tendsto_comap,
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 [(∘), sub_eq_add_neg, add_comm, add_left_comm] using this
end
end
lemma to_uniform_space_eq {α : Type*} [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 α) = 𝓤 α,
rw [uniformity_eq_comap_nhds_zero' α, uniformity_eq_comap_nhds_zero α]
end
end topological_add_comm_group
namespace add_comm_group
section Z_bilin
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables [add_comm_group α] [add_comm_group β] [add_comm_group γ]
/- TODO: when modules are changed to have more explicit base ring, then change replace `is_Z_bilin`
by using `is_bilinear_map ℤ` from `tensor_product`. -/
class is_Z_bilin (f : α × β → γ) : Prop :=
(add_left : ∀ a a' b, f (a + a', b) = f (a, b) + f (a', b))
(add_right : ∀ a b b', f (a, b + b') = f (a, b) + f (a, b'))
variables (f : α × β → γ) [is_Z_bilin f]
instance is_Z_bilin.comp_hom {g : γ → δ} [add_comm_group δ] [is_add_group_hom g] :
is_Z_bilin (g ∘ f) :=
by constructor; simp [(∘), is_Z_bilin.add_left f, is_Z_bilin.add_right f, is_add_hom.map_add g]
instance is_Z_bilin.comp_swap : is_Z_bilin (f ∘ prod.swap) :=
⟨λ a a' b, is_Z_bilin.add_right f b a a',
λ a b b', is_Z_bilin.add_left f b b' a⟩
lemma is_Z_bilin.zero_left : ∀ b, f (0, b) = 0 :=
begin
intro b,
apply add_self_iff_eq_zero.1,
rw ←is_Z_bilin.add_left f,
simp
end
lemma is_Z_bilin.zero_right : ∀ a, f (a, 0) = 0 :=
is_Z_bilin.zero_left (f ∘ prod.swap)
lemma is_Z_bilin.zero : f (0, 0) = 0 :=
is_Z_bilin.zero_left f 0
lemma is_Z_bilin.neg_left : ∀ a b, f (-a, b) = -f (a, b) :=
begin
intros a b,
apply eq_of_sub_eq_zero,
rw [sub_eq_add_neg, neg_neg, ←is_Z_bilin.add_left f, neg_add_self, is_Z_bilin.zero_left f]
end
lemma is_Z_bilin.neg_right : ∀ a b, f (a, -b) = -f (a, b) :=
assume a b, is_Z_bilin.neg_left (f ∘ prod.swap) b a
lemma is_Z_bilin.sub_left : ∀ a a' b, f (a - a', b) = f (a, b) - f (a', b) :=
begin
intros,
simp [sub_eq_add_neg],
rw [is_Z_bilin.add_left f, is_Z_bilin.neg_left f]
end
lemma is_Z_bilin.sub_right : ∀ a b b', f (a, b - b') = f (a, b) - f (a,b') :=
assume a b b', is_Z_bilin.sub_left (f ∘ prod.swap) b b' a
end Z_bilin
end add_comm_group
open add_comm_group filter set function
section
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
-- α, β and G are abelian topological groups, G is a uniform space
variables [topological_space α] [add_comm_group α]
variables [topological_space β] [add_comm_group β]
variables {G : Type*} [uniform_space G] [add_comm_group G]
variables {ψ : α × β → G} (hψ : continuous ψ) [ψbilin : is_Z_bilin ψ]
include hψ ψbilin
lemma is_Z_bilin.tendsto_zero_left (x₁ : α) : tendsto ψ (𝓝 (x₁, 0)) (𝓝 0) :=
begin
have := hψ.tendsto (x₁, 0),
rwa [is_Z_bilin.zero_right ψ] at this
end
lemma is_Z_bilin.tendsto_zero_right (y₁ : β) : tendsto ψ (𝓝 (0, y₁)) (𝓝 0) :=
begin
have := hψ.tendsto (0, y₁),
rwa [is_Z_bilin.zero_left ψ] at this
end
end
section
variables {α : Type*} {β : Type*}
variables [topological_space α] [add_comm_group α] [topological_add_group α]
-- β is a dense subgroup of α, inclusion is denoted by e
variables [topological_space β] [add_comm_group β]
variables {e : β → α} [is_add_group_hom e] (de : dense_inducing e)
include de
lemma tendsto_sub_comap_self (x₀ : α) :
tendsto (λt:β×β, t.2 - t.1) (comap (λp:β×β, (e p.1, e p.2)) $ 𝓝 (x₀, x₀)) (𝓝 0) :=
begin
have comm : (λx:α×α, x.2-x.1) ∘ (λt:β×β, (e t.1, e t.2)) = e ∘ (λt:β×β, t.2 - t.1),
{ ext t,
change e t.2 - e t.1 = e (t.2 - t.1),
rwa ← is_add_group_hom.map_sub e t.2 t.1 },
have lim : tendsto (λ x : α × α, x.2-x.1) (𝓝 (x₀, x₀)) (𝓝 (e 0)),
{ have := (continuous_sub.comp continuous_swap).tendsto (x₀, x₀),
simpa [-sub_eq_add_neg, sub_self, eq.symm (is_add_group_hom.map_zero e)] using this },
have := de.tendsto_comap_nhds_nhds lim comm,
simp [-sub_eq_add_neg, this]
end
end
namespace dense_inducing
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables {G : Type*}
-- β is a dense subgroup of α, inclusion is denoted by e
-- δ is a dense subgroup of γ, inclusion is denoted by f
variables [topological_space α] [add_comm_group α] [topological_add_group α]
variables [topological_space β] [add_comm_group β] [topological_add_group β]
variables [topological_space γ] [add_comm_group γ] [topological_add_group γ]
variables [topological_space δ] [add_comm_group δ] [topological_add_group δ]
variables [uniform_space G] [add_comm_group G] [uniform_add_group G] [separated G] [complete_space G]
variables {e : β → α} [is_add_group_hom e] (de : dense_inducing e)
variables {f : δ → γ} [is_add_group_hom f] (df : dense_inducing f)
variables {φ : β × δ → G} (hφ : continuous φ) [bilin : is_Z_bilin φ]
include de df hφ bilin
variables {W' : set G} (W'_nhd : W' ∈ 𝓝 (0 : G))
include W'_nhd
private lemma extend_Z_bilin_aux (x₀ : α) (y₁ : δ) :
∃ U₂ ∈ comap e (𝓝 x₀), ∀ x x' ∈ U₂, φ (x' - x, y₁) ∈ W' :=
begin
let Nx := 𝓝 x₀,
let ee := λ u : β × β, (e u.1, e u.2),
have lim1 : tendsto (λ a : β × β, (a.2 - a.1, y₁)) (filter.prod (comap e Nx) (comap e Nx)) (𝓝 (0, y₁)),
{ have := tendsto.prod_mk (tendsto_sub_comap_self de x₀) (tendsto_const_nhds : tendsto (λ (p : β × β), y₁) (comap ee $ 𝓝 (x₀, x₀)) (𝓝 y₁)),
rw [nhds_prod_eq, prod_comap_comap_eq, ←nhds_prod_eq],
exact (this : _) },
have lim := tendsto.comp (is_Z_bilin.tendsto_zero_right hφ y₁) lim1,
rw tendsto_prod_self_iff at lim,
exact lim W' W'_nhd,
end
private lemma extend_Z_bilin_key (x₀ : α) (y₀ : γ) :
∃ U ∈ comap e (𝓝 x₀), ∃ V ∈ comap f (𝓝 y₀),
∀ x x' ∈ U, ∀ y y' ∈ V, φ (x', y') - φ (x, y) ∈ W' :=
begin
let Nx := 𝓝 x₀,
let Ny := 𝓝 y₀,
let dp := dense_inducing.prod de df,
let ee := λ u : β × β, (e u.1, e u.2),
let ff := λ u : δ × δ, (f u.1, f u.2),
have lim_φ : filter.tendsto φ (𝓝 (0, 0)) (𝓝 0),
{ have := hφ.tendsto (0, 0),
rwa [is_Z_bilin.zero φ] at this },
have lim_φ_sub_sub : tendsto (λ (p : (β × β) × (δ × δ)), φ (p.1.2 - p.1.1, p.2.2 - p.2.1))
(filter.prod (comap ee $ 𝓝 (x₀, x₀)) (comap ff $ 𝓝 (y₀, y₀))) (𝓝 0),
{ have lim_sub_sub : tendsto (λ (p : (β × β) × δ × δ), (p.1.2 - p.1.1, p.2.2 - p.2.1))
(filter.prod (comap ee (𝓝 (x₀, x₀))) (comap ff (𝓝 (y₀, y₀)))) (filter.prod (𝓝 0) (𝓝 0)),
{ have := filter.prod_mono (tendsto_sub_comap_self de x₀) (tendsto_sub_comap_self df y₀),
rwa prod_map_map_eq at this },
rw ← nhds_prod_eq at lim_sub_sub,
exact tendsto.comp lim_φ lim_sub_sub },
rcases exists_nhds_quarter W'_nhd with ⟨W, W_nhd, W4⟩,
have : ∃ U₁ ∈ comap e (𝓝 x₀), ∃ V₁ ∈ comap f (𝓝 y₀),
∀ x x' ∈ U₁, ∀ y y' ∈ V₁, φ (x'-x, y'-y) ∈ W,
{ have := tendsto_prod_iff.1 lim_φ_sub_sub W W_nhd,
repeat { rw [nhds_prod_eq, ←prod_comap_comap_eq] at this },
rcases this with ⟨U, U_in, V, V_in, H⟩,
rw [mem_prod_same_iff] at U_in V_in,
rcases U_in with ⟨U₁, U₁_in, HU₁⟩,
rcases V_in with ⟨V₁, V₁_in, HV₁⟩,
existsi [U₁, U₁_in, V₁, V₁_in],
intros x x' x_in x'_in y y' y_in y'_in,
exact H _ _ (HU₁ (mk_mem_prod x_in x'_in)) (HV₁ (mk_mem_prod y_in y'_in)) },
rcases this with ⟨U₁, U₁_nhd, V₁, V₁_nhd, H⟩,
obtain ⟨x₁, x₁_in⟩ : U₁.nonempty :=
(forall_sets_nonempty_iff_ne_bot.2 de.comap_nhds_ne_bot U₁ U₁_nhd),
obtain ⟨y₁, y₁_in⟩ : V₁.nonempty :=
(forall_sets_nonempty_iff_ne_bot.2 df.comap_nhds_ne_bot V₁ V₁_nhd),
rcases (extend_Z_bilin_aux de df hφ W_nhd x₀ y₁) with ⟨U₂, U₂_nhd, HU⟩,
rcases (extend_Z_bilin_aux df de (hφ.comp continuous_swap) W_nhd y₀ x₁) with ⟨V₂, V₂_nhd, HV⟩,
existsi [U₁ ∩ U₂, inter_mem_sets U₁_nhd U₂_nhd,
V₁ ∩ V₂, inter_mem_sets V₁_nhd V₂_nhd],
rintros x x' ⟨xU₁, xU₂⟩ ⟨x'U₁, x'U₂⟩ y y' ⟨yV₁, yV₂⟩ ⟨y'V₁, y'V₂⟩,
have key_formula : φ(x', y') - φ(x, y) = φ(x' - x, y₁) + φ(x' - x, y' - y₁) + φ(x₁, y' - y) + φ(x - x₁, y' - y),
{ repeat { rw is_Z_bilin.sub_left φ },
repeat { rw is_Z_bilin.sub_right φ },
apply eq_of_sub_eq_zero,
simp [sub_eq_add_neg], abel },
rw key_formula,
have h₁ := HU x x' xU₂ x'U₂,
have h₂ := H x x' xU₁ x'U₁ y₁ y' y₁_in y'V₁,
have h₃ := HV y y' yV₂ y'V₂,
have h₄ := H x₁ x x₁_in xU₁ y y' yV₁ y'V₁,
exact W4 h₁ h₂ h₃ h₄
end
omit W'_nhd
open dense_inducing
/-- Bourbaki GT III.6.5 Theorem I:
ℤ-bilinear continuous maps from dense images into a complete Hausdorff group extend by continuity.
Note: Bourbaki assumes that α and β are also complete Hausdorff, but this is not necessary. -/
theorem extend_Z_bilin : continuous (extend (de.prod df) φ) :=
begin
refine continuous_extend_of_cauchy _ _,
rintro ⟨x₀, y₀⟩,
split,
{ apply map_ne_bot,
apply comap_ne_bot,
intros U h,
rcases mem_closure_iff_nhds.1 ((de.prod df).dense (x₀, y₀)) U h with ⟨x, x_in, ⟨z, z_x⟩⟩,
existsi z,
cc },
{ suffices : map (λ (p : (β × δ) × (β × δ)), φ p.2 - φ p.1)
(comap (λ (p : (β × δ) × β × δ), ((e p.1.1, f p.1.2), (e p.2.1, f p.2.2)))
(filter.prod (𝓝 (x₀, y₀)) (𝓝 (x₀, y₀)))) ≤ 𝓝 0,
by rwa [uniformity_eq_comap_nhds_zero G, prod_map_map_eq, ←map_le_iff_le_comap, filter.map_map,
prod_comap_comap_eq],
intros W' W'_nhd,
have key := extend_Z_bilin_key de df hφ W'_nhd x₀ y₀,
rcases key with ⟨U, U_nhd, V, V_nhd, h⟩,
rw mem_comap_sets at U_nhd,
rcases U_nhd with ⟨U', U'_nhd, U'_sub⟩,
rw mem_comap_sets at V_nhd,
rcases V_nhd with ⟨V', V'_nhd, V'_sub⟩,
rw [mem_map, mem_comap_sets, nhds_prod_eq],
existsi set.prod (set.prod U' V') (set.prod U' V'),
rw mem_prod_same_iff,
simp only [exists_prop],
split,
{ change U' ∈ 𝓝 x₀ at U'_nhd,
change V' ∈ 𝓝 y₀ at V'_nhd,
have := prod_mem_prod U'_nhd V'_nhd,
tauto },
{ intros p h',
simp only [set.mem_preimage, set.prod_mk_mem_set_prod_eq] at h',
rcases p with ⟨⟨x, y⟩, ⟨x', y'⟩⟩,
apply h ; tauto } }
end
end dense_inducing
|
4ffb2f23d49712adc4948697e103c84957a06593 | abd85493667895c57a7507870867b28124b3998f | /src/data/monoid_algebra.lean | 8da25231757fd388a41afc31da193007c9dfedcb | [
"Apache-2.0"
] | permissive | pechersky/mathlib | d56eef16bddb0bfc8bc552b05b7270aff5944393 | f1df14c2214ee114c9738e733efd5de174deb95d | refs/heads/master | 1,666,714,392,571 | 1,591,747,567,000 | 1,591,747,567,000 | 270,557,274 | 0 | 0 | Apache-2.0 | 1,591,597,975,000 | 1,591,597,974,000 | null | UTF-8 | Lean | false | false | 25,711 | 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, Yury G. Kudryashov, Scott Morrison
-/
import data.finsupp
import ring_theory.algebra
/-!
# Monoid algebras
When the domain of a `finsupp` has a multiplicative or additive structure, we can define
a convolution product. To mathematicians this structure is known as the "monoid algebra",
i.e. the finite formal linear combinations over a given semiring of elements of the monoid.
The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses.
In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G`
in the same way, and then define the convolution product on these.
When the domain is additive, this is used to define polynomials:
```
polynomial α := add_monoid_algebra ℕ α
mv_polynominal σ α := add_monoid_algebra (σ →₀ ℕ) α
```
When the domain is multiplicative, e.g. a group, this will be used to define the group ring.
## Implementation note
Unfortunately because additive and multiplicative structures both appear in both cases,
it doesn't appear to be possible to make much use of `to_additive`, and we just settle for
saying everything twice.
Similarly, I attempted to just define `add_monoid_algebra k G := monoid_algebra k (multiplicative G)`,
but the definitional equality `multiplicative G = G` leaks through everywhere, and
seems impossible to use.
-/
noncomputable theory
open_locale classical big_operators
open finset finsupp
universes u₁ u₂ u₃
variables (k : Type u₁) (G : Type u₂)
section
variables [semiring k]
/--
The monoid algebra over a semiring `k` generated by the monoid `G`.
It is the type of finite formal `k`-linear combinations of terms of `G`,
endowed with the convolution product.
-/
@[derive [inhabited, add_comm_monoid]]
def monoid_algebra : Type (max u₁ u₂) := G →₀ k
end
namespace monoid_algebra
variables {k G}
local attribute [reducible] monoid_algebra
section
variables [semiring k] [monoid G]
/-- The product of `f g : monoid_algebra k G` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x * y = a`. (Think of the group ring of a group.) -/
instance : has_mul (monoid_algebra k G) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩
lemma mul_def {f g : monoid_algebra k G} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) :=
rfl
lemma mul_apply (f g : monoid_algebra k G) (x : G) :
(f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ * a₂ = x then b₁ * b₂ else 0) :=
begin
rw [mul_def],
simp only [finsupp.sum_apply, single_apply],
end
lemma mul_apply_antidiagonal (f g : monoid_algebra k G) (x : G) (s : finset (G × G))
(hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) :
(f * g) x = s.sum (λ p, f p.1 * g p.2) :=
let F : G × G → k := λ p, if p.1 * p.2 = x then f p.1 * g p.2 else 0 in
calc (f * g) x = (f.support.sum $ λ a₁, g.support.sum $ λ a₂, F (a₁, a₂)) :
mul_apply f g x
... = (f.support.product g.support).sum F : finset.sum_product.symm
... = ((f.support.product g.support).filter (λ p : G × G, p.1 * p.2 = x)).sum (λ p, f p.1 * g p.2) :
(finset.sum_filter _ _).symm
... = (s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support)).sum (λ p, f p.1 * g p.2) :
sum_congr (by { ext, simp [hs, and_comm] }) (λ _ _, rfl)
... = s.sum (λ p, f p.1 * g p.2) : sum_subset (filter_subset _) $ λ p hps hp,
begin
simp only [mem_filter, mem_support_iff, not_and, not_not] at hp ⊢,
by_cases h1 : f p.1 = 0,
{ rw [h1, zero_mul] },
{ rw [hp hps h1, mul_zero] }
end
end
section
variables [semiring k] [monoid G]
lemma support_mul (a b : monoid_algebra k G) :
(a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ * a₂}) :=
subset.trans support_sum $ bind_mono $ assume a₁ _,
subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset
/-- The unit of the multiplication is `single 1 1`, i.e. the function
that is `1` at `1` and zero elsewhere. -/
instance : has_one (monoid_algebra k G) :=
⟨single 1 1⟩
lemma one_def : (1 : monoid_algebra k G) = single 1 1 :=
rfl
-- TODO: the simplifier unfolds 0 in the instance proof!
protected lemma zero_mul (f : monoid_algebra k G) : 0 * f = 0 :=
by simp only [mul_def, sum_zero_index]
protected lemma mul_zero (f : monoid_algebra k G) : f * 0 = 0 :=
by simp only [mul_def, sum_zero_index, sum_zero]
private lemma left_distrib (a b c : monoid_algebra k G) : a * (b + c) = a * b + a * c :=
by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add]
private lemma right_distrib (a b c : monoid_algebra k G) : (a + b) * c = a * c + b * c :=
by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero,
single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add]
instance : semiring (monoid_algebra k G) :=
{ one := 1,
mul := (*),
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul,
single_zero, sum_zero, zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero,
single_zero, sum_zero, add_zero, mul_one, sum_single],
zero_mul := monoid_algebra.zero_mul,
mul_zero := monoid_algebra.mul_zero,
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add],
left_distrib := left_distrib,
right_distrib := right_distrib,
.. finsupp.add_comm_monoid }
@[simp] lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} :
(single a₁ b₁ : monoid_algebra k G) * single a₂ b₂ = single (a₁ * a₂) (b₁ * b₂) :=
(sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans
(sum_single_index (by rw [mul_zero, single_zero]))
@[simp] lemma single_pow {a : G} {b : k} :
∀ n : ℕ, (single a b : monoid_algebra k G)^n = single (a^n) (b ^ n)
| 0 := rfl
| (n+1) := by simp only [pow_succ, single_pow n, single_mul_single]
section
variables (k G)
/-- Embedding of a monoid into its monoid algebra. -/
def of : G →* monoid_algebra k G :=
{ to_fun := λ a, single a 1,
map_one' := rfl,
map_mul' := λ a b, by rw [single_mul_single, one_mul] }
end
@[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl
lemma mul_single_apply_aux (f : monoid_algebra k G) {r : k}
{x y z : G} (H : ∀ a, a * x = z ↔ a = y) :
(f * single x r) z = f y * r :=
have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ * a₂ = z) (b₁ * b₂) 0) =
ite (a₁ * x = z) (b₁ * r) 0,
from λ a₁ b₁, sum_single_index $ by simp,
calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) :
-- different `decidable` instances make it not trivial
by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl }
... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _
... = f y * r : by split_ifs with h; simp at h; simp [h]
lemma mul_single_one_apply (f : monoid_algebra k G) (r : k) (x : G) :
(f * single 1 r) x = f x * r :=
f.mul_single_apply_aux $ λ a, by rw [mul_one]
lemma single_mul_apply_aux (f : monoid_algebra k G) {r : k} {x y z : G}
(H : ∀ a, x * a = y ↔ a = z) :
(single x r * f) y = r * f z :=
have f.sum (λ a b, ite (x * a = y) (0 * b) 0) = 0, by simp,
calc (single x r * f) y = sum f (λ a b, ite (x * a = y) (r * b) 0) :
(mul_apply _ _ _).trans $ sum_single_index this
... = f.sum (λ a b, ite (a = z) (r * b) 0) :
by { simp only [H], congr, ext; split_ifs; refl }
... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _
... = _ : by split_ifs with h; simp at h; simp [h]
lemma single_one_mul_apply (f : monoid_algebra k G) (r : k) (x : G) :
(single 1 r * f) x = r * f x :=
f.single_mul_apply_aux $ λ a, by rw [one_mul]
end
instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) :=
{ mul_comm := assume f g,
begin
simp only [mul_def, finsupp.sum, mul_comm],
rw [finset.sum_comm],
simp only [mul_comm]
end,
.. monoid_algebra.semiring }
instance [ring k] : has_neg (monoid_algebra k G) :=
by apply_instance
instance [ring k] [monoid G] : ring (monoid_algebra k G) :=
{ neg := has_neg.neg,
add_left_neg := add_left_neg,
.. monoid_algebra.semiring }
instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) :=
{ mul_comm := mul_comm, .. monoid_algebra.ring}
instance [semiring k] : has_scalar k (monoid_algebra k G) :=
finsupp.has_scalar
instance [semiring k] : semimodule k (monoid_algebra k G) :=
finsupp.semimodule G k
instance [ring k] : module k (monoid_algebra k G) :=
finsupp.module G k
lemma single_one_comm [comm_semiring k] [monoid G] (r : k) (f : monoid_algebra k G) :
single 1 r * f = f * single 1 r :=
by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] }
instance [comm_semiring k] [monoid G] : algebra k (monoid_algebra k G) :=
{ to_fun := single 1,
map_one' := rfl,
map_mul' := λ x y, by rw [single_mul_single, one_mul],
map_zero' := single_zero,
map_add' := λ x y, single_add,
smul_def' := λ r a, ext (λ _, smul_apply.trans (single_one_mul_apply _ _ _).symm),
commutes' := λ r f, ext $ λ _, by rw [single_one_mul_apply, mul_single_one_apply, mul_comm] }
@[simp] lemma coe_algebra_map [comm_semiring k] [monoid G] :
(algebra_map k (monoid_algebra k G) : k → monoid_algebra k G) = single 1 :=
rfl
lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) :
single a b = (algebra_map k (monoid_algebra k G) : k → monoid_algebra k G) b * of k G a :=
by simp
instance [group G] [semiring k] :
distrib_mul_action G (monoid_algebra k G) :=
finsupp.comap_distrib_mul_action_self
section lift
variables (k G) [comm_semiring k] [monoid G] (R : Type u₃) [semiring R] [algebra k R]
/-- Any monoid homomorphism `G →* R` can be lifted to an algebra homomorphism
`monoid_algebra k G →ₐ[k] R`. -/
def lift : (G →* R) ≃ (monoid_algebra k G →ₐ[k] R) :=
{ inv_fun := λ f, (f : monoid_algebra k G →* R).comp (of k G),
to_fun := λ F, { to_fun := λ f, f.sum (λ a b, b • F a),
map_one' := by { rw [one_def, sum_single_index, one_smul, F.map_one], apply zero_smul },
map_mul' :=
begin
intros f g,
rw [mul_def, finsupp.sum_mul, finsupp.sum_sum_index];
try { intros, simp only [zero_smul, add_smul], done },
refine finset.sum_congr rfl (λ a ha, _), simp only [],
rw [finsupp.mul_sum, finsupp.sum_sum_index];
try { intros, simp only [zero_smul, add_smul], done },
refine finset.sum_congr rfl (λ a' ha', _), simp only [],
rw [sum_single_index, F.map_mul, algebra.mul_smul_comm, algebra.smul_mul_assoc,
smul_smul, mul_comm],
apply zero_smul
end,
map_zero' := sum_zero_index,
map_add' := λ f g, by rw [sum_add_index]; intros; simp only [zero_smul, add_smul],
commutes' := λ r, by rw [coe_algebra_map, sum_single_index, F.map_one, algebra.smul_def,
mul_one]; apply zero_smul },
left_inv := λ f, begin ext x, simp [sum_single_index] end,
right_inv := λ F,
begin
ext f,
conv_rhs { rw ← f.sum_single },
simp [← F.map_smul, finsupp.sum, ← F.map_sum]
end }
variables {k G R}
lemma lift_apply (F : G →* R) (f : monoid_algebra k G) :
lift k G R F f = f.sum (λ a b, b • F a) := rfl
@[simp] lemma lift_symm_apply (F : monoid_algebra k G →ₐ[k] R) (x : G) :
(lift k G R).symm F x = F (single x 1) := rfl
lemma lift_of (F : G →* R) (x) :
lift k G R F (of k G x) = F x :=
by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply]
@[simp] lemma lift_single (F : G →* R) (a b) :
lift k G R F (single a b) = b • F a :=
by rw [single_eq_algebra_map_mul_of, ← algebra.smul_def, alg_hom.map_smul, lift_of]
lemma lift_unique' (F : monoid_algebra k G →ₐ[k] R) :
F = lift k G R ((F : monoid_algebra k G →* R).comp (of k G)) :=
((lift k G R).apply_symm_apply F).symm
/-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by
its values on `F (single a 1)`. -/
lemma lift_unique (F : monoid_algebra k G →ₐ[k] R) (f : monoid_algebra k G) :
F f = f.sum (λ a b, b • F (single a 1)) :=
by conv_lhs { rw lift_unique' F, simp [lift_apply] }
/-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its
values on the functions `single a 1`. -/
lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] R⦄
(h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ :=
(lift k G R).symm.injective $ monoid_hom.ext h
end lift
section
variables (k)
/-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/
def group_smul.linear_map [group G] [comm_ring k]
(V : Type u₃) [add_comm_group V] [module (monoid_algebra k G) V] (g : G) :
(module.restrict_scalars k (monoid_algebra k G) V) →ₗ[k]
(module.restrict_scalars k (monoid_algebra k G) V) :=
{ to_fun := λ v, (single g (1 : k) • v : V),
add := λ x y, smul_add (single g (1 : k)) x y,
smul := λ c x,
by simp only [module.restrict_scalars_smul_def, coe_algebra_map, ←mul_smul, single_one_comm], }.
@[simp]
lemma group_smul.linear_map_apply [group G] [comm_ring k]
(V : Type u₃) [add_comm_group V] [module (monoid_algebra k G) V] (g : G) (v : V) :
(group_smul.linear_map k V g) v = (single g (1 : k) • v : V) :=
rfl
section
variables {k}
variables [group G] [comm_ring k]
{V : Type u₃} {gV : add_comm_group V} {mV : module (monoid_algebra k G) V}
{W : Type u₃} {gW : add_comm_group W} {mW : module (monoid_algebra k G) W}
(f : (module.restrict_scalars k (monoid_algebra k G) V) →ₗ[k]
(module.restrict_scalars k (monoid_algebra k G) W))
(h : ∀ (g : G) (v : V), f (single g (1 : k) • v : V) = (single g (1 : k) • (f v) : W))
include h
/-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/
def equivariant_of_linear_of_comm : V →ₗ[monoid_algebra k G] W :=
{ to_fun := f,
add := λ v v', by simp,
smul := λ c v,
begin
apply finsupp.induction c,
{ simp, },
{ intros g r c' nm nz w,
rw [add_smul, linear_map.map_add, w, add_smul, add_left_inj,
single_eq_algebra_map_mul_of, ←smul_smul, ←smul_smul],
erw [f.map_smul, h g v],
refl, }
end, }
@[simp]
lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v :=
rfl
end
end
universe ui
variable {ι : Type ui}
lemma prod_single [comm_semiring k] [comm_monoid G]
{s : finset ι} {a : ι → G} {b : ι → k} :
(∏ i in s, single (a i) (b i)) = single (∏ i in s, a i) (∏ i in s, b i) :=
finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih,
single_mul_single, prod_insert has, prod_insert has]
section -- We now prove some additional statements that hold for group algebras.
variables [semiring k] [group G]
@[simp]
lemma mul_single_apply (f : monoid_algebra k G) (r : k) (x y : G) :
(f * single x r) y = f (y * x⁻¹) * r :=
f.mul_single_apply_aux $ λ a, eq_mul_inv_iff_mul_eq.symm
@[simp]
lemma single_mul_apply (r : k) (x : G) (f : monoid_algebra k G) (y : G) :
(single x r * f) y = r * f (x⁻¹ * y) :=
f.single_mul_apply_aux $ λ z, eq_inv_mul_iff_mul_eq.symm
lemma mul_apply_left (f g : monoid_algebra k G) (x : G) :
(f * g) x = (f.sum $ λ a b, b * (g (a⁻¹ * x))) :=
calc (f * g) x = sum f (λ a b, (single a (f a) * g) x) :
by rw [← finsupp.sum_apply, ← finsupp.sum_mul, f.sum_single]
... = _ : by simp only [single_mul_apply, finsupp.sum]
-- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`.
lemma mul_apply_right (f g : monoid_algebra k G) (x : G) :
(f * g) x = (g.sum $ λa b, (f (x * a⁻¹)) * b) :=
calc (f * g) x = sum g (λ a b, (f * single a (g a)) x) :
by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single]
... = _ : by simp only [mul_single_apply, finsupp.sum]
end
end monoid_algebra
section
variables [semiring k]
/--
The monoid algebra over a semiring `k` generated by the additive monoid `G`.
It is the type of finite formal `k`-linear combinations of terms of `G`,
endowed with the convolution product.
-/
@[derive [inhabited, add_comm_monoid]]
def add_monoid_algebra := G →₀ k
end
namespace add_monoid_algebra
variables {k G}
local attribute [reducible] add_monoid_algebra
section
variables [semiring k] [add_monoid G]
/-- The product of `f g : add_monoid_algebra k G` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x + y = a`. (Think of the product of multivariate
polynomials where `α` is the additive monoid of monomial exponents.) -/
instance : has_mul (add_monoid_algebra k G) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩
lemma mul_def {f g : add_monoid_algebra k G} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) :=
rfl
lemma mul_apply (f g : add_monoid_algebra k G) (x : G) :
(f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ + a₂ = x then b₁ * b₂ else 0) :=
begin
rw [mul_def],
simp only [finsupp.sum_apply, single_apply],
end
lemma support_mul (a b : add_monoid_algebra k G) :
(a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) :=
subset.trans support_sum $ bind_mono $ assume a₁ _,
subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset
/-- The unit of the multiplication is `single 1 1`, i.e. the function
that is `1` at `0` and zero elsewhere. -/
instance : has_one (add_monoid_algebra k G) :=
⟨single 0 1⟩
lemma one_def : (1 : add_monoid_algebra k G) = single 0 1 :=
rfl
-- TODO: the simplifier unfolds 0 in the instance proof!
protected lemma zero_mul (f : add_monoid_algebra k G) : 0 * f = 0 :=
by simp only [mul_def, sum_zero_index]
protected lemma mul_zero (f : add_monoid_algebra k G) : f * 0 = 0 :=
by simp only [mul_def, sum_zero_index, sum_zero]
private lemma left_distrib (a b c : add_monoid_algebra k G) : a * (b + c) = a * b + a * c :=
by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add]
private lemma right_distrib (a b c : add_monoid_algebra k G) : (a + b) * c = a * c + b * c :=
by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero,
single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add]
instance : semiring (add_monoid_algebra k G) :=
{ one := 1,
mul := (*),
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul,
single_zero, sum_zero, zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero,
single_zero, sum_zero, add_zero, mul_one, sum_single],
zero_mul := add_monoid_algebra.zero_mul,
mul_zero := add_monoid_algebra.mul_zero,
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add],
left_distrib := left_distrib,
right_distrib := right_distrib,
.. finsupp.add_comm_monoid }
lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} :
(single a₁ b₁ : add_monoid_algebra k G) * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) :=
(sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans
(sum_single_index (by rw [mul_zero, single_zero]))
section
variables (k G)
/-- Embedding of a monoid into its monoid algebra. -/
def of : multiplicative G →* add_monoid_algebra k G :=
{ to_fun := λ a, single a 1,
map_one' := rfl,
map_mul' := λ a b, by { rw [single_mul_single, one_mul], refl } }
end
@[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl
lemma mul_single_apply_aux (f : add_monoid_algebra k G) (r : k)
(x y z : G) (H : ∀ a, a + x = z ↔ a = y) :
(f * single x r) z = f y * r :=
have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ + a₂ = z) (b₁ * b₂) 0) =
ite (a₁ + x = z) (b₁ * r) 0,
from λ a₁ b₁, sum_single_index $ by simp,
calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) :
-- different `decidable` instances make it not trivial
by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl }
... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _
... = f y * r : by split_ifs with h; simp at h; simp [h]
lemma mul_single_zero_apply (f : add_monoid_algebra k G) (r : k) (x : G) :
(f * single 0 r) x = f x * r :=
f.mul_single_apply_aux r _ _ _ $ λ a, by rw [add_zero]
lemma single_mul_apply_aux (f : add_monoid_algebra k G) (r : k) (x y z : G)
(H : ∀ a, x + a = y ↔ a = z) :
(single x r * f) y = r * f z :=
have f.sum (λ a b, ite (x + a = y) (0 * b) 0) = 0, by simp,
calc (single x r * f) y = sum f (λ a b, ite (x + a = y) (r * b) 0) :
(mul_apply _ _ _).trans $ sum_single_index this
... = f.sum (λ a b, ite (a = z) (r * b) 0) :
by { simp only [H], congr, ext; split_ifs; refl }
... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _
... = _ : by split_ifs with h; simp at h; simp [h]
lemma single_zero_mul_apply (f : add_monoid_algebra k G) (r : k) (x : G) :
(single 0 r * f) x = r * f x :=
f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add]
end
instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) :=
{ mul_comm := assume f g,
begin
simp only [mul_def, finsupp.sum, mul_comm],
rw [finset.sum_comm],
simp only [add_comm]
end,
.. add_monoid_algebra.semiring }
instance [ring k] : has_neg (add_monoid_algebra k G) :=
by apply_instance
instance [ring k] [add_monoid G] : ring (add_monoid_algebra k G) :=
{ neg := has_neg.neg,
add_left_neg := add_left_neg,
.. add_monoid_algebra.semiring }
instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) :=
{ mul_comm := mul_comm, .. add_monoid_algebra.ring}
instance [semiring k] : has_scalar k (add_monoid_algebra k G) :=
finsupp.has_scalar
instance [semiring k] : semimodule k (add_monoid_algebra k G) :=
finsupp.semimodule G k
instance [ring k] : module k (add_monoid_algebra k G) :=
finsupp.module G k
instance [comm_semiring k] [add_monoid G] : algebra k (add_monoid_algebra k G) :=
{ to_fun := single 0,
map_one' := rfl,
map_mul' := λ x y, by rw [single_mul_single, zero_add],
map_zero' := single_zero,
map_add' := λ x y, single_add,
smul_def' := λ r a, by { ext x, exact smul_apply.trans (single_zero_mul_apply _ _ _).symm },
commutes' := λ r f, show single 0 r * f = f * single 0 r,
by ext; rw [single_zero_mul_apply, mul_single_zero_apply, mul_comm] }
@[simp] lemma coe_algebra_map [comm_semiring k] [add_monoid G] :
(algebra_map k (add_monoid_algebra k G) : k → add_monoid_algebra k G) = single 0 :=
rfl
/-- Any monoid homomorphism `multiplicative G →* R` can be lifted to an algebra homomorphism
`add_monoid_algebra k G →ₐ[k] R`. -/
def lift [comm_semiring k] [add_monoid G] {R : Type u₃} [semiring R] [algebra k R] :
(multiplicative G →* R) ≃ (add_monoid_algebra k G →ₐ[k] R) :=
{ inv_fun := λ f, ((f : add_monoid_algebra k G →+* R) : add_monoid_algebra k G →* R).comp (of k G),
to_fun := λ F, { to_fun := λ f, f.sum (λ a b, b • F a),
map_one' := by { rw [one_def, sum_single_index, one_smul], erw [F.map_one], apply zero_smul },
map_mul' :=
begin
intros f g,
rw [mul_def, finsupp.sum_mul, finsupp.sum_sum_index];
try { intros, simp only [zero_smul, add_smul], done },
refine finset.sum_congr rfl (λ a ha, _), simp only [],
rw [finsupp.mul_sum, finsupp.sum_sum_index];
try { intros, simp only [zero_smul, add_smul], done },
refine finset.sum_congr rfl (λ a' ha', _), simp only [],
rw [sum_single_index],
erw [F.map_mul],
rw [algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_smul, mul_comm],
apply zero_smul
end,
map_zero' := sum_zero_index,
map_add' := λ f g, by rw [sum_add_index]; intros; simp only [zero_smul, add_smul],
commutes' := λ r,
begin
rw [coe_algebra_map, sum_single_index],
erw [F.map_one],
rw [algebra.smul_def, mul_one],
apply zero_smul
end, },
left_inv := λ f, begin ext x, simp [sum_single_index] end,
right_inv := λ F,
begin
ext f,
conv_rhs { rw ← f.sum_single },
simp [← F.map_smul, finsupp.sum, ← F.map_sum]
end }
-- It is hard to state the equivalent of `distrib_mul_action G (monoid_algebra k G)`
-- because we've never discussed actions of additive groups.
universe ui
variable {ι : Type ui}
lemma prod_single [comm_semiring k] [add_comm_monoid G]
{s : finset ι} {a : ι → G} {b : ι → k} :
(∏ i in s, single (a i) (b i)) = single (s.sum a) (∏ i in s, b i) :=
finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih,
single_mul_single, sum_insert has, prod_insert has]
end add_monoid_algebra
|
49be0173d5c403307b49a8c05f5e548ffd1c3288 | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /src/game/functions/twoSidedInverse.lean | ea22a646d3915283dd571c21ce873cfe96294bb6 | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,637 | lean | import data.real.basic
open function
/-
# Chapter 6 : Functions
## Level 4
A classical result in composition of functions.
-/
-- inverses
def two_sided_inverse {X Y : set ℝ} (f : X → Y) (g : Y → X)
:= (∀ x : X, (g ∘ f)(x) = x) ∧ (∀ y : Y, (f ∘ g)(y) = y)
/- Lemma
A function $f : X → Y$ has a two-sided inverse if and only if it is a bijection.
-/
theorem exist_two_sided_inverse (X Y : set ℝ) (f : X → Y) :
(∃ g : Y → X, two_sided_inverse f g) ↔ bijective f :=
begin
split,
{
intro Eg,
cases Eg with g invg,
cases invg with gf fg,
-- show f is injective
have hinjf : injective f,
intros x1 x2 f1f2,
replace f1f2 : g ( f x1 ) = g ( f x2 ),
rw f1f2,
have h1 : g (f x1) = x1 := gf x1,
have h2 : g (f x2) = x2 := gf x2,
rw [ h1, h2 ] at f1f2, exact f1f2,
-- show f is surjective
have hsurf : surjective f,
intro y,
existsi g y,
exact fg y,
-- put these results together
exact and.intro hinjf hsurf,
},
{
rintro bf,
cases bf with finj fsurj,
-- Since $f$ is surjective, $∀ y ∈ Y, ∃ x ∈ X$ such that $f(x) = y$;
-- choose this $x$ to be the output of $g(y)$.
choose g hg using fsurj,
existsi g,
split,
intro x,
-- by definition of $g$, $∀ y ∈ Y, f(g(y)) = y$
-- so we have $f(g(f(x))) = f(x)$:
have hx : f (g (f x)) = f x, rw hg (f x),
apply finj,
exact hx,
exact hg,
}
end
|
98c06f155348106688c1d89db747b34c54556a28 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1730.lean | b09f4fe1f2400e1d72ce7ad48a800cbce28c9af4 | [
"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 | 486 | lean | import Lean
set_option trace.Meta.debug true
class W where
/-- w -/
w : Unit
class X extends W where
/-- x -/
x : Unit
class Y extends W where
/-- y -/
y : Unit
class Y' extends Y where
/-- h -/
h : Uint
class Z extends X, Y'
open Lean
def test (declName : Name) : CoreM Unit := do
let some docstr ← findDocString? (← getEnv) declName | throwError "docstring not found"
IO.println docstr
#eval test ``W.w
#eval test ``X.x
#eval test ``Z.y
#eval test ``Z.h
|
96ef6029e3b3e39dc2898179276ce11398955d3b | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/have_tactic.lean | 309c5239a45d9850deb2adfc2bb495936d809ec3 | [
"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 | 118 | lean | example (a b c : nat) : a = b → b = c → a = c :=
begin
intro h₁ h₂,
have a = c, from eq.trans h₁ _,
end
|
347ed6b1d7c257a9bc4cad089351dd450ee3ac3e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1650.lean | 8a038eec58483e3f2603f8c039763d1d2da2a07a | [
"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 | 149 | lean | mutual
protected def Foo.toString : Foo → String
:= fun _ => "foo"
def toString' : Foo → String := fun _ => "foo"
end
#check @Foo.toString
|
51d1636b475e980aee75efc1c75e376b1b277ee6 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/order/heyting/basic.lean | f295ebab1a3f3a976542ff0bd68df79dccb46353 | [
"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 | 38,799 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import order.bounded_order
/-!
# Heyting algebras
This file defines Heyting, co-Heyting and bi-Heyting algebras.
An Heyting algebra is a bounded distributive lattice with an implication operation `⇨` such that
`a ≤ b ⇨ c ↔ a ⊓ b ≤ c`. It also comes with a pseudo-complement `ᶜ`, such that `aᶜ = a ⇨ ⊥`.
Co-Heyting algebras are dual to Heyting algebras. They have a difference `\` and a negation `¬`
such that `a \ b ≤ c ↔ a ≤ b ⊔ c` and `¬a = ⊤ \ a`.
Bi-Heyting algebras are Heyting algebras that are also co-Heyting algebras.
From a logic standpoint, Heyting algebras precisely model intuitionistic logic, whereas boolean
algebras model classical logic.
Heyting algebras are the order theoretic equivalent of cartesian-closed categories.
## Main declarations
* `generalized_heyting_algebra`: Heyting algebra without a top element (nor negation).
* `generalized_coheyting_algebra`: Co-Heyting algebra without a bottom element (nor complement).
* `heyting_algebra`: Heyting algebra.
* `coheyting_algebra`: Co-Heyting algebra.
* `biheyting_algebra`: bi-Heyting algebra.
## Notation
* `⇨`: Heyting implication
* `\`: Difference
* `¬`: Heyting negation
* `ᶜ`: (Pseudo-)complement
## References
* [Francis Borceux, *Handbook of Categorical Algebra III*][borceux-vol3]
## Tags
Heyting, Brouwer, algebra, implication, negation, intuitionistic
-/
set_option old_structure_cmd true
open function order_dual
universes u
variables {ι α β : Type*}
/-! ### Notation -/
/-- Syntax typeclass for Heyting implication `⇨`. -/
@[notation_class] class has_himp (α : Type*) := (himp : α → α → α)
/-- Syntax typeclass for Heyting negation `¬`.
The difference between `has_hnot` and `has_compl` is that the former belongs to Heyting algebras,
while the latter belongs to co-Heyting algebras. They are both pseudo-complements, but `compl`
underestimates while `hnot` overestimates. In boolean algebras, they are equal. See `hnot_eq_compl`.
-/
@[notation_class] class has_hnot (α : Type*) := (hnot : α → α)
export has_himp (himp) has_sdiff (sdiff) has_hnot (hnot)
infixr ` ⇨ `:60 := himp
prefix `¬`:72 := hnot
instance [has_himp α] [has_himp β] : has_himp (α × β) := ⟨λ a b, (a.1 ⇨ b.1, a.2 ⇨ b.2)⟩
instance [has_hnot α] [has_hnot β] : has_hnot (α × β) := ⟨λ a, (¬a.1, ¬a.2)⟩
instance [has_sdiff α] [has_sdiff β] : has_sdiff (α × β) := ⟨λ a b, (a.1 \ b.1, a.2 \ b.2)⟩
instance [has_compl α] [has_compl β] : has_compl (α × β) := ⟨λ a, (a.1ᶜ, a.2ᶜ)⟩
@[simp] lemma fst_himp [has_himp α] [has_himp β] (a b : α × β) : (a ⇨ b).1 = a.1 ⇨ b.1 := rfl
@[simp] lemma snd_himp [has_himp α] [has_himp β] (a b : α × β) : (a ⇨ b).2 = a.2 ⇨ b.2 := rfl
@[simp] lemma fst_hnot [has_hnot α] [has_hnot β] (a : α × β) : (¬a).1 = ¬a.1 := rfl
@[simp] lemma snd_hnot [has_hnot α] [has_hnot β] (a : α × β) : (¬a).2 = ¬a.2 := rfl
@[simp] lemma fst_sdiff [has_sdiff α] [has_sdiff β] (a b : α × β) : (a \ b).1 = a.1 \ b.1 := rfl
@[simp] lemma snd_sdiff [has_sdiff α] [has_sdiff β] (a b : α × β) : (a \ b).2 = a.2 \ b.2 := rfl
@[simp] lemma fst_compl [has_compl α] [has_compl β] (a : α × β) : aᶜ.1 = a.1ᶜ := rfl
@[simp] lemma snd_compl [has_compl α] [has_compl β] (a : α × β) : aᶜ.2 = a.2ᶜ := rfl
namespace pi
variables {π : ι → Type*}
instance [Π i, has_himp (π i)] : has_himp (Π i, π i) := ⟨λ a b i, a i ⇨ b i⟩
instance [Π i, has_hnot (π i)] : has_hnot (Π i, π i) := ⟨λ a i, ¬a i⟩
lemma himp_def [Π i, has_himp (π i)] (a b : Π i, π i) : (a ⇨ b) = λ i, a i ⇨ b i := rfl
lemma hnot_def [Π i, has_hnot (π i)] (a : Π i, π i) : ¬a = λ i, ¬a i := rfl
@[simp] lemma himp_apply [Π i, has_himp (π i)] (a b : Π i, π i) (i : ι) : (a ⇨ b) i = a i ⇨ b i :=
rfl
@[simp] lemma hnot_apply [Π i, has_hnot (π i)] (a : Π i, π i) (i : ι) : (¬a) i = ¬a i := rfl
end pi
/-- A generalized Heyting algebra is a lattice with an additional binary operation `⇨` called
Heyting implication such that `a ⇨` is right adjoint to `a ⊓`.
This generalizes `heyting_algebra` by not requiring a bottom element. -/
class generalized_heyting_algebra (α : Type*) extends lattice α, has_top α, has_himp α :=
(le_top : ∀ a : α, a ≤ ⊤)
(le_himp_iff (a b c : α) : a ≤ b ⇨ c ↔ a ⊓ b ≤ c)
/-- A generalized co-Heyting algebra is a lattice with an additional binary difference operation `\`
such that `\ a` is right adjoint to `⊔ a`.
This generalizes `coheyting_algebra` by not requiring a top element. -/
class generalized_coheyting_algebra (α : Type*) extends lattice α, has_bot α, has_sdiff α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
(sdiff_le_iff (a b c : α) : a \ b ≤ c ↔ a ≤ b ⊔ c)
/-- A Heyting algebra is a bounded lattice with an additional binary operation `⇨` called Heyting
implication such that `a ⇨` is right adjoint to `a ⊓`. -/
class heyting_algebra (α : Type*) extends generalized_heyting_algebra α, has_bot α, has_compl α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
(himp_bot (a : α) : a ⇨ ⊥ = aᶜ)
/-- A co-Heyting algebra is a bounded lattice with an additional binary difference operation `\`
such that `\ a` is right adjoint to `⊔ a`. -/
class coheyting_algebra (α : Type*)
extends generalized_coheyting_algebra α, has_top α, has_hnot α :=
(le_top : ∀ a : α, a ≤ ⊤)
(top_sdiff (a : α) : ⊤ \ a = ¬a)
/-- A bi-Heyting algebra is a Heyting algebra that is also a co-Heyting algebra. -/
class biheyting_algebra (α : Type*) extends heyting_algebra α, has_sdiff α, has_hnot α :=
(sdiff_le_iff (a b c : α) : a \ b ≤ c ↔ a ≤ b ⊔ c)
(top_sdiff (a : α) : ⊤ \ a = ¬a)
@[priority 100] -- See note [lower instance priority]
instance generalized_heyting_algebra.to_order_top [generalized_heyting_algebra α] : order_top α :=
{ ..‹generalized_heyting_algebra α› }
@[priority 100] -- See note [lower instance priority]
instance generalized_coheyting_algebra.to_order_bot [generalized_coheyting_algebra α] :
order_bot α :=
{ ..‹generalized_coheyting_algebra α› }
@[priority 100] -- See note [lower instance priority]
instance heyting_algebra.to_bounded_order [heyting_algebra α] : bounded_order α :=
{ ..‹heyting_algebra α› }
@[priority 100] -- See note [lower instance priority]
instance coheyting_algebra.to_bounded_order [coheyting_algebra α] : bounded_order α :=
{ ..‹coheyting_algebra α› }
@[priority 100] -- See note [lower instance priority]
instance biheyting_algebra.to_coheyting_algebra [biheyting_algebra α] : coheyting_algebra α :=
{ ..‹biheyting_algebra α› }
/-- Construct a Heyting algebra from the lattice structure and Heyting implication alone. -/
@[reducible] -- See note [reducible non-instances]
def heyting_algebra.of_himp [distrib_lattice α] [bounded_order α] (himp : α → α → α)
(le_himp_iff : ∀ a b c, a ≤ himp b c ↔ a ⊓ b ≤ c) : heyting_algebra α :=
{ himp := himp,
compl := λ a, himp a ⊥,
le_himp_iff := le_himp_iff,
himp_bot := λ a, rfl,
..‹distrib_lattice α›, ..‹bounded_order α› }
/-- Construct a Heyting algebra from the lattice structure and complement operator alone. -/
@[reducible] -- See note [reducible non-instances]
def heyting_algebra.of_compl [distrib_lattice α] [bounded_order α] (compl : α → α)
(le_himp_iff : ∀ a b c, a ≤ compl b ⊔ c ↔ a ⊓ b ≤ c) : heyting_algebra α :=
{ himp := λ a, (⊔) (compl a),
compl := compl,
le_himp_iff := le_himp_iff,
himp_bot := λ a, sup_bot_eq,
..‹distrib_lattice α›, ..‹bounded_order α› }
/-- Construct a co-Heyting algebra from the lattice structure and the difference alone. -/
@[reducible] -- See note [reducible non-instances]
def coheyting_algebra.of_sdiff [distrib_lattice α] [bounded_order α] (sdiff : α → α → α)
(sdiff_le_iff : ∀ a b c, sdiff a b ≤ c ↔ a ≤ b ⊔ c) : coheyting_algebra α :=
{ sdiff := sdiff,
hnot := λ a, sdiff ⊤ a,
sdiff_le_iff := sdiff_le_iff,
top_sdiff := λ a, rfl,
..‹distrib_lattice α›, ..‹bounded_order α› }
/-- Construct a co-Heyting algebra from the difference and Heyting negation alone. -/
@[reducible] -- See note [reducible non-instances]
def coheyting_algebra.of_hnot [distrib_lattice α] [bounded_order α] (hnot : α → α)
(sdiff_le_iff : ∀ a b c, a ⊓ hnot b ≤ c ↔ a ≤ b ⊔ c) : coheyting_algebra α :=
{ sdiff := λ a b, (a ⊓ hnot b),
hnot := hnot,
sdiff_le_iff := sdiff_le_iff,
top_sdiff := λ a, top_inf_eq,
..‹distrib_lattice α›, ..‹bounded_order α› }
section generalized_heyting_algebra
variables [generalized_heyting_algebra α] {a b c d : α}
/- In this section, we'll give interpretations of these results in the Heyting algebra model of
intuitionistic logic,- where `≤` can be interpreted as "validates", `⇨` as "implies", `⊓` as "and",
`⊔` as "or", `⊥` as "false" and `⊤` as "true". Note that we confuse `→` and `⊢` because those are
the same in this logic.
See also `Prop.heyting_algebra`. -/
-- `p → q → r ↔ p ∧ q → r`
@[simp] lemma le_himp_iff : a ≤ b ⇨ c ↔ a ⊓ b ≤ c := generalized_heyting_algebra.le_himp_iff _ _ _
-- `p → q → r ↔ q ∧ p → r`
lemma le_himp_iff' : a ≤ b ⇨ c ↔ b ⊓ a ≤ c := by rw [le_himp_iff, inf_comm]
-- `p → q → r ↔ q → p → r`
lemma le_himp_comm : a ≤ b ⇨ c ↔ b ≤ a ⇨ c := by rw [le_himp_iff, le_himp_iff']
-- `p → q → p`
lemma le_himp : a ≤ b ⇨ a := le_himp_iff.2 inf_le_left
-- `p → p → q ↔ p → q`
@[simp] lemma le_himp_iff_left : a ≤ a ⇨ b ↔ a ≤ b := by rw [le_himp_iff, inf_idem]
-- `p → p`
@[simp] lemma himp_self : a ⇨ a = ⊤ := top_le_iff.1 $ le_himp_iff.2 inf_le_right
-- `(p → q) ∧ p → q`
lemma himp_inf_le : (a ⇨ b) ⊓ a ≤ b := le_himp_iff.1 le_rfl
-- `p ∧ (p → q) → q`
lemma inf_himp_le : a ⊓ (a ⇨ b) ≤ b := by rw [inf_comm, ←le_himp_iff]
-- `p ∧ (p → q) ↔ p ∧ q`
@[simp] lemma inf_himp (a b : α) : a ⊓ (a ⇨ b) = a ⊓ b :=
le_antisymm (le_inf inf_le_left $ by rw [inf_comm, ←le_himp_iff]) $ inf_le_inf_left _ le_himp
-- `(p → q) ∧ p ↔ q ∧ p`
@[simp] lemma himp_inf_self (a b : α) : (a ⇨ b) ⊓ a = b ⊓ a := by rw [inf_comm, inf_himp, inf_comm]
/-- The **deduction theorem** in the Heyting algebra model of intuitionistic logic:
an implication holds iff the conclusion follows from the hypothesis. -/
@[simp] lemma himp_eq_top_iff : a ⇨ b = ⊤ ↔ a ≤ b := by rw [←top_le_iff, le_himp_iff, top_inf_eq]
-- `p → true`, `true → p ↔ p`
@[simp] lemma himp_top : a ⇨ ⊤ = ⊤ := himp_eq_top_iff.2 le_top
@[simp] lemma top_himp : ⊤ ⇨ a = a := eq_of_forall_le_iff $ λ b, by rw [le_himp_iff, inf_top_eq]
-- `p → q → r ↔ p ∧ q → r`
lemma himp_himp (a b c : α) : a ⇨ b ⇨ c = a ⊓ b ⇨ c :=
eq_of_forall_le_iff $ λ d, by simp_rw [le_himp_iff, inf_assoc]
-- `(q → r) → (p → q) → q → r`
@[simp] lemma himp_le_himp_himp_himp : b ⇨ c ≤ (a ⇨ b) ⇨ a ⇨ c :=
begin
rw [le_himp_iff, le_himp_iff, inf_assoc, himp_inf_self, ←inf_assoc, himp_inf_self, inf_assoc],
exact inf_le_left,
end
-- `p → q → r ↔ q → p → r`
lemma himp_left_comm (a b c : α) : a ⇨ b ⇨ c = b ⇨ a ⇨ c := by simp_rw [himp_himp, inf_comm]
lemma himp_inf_distrib (a b c : α) : a ⇨ b ⊓ c = (a ⇨ b) ⊓ (a ⇨ c) :=
eq_of_forall_le_iff $ λ d, by simp_rw [le_himp_iff, le_inf_iff, le_himp_iff]
lemma sup_himp_distrib (a b c : α) : a ⊔ b ⇨ c = (a ⇨ c) ⊓ (b ⇨ c) :=
eq_of_forall_le_iff $ λ d, by { rw [le_inf_iff, le_himp_comm, sup_le_iff], simp_rw le_himp_comm }
lemma himp_le_himp_left (h : a ≤ b) : c ⇨ a ≤ c ⇨ b := le_himp_iff.2 $ himp_inf_le.trans h
lemma himp_le_himp_right (h : a ≤ b) : b ⇨ c ≤ a ⇨ c :=
le_himp_iff.2 $ (inf_le_inf_left _ h).trans himp_inf_le
lemma himp_le_himp (hab : a ≤ b) (hcd : c ≤ d) : b ⇨ c ≤ a ⇨ d :=
(himp_le_himp_right hab).trans $ himp_le_himp_left hcd
@[simp] lemma sup_himp_self_left (a b : α) : (a ⊔ b) ⇨ a = b ⇨ a :=
by rw [sup_himp_distrib, himp_self, top_inf_eq]
@[simp] lemma sup_himp_self_right (a b : α) : (a ⊔ b) ⇨ b = a ⇨ b :=
by rw [sup_himp_distrib, himp_self, inf_top_eq]
lemma codisjoint.himp_eq_right (h : codisjoint a b) : b ⇨ a = a :=
by { conv_rhs { rw ←@top_himp _ _ a }, rw [←h.eq_top, sup_himp_self_left] }
lemma codisjoint.himp_eq_left (h : codisjoint a b) : a ⇨ b = b := h.symm.himp_eq_right
lemma codisjoint.himp_inf_cancel_right (h : codisjoint a b) : a ⇨ (a ⊓ b) = b :=
by rw [himp_inf_distrib, himp_self, top_inf_eq, h.himp_eq_left]
lemma codisjoint.himp_inf_cancel_left (h : codisjoint a b) : b ⇨ (a ⊓ b) = a :=
by rw [himp_inf_distrib, himp_self, inf_top_eq, h.himp_eq_right]
lemma le_himp_himp : a ≤ (a ⇨ b) ⇨ b := le_himp_iff.2 inf_himp_le
lemma himp_triangle (a b c : α) : (a ⇨ b) ⊓ (b ⇨ c) ≤ a ⇨ c :=
by { rw [le_himp_iff, inf_right_comm, ←le_himp_iff], exact himp_inf_le.trans le_himp_himp }
lemma himp_inf_himp_cancel (hba : b ≤ a) (hcb : c ≤ b) : (a ⇨ b) ⊓ (b ⇨ c) = a ⇨ c :=
(himp_triangle _ _ _).antisymm $ le_inf (himp_le_himp_left hcb) (himp_le_himp_right hba)
@[priority 100] -- See note [lower instance priority]
instance generalized_heyting_algebra.to_distrib_lattice : distrib_lattice α :=
distrib_lattice.of_inf_sup_le $ λ a b c,
by simp_rw [@inf_comm _ _ a, ←le_himp_iff, sup_le_iff, le_himp_iff, ←sup_le_iff]
instance : generalized_coheyting_algebra αᵒᵈ :=
{ sdiff := λ a b, to_dual (of_dual b ⇨ of_dual a),
sdiff_le_iff := λ a b c, by { rw sup_comm, exact le_himp_iff },
..order_dual.lattice α, ..order_dual.order_bot α }
instance prod.generalized_heyting_algebra [generalized_heyting_algebra β] :
generalized_heyting_algebra (α × β) :=
{ le_himp_iff := λ a b c, and_congr le_himp_iff le_himp_iff,
..prod.lattice α β, ..prod.order_top α β, ..prod.has_himp, ..prod.has_compl }
instance pi.generalized_heyting_algebra {α : ι → Type*} [Π i, generalized_heyting_algebra (α i)] :
generalized_heyting_algebra (Π i, α i) :=
by { pi_instance, exact λ a b c, forall_congr (λ i, le_himp_iff) }
end generalized_heyting_algebra
section generalized_coheyting_algebra
variables [generalized_coheyting_algebra α] {a b c d : α}
@[simp] lemma sdiff_le_iff : a \ b ≤ c ↔ a ≤ b ⊔ c :=
generalized_coheyting_algebra.sdiff_le_iff _ _ _
lemma sdiff_le_iff' : a \ b ≤ c ↔ a ≤ c ⊔ b := by rw [sdiff_le_iff, sup_comm]
lemma sdiff_le_comm : a \ b ≤ c ↔ a \ c ≤ b := by rw [sdiff_le_iff, sdiff_le_iff']
lemma sdiff_le : a \ b ≤ a := sdiff_le_iff.2 le_sup_right
lemma disjoint.disjoint_sdiff_left (h : disjoint a b) : disjoint (a \ c) b := h.mono_left sdiff_le
lemma disjoint.disjoint_sdiff_right (h : disjoint a b) : disjoint a (b \ c) := h.mono_right sdiff_le
@[simp] lemma sdiff_le_iff_left : a \ b ≤ b ↔ a ≤ b := by rw [sdiff_le_iff, sup_idem]
@[simp] lemma sdiff_self : a \ a = ⊥ := le_bot_iff.1 $ sdiff_le_iff.2 le_sup_left
lemma le_sup_sdiff : a ≤ b ⊔ a \ b := sdiff_le_iff.1 le_rfl
lemma le_sdiff_sup : a ≤ a \ b ⊔ b := by rw [sup_comm, ←sdiff_le_iff]
@[simp] lemma sup_sdiff_left : a ⊔ a \ b = a := sup_of_le_left sdiff_le
@[simp] lemma sup_sdiff_right : a \ b ⊔ a = a := sup_of_le_right sdiff_le
@[simp] lemma inf_sdiff_left : a \ b ⊓ a = a \ b := inf_of_le_left sdiff_le
@[simp] lemma inf_sdiff_right : a ⊓ a \ b = a \ b := inf_of_le_right sdiff_le
@[simp] lemma sup_sdiff_self (a b : α) : a ⊔ b \ a = a ⊔ b :=
le_antisymm (sup_le_sup_left sdiff_le _) (sup_le le_sup_left le_sup_sdiff)
@[simp] lemma sdiff_sup_self (a b : α) : b \ a ⊔ a = b ⊔ a :=
by rw [sup_comm, sup_sdiff_self, sup_comm]
alias sdiff_sup_self ← sup_sdiff_self_left
alias sup_sdiff_self ← sup_sdiff_self_right
lemma sup_sdiff_eq_sup (h : c ≤ a) : a ⊔ b \ c = a ⊔ b :=
sup_congr_left (sdiff_le.trans le_sup_right) $ le_sup_sdiff.trans $ sup_le_sup_right h _
-- cf. `set.union_diff_cancel'`
lemma sup_sdiff_cancel' (hab : a ≤ b) (hbc : b ≤ c) : b ⊔ c \ a = c :=
by rw [sup_sdiff_eq_sup hab, sup_of_le_right hbc]
lemma sup_sdiff_cancel_right (h : a ≤ b) : a ⊔ b \ a = b := sup_sdiff_cancel' le_rfl h
lemma sdiff_sup_cancel (h : b ≤ a) : a \ b ⊔ b = a := by rw [sup_comm, sup_sdiff_cancel_right h]
lemma sup_le_of_le_sdiff_left (h : b ≤ c \ a) (hac : a ≤ c) : a ⊔ b ≤ c :=
sup_le hac $ h.trans sdiff_le
lemma sup_le_of_le_sdiff_right (h : a ≤ c \ b) (hbc : b ≤ c) : a ⊔ b ≤ c :=
sup_le (h.trans sdiff_le) hbc
@[simp] lemma sdiff_eq_bot_iff : a \ b = ⊥ ↔ a ≤ b := by rw [←le_bot_iff, sdiff_le_iff, sup_bot_eq]
@[simp] lemma sdiff_bot : a \ ⊥ = a := eq_of_forall_ge_iff $ λ b, by rw [sdiff_le_iff, bot_sup_eq]
@[simp] lemma bot_sdiff : ⊥ \ a = ⊥ := sdiff_eq_bot_iff.2 bot_le
@[simp] lemma sdiff_sdiff_sdiff_le_sdiff : a \ b \ (a \ c) ≤ c \ b :=
begin
rw [sdiff_le_iff, sdiff_le_iff, sup_left_comm, sup_sdiff_self, sup_left_comm, sdiff_sup_self,
sup_left_comm],
exact le_sup_left,
end
lemma sdiff_sdiff (a b c : α) : a \ b \ c = a \ (b ⊔ c) :=
eq_of_forall_ge_iff $ λ d, by simp_rw [sdiff_le_iff, sup_assoc]
lemma sdiff_sdiff_left : a \ b \ c = a \ (b ⊔ c) := sdiff_sdiff _ _ _
lemma sdiff_right_comm (a b c : α) : a \ b \ c = a \ c \ b := by simp_rw [sdiff_sdiff, sup_comm]
lemma sdiff_sdiff_comm : a \ b \ c = a \ c \ b := sdiff_right_comm _ _ _
@[simp] lemma sdiff_idem : a \ b \ b = a \ b := by rw [sdiff_sdiff_left, sup_idem]
@[simp] lemma sdiff_sdiff_self : a \ b \ a = ⊥ := by rw [sdiff_sdiff_comm, sdiff_self, bot_sdiff]
lemma sup_sdiff_distrib (a b c : α) : (a ⊔ b) \ c = a \ c ⊔ b \ c :=
eq_of_forall_ge_iff $ λ d, by simp_rw [sdiff_le_iff, sup_le_iff, sdiff_le_iff]
lemma sdiff_inf_distrib (a b c : α) : a \ (b ⊓ c) = a \ b ⊔ a \ c :=
eq_of_forall_ge_iff $ λ d, by { rw [sup_le_iff, sdiff_le_comm, le_inf_iff], simp_rw sdiff_le_comm }
lemma sup_sdiff : (a ⊔ b) \ c = a \ c ⊔ b \ c := sup_sdiff_distrib _ _ _
@[simp] lemma sup_sdiff_right_self : (a ⊔ b) \ b = a \ b :=
by rw [sup_sdiff, sdiff_self, sup_bot_eq]
@[simp] lemma sup_sdiff_left_self : (a ⊔ b) \ a = b \ a := by rw [sup_comm, sup_sdiff_right_self]
lemma sdiff_le_sdiff_right (h : a ≤ b) : a \ c ≤ b \ c := sdiff_le_iff.2 $ h.trans $ le_sup_sdiff
lemma sdiff_le_sdiff_left (h : a ≤ b) : c \ b ≤ c \ a :=
sdiff_le_iff.2 $ le_sup_sdiff.trans $ sup_le_sup_right h _
lemma sdiff_le_sdiff (hab : a ≤ b) (hcd : c ≤ d) : a \ d ≤ b \ c :=
(sdiff_le_sdiff_right hab).trans $ sdiff_le_sdiff_left hcd
-- cf. `is_compl.inf_sup`
lemma sdiff_inf : a \ (b ⊓ c) = a \ b ⊔ a \ c := sdiff_inf_distrib _ _ _
@[simp] lemma sdiff_inf_self_left (a b : α) : a \ (a ⊓ b) = a \ b :=
by rw [sdiff_inf, sdiff_self, bot_sup_eq]
@[simp] lemma sdiff_inf_self_right (a b : α) : b \ (a ⊓ b) = b \ a :=
by rw [sdiff_inf, sdiff_self, sup_bot_eq]
lemma disjoint.sdiff_eq_left (h : disjoint a b) : a \ b = a :=
by { conv_rhs { rw ←@sdiff_bot _ _ a }, rw [←h.eq_bot, sdiff_inf_self_left] }
lemma disjoint.sdiff_eq_right (h : disjoint a b) : b \ a = b := h.symm.sdiff_eq_left
lemma disjoint.sup_sdiff_cancel_left (h : disjoint a b) : (a ⊔ b) \ a = b :=
by rw [sup_sdiff, sdiff_self, bot_sup_eq, h.sdiff_eq_right]
lemma disjoint.sup_sdiff_cancel_right (h : disjoint a b) : (a ⊔ b) \ b = a :=
by rw [sup_sdiff, sdiff_self, sup_bot_eq, h.sdiff_eq_left]
lemma sdiff_sdiff_le : a \ (a \ b) ≤ b := sdiff_le_iff.2 le_sdiff_sup
lemma sdiff_triangle (a b c : α) : a \ c ≤ a \ b ⊔ b \ c :=
by { rw [sdiff_le_iff, sup_left_comm, ←sdiff_le_iff], exact sdiff_sdiff_le.trans le_sup_sdiff }
lemma sdiff_sup_sdiff_cancel (hba : b ≤ a) (hcb : c ≤ b) : a \ b ⊔ b \ c = a \ c :=
(sdiff_triangle _ _ _).antisymm' $ sup_le (sdiff_le_sdiff_left hcb) (sdiff_le_sdiff_right hba)
lemma sdiff_le_sdiff_of_sup_le_sup_left (h : c ⊔ a ≤ c ⊔ b) : a \ c ≤ b \ c :=
by { rw [←sup_sdiff_left_self, ←@sup_sdiff_left_self _ _ _ b], exact sdiff_le_sdiff_right h }
lemma sdiff_le_sdiff_of_sup_le_sup_right (h : a ⊔ c ≤ b ⊔ c) : a \ c ≤ b \ c :=
by { rw [←sup_sdiff_right_self, ←@sup_sdiff_right_self _ _ b], exact sdiff_le_sdiff_right h }
@[simp] lemma inf_sdiff_sup_left : a \ c ⊓ (a ⊔ b) = a \ c :=
inf_of_le_left $ sdiff_le.trans le_sup_left
@[simp] lemma inf_sdiff_sup_right : a \ c ⊓ (b ⊔ a) = a \ c :=
inf_of_le_left $ sdiff_le.trans le_sup_right
@[priority 100] -- See note [lower instance priority]
instance generalized_coheyting_algebra.to_distrib_lattice : distrib_lattice α :=
{ le_sup_inf := λ a b c, by simp_rw [←sdiff_le_iff, le_inf_iff, sdiff_le_iff, ←le_inf_iff],
..‹generalized_coheyting_algebra α› }
instance : generalized_heyting_algebra αᵒᵈ :=
{ himp := λ a b, to_dual (of_dual b \ of_dual a),
le_himp_iff := λ a b c, by { rw inf_comm, exact sdiff_le_iff },
..order_dual.lattice α, ..order_dual.order_top α }
instance prod.generalized_coheyting_algebra [generalized_coheyting_algebra β] :
generalized_coheyting_algebra (α × β) :=
{ sdiff_le_iff := λ a b c, and_congr sdiff_le_iff sdiff_le_iff,
..prod.lattice α β, ..prod.order_bot α β, ..prod.has_sdiff, ..prod.has_hnot }
instance pi.generalized_coheyting_algebra {α : ι → Type*}
[Π i, generalized_coheyting_algebra (α i)] : generalized_coheyting_algebra (Π i, α i) :=
by { pi_instance, exact λ a b c, forall_congr (λ i, sdiff_le_iff) }
end generalized_coheyting_algebra
section heyting_algebra
variables [heyting_algebra α] {a b c : α}
@[simp] lemma himp_bot (a : α) : a ⇨ ⊥ = aᶜ := heyting_algebra.himp_bot _
@[simp] lemma bot_himp (a : α) : ⊥ ⇨ a = ⊤ := himp_eq_top_iff.2 bot_le
lemma compl_sup_distrib (a b : α) : (a ⊔ b)ᶜ = aᶜ ⊓ bᶜ := by simp_rw [←himp_bot, sup_himp_distrib]
@[simp] lemma compl_sup : (a ⊔ b)ᶜ = aᶜ ⊓ bᶜ := compl_sup_distrib _ _
lemma compl_le_himp : aᶜ ≤ a ⇨ b := (himp_bot _).ge.trans $ himp_le_himp_left bot_le
lemma compl_sup_le_himp : aᶜ ⊔ b ≤ a ⇨ b := sup_le compl_le_himp le_himp
lemma sup_compl_le_himp : b ⊔ aᶜ ≤ a ⇨ b := sup_le le_himp compl_le_himp
-- `p → ¬ p ↔ ¬ p`
@[simp] lemma himp_compl (a : α) : a ⇨ aᶜ = aᶜ := by rw [←himp_bot, himp_himp, inf_idem]
-- `p → ¬ q ↔ q → ¬ p`
lemma himp_compl_comm (a b : α) : a ⇨ bᶜ = b ⇨ aᶜ := by simp_rw [←himp_bot, himp_left_comm]
lemma le_compl_iff_disjoint_right : a ≤ bᶜ ↔ disjoint a b :=
by rw [←himp_bot, le_himp_iff, disjoint]
lemma le_compl_iff_disjoint_left : a ≤ bᶜ ↔ disjoint b a :=
le_compl_iff_disjoint_right.trans disjoint.comm
lemma le_compl_comm : a ≤ bᶜ ↔ b ≤ aᶜ :=
by rw [le_compl_iff_disjoint_right, le_compl_iff_disjoint_left]
alias le_compl_iff_disjoint_right ↔ _ disjoint.le_compl_right
alias le_compl_iff_disjoint_left ↔ _ disjoint.le_compl_left
alias le_compl_comm ← le_compl_iff_le_compl
alias le_compl_comm ↔ le_compl_of_le_compl _
lemma disjoint_compl_left : disjoint aᶜ a := le_himp_iff.1 (himp_bot _).ge
lemma disjoint_compl_right : disjoint a aᶜ := disjoint_compl_left.symm
lemma has_le.le.disjoint_compl_left (h : b ≤ a) : disjoint aᶜ b := disjoint_compl_left.mono_right h
lemma has_le.le.disjoint_compl_right (h : a ≤ b) : disjoint a bᶜ := disjoint_compl_right.mono_left h
lemma is_compl.compl_eq (h : is_compl a b) : aᶜ = b :=
h.1.le_compl_left.antisymm' $ disjoint.le_of_codisjoint disjoint_compl_left h.2
lemma is_compl.eq_compl (h : is_compl a b) : a = bᶜ :=
h.1.le_compl_right.antisymm $ disjoint.le_of_codisjoint disjoint_compl_left h.2.symm
lemma compl_unique (h₀ : a ⊓ b = ⊥) (h₁ : a ⊔ b = ⊤) : aᶜ = b := (is_compl.of_eq h₀ h₁).compl_eq
@[simp] lemma inf_compl_self (a : α) : a ⊓ aᶜ = ⊥ := disjoint_compl_right.eq_bot
@[simp] lemma compl_inf_self (a : α) : aᶜ ⊓ a = ⊥ := disjoint_compl_left.eq_bot
lemma inf_compl_eq_bot : a ⊓ aᶜ = ⊥ := inf_compl_self _
lemma compl_inf_eq_bot : aᶜ ⊓ a = ⊥ := compl_inf_self _
@[simp] lemma compl_top : (⊤ : α)ᶜ = ⊥ :=
eq_of_forall_le_iff $ λ a, by rw [le_compl_iff_disjoint_right, disjoint_top, le_bot_iff]
@[simp] lemma compl_bot : (⊥ : α)ᶜ = ⊤ := by rw [←himp_bot, himp_self]
lemma le_compl_compl : a ≤ aᶜᶜ := disjoint_compl_right.le_compl_right
lemma compl_anti : antitone (compl : α → α) := λ a b h, le_compl_comm.1 $ h.trans le_compl_compl
lemma compl_le_compl (h : a ≤ b) : bᶜ ≤ aᶜ := compl_anti h
@[simp] lemma compl_compl_compl (a : α) : aᶜᶜᶜ = aᶜ :=
(compl_anti le_compl_compl).antisymm le_compl_compl
@[simp] lemma disjoint_compl_compl_left_iff : disjoint aᶜᶜ b ↔ disjoint a b :=
by simp_rw [←le_compl_iff_disjoint_left, compl_compl_compl]
@[simp] lemma disjoint_compl_compl_right_iff : disjoint a bᶜᶜ ↔ disjoint a b :=
by simp_rw [←le_compl_iff_disjoint_right, compl_compl_compl]
lemma compl_sup_compl_le : aᶜ ⊔ bᶜ ≤ (a ⊓ b)ᶜ :=
sup_le (compl_anti inf_le_left) $ compl_anti inf_le_right
lemma compl_compl_inf_distrib (a b : α) : (a ⊓ b)ᶜᶜ = aᶜᶜ ⊓ bᶜᶜ :=
begin
refine ((compl_anti compl_sup_compl_le).trans (compl_sup_distrib _ _).le).antisymm _,
rw [le_compl_iff_disjoint_right, disjoint_assoc, disjoint_compl_compl_left_iff,
disjoint_left_comm, disjoint_compl_compl_left_iff, ←disjoint_assoc, inf_comm],
exact disjoint_compl_right,
end
lemma compl_compl_himp_distrib (a b : α) : (a ⇨ b)ᶜᶜ = aᶜᶜ ⇨ bᶜᶜ :=
begin
refine le_antisymm _ _,
{ rw [le_himp_iff, ←compl_compl_inf_distrib],
exact compl_anti (compl_anti himp_inf_le) },
{ refine le_compl_comm.1 ((compl_anti compl_sup_le_himp).trans _),
rw [compl_sup_distrib, le_compl_iff_disjoint_right, disjoint_right_comm,
←le_compl_iff_disjoint_right],
exact inf_himp_le }
end
instance : coheyting_algebra αᵒᵈ :=
{ hnot := to_dual ∘ compl ∘ of_dual,
sdiff := λ a b, to_dual (of_dual b ⇨ of_dual a),
sdiff_le_iff := λ a b c, by { rw sup_comm, exact le_himp_iff },
top_sdiff := himp_bot,
..order_dual.lattice α, ..order_dual.bounded_order α }
@[simp] lemma of_dual_hnot (a : αᵒᵈ) : of_dual ¬a = (of_dual a)ᶜ := rfl
@[simp] lemma to_dual_compl (a : α) : to_dual aᶜ = ¬to_dual a := rfl
instance prod.heyting_algebra [heyting_algebra β] : heyting_algebra (α × β) :=
{ himp_bot := λ a, prod.ext (himp_bot a.1) (himp_bot a.2),
..prod.generalized_heyting_algebra, ..prod.bounded_order α β, ..prod.has_compl }
instance pi.heyting_algebra {α : ι → Type*} [Π i, heyting_algebra (α i)] :
heyting_algebra (Π i, α i) :=
by { pi_instance, exact λ a b c, forall_congr (λ i, le_himp_iff) }
end heyting_algebra
section coheyting_algebra
variables [coheyting_algebra α] {a b c : α}
@[simp] lemma top_sdiff' (a : α) : ⊤ \ a = ¬a := coheyting_algebra.top_sdiff _
@[simp] lemma sdiff_top (a : α) : a \ ⊤ = ⊥ := sdiff_eq_bot_iff.2 le_top
lemma hnot_inf_distrib (a b : α) : ¬ (a ⊓ b) = ¬a ⊔ ¬b :=
by simp_rw [←top_sdiff', sdiff_inf_distrib]
lemma sdiff_le_hnot : a \ b ≤ ¬b := (sdiff_le_sdiff_right le_top).trans_eq $ top_sdiff' _
lemma sdiff_le_inf_hnot : a \ b ≤ a ⊓ ¬b := le_inf sdiff_le sdiff_le_hnot
@[priority 100] -- See note [lower instance priority]
instance coheyting_algebra.to_distrib_lattice : distrib_lattice α :=
{ le_sup_inf := λ a b c, by simp_rw [←sdiff_le_iff, le_inf_iff, sdiff_le_iff, ←le_inf_iff],
..‹coheyting_algebra α› }
@[simp] lemma hnot_sdiff (a : α) : ¬a \ a = ¬a := by rw [←top_sdiff', sdiff_sdiff, sup_idem]
lemma hnot_sdiff_comm (a b : α) : ¬a \ b = ¬b \ a := by simp_rw [←top_sdiff', sdiff_right_comm]
lemma hnot_le_iff_codisjoint_right : ¬a ≤ b ↔ codisjoint a b :=
by rw [←top_sdiff', sdiff_le_iff, codisjoint]
lemma hnot_le_iff_codisjoint_left : ¬a ≤ b ↔ codisjoint b a :=
hnot_le_iff_codisjoint_right.trans codisjoint.comm
lemma hnot_le_comm : ¬a ≤ b ↔ ¬b ≤ a :=
by rw [hnot_le_iff_codisjoint_right, hnot_le_iff_codisjoint_left]
alias hnot_le_iff_codisjoint_right ↔ _ codisjoint.hnot_le_right
alias hnot_le_iff_codisjoint_left ↔ _ codisjoint.hnot_le_left
lemma codisjoint_hnot_right : codisjoint a (¬a) := sdiff_le_iff.1 (top_sdiff' _).le
lemma codisjoint_hnot_left : codisjoint (¬a) a := codisjoint_hnot_right.symm
lemma has_le.le.codisjoint_hnot_left (h : a ≤ b) : codisjoint (¬a) b :=
codisjoint_hnot_left.mono_right h
lemma has_le.le.codisjoint_hnot_right (h : b ≤ a) : codisjoint a (¬b) :=
codisjoint_hnot_right.mono_left h
lemma is_compl.hnot_eq (h : is_compl a b) : ¬a = b :=
h.2.hnot_le_right.antisymm $ disjoint.le_of_codisjoint h.1.symm codisjoint_hnot_right
lemma is_compl.eq_hnot (h : is_compl a b) : a = ¬b :=
h.2.hnot_le_left.antisymm' $ disjoint.le_of_codisjoint h.1 codisjoint_hnot_right
@[simp] lemma sup_hnot_self (a : α) : a ⊔ ¬a = ⊤ := codisjoint_hnot_right.eq_top
@[simp] lemma hnot_sup_self (a : α) : ¬a ⊔ a = ⊤ := codisjoint_hnot_left.eq_top
@[simp] lemma hnot_bot : ¬(⊥ : α) = ⊤ :=
eq_of_forall_ge_iff $ λ a, by rw [hnot_le_iff_codisjoint_left, codisjoint_bot, top_le_iff]
@[simp] lemma hnot_top : ¬(⊤ : α) = ⊥ := by rw [←top_sdiff', sdiff_self]
lemma hnot_hnot_le : ¬¬a ≤ a := codisjoint_hnot_right.hnot_le_left
lemma hnot_anti : antitone (hnot : α → α) := λ a b h, hnot_le_comm.1 $ hnot_hnot_le.trans h
lemma hnot_le_hnot (h : a ≤ b) : ¬b ≤ ¬a := hnot_anti h
@[simp] lemma hnot_hnot_hnot (a : α) : ¬¬¬a = ¬a := hnot_hnot_le.antisymm $ hnot_anti hnot_hnot_le
@[simp] lemma codisjoint_hnot_hnot_left_iff : codisjoint (¬¬a) b ↔ codisjoint a b :=
by simp_rw [←hnot_le_iff_codisjoint_right, hnot_hnot_hnot]
@[simp] lemma codisjoint_hnot_hnot_right_iff : codisjoint a (¬¬b) ↔ codisjoint a b :=
by simp_rw [←hnot_le_iff_codisjoint_left, hnot_hnot_hnot]
lemma le_hnot_inf_hnot : ¬ (a ⊔ b) ≤ ¬a ⊓ ¬b :=
le_inf (hnot_anti le_sup_left) $ hnot_anti le_sup_right
lemma hnot_hnot_sup_distrib (a b : α) : ¬¬(a ⊔ b) = ¬¬a ⊔ ¬¬b :=
begin
refine ((hnot_inf_distrib _ _).ge.trans $ hnot_anti le_hnot_inf_hnot).antisymm' _,
rw [hnot_le_iff_codisjoint_left, codisjoint_assoc, codisjoint_hnot_hnot_left_iff,
codisjoint_left_comm, codisjoint_hnot_hnot_left_iff, ←codisjoint_assoc, sup_comm],
exact codisjoint_hnot_right,
end
lemma hnot_hnot_sdiff_distrib (a b : α) : ¬¬(a \ b) = ¬¬a \ ¬¬b :=
begin
refine le_antisymm _ _,
{ refine hnot_le_comm.1 ((hnot_anti sdiff_le_inf_hnot).trans' _),
rw [hnot_inf_distrib, hnot_le_iff_codisjoint_right, codisjoint_left_comm,
←hnot_le_iff_codisjoint_right],
exact le_sdiff_sup },
{ rw [sdiff_le_iff, ←hnot_hnot_sup_distrib],
exact hnot_anti (hnot_anti le_sup_sdiff) }
end
instance : heyting_algebra αᵒᵈ :=
{ compl := to_dual ∘ hnot ∘ of_dual,
himp := λ a b, to_dual (of_dual b \ of_dual a),
le_himp_iff := λ a b c, by { rw inf_comm, exact sdiff_le_iff },
himp_bot := top_sdiff',
..order_dual.lattice α, ..order_dual.bounded_order α }
@[simp] lemma of_dual_compl (a : αᵒᵈ) : of_dual aᶜ = ¬of_dual a := rfl
@[simp] lemma of_dual_himp (a b : αᵒᵈ) : of_dual (a ⇨ b) = of_dual b \ of_dual a := rfl
@[simp] lemma to_dual_hnot (a : α) : to_dual ¬a = (to_dual a)ᶜ := rfl
@[simp] lemma to_dual_sdiff (a b : α) : to_dual (a \ b) = to_dual b ⇨ to_dual a := rfl
instance prod.coheyting_algebra [coheyting_algebra β] : coheyting_algebra (α × β) :=
{ sdiff_le_iff := λ a b c, and_congr sdiff_le_iff sdiff_le_iff,
top_sdiff := λ a, prod.ext (top_sdiff' a.1) (top_sdiff' a.2),
..prod.lattice α β, ..prod.bounded_order α β, ..prod.has_sdiff, ..prod.has_hnot }
instance pi.coheyting_algebra {α : ι → Type*} [Π i, coheyting_algebra (α i)] :
coheyting_algebra (Π i, α i) :=
by { pi_instance, exact λ a b c, forall_congr (λ i, sdiff_le_iff) }
end coheyting_algebra
section biheyting_algebra
variables [biheyting_algebra α] {a : α}
lemma compl_le_hnot : aᶜ ≤ ¬a :=
(disjoint_compl_left : disjoint _ a).le_of_codisjoint codisjoint_hnot_right
end biheyting_algebra
/-- Propositions form a Heyting algebra with implication as Heyting implication and negation as
complement. -/
instance Prop.heyting_algebra : heyting_algebra Prop :=
{ himp := (→),
le_himp_iff := λ p q r, and_imp.symm,
himp_bot := λ p, rfl,
..Prop.has_compl, ..Prop.distrib_lattice, ..Prop.bounded_order }
@[simp] lemma himp_iff_imp (p q : Prop) : p ⇨ q ↔ p → q := iff.rfl
@[simp] lemma compl_iff_not (p : Prop) : pᶜ ↔ ¬ p := iff.rfl
/-- A bounded linear order is a bi-Heyting algebra by setting
* `a ⇨ b = ⊤` if `a ≤ b` and `a ⇨ b = b` otherwise.
* `a \ b = ⊥` if `a ≤ b` and `a \ b = a` otherwise. -/
@[reducible] -- See note [reducible non-instances]
def linear_order.to_biheyting_algebra [linear_order α] [bounded_order α] : biheyting_algebra α :=
{ himp := λ a b, if a ≤ b then ⊤ else b,
compl := λ a, if a = ⊥ then ⊤ else ⊥,
le_himp_iff := λ a b c, begin
change _ ≤ ite _ _ _ ↔ _,
split_ifs,
{ exact iff_of_true le_top (inf_le_of_right_le h) },
{ rw [inf_le_iff, or_iff_left h] }
end,
himp_bot := λ a, if_congr le_bot_iff rfl rfl,
sdiff := λ a b, if a ≤ b then ⊥ else a,
hnot := λ a, if a = ⊤ then ⊥ else ⊤,
sdiff_le_iff := λ a b c, begin
change ite _ _ _ ≤ _ ↔ _,
split_ifs,
{ exact iff_of_true bot_le (le_sup_of_le_left h) },
{ rw [le_sup_iff, or_iff_right h] }
end,
top_sdiff := λ a, if_congr top_le_iff rfl rfl,
..linear_order.to_lattice, ..‹bounded_order α› }
section lift
/-- Pullback a `generalized_heyting_algebra` along an injection. -/
@[reducible] -- See note [reducible non-instances]
protected def function.injective.generalized_heyting_algebra [has_sup α] [has_inf α] [has_top α]
[has_himp α] [generalized_heyting_algebra β] (f : α → β) (hf : injective f)
(map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b)
(map_top : f ⊤ = ⊤) (map_himp : ∀ a b, f (a ⇨ b) = f a ⇨ f b) :
generalized_heyting_algebra α :=
{ le_top := λ a, by { change f _ ≤ _, rw map_top, exact le_top },
le_himp_iff := λ a b c, by { change f _ ≤ _ ↔ f _ ≤ _, erw [map_himp, map_inf, le_himp_iff] },
..hf.lattice f map_sup map_inf, ..‹has_top α›, ..‹has_himp α› }
/-- Pullback a `generalized_coheyting_algebra` along an injection. -/
@[reducible] -- See note [reducible non-instances]
protected def function.injective.generalized_coheyting_algebra [has_sup α] [has_inf α] [has_bot α]
[has_sdiff α] [generalized_coheyting_algebra β] (f : α → β) (hf : injective f)
(map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b)
(map_bot : f ⊥ = ⊥) (map_sdiff : ∀ a b, f (a \ b) = f a \ f b) :
generalized_coheyting_algebra α :=
{ bot_le := λ a, by { change f _ ≤ _, rw map_bot, exact bot_le },
sdiff_le_iff := λ a b c, by { change f _ ≤ _ ↔ f _ ≤ _, erw [map_sdiff, map_sup, sdiff_le_iff] },
..hf.lattice f map_sup map_inf, ..‹has_bot α›, ..‹has_sdiff α› }
/-- Pullback a `heyting_algebra` along an injection. -/
@[reducible] -- See note [reducible non-instances]
protected def function.injective.heyting_algebra [has_sup α] [has_inf α] [has_top α] [has_bot α]
[has_compl α] [has_himp α] [heyting_algebra β] (f : α → β) (hf : injective f)
(map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b)
(map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) (map_compl : ∀ a, f aᶜ = (f a)ᶜ)
(map_himp : ∀ a b, f (a ⇨ b) = f a ⇨ f b) :
heyting_algebra α :=
{ bot_le := λ a, by { change f _ ≤ _, rw map_bot, exact bot_le },
himp_bot := λ a, hf $ by erw [map_himp, map_compl, map_bot, himp_bot],
..hf.generalized_heyting_algebra f map_sup map_inf map_top map_himp,
..‹has_bot α›, ..‹has_compl α› }
/-- Pullback a `coheyting_algebra` along an injection. -/
@[reducible] -- See note [reducible non-instances]
protected def function.injective.coheyting_algebra [has_sup α] [has_inf α] [has_top α] [has_bot α]
[has_hnot α] [has_sdiff α] [coheyting_algebra β] (f : α → β) (hf : injective f)
(map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b)
(map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) (map_hnot : ∀ a, f ¬a = ¬f a)
(map_sdiff : ∀ a b, f (a \ b) = f a \ f b) :
coheyting_algebra α :=
{ le_top := λ a, by { change f _ ≤ _, rw map_top, exact le_top },
top_sdiff := λ a, hf $ by erw [map_sdiff, map_hnot, map_top, top_sdiff'],
..hf.generalized_coheyting_algebra f map_sup map_inf map_bot map_sdiff,
..‹has_top α›, ..‹has_hnot α› }
/-- Pullback a `biheyting_algebra` along an injection. -/
@[reducible] -- See note [reducible non-instances]
protected def function.injective.biheyting_algebra [has_sup α] [has_inf α] [has_top α] [has_bot α]
[has_compl α] [has_hnot α] [has_himp α] [has_sdiff α] [biheyting_algebra β] (f : α → β)
(hf : injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b)
(map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥)
(map_compl : ∀ a, f aᶜ = (f a)ᶜ) (map_hnot : ∀ a, f ¬a = ¬f a)
(map_himp : ∀ a b, f (a ⇨ b) = f a ⇨ f b) (map_sdiff : ∀ a b, f (a \ b) = f a \ f b) :
biheyting_algebra α :=
{ ..hf.heyting_algebra f map_sup map_inf map_top map_bot map_compl map_himp,
..hf.coheyting_algebra f map_sup map_inf map_top map_bot map_hnot map_sdiff }
end lift
namespace punit
variables (a b : punit.{u+1})
instance : biheyting_algebra punit :=
by refine_struct
{ top := star,
bot := star,
sup := λ _ _, star,
inf := λ _ _, star,
compl := λ _, star,
sdiff := λ _ _, star,
hnot := λ _, star,
himp := λ _ _, star, ..punit.linear_order };
intros; trivial <|> exact subsingleton.elim _ _
@[simp] lemma top_eq : (⊤ : punit) = star := rfl
@[simp] lemma bot_eq : (⊥ : punit) = star := rfl
@[simp] lemma sup_eq : a ⊔ b = star := rfl
@[simp] lemma inf_eq : a ⊓ b = star := rfl
@[simp] lemma compl_eq : aᶜ = star := rfl
@[simp] lemma sdiff_eq : a \ b = star := rfl
@[simp, nolint simp_nf] lemma hnot_eq : ¬a = star := rfl -- eligible for `dsimp`
@[simp] lemma himp_eq : a ⇨ b = star := rfl
end punit
|
abf39c29e517d272b311db279f150d6d7872529b | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/analysis/complex/exponential.lean | 8aebb5279beea1e7bf4a01676c3444ed7ca3098c | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 82,267 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne
-/
import tactic.linarith data.complex.exponential analysis.specific_limits
group_theory.quotient_group analysis.complex.basic
/-!
# Exponential
## Main definitions
This file contains the following definitions:
* π, arcsin, arccos, arctan
* argument of a complex number
* logarithm on real and complex numbers
* complex and real power function
## Main statements
The following functions are shown to be continuous:
* complex and real exponential function
* sin, cos, tan, sinh, cosh
* logarithm on real numbers
* real power function
* square root function
The following functions are shown to be differentiable, and their derivatives are computed:
* complex and real exponential function
* sin, cos, sinh, cosh
## Tags
exp, log, sin, cos, tan, arcsin, arccos, arctan, angle, argument, power, square root,
-/
noncomputable theory
open finset filter metric asymptotics
open_locale topological_space
namespace complex
/-- The complex exponential is everywhere differentiable, with the derivative `exp x`. -/
lemma has_deriv_at_exp (x : ℂ) : has_deriv_at exp (exp x) x :=
begin
rw has_deriv_at_iff_is_o_nhds_zero,
have : (1 : ℕ) < 2 := by norm_num,
refine is_O.trans_is_o (is_O_iff.2 ⟨∥exp x∥, _⟩) (is_o_pow_id this),
have : metric.ball (0 : ℂ) 1 ∈ nhds (0 : ℂ) :=
mem_nhds_sets metric.is_open_ball (by simp [zero_lt_one]),
apply filter.mem_sets_of_superset this (λz hz, _),
simp only [metric.mem_ball, dist_zero_right] at hz,
simp only [exp_zero, mul_one, one_mul, add_comm, normed_field.norm_pow,
zero_add, set.mem_set_of_eq],
calc ∥exp (x + z) - exp x - z * exp x∥
= ∥exp x * (exp z - 1 - z)∥ : by { congr, rw [exp_add], ring }
... = ∥exp x∥ * ∥exp z - 1 - z∥ : normed_field.norm_mul _ _
... ≤ ∥exp x∥ * ∥z∥^2 :
mul_le_mul_of_nonneg_left (abs_exp_sub_one_sub_id_le (le_of_lt hz)) (norm_nonneg _)
end
lemma differentiable_exp : differentiable ℂ exp :=
λx, (has_deriv_at_exp x).differentiable_at
@[simp] lemma deriv_exp {x : ℂ} : deriv exp x = exp x :=
(has_deriv_at_exp x).deriv
lemma continuous_exp : continuous exp :=
differentiable_exp.continuous
/-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/
lemma has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x :=
begin
have A : has_deriv_at (λ(z:ℂ), exp (z * I)) (I * exp (x * I)) x,
{ convert (has_deriv_at_exp _).comp x ((has_deriv_at_id x).mul (has_deriv_at_const x I)),
simp },
have B : has_deriv_at (λ(z:ℂ), exp (-z * I)) (-I * exp (-x * I)) x,
{ convert (has_deriv_at_exp _).comp x ((has_deriv_at_id x).neg.mul (has_deriv_at_const x I)),
simp },
have C : has_deriv_at (λ(z:ℂ), exp (-z * I) - exp (z * I)) (-I * (exp (x * I) + exp (-x * I))) x,
by { convert has_deriv_at.sub B A, ring },
convert has_deriv_at.mul C (has_deriv_at_const x (I/(2:ℂ))),
{ ext z, simp [sin, mul_div_assoc] },
{ simp only [cos, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, zero_add, sub_eq_add_neg, mul_zero],
rw [← mul_assoc, ← mul_div_right_comm, I_mul_I, div_eq_mul_inv, div_eq_mul_inv],
generalize : (2 : ℂ)⁻¹ = u,
ring }
end
lemma differentiable_sin : differentiable ℂ sin :=
λx, (has_deriv_at_sin x).differentiable_at
@[simp] lemma deriv_sin {x : ℂ} : deriv sin x = cos x :=
(has_deriv_at_sin x).deriv
lemma continuous_sin : continuous sin :=
differentiable_sin.continuous
/-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/
lemma has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x :=
begin
have A : has_deriv_at (λ(z:ℂ), exp (z * I)) (I * exp (x * I)) x,
{ convert (has_deriv_at_exp _).comp x ((has_deriv_at_id x).mul (has_deriv_at_const x I)),
simp },
have B : has_deriv_at (λ(z:ℂ), exp (-z * I)) (-I * exp (-x * I)) x,
{ convert (has_deriv_at_exp _).comp x ((has_deriv_at_id x).neg.mul (has_deriv_at_const x I)),
simp },
have C : has_deriv_at (λ(z:ℂ), exp (z * I) + exp (-z * I)) (I * (exp (x * I) - exp (-x * I))) x,
by { convert has_deriv_at.add A B, ring },
convert has_deriv_at.mul C (has_deriv_at_const x (1/(2:ℂ))),
{ ext z, simp [cos, mul_div_assoc], refl },
{ simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul_symm, one_mul, zero_add, sub_eq_add_neg, mul_zero],
generalize : (2 : ℂ)⁻¹ = u,
ring }
end
lemma differentiable_cos : differentiable ℂ cos :=
λx, (has_deriv_at_cos x).differentiable_at
@[simp] lemma deriv_cos {x : ℂ} : deriv cos x = -sin x :=
(has_deriv_at_cos x).deriv
lemma continuous_cos : continuous cos :=
differentiable_cos.continuous
lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) :=
(continuous_sin.comp continuous_subtype_val).mul
(continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val))
/-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `sinh x`. -/
lemma has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x :=
begin
have C : has_deriv_at (λ(z:ℂ), exp z - exp(-z)) (exp x + exp (-x)) x,
{ convert (has_deriv_at_exp x).sub ((has_deriv_at_exp _).comp x (has_deriv_at_id x).neg),
simp },
convert has_deriv_at.mul C (has_deriv_at_const x (1/(2:ℂ))),
{ ext z, simp [sinh, div_eq_mul_inv] },
{ simp [cosh, div_eq_mul_inv, mul_comm] }
end
lemma differentiable_sinh : differentiable ℂ sinh :=
λx, (has_deriv_at_sinh x).differentiable_at
@[simp] lemma deriv_sinh {x : ℂ} : deriv sinh x = cosh x :=
(has_deriv_at_sinh x).deriv
lemma continuous_sinh : continuous sinh :=
differentiable_sinh.continuous
/-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `cosh x`. -/
lemma has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x :=
begin
have C : has_deriv_at (λ(z:ℂ), exp z + exp(-z)) (exp x - exp (-x)) x,
{ convert (has_deriv_at_exp x).add ((has_deriv_at_exp _).comp x (has_deriv_at_id x).neg),
simp },
convert has_deriv_at.mul C (has_deriv_at_const x (1/(2:ℂ))),
{ ext z, simp [cosh, div_eq_mul_inv] },
{ simp [sinh, div_eq_mul_inv, mul_comm] }
end
lemma differentiable_cosh : differentiable ℂ cosh :=
λx, (has_deriv_at_cosh x).differentiable_at
@[simp] lemma deriv_cosh {x : ℂ} : deriv cosh x = sinh x :=
(has_deriv_at_cosh x).deriv
lemma continuous_cosh : continuous cosh :=
differentiable_cosh.continuous
end complex
namespace real
variables {x y z : ℝ}
lemma has_deriv_at_exp (x : ℝ) : has_deriv_at exp (exp x) x :=
has_deriv_at_real_of_complex (complex.has_deriv_at_exp x)
lemma differentiable_exp : differentiable ℝ exp :=
λx, (has_deriv_at_exp x).differentiable_at
@[simp] lemma deriv_exp : deriv exp x = exp x :=
(has_deriv_at_exp x).deriv
lemma continuous_exp : continuous exp :=
differentiable_exp.continuous
lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x :=
has_deriv_at_real_of_complex (complex.has_deriv_at_sin x)
lemma differentiable_sin : differentiable ℝ sin :=
λx, (has_deriv_at_sin x).differentiable_at
@[simp] lemma deriv_sin : deriv sin x = cos x :=
(has_deriv_at_sin x).deriv
lemma continuous_sin : continuous sin :=
differentiable_sin.continuous
lemma has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x :=
(has_deriv_at_real_of_complex (complex.has_deriv_at_cos x) : _)
lemma differentiable_cos : differentiable ℝ cos :=
λx, (has_deriv_at_cos x).differentiable_at
@[simp] lemma deriv_cos : deriv cos x = - sin x :=
(has_deriv_at_cos x).deriv
lemma continuous_cos : continuous cos :=
differentiable_cos.continuous
lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) :=
by simp only [tan_eq_sin_div_cos]; exact
(continuous_sin.comp continuous_subtype_val).mul
(continuous.inv subtype.property
(continuous_cos.comp continuous_subtype_val))
lemma has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x :=
has_deriv_at_real_of_complex (complex.has_deriv_at_sinh x)
lemma differentiable_sinh : differentiable ℝ sinh :=
λx, (has_deriv_at_sinh x).differentiable_at
@[simp] lemma deriv_sinh : deriv sinh x = cosh x :=
(has_deriv_at_sinh x).deriv
lemma continuous_sinh : continuous sinh :=
differentiable_sinh.continuous
lemma has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x :=
has_deriv_at_real_of_complex (complex.has_deriv_at_cosh x)
lemma differentiable_cosh : differentiable ℝ cosh :=
λx, (has_deriv_at_cosh x).differentiable_at
@[simp] lemma deriv_cosh : deriv cosh x = sinh x :=
(has_deriv_at_cosh x).deriv
lemma continuous_cosh : continuous cosh :=
differentiable_cosh.continuous
lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x :=
have ∀ {z:ℝ}, 1 ≤ z → z ∈ set.range exp,
from λ z hz, intermediate_value_univ 0 (z - 1) continuous_exp
⟨by simpa, by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hz)⟩,
match le_total x 1 with
| (or.inl hx1) := let ⟨y, hy⟩ := this (one_le_inv hx hx1) in
⟨-y, by rw [exp_neg, hy, inv_inv']⟩
| (or.inr hx1) := this hx1
end
/-- The real logarithm function, equal to `0` for `x ≤ 0` and to the inverse of the exponential
for `x > 0`. -/
noncomputable def log (x : ℝ) : ℝ :=
if hx : 0 < x then classical.some (exists_exp_eq_of_pos hx) else 0
lemma exp_log {x : ℝ} (hx : 0 < x) : exp (log x) = x :=
by rw [log, dif_pos hx]; exact classical.some_spec (exists_exp_eq_of_pos hx)
@[simp] lemma log_exp (x : ℝ) : log (exp x) = x :=
exp_injective $ exp_log (exp_pos x)
@[simp] lemma log_zero : log 0 = 0 :=
by simp [log, lt_irrefl]
@[simp] lemma log_one : log 1 = 0 :=
exp_injective $ by rw [exp_log zero_lt_one, exp_zero]
lemma log_mul {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : log (x * y) = log x + log y :=
exp_injective $ by rw [exp_log (mul_pos hx hy), exp_add, exp_log hx, exp_log hy]
lemma log_le_log {x y : ℝ} (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y :=
⟨λ h₂, by rwa [←real.exp_le_exp, real.exp_log h, real.exp_log h₁] at h₂, λ h₂,
(real.exp_le_exp).1 $ by rwa [real.exp_log h₁, real.exp_log h]⟩
lemma log_lt_log (hx : 0 < x) : x < y → log x < log y :=
by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] }
lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y :=
by { rw [← exp_lt_exp, exp_log hx, exp_log hy] }
lemma log_pos_iff (x : ℝ) : 0 < log x ↔ 1 < x :=
begin
by_cases h : 0 < x,
{ rw ← log_one, exact log_lt_log_iff (by norm_num) h },
{ rw [log, dif_neg], split, repeat {intro, linarith} }
end
lemma log_pos : 1 < x → 0 < log x := (log_pos_iff x).2
lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 :=
by { rw ← log_one, exact log_lt_log_iff h (by norm_num) }
lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1
lemma log_nonneg : 1 ≤ x → 0 ≤ log x :=
by { intro, rwa [← log_one, log_le_log], norm_num, linarith }
lemma log_nonpos : x ≤ 1 → log x ≤ 0 :=
begin
intro, by_cases hx : 0 < x,
{ rwa [← log_one, log_le_log], exact hx, norm_num },
{ simp [log, dif_neg hx] }
end
section prove_log_is_continuous
lemma tendsto_log_one_zero : tendsto log (𝓝 1) (𝓝 0) :=
begin
rw tendsto_nhds_nhds, assume ε ε0,
let δ := min (exp ε - 1) (1 - exp (-ε)),
have : 0 < δ,
refine lt_min (sub_pos_of_lt (by rwa one_lt_exp_iff)) (sub_pos_of_lt _),
by { rw exp_lt_one_iff, linarith },
use [δ, this], assume x h,
cases le_total 1 x with hx hx,
{ have h : x < exp ε,
rw [dist_eq, abs_of_nonneg (sub_nonneg_of_le hx)] at h,
linarith [(min_le_left _ _ : δ ≤ exp ε - 1)],
calc abs (log x - 0) = abs (log x) : by simp
... = log x : abs_of_nonneg $ log_nonneg hx
... < ε : by { rwa [← exp_lt_exp, exp_log], linarith }},
{ have h : exp (-ε) < x,
rw [dist_eq, abs_of_nonpos (sub_nonpos_of_le hx)] at h,
linarith [(min_le_right _ _ : δ ≤ 1 - exp (-ε))],
have : 0 < x := lt_trans (exp_pos _) h,
calc abs (log x - 0) = abs (log x) : by simp
... = -log x : abs_of_nonpos $ log_nonpos hx
... < ε : by { rw [neg_lt, ← exp_lt_exp, exp_log], assumption' } }
end
lemma continuous_log' : continuous (λx : {x:ℝ // 0 < x}, log x.val) :=
continuous_iff_continuous_at.2 $ λ x,
begin
rw continuous_at,
let f₁ := λ h:{h:ℝ // 0 < h}, log (x.1 * h.1),
let f₂ := λ y:{y:ℝ // 0 < y}, subtype.mk (x.1 ⁻¹ * y.1) (mul_pos (inv_pos x.2) y.2),
have H1 : tendsto f₁ (𝓝 ⟨1, zero_lt_one⟩) (𝓝 (log (x.1*1))),
have : f₁ = λ h:{h:ℝ // 0 < h}, log x.1 + log h.1,
ext h, rw ← log_mul x.2 h.2,
simp only [this, log_mul x.2 zero_lt_one, log_one],
exact tendsto_const_nhds.add (tendsto.comp tendsto_log_one_zero continuous_at_subtype_val),
have H2 : tendsto f₂ (𝓝 x) (𝓝 ⟨x.1⁻¹ * x.1, mul_pos (inv_pos x.2) x.2⟩),
rw tendsto_subtype_rng, exact tendsto_const_nhds.mul continuous_at_subtype_val,
suffices h : tendsto (f₁ ∘ f₂) (𝓝 x) (𝓝 (log x.1)),
begin
convert h, ext y,
have : x.val * (x.val⁻¹ * y.val) = y.val,
rw [← mul_assoc, mul_inv_cancel (ne_of_gt x.2), one_mul],
show log (y.val) = log (x.val * (x.val⁻¹ * y.val)), rw this
end,
exact tendsto.comp (by rwa mul_one at H1)
(by { simp only [inv_mul_cancel (ne_of_gt x.2)] at H2, assumption })
end
lemma continuous_at_log (hx : 0 < x) : continuous_at log x :=
continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_log' _ hx)
(mem_nhds_sets (is_open_lt' _) hx)
/--
Three forms of the continuity of `real.log` is provided.
For the other two forms, see `real.continuous_log'` and `real.continuous_at_log`
-/
lemma continuous_log {α : Type*} [topological_space α] {f : α → ℝ} (h : ∀a, 0 < f a)
(hf : continuous f) : continuous (λa, log (f a)) :=
show continuous ((log ∘ @subtype.val ℝ (λr, 0 < r)) ∘ λa, ⟨f a, h a⟩),
from continuous_log'.comp (continuous_subtype_mk _ hf)
end prove_log_is_continuous
lemma exists_cos_eq_zero : 0 ∈ cos '' set.Icc (1:ℝ) 2 :=
intermediate_value_Icc' (by norm_num) continuous_cos.continuous_on
⟨le_of_lt cos_two_neg, le_of_lt cos_one_pos⟩
/-- The number π = 3.14159265... Defined here using choice as twice a zero of cos in [1,2], from
which one can derive all its properties. For explicit bounds on π, see `data.real.pi`. -/
noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero
localized "notation `π` := real.pi" in real
@[simp] lemma cos_pi_div_two : cos (π / 2) = 0 :=
by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)];
exact (classical.some_spec exists_cos_eq_zero).2
lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 :=
by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)];
exact (classical.some_spec exists_cos_eq_zero).1.1
lemma pi_div_two_le_two : π / 2 ≤ 2 :=
by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)];
exact (classical.some_spec exists_cos_eq_zero).1.2
lemma two_le_pi : (2 : ℝ) ≤ π :=
(div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1
(by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two)
lemma pi_le_four : π ≤ 4 :=
(div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1
(calc π / 2 ≤ 2 : pi_div_two_le_two
... = 4 / 2 : by norm_num)
lemma pi_pos : 0 < π :=
lt_of_lt_of_le (by norm_num) two_le_pi
lemma pi_div_two_pos : 0 < π / 2 :=
half_pos pi_pos
lemma two_pi_pos : 0 < 2 * π :=
by linarith [pi_pos]
@[simp] lemma sin_pi : sin π = 0 :=
by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), two_mul, add_div,
sin_add, cos_pi_div_two]; simp
@[simp] lemma cos_pi : cos π = -1 :=
by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), mul_div_assoc,
cos_two_mul, cos_pi_div_two];
simp [bit0, pow_add]
@[simp] lemma sin_two_pi : sin (2 * π) = 0 :=
by simp [two_mul, sin_add]
@[simp] lemma cos_two_pi : cos (2 * π) = 1 :=
by simp [two_mul, cos_add]
lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x :=
by simp [sin_add]
lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x :=
by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi]
lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x :=
by simp [cos_add, cos_two_pi, sin_two_pi]
lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x :=
by simp [sin_add]
lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x :=
by simp [cos_add]
lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x :=
by simp [cos_add]
lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x :=
if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2
else
have (2 : ℝ) + 2 = 4, from rfl,
have π - x ≤ 2, from sub_le_iff_le_add.2
(le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)),
sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this
lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x :=
match lt_or_eq_of_le h0x with
| or.inl h0x := (lt_or_eq_of_le hxp).elim
(le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x)
(λ hpx, by simp [hpx])
| or.inr h0x := by simp [h0x.symm]
end
lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 :=
neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx)
lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 :=
neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx)
@[simp] lemma sin_pi_div_two : sin (π / 2) = 1 :=
have sin (π / 2) = 1 ∨ sin (π / 2) = -1 :=
by simpa [pow_two, mul_self_eq_one_iff] using sin_sq_add_cos_sq (π / 2),
this.resolve_right
(λ h, (show ¬(0 : ℝ) < -1, by norm_num) $
h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos))
lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x :=
by simp [sin_add]
lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x :=
by simp [sin_add]
lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x :=
by simp [sin_add]
lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x :=
by simp [cos_add]
lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x :=
by simp [cos_add]
lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x :=
by rw [← cos_neg, neg_sub, cos_sub_pi_div_two]
lemma cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two
{x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x :=
sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith)
lemma cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two
{x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x :=
match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with
| or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two hx₁ hx₂)
| or.inl hx₁, or.inr hx₂ := by simp [hx₂]
| or.inr hx₁, _ := by simp [hx₁.symm]
end
lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 :=
neg_pos.1 $ cos_pi_sub x ▸
cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) (by linarith)
lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 :=
neg_nonneg.1 $ cos_pi_sub x ▸
cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (by linarith) (by linarith)
lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 :=
by induction n; simp [add_mul, sin_add, *]
lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 :=
by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi]
lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 :=
by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi]
lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 :=
by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe,
int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg,
(neg_mul_eq_neg_mul _ _).symm, cos_neg]
lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 :=
by simp [cos_add, sin_add, cos_int_mul_two_pi]
lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) :
sin x = 0 ↔ x = 0 :=
⟨λ h, le_antisymm
(le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $
calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂
... = 0 : h))
(le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $
calc 0 = sin x : h.symm
... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)),
λ h, by simp [h]⟩
lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x :=
⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos))
(sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos))
(by simp [sin_add, h, sin_int_mul_pi]))⟩,
λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩
lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 :=
by rw [← mul_self_eq_one_iff (cos x), ← sin_sq_add_cos_sq x,
pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self];
exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩
theorem sin_sub_sin (θ ψ : ℝ) : sin θ - sin ψ = 2 * sin((θ - ψ)/2) * cos((θ + ψ)/2) :=
begin
have s1 := sin_add ((θ + ψ) / 2) ((θ - ψ) / 2),
have s2 := sin_sub ((θ + ψ) / 2) ((θ - ψ) / 2),
rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, add_self_div_two] at s1,
rw [div_sub_div_same, ←sub_add, add_sub_cancel', add_self_div_two] at s2,
rw [s1, s2, ←sub_add, add_sub_cancel', ← two_mul, ← mul_assoc, mul_right_comm]
end
lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x :=
⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in
⟨n / 2, (int.mod_two_eq_zero_or_one n).elim
(λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel
((int.dvd_iff_mod_eq_zero _ _).2 hn0)])
(λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul,
one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn;
rw [← hn, cos_int_mul_two_pi_add_pi] at h;
exact absurd h (by norm_num))⟩,
λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩
theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * pi / 2 :=
begin
rw [←real.sin_pi_div_two_sub, sin_eq_zero_iff],
split,
{ rintro ⟨n, hn⟩, existsi -n,
rw [int.cast_neg, add_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero,
one_mul, ←neg_mul_eq_neg_mul, hn, neg_sub, sub_add_cancel] },
{ rintro ⟨n, hn⟩, existsi -n,
rw [hn, add_mul, one_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero,
sub_add_eq_sub_sub_swap, sub_self, zero_sub, neg_mul_eq_neg_mul, int.cast_neg] }
end
lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 :=
⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in
begin
clear _let_match,
subst hn,
rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂,
rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt,
← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁,
exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))),
end,
λ h, by simp [h]⟩
theorem cos_sub_cos (θ ψ : ℝ) : cos θ - cos ψ = -2 * sin((θ + ψ)/2) * sin((θ - ψ)/2) :=
by rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub, sin_sub_sin, sub_sub_sub_cancel_left,
add_sub, sub_add_eq_add_sub, add_halves, sub_sub, sub_div π, cos_pi_div_two_sub,
← neg_sub, neg_div, sin_neg, ← neg_mul_eq_mul_neg, neg_mul_eq_neg_mul, mul_right_comm]
lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π / 2)
(hy₁ : 0 ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x :=
calc cos y = cos x * cos (y - x) - sin x * sin (y - x) :
by rw [← cos_add, add_sub_cancel'_right]
... < (cos x * 1) - sin x * sin (y - x) :
sub_lt_sub_right ((mul_lt_mul_left
(cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (lt_of_lt_of_le (neg_neg_of_pos pi_div_two_pos) hx₁)
(lt_of_lt_of_le hxy hy₂))).2
(lt_of_le_of_ne (cos_le_one _) (mt (cos_eq_one_iff_of_lt_of_lt
(show -(2 * π) < y - x, by linarith) (show y - x < 2 * π, by linarith)).1
(sub_ne_zero.2 (ne_of_lt hxy).symm)))) _
... ≤ _ : by rw mul_one;
exact sub_le_self _ (mul_nonneg (sin_nonneg_of_nonneg_of_le_pi hx₁ (by linarith))
(sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith)))
lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π)
(hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x < y) : cos y < cos x :=
match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with
| or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hx hy₁ hy hxy
| or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim
(λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith [pi_pos])
... < cos x : cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hx)
(λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith [pi_pos])
... = cos x : by rw [hx, cos_pi_div_two])
| or.inr hx, or.inl hy := by linarith
| or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub];
apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith)
end
lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π)
(hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x ≤ y) : cos y ≤ cos x :=
(lt_or_eq_of_le hxy).elim
(le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hx₂ hy₁ hy₂)
(λ h, h ▸ le_refl _)
lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y)
(hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y :=
by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)];
apply cos_lt_cos_of_nonneg_of_le_pi; linarith
lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y)
(hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y :=
(lt_or_eq_of_le hxy).elim
(le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂)
(λ h, h ▸ le_refl _)
lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y)
(hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y :=
match lt_trichotomy x y with
| or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _)
| or.inr (or.inl h) := h
| or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _)
end
lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π)
(hxy : cos x = cos y) : x = y :=
begin
rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy,
refine (sub_left_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy);
linarith
end
lemma exists_sin_eq : set.Icc (-1:ℝ) 1 ⊆ sin '' set.Icc (-(π / 2)) (π / 2) :=
by convert intermediate_value_Icc
(le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos))
continuous_sin.continuous_on; simp only [sin_neg, sin_pi_div_two]
lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x :=
begin
cases le_or_gt x 1 with h' h',
{ have hx : abs x = x := abs_of_nonneg (le_of_lt h),
have : abs x ≤ 1, rwa [hx],
have := sin_bound this, rw [abs_le] at this,
have := this.2, rw [sub_le_iff_le_add', hx] at this,
apply lt_of_le_of_lt this, rw [sub_add], apply lt_of_lt_of_le _ (le_of_eq (sub_zero x)),
apply sub_lt_sub_left, rw sub_pos, apply mul_lt_mul',
{ rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)),
rw mul_le_mul_right, exact h', apply pow_pos h },
norm_num, norm_num, apply pow_pos h },
exact lt_of_le_of_lt (sin_le_one x) h'
end
/- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6.
note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/
lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ 3 / 4 < sin x :=
begin
have hx : abs x = x := abs_of_nonneg (le_of_lt h),
have : abs x ≤ 1, rwa [hx],
have := sin_bound this, rw [abs_le] at this,
have := this.1, rw [le_sub_iff_add_le, hx] at this,
refine lt_of_lt_of_le _ this,
rw [add_comm, sub_add, sub_neg_eq_add], apply sub_lt_sub_left,
apply add_lt_of_lt_sub_left,
rw (show x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 / 12,
by simp [div_eq_mul_inv, (mul_sub _ _ _).symm, -sub_eq_add_neg]; congr; norm_num),
apply mul_lt_mul',
{ rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)),
rw mul_le_mul_right, exact h', apply pow_pos h },
norm_num, norm_num, apply pow_pos h
end
/-- The type of angles -/
def angle : Type :=
quotient_add_group.quotient (gmultiples (2 * π))
namespace angle
instance angle.add_comm_group : add_comm_group angle :=
quotient_add_group.add_comm_group _
instance angle.has_coe : has_coe ℝ angle :=
⟨quotient.mk'⟩
instance angle.is_add_group_hom : is_add_group_hom (coe : ℝ → angle) :=
@quotient_add_group.is_add_group_hom _ _ _ (normal_add_subgroup_of_add_comm_group _)
@[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl
@[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl
@[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl
@[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl
@[simp] lemma coe_gsmul (x : ℝ) (n : ℤ) : ↑(gsmul n x : ℝ) = gsmul n (↑x : angle) := is_add_group_hom.map_gsmul _ _ _
@[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) :=
quotient.sound' ⟨-1, by dsimp only; rw [neg_one_gsmul, add_zero]⟩
lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k :=
by simp only [quotient_add_group.eq, gmultiples, set.mem_range, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm]
theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ :=
begin
split,
{ intro Hcos,
rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero,
false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos,
rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩,
{ right,
rw [eq_div_iff_mul_eq _ _ two_ne_zero, ← sub_eq_iff_eq_add] at hn,
rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc,
← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero] },
{ left,
rw [eq_div_iff_mul_eq _ _ two_ne_zero, eq_sub_iff_add_eq] at hn,
rw [← hn, coe_add, mul_assoc,
← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] } },
{ rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub],
rintro (⟨k, H⟩ | ⟨k, H⟩),
rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero,
mul_comm π _, sin_int_mul_pi, mul_zero],
rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k,
mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] }
end
theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π :=
begin
split,
{ intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin,
cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h,
{ left, rw coe_sub at h, exact sub_left_inj.1 h },
right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub,
sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h,
exact h.symm },
{ rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub],
rintro (⟨k, H⟩ | ⟨k, H⟩),
rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero,
mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul],
have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add,
mul_assoc, mul_comm π _, ←mul_assoc] at H,
rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ two_ne_zero,
cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] }
end
theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ :=
begin
cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc },
cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs },
rw [eq_neg_iff_add_eq_zero, hs] at hc,
cases quotient.exact' hc with n hn, dsimp only at hn,
rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul,
mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add,
← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn,
have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn,
rw [add_comm, int.add_mul_mod_self] at this,
exact absurd this one_ne_zero
end
end angle
/-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`.
If the argument is not between `-1` and `1` it defaults to `0` -/
noncomputable def arcsin (x : ℝ) : ℝ :=
if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx) else 0
lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 :=
if hx : -1 ≤ x ∧ x ≤ 1
then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.2
else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos
lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x :=
if hx : -1 ≤ x ∧ x ≤ 1
then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.1
else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos)
lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x :=
by rw [arcsin, dif_pos (and.intro hx₁ hx₂)];
exact (classical.some_spec (exists_sin_eq ⟨hx₁, hx₂⟩)).2
lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x :=
sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂
(by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _))
lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1)
(hxy : arcsin x = arcsin y) : x = y :=
by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy]
@[simp] lemma arcsin_zero : arcsin 0 = 0 :=
sin_inj_of_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _)
(arcsin_le_pi_div_two _)
(neg_nonpos.2 (le_of_lt pi_div_two_pos))
(le_of_lt pi_div_two_pos)
(by rw [sin_arcsin, sin_zero]; norm_num)
@[simp] lemma arcsin_one : arcsin 1 = π / 2 :=
sin_inj_of_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _)
(arcsin_le_pi_div_two _)
(by linarith [pi_pos])
(le_refl _)
(by rw [sin_arcsin, sin_pi_div_two]; norm_num)
@[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x :=
if h : -1 ≤ x ∧ x ≤ 1 then
have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm],
sin_inj_of_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _)
(arcsin_le_pi_div_two _)
(neg_le_neg (arcsin_le_pi_div_two _))
(neg_le.1 (neg_pi_div_two_le_arcsin _))
(by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2])
else
have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm],
by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero]
@[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp
lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x :=
if hx₁ : x ≤ 1 then
not_lt.1 (λ h, not_lt.2 hx begin
have := sin_lt_sin_of_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _)
(neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) h,
rw [real.sin_arcsin, sin_zero] at this; linarith
end)
else by rw [arcsin, dif_neg]; simp [hx₁]
lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 :=
⟨λ h, have sin (arcsin x) = 0, by simp [h],
by rwa [sin_arcsin hx₁ hx₂] at this,
λ h, by simp [h]⟩
lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x :=
lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁))
(ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm))
lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 :=
neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx))
/-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`.
If the argument is not between `-1` and `1` it defaults to `π / 2` -/
noncomputable def arccos (x : ℝ) : ℝ :=
π / 2 - arcsin x
lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl
lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x := by simp [arccos]
lemma arccos_le_pi (x : ℝ) : arccos x ≤ π :=
by unfold arccos; linarith [neg_pi_div_two_le_arcsin x]
lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x :=
by unfold arccos; linarith [arcsin_le_pi_div_two x]
lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x :=
by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂]
lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x :=
by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp; linarith
lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1)
(hxy : arccos x = arccos y) : x = y :=
arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at *
@[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos]
@[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos]
@[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves]
lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x :=
by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp
lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) :=
cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _)
lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) :=
have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_sq_add_cos_sq (arcsin x),
begin
rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))),
pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this,
rw [this, sin_arcsin hx₁ hx₂],
end
lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) :=
by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂]
lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 :=
have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _),
have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁,
by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul,
mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _),
← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)),
abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm];
exact lt_add_one _
lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 :=
(abs_lt.1 (abs_div_sqrt_one_add_lt _)).2
lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) :=
(abs_lt.1 (abs_div_sqrt_one_add_lt _)).1
lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x :=
by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith))
(cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hxp)
lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x :=
match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with
| or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp)
| or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos]
| or.inr hx0, _ := by simp [hx0.symm]
end
lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 :=
neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith [pi_pos]))
lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 :=
neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith [pi_pos]))
lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x < π / 2) (hy₁ : 0 ≤ y)
(hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y :=
begin
rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos],
exact div_lt_div
(sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hx₂)
(by linarith) (le_of_lt hy₂) hxy)
(cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) hy₁ (by linarith) (le_of_lt hxy))
(sin_nonneg_of_nonneg_of_le_pi hy₁ (by linarith))
(cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hy₂)
end
lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2)
(hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y :=
match le_total x 0, le_total y 0 with
| or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact
tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0) (neg_lt.2 hy₁)
(neg_nonneg.2 hx0) (neg_lt.2 hx₁) (neg_lt_neg hxy)
| or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim
(λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁)
... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂)
(λ hy0, by rw [← hy0, tan_zero]; exact
tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁)
| or.inr hx0, or.inl hy0 := by linarith
| or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hx₂ hy0 hy₂ hxy
end
lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2)
(hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y :=
match lt_trichotomy x y with
| or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _)
| or.inr (or.inl h) := h
| or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _)
end
/-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/
noncomputable def arctan (x : ℝ) : ℝ :=
arcsin (x / sqrt (1 + x ^ 2))
lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) :=
sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _))
lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) :=
have h₁ : (0 : ℝ) < 1 + x ^ 2,
from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _),
have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1,
by rw [pow_two, ← abs_mul_self, _root_.abs_mul];
exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _)
(abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)),
by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)),
one_div_eq_inv, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)),
div_pow _ (mt sqrt_eq_zero'.1 (not_le.2 h₁)), pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁),
← domain.mul_left_inj (ne.symm (ne_of_lt h₁)), mul_sub,
mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))];
simp
lemma tan_arctan (x : ℝ) : tan (arctan x) = x :=
by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one,
mul_div_assoc,
div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))),
mul_one]
lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 :=
lt_of_le_of_ne (arcsin_le_pi_div_two _)
(λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $
by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _))
(le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two])
lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x :=
lt_of_le_of_ne (neg_pi_div_two_le_arcsin _)
(λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $
by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _))
(le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two])
lemma tan_surjective : function.surjective tan :=
function.surjective_of_has_right_inverse ⟨_, tan_arctan⟩
lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x :=
tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _)
(arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan)
@[simp] lemma arctan_zero : arctan 0 = 0 :=
by simp [arctan]
@[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x :=
by simp [arctan, neg_div]
end real
namespace complex
open_locale real
/-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`,
`sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`,
`arg 0` defaults to `0` -/
noncomputable def arg (x : ℂ) : ℝ :=
if 0 ≤ x.re
then real.arcsin (x.im / x.abs)
else if 0 ≤ x.im
then real.arcsin ((-x).im / x.abs) + π
else real.arcsin ((-x).im / x.abs) - π
lemma arg_le_pi (x : ℂ) : arg x ≤ π :=
if hx₁ : 0 ≤ x.re
then by rw [arg, if_pos hx₁];
exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos))
else
have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁,
if hx₂ : 0 ≤ x.im
then by rw [arg, if_neg hx₁, if_pos hx₂];
exact le_sub_iff_add_le.1 (by rw sub_self;
exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_pos.2 hx)))
else by rw [arg, if_neg hx₁, if_neg hx₂];
exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _)
(by linarith [real.pi_pos]))
lemma neg_pi_lt_arg (x : ℂ) : -π < arg x :=
if hx₁ : 0 ≤ x.re
then by rw [arg, if_pos hx₁];
exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _)
else
have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁,
if hx₂ : 0 ≤ x.im
then by rw [arg, if_neg hx₁, if_pos hx₂];
exact sub_lt_iff_lt_add.1
(lt_of_lt_of_le (by linarith [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _))
else by rw [arg, if_neg hx₁, if_neg hx₂];
exact lt_sub_iff_add_lt.2 (by rw neg_add_self;
exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂))
(abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2))
lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) :
arg x = arg (-x) + π :=
have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos],
by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg]
lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) :
arg x = arg (-x) - π :=
have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos],
by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg]
@[simp] lemma arg_zero : arg 0 = 0 :=
by simp [arg, le_refl]
@[simp] lemma arg_one : arg 1 = 0 :=
by simp [arg, zero_le_one]
@[simp] lemma arg_neg_one : arg (-1) = π :=
by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _)]
@[simp] lemma arg_I : arg I = π / 2 :=
by simp [arg, le_refl]
@[simp] lemma arg_neg_I : arg (-I) = -(π / 2) :=
by simp [arg, le_refl]
lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs :=
by unfold arg; split_ifs;
simp [arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1
(abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg,
real.sin_neg]
private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs :=
have 0 ≤ 1 - (x.im / abs x) ^ 2,
from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two];
exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _),
by rw [eq_div_iff_mul_eq _ _ (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x),
arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1
(abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this,
sub_mul, div_pow _ (mt abs_eq_zero.1 hx), ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)),
one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr]
lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs :=
if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr
else
have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr,
if hxi : 0 ≤ x.im
then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr,
by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi,
cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this];
simp [neg_div]
else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)];
simp [real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]
lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re :=
if hx : x = 0 then by simp [hx]
else by rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg hx,
div_div_div_cancel_right _ _ (mt abs_eq_zero.1 hx)]
lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) :
arg (cos x + sin x * I) = x :=
if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2
then
have hx₄ : 0 ≤ (cos x + sin x * I).re,
by simp; exact real.cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two hx₃.1 hx₃.2,
by rw [arg, if_pos hx₄];
simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2]
else if hx₄ : x < -(π / 2)
then
have hx₅ : ¬0 ≤ (cos x + sin x * I).re :=
suffices ¬ 0 ≤ real.cos x, by simpa,
not_le.2 $ by rw ← real.cos_neg;
apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith,
have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im :=
suffices real.sin x < 0, by simpa,
by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith,
suffices -π + -real.arcsin (real.sin x) = x,
by rw [arg, if_neg hx₅, if_neg hx₆];
simpa [abs_cos_add_sin_mul_I, sin_of_real_re],
by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; simp; linarith
else
have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith,
have hx₆ : ¬0 ≤ (cos x + sin x * I).re :=
suffices ¬0 ≤ real.cos x, by simpa,
not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith,
have hx₇ : 0 ≤ (cos x + sin x * I).im :=
suffices 0 ≤ real.sin x, by simpa,
by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith,
suffices π - real.arcsin (real.sin x) = x,
by rw [arg, if_neg hx₆, if_pos hx₇];
simpa [abs_cos_add_sin_mul_I, sin_of_real_re],
by rw [← real.sin_pi_sub, real.arcsin_sin]; simp; linarith
lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) :
arg x = arg y ↔ (abs y / abs x : ℂ) * x = y :=
have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx),
have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy),
⟨λ h,
begin
have hcos := congr_arg real.cos h,
rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos,
have hsin := congr_arg real.sin h,
rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin,
apply complex.ext,
{ rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm,
← mul_div_assoc, hcos, mul_div_cancel _ hax] },
{ rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero,
mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] }
end,
λ h,
have hre : abs (y / x) * x.re = y.re,
by rw ← of_real_div at h;
simpa [-of_real_div] using congr_arg re h,
have hre' : abs (x / y) * y.re = x.re,
by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div,
mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul],
have him : abs (y / x) * x.im = y.im,
by rw ← of_real_div at h;
simpa [-of_real_div] using congr_arg im h,
have him' : abs (x / y) * y.im = x.im,
by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div,
mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul],
have hxya : x.im / abs x = y.im / abs y,
by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay],
have hnxya : (-x).im / abs x = (-y).im / abs y,
by rw [neg_im, neg_im, neg_div, neg_div, hxya],
if hxr : 0 ≤ x.re
then
have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr,
by simp [arg, *] at *
else
have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr,
if hxi : 0 ≤ x.im
then
have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi,
by simp [arg, *] at *
else
have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi,
by simp [arg, *] at *⟩
lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x :=
if hx : x = 0 then by simp [hx]
else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $
by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc,
of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul,
div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm),
div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul]
lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y :=
if hy : y = 0 then by simp * at *
else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *,
by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂
lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 :=
by simp [arg, hx]
lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π :=
by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg];
simp [*, le_iff_eq_or_lt, lt_neg]
/-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`.
`log 0 = 0`-/
noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I
lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log]
lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log]
lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x :=
by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx,
← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div,
mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc,
mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im]
lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π)
(hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y :=
by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy;
exact complex.ext
(real.exp_injective $
by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy)
(by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _),
arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy)
lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x :=
exp_inj_of_neg_pi_lt_of_le_pi
(by rw log_im; exact neg_pi_lt_arg _)
(by rw log_im; exact arg_le_pi _)
hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)])
lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x :=
complex.ext
(by rw [log_re, of_real_re, abs_of_nonneg hx])
(by rw [of_real_im, log_im, arg_of_real_of_nonneg hx])
@[simp] lemma log_zero : log 0 = 0 := by simp [log]
@[simp] lemma log_one : log 1 = 0 := by simp [log]
lemma log_neg_one : log (-1) = π * I := by simp [log]
lemma log_I : log I = π / 2 * I := by simp [log]
lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log]
lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) :=
have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1,
from λ h₁ h₂, begin
rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁,
have := real.exp_pos x.re,
rw ← h₁ at this,
exact absurd this (by norm_num)
end,
calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff]
... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 :
begin
rw exp_eq_exp_re_mul_sin_add_cos,
simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re,
real.exp_ne_zero],
split; finish [real.sin_eq_zero_iff_cos_eq]
end
... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 :
by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff]
... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) :
⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩,
λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩,
by simp [hn]⟩⟩
lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 :=
by rw [exp_sub, div_eq_one_iff_eq _ (exp_ne_zero _)]
lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) :=
by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add']
@[simp] lemma cos_pi_div_two : cos (π / 2) = 0 :=
calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp
... = 0 : by simp
@[simp] lemma sin_pi_div_two : sin (π / 2) = 1 :=
calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp
... = 1 : by simp
@[simp] lemma sin_pi : sin π = 0 :=
by rw [← of_real_sin, real.sin_pi]; simp
@[simp] lemma cos_pi : cos π = -1 :=
by rw [← of_real_cos, real.cos_pi]; simp
@[simp] lemma sin_two_pi : sin (2 * π) = 0 :=
by simp [two_mul, sin_add]
@[simp] lemma cos_two_pi : cos (2 * π) = 1 :=
by simp [two_mul, cos_add]
lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x :=
by simp [sin_add]
lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x :=
by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi]
lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x :=
by simp [cos_add, cos_two_pi, sin_two_pi]
lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x :=
by simp [sin_add]
lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x :=
by simp [cos_add]
lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x :=
by simp [cos_add]
lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x :=
by simp [sin_add]
lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x :=
by simp [sin_add]
lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x :=
by simp [sin_add]
lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x :=
by simp [cos_add]
lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x :=
by simp [cos_add]
lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x :=
by rw [← cos_neg, neg_sub, cos_sub_pi_div_two]
lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 :=
by induction n; simp [add_mul, sin_add, *]
lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 :=
by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi]
lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 :=
by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi]
lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 :=
by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe,
int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg,
(neg_mul_eq_neg_mul _ _).symm, cos_neg]
lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 :=
by simp [cos_add, sin_add, cos_int_mul_two_pi]
section pow
/-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal
determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for
`y ≠ 0`. -/
noncomputable def cpow (x y : ℂ) : ℂ :=
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y)
noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩
lemma cpow_def (x y : ℂ) : x ^ y =
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y) := rfl
@[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def]
@[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 :=
by simp [cpow_def, *]
@[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x :=
if hx : x = 0 then by simp [hx, cpow_def]
else by rw [cpow_def, if_neg (@one_ne_zero ℂ _), if_neg hx, mul_one, exp_log hx]
@[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 :=
by rw cpow_def; split_ifs; simp [one_ne_zero, *] at *
lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z :=
by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at *
lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) :
x ^ (y * z) = (x ^ y) ^ z :=
begin
simp [cpow_def],
split_ifs;
simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at *
end
lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ :=
by simp [cpow_def]; split_ifs; simp [exp_neg]
@[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n
| 0 := by simp
| (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ,
complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul]
else by simp [cpow_def, hx, mul_add, exp_add, pow_succ, (cpow_nat_cast n).symm, exp_log hx]
@[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n
| (n : ℕ) := by simp; refl
| -[1+ n] := by rw fpow_neg_succ_of_nat;
simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div,
int.cast_coe_nat, cpow_nat_cast]
lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x :=
have (log x * (↑n)⁻¹).im = (log x).im / n,
by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im,
of_real_re, of_real_im]; simp,
have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π,
from (le_total (log x).im 0).elim
(λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg]
... ≤ ((log x).im * 1) / n : le_div_of_mul_le (nat.cast_pos.2 hn)
(mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)
... = (log x * (↑n)⁻¹).im : by simp [this],
this.symm ▸ le_trans (div_nonpos_of_nonpos_of_pos h (nat.cast_pos.2 hn))
(le_of_lt real.pi_pos)⟩)
(λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos)
(div_nonneg h (nat.cast_pos.2 hn)),
calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this]
... ≤ (log x).im : (div_le_of_le_mul (nat.cast_pos.2 hn)
(mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h))
... ≤ _ : by simp [log, arg_le_pi]⟩),
by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2,
inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)),
cpow_one]
end pow
end complex
namespace real
/-- The real power function `x^y`, defined as the real part of the complex power function.
For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`.
For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex
determination of the logarithm. With our conventions, it is equal to `exp (y log (-x)) cos (πy)`. -/
noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re
noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩
lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl
lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y =
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y) :=
by simp only [rpow_def, complex.cpow_def];
split_ifs;
simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul,
(complex.of_real_mul _ _).symm, complex.exp_of_real_re] at *
lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) :=
by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)]
open_locale real
lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log (-x) * y) * cos (y * π) :=
begin
rw [rpow_def, complex.cpow_def, if_neg],
have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I,
simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx,
complex.abs_of_real, complex.of_real_mul], ring,
{ rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos,
← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul,
complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im], ring },
{ rw complex.of_real_eq_zero, exact ne_of_lt hx }
end
lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y =
if x = 0
then if y = 0
then 1
else 0
else exp (log (-x) * y) * cos (y * π) :=
by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _
lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y :=
by rw rpow_def_of_pos hx; apply exp_pos
lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y :=
abs_le_of_le_of_neg_le
begin
cases lt_trichotomy 0 x, { rw abs_of_pos h },
cases h, { simp [h.symm] },
rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h],
calc exp (log (-x) * y) * cos (y * π) ≤ exp (log (-x) * y) * 1 :
mul_le_mul_of_nonneg_left (cos_le_one _) (le_of_lt $ exp_pos _)
... = _ : mul_one _
end
begin
cases lt_trichotomy 0 x, { rw abs_of_pos h, have : 0 < x^y := rpow_pos_of_pos h _, linarith },
cases h, { simp only [h.symm, abs_zero, rpow_def_of_nonneg], split_ifs, repeat {norm_num}},
rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h],
calc -(exp (log (-x) * y) * cos (y * π)) = exp (log (-x) * y) * (-cos (y * π)) : by ring
... ≤ exp (log (-x) * y) * 1 :
mul_le_mul_of_nonneg_left (neg_le.2 $ neg_one_le_cos _) (le_of_lt $ exp_pos _)
... = exp (log (-x) * y) : mul_one _
end
end real
namespace complex
lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) :=
by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx]
@[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y :=
begin
rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def],
split_ifs;
simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add,
add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I,
(complex.of_real_mul _ _).symm, -complex.of_real_mul] at *
end
@[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) :=
by rw ← abs_cpow_real; simp [-abs_cpow_real]
end complex
namespace real
open_locale real
variables {x y z : ℝ}
@[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def]
@[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 :=
by simp [rpow_def, *]
@[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def]
@[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def]
lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y :=
by rw [rpow_def_of_nonneg hx];
split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)]
lemma rpow_add {x : ℝ} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z :=
by simp only [rpow_def_of_pos hx, mul_add, exp_add]
lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z :=
by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _),
complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx];
simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm,
complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos]
lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ :=
by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at *
@[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n :=
by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast,
complex.of_real_nat_cast, complex.of_real_re]
@[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n :=
by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast,
complex.of_real_int_cast, complex.of_real_re]
lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z :=
begin
iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *,
{ have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂,
have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂,
rw [log_mul hx hy, add_mul, exp_add]},
{ exact h₁},
{ exact h},
{ exact mul_nonneg h h₁},
end
lemma one_le_rpow {x z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z :=
begin
rw real.rpow_def_of_nonneg, split_ifs with h₂ h₃,
{ refl},
{ simp [*, not_le_of_gt zero_lt_one] at *},
{ have hx : 0 < x, exact lt_of_lt_of_le zero_lt_one h,
rw [←log_le_log zero_lt_one hx, log_one] at h,
have pos : 0 ≤ log x * z, exact mul_nonneg h h₁,
rwa [←exp_le_exp, exp_zero] at pos},
{ exact le_trans zero_le_one h},
end
lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z :=
begin
rw le_iff_eq_or_lt at h h₂, cases h₂,
{ rw [←h₂, rpow_zero, rpow_zero]},
{ cases h,
{ rw [←h, zero_rpow], rw real.rpow_def_of_nonneg, split_ifs,
{ exact zero_le_one},
{ refl},
{ exact le_of_lt (exp_pos (log y * z))},
{ rwa ←h at h₁},
{ exact ne.symm (ne_of_lt h₂)}},
{ have one_le : 1 ≤ y / x, rw one_le_div_iff_le h, exact h₁,
have one_le_pow : 1 ≤ (y / x)^z, exact one_le_rpow one_le (le_of_lt h₂),
rw [←mul_div_cancel y (ne.symm (ne_of_lt h)), mul_comm, mul_div_assoc],
rw [mul_rpow (le_of_lt h) (le_trans zero_le_one one_le), mul_comm],
exact (le_mul_of_ge_one_left (rpow_nonneg_of_nonneg (le_of_lt h) z) one_le_pow) } }
end
lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z :=
begin
rw le_iff_eq_or_lt at hx, cases hx,
{ rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ },
rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp],
exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz
end
lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z :=
begin
repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]},
rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx),
end
lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z :=
begin
repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]},
rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx),
end
lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) :
x^y < x^z :=
begin
repeat {rw [rpow_def_of_pos hx0]},
rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1),
end
lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) :
x^y ≤ x^z :=
begin
repeat {rw [rpow_def_of_pos hx0]},
rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos hx1),
end
lemma rpow_le_one {x e : ℝ} (he : 0 ≤ e) (hx : 0 ≤ x) (hx2 : x ≤ 1) : x^e ≤ 1 :=
by rw ←one_rpow e; apply rpow_le_rpow; assumption
lemma one_lt_rpow (hx : 1 < x) (hz : 0 < z) : 1 < x^z :=
by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz }
lemma rpow_lt_one (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 :=
by { rw ← one_rpow z, exact rpow_lt_rpow (le_of_lt hx) hx1 hz }
lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) :
(x ^ n) ^ (n⁻¹ : ℝ) = x :=
have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn,
by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one]
section prove_rpow_is_continuous
lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) :=
suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)),
by { convert h, ext p, rw rpow_def_of_pos p.2 },
continuous_exp.comp $
(show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from
continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul
(continuous_snd.comp $ continuous_subtype_val.comp continuous_id)
lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) :=
suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)),
by { convert h, ext p, rw [rpow_def_of_neg p.2] },
(continuous_exp.comp $
(show continuous $ (λp:{p:ℝ//0<p},
log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩),
from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $
continuous_fst.comp continuous_subtype_val).mul
(continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul
(continuous_cos.comp $
(continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const)
lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) :
continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) :=
begin
cases lt_trichotomy 0 x,
exact continuous_within_at.continuous_at
(continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h)
(mem_nhds_sets (by { convert is_open_prod (is_open_lt' (0:ℝ)) is_open_univ, ext, finish }) h),
cases h,
{ exact absurd h.symm hx },
exact continuous_within_at.continuous_at
(continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h)
(mem_nhds_sets (by { convert is_open_prod (is_open_gt' (0:ℝ)) is_open_univ, ext, finish }) h)
end
lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) :=
continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩,
begin
by_cases hx₀ : x₀ = 0,
{ simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), tendsto_nhds_nhds], assume ε ε0,
rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩,
let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos,
let δ := min (min q (ε ^ (1 / q))) (1/2),
have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num),
have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _),
have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _),
have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num),
use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩,
simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero],
assume h, rw max_lt_iff at h, cases h with xδ yy₀,
have qy : q < y, calc q < y₀ / 2 : q_lt
... = y₀ - y₀ / 2 : (sub_half _).symm
... ≤ y₀ - δ : by linarith
... < y : sub_lt_of_abs_sub_lt_left yy₀,
calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _
... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy
... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} }
... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} }
... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }},
{ exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1
(continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at }
end
lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) :
continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) :=
continuous_within_at.continuous_at
(continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy)
(mem_nhds_sets (by { convert is_open_prod is_open_univ (is_open_lt' (0:ℝ)), ext, finish }) hy)
variables {α : Type*} [topological_space α] {f g : α → ℝ}
/--
`real.rpow` is continuous at all points except for the lower half of the y-axis.
In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`.
Multiple forms of the claim is provided in the current section.
-/
lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g):
continuous (λa:α, (f a) ^ (g a)) :=
continuous_iff_continuous_at.2 $ λ a,
begin
show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a,
refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _),
{ replace h := h a, cases h,
{ exact continuous_at_rpow_of_ne_zero h _ },
{ exact continuous_at_rpow_of_pos h _ }},
end
lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g):
continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg
lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g):
continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg
end prove_rpow_is_continuous
section sqrt
lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) :=
begin
funext, by_cases h : 0 ≤ x,
{ rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h],
norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ },
{ replace h : x < 0 := lt_of_not_ge h,
have : 1 / (2:ℝ) * π = π / (2:ℝ), ring,
rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] }
end
lemma continuous_sqrt : continuous sqrt :=
by rw sqrt_eq_rpow; exact continuous_rpow_of_pos (λa, by norm_num) continuous_id continuous_const
end sqrt
section exp
/-- The real exponential function tends to +infinity at +infinity -/
lemma tendsto_exp_at_top : tendsto exp at_top at_top :=
begin
have A : tendsto (λx:ℝ, x + 1) at_top at_top :=
tendsto_at_top_add_const_right at_top 1 tendsto_id,
have B : {x : ℝ | x + 1 ≤ exp x} ∈ at_top,
{ have : {x : ℝ | 0 ≤ x} ∈ at_top := mem_at_top 0,
filter_upwards [this],
exact λx hx, add_one_le_exp_of_nonneg hx },
exact tendsto_at_top_mono' at_top B A
end
/-- The real exponential function tends to 0 at -infinity or, equivalently, `exp(-x)` tends to `0`
at +infinity -/
lemma tendsto_exp_neg_at_top_nhds_0 : tendsto (λx, exp (-x)) at_top (𝓝 0) :=
(tendsto.comp tendsto_inverse_at_top_nhds_0 (tendsto_exp_at_top)).congr (λx, (exp_neg x).symm)
/-- The function `exp(x)/x^n` tends to +infinity at +infinity, for any natural number `n` -/
lemma tendsto_exp_div_pow_at_top (n : ℕ) : tendsto (λx, exp x / x^n) at_top at_top :=
begin
have n_pos : (0 : ℝ) < n + 1 := nat.cast_add_one_pos n,
have n_ne_zero : (n : ℝ) + 1 ≠ 0 := ne_of_gt n_pos,
have A : ∀x:ℝ, 0 < x → exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n,
{ assume x hx,
let y := x / (n+1),
have y_pos : 0 < y := div_pos hx n_pos,
have : exp (x / (n+1)) ≤ (n+1)^n * (exp x / x^n), from calc
exp y = exp y * 1 : by simp
... ≤ exp y * (exp y / y)^n : begin
apply mul_le_mul_of_nonneg_left (one_le_pow_of_one_le _ n) (le_of_lt (exp_pos _)),
apply one_le_div_of_le _ y_pos,
apply le_trans _ (add_one_le_exp_of_nonneg (le_of_lt y_pos)),
exact le_add_of_le_of_nonneg (le_refl _) (zero_le_one)
end
... = exp y * exp (n * y) / y^n :
by rw [div_pow _ (ne_of_gt y_pos), exp_nat_mul, mul_div_assoc]
... = exp ((n + 1) * y) / y^n :
by rw [← exp_add, add_mul, one_mul, add_comm]
... = exp x / (x / (n+1))^n :
by { dsimp [y], rw mul_div_cancel' _ n_ne_zero }
... = (n+1)^n * (exp x / x^n) :
by rw [← mul_div_assoc, div_pow _ n_ne_zero, div_div_eq_mul_div, mul_comm],
rwa div_le_iff' (pow_pos n_pos n) },
have B : {x : ℝ | exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n} ∈ at_top :=
mem_at_top_sets.2 ⟨1, λx hx, A _ (lt_of_lt_of_le zero_lt_one hx)⟩,
have C : tendsto (λx, exp (x / (n+1)) / (n+1)^n) at_top at_top :=
tendsto_at_top_div (pow_pos n_pos n)
(tendsto_exp_at_top.comp (tendsto_at_top_div (nat.cast_add_one_pos n) tendsto_id)),
exact tendsto_at_top_mono' at_top B C
end
/-- The function `x^n * exp(-x)` tends to `0` at +infinity, for any natural number `n`. -/
lemma tendsto_pow_mul_exp_neg_at_top_nhds_0 (n : ℕ) : tendsto (λx, x^n * exp (-x)) at_top (𝓝 0) :=
(tendsto_inverse_at_top_nhds_0.comp (tendsto_exp_div_pow_at_top n)).congr $ λx,
by rw [function.comp_app, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_eq_mul_inv, exp_neg]
end exp
end real
|
20190782edab25e9c9a5cc4a893bcab1c8386688 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /src/Lean/Meta/FunInfo.lean | 956549ddffcd9456b8f5e81aaf1e7efd466136a7 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,195 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Basic
import Lean.Meta.InferType
namespace Lean
namespace Meta
@[inline] private def checkFunInfoCache (fn : Expr) (maxArgs? : Option Nat) (k : MetaM FunInfo) : MetaM FunInfo := do
s ← get;
t ← getTransparency;
match s.cache.funInfo.find? ⟨t, fn, maxArgs?⟩ with
| some finfo => pure finfo
| none => do
finfo ← k;
modify $ fun s => { s with cache := { s.cache with funInfo := s.cache.funInfo.insert ⟨t, fn, maxArgs?⟩ finfo } };
pure finfo
@[inline] private def whenHasVar {α} (e : Expr) (deps : α) (k : α → α) : α :=
if e.hasFVar then k deps else deps
private def collectDepsAux (fvars : Array Expr) : Expr → Array Nat → Array Nat
| e@(Expr.app f a _), deps => whenHasVar e deps (collectDepsAux a ∘ collectDepsAux f)
| e@(Expr.forallE _ d b _), deps => whenHasVar e deps (collectDepsAux b ∘ collectDepsAux d)
| e@(Expr.lam _ d b _), deps => whenHasVar e deps (collectDepsAux b ∘ collectDepsAux d)
| e@(Expr.letE _ t v b _), deps => whenHasVar e deps (collectDepsAux b ∘ collectDepsAux v ∘ collectDepsAux t)
| Expr.proj _ _ e _, deps => collectDepsAux e deps
| Expr.mdata _ e _, deps => collectDepsAux e deps
| e@(Expr.fvar _ _), deps =>
match fvars.indexOf e with
| none => deps
| some i => if deps.contains i.val then deps else deps.push i.val
| _, deps => deps
private def collectDeps (fvars : Array Expr) (e : Expr) : Array Nat :=
let deps := collectDepsAux fvars e #[];
deps.qsort (fun i j => i < j)
/-- Update `hasFwdDeps` fields using new `backDeps` -/
private def updateHasFwdDeps (pinfo : Array ParamInfo) (backDeps : Array Nat) : Array ParamInfo :=
if backDeps.size == 0 then
pinfo
else
-- update hasFwdDeps fields
pinfo.mapIdx $ fun i info =>
if info.hasFwdDeps then info
else if backDeps.contains i then
{ info with hasFwdDeps := true }
else
info
private def getFunInfoAux (fn : Expr) (maxArgs? : Option Nat) : MetaM FunInfo :=
checkFunInfoCache fn maxArgs? $ do
fnType ← inferType fn;
withTransparency TransparencyMode.default $
forallBoundedTelescope fnType maxArgs? $ fun fvars type => do
pinfo ← fvars.size.foldM
(fun (i : Nat) (pinfo : Array ParamInfo) => do
let fvar := fvars.get! i;
decl ← getFVarLocalDecl fvar;
let backDeps := collectDeps fvars decl.type;
let pinfo := updateHasFwdDeps pinfo backDeps;
pure $ pinfo.push {
backDeps := backDeps,
implicit := decl.binderInfo == BinderInfo.implicit,
instImplicit := decl.binderInfo == BinderInfo.instImplicit })
#[];
let resultDeps := collectDeps fvars type;
let pinfo := updateHasFwdDeps pinfo resultDeps;
pure { resultDeps := resultDeps, paramInfo := pinfo }
def getFunInfo (fn : Expr) : MetaM FunInfo :=
getFunInfoAux fn none
def getFunInfoNArgs (fn : Expr) (nargs : Nat) : MetaM FunInfo :=
getFunInfoAux fn (some nargs)
end Meta
end Lean
|
3bb6c9782935954c6ac5e3edaf8c0ad80469af7c | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/algebra/ordered/liminf_limsup.lean | b2ba794ddb09bc7dc09105660c3787c772e4eca0 | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,745 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov
-/
import topology.algebra.ordered.basic
import order.liminf_limsup
/-!
# Lemmas about liminf and limsup in an order topology.
-/
open filter
open_locale topological_space classical
universes u v
variables {α : Type u} {β : Type v}
section liminf_limsup
section order_closed_topology
variables [semilattice_sup α] [topological_space α] [order_topology α]
lemma is_bounded_le_nhds (a : α) : (𝓝 a).is_bounded (≤) :=
match forall_le_or_exists_lt_sup a with
| or.inl h := ⟨a, eventually_of_forall h⟩
| or.inr ⟨b, hb⟩ := ⟨b, ge_mem_nhds hb⟩
end
lemma filter.tendsto.is_bounded_under_le {f : filter β} {u : β → α} {a : α}
(h : tendsto u f (𝓝 a)) : f.is_bounded_under (≤) u :=
(is_bounded_le_nhds a).mono h
lemma is_cobounded_ge_nhds (a : α) : (𝓝 a).is_cobounded (≥) :=
(is_bounded_le_nhds a).is_cobounded_flip
lemma filter.tendsto.is_cobounded_under_ge {f : filter β} {u : β → α} {a : α}
[ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≥) u :=
h.is_bounded_under_le.is_cobounded_flip
end order_closed_topology
section order_closed_topology
variables [semilattice_inf α] [topological_space α] [order_topology α]
lemma is_bounded_ge_nhds (a : α) : (𝓝 a).is_bounded (≥) :=
@is_bounded_le_nhds (order_dual α) _ _ _ a
lemma filter.tendsto.is_bounded_under_ge {f : filter β} {u : β → α} {a : α}
(h : tendsto u f (𝓝 a)) : f.is_bounded_under (≥) u :=
(is_bounded_ge_nhds a).mono h
lemma is_cobounded_le_nhds (a : α) : (𝓝 a).is_cobounded (≤) :=
(is_bounded_ge_nhds a).is_cobounded_flip
lemma filter.tendsto.is_cobounded_under_le {f : filter β} {u : β → α} {a : α}
[ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≤) u :=
h.is_bounded_under_ge.is_cobounded_flip
end order_closed_topology
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α]
theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) :
∀ᶠ a in f, a < b :=
let ⟨c, (h : ∀ᶠ a in f, a ≤ c), hcb⟩ := exists_lt_of_cInf_lt h l in
mem_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb
theorem gt_mem_sets_of_Liminf_gt : ∀ {f : filter α} {b}, f.is_bounded (≥) → b < f.Liminf →
∀ᶠ a in f, b < a :=
@lt_mem_sets_of_Limsup_lt (order_dual α) _
variables [topological_space α] [order_topology α]
/-- If the liminf and the limsup of a filter coincide, then this filter converges to
their common value, at least if the filter is eventually bounded above and below. -/
theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α}
(hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) :
f ≤ 𝓝 a :=
tendsto_order.2 $ and.intro
(assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb)
(assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb)
theorem Limsup_nhds (a : α) : Limsup (𝓝 a) = a :=
cInf_eq_of_forall_ge_of_forall_gt_exists_lt (is_bounded_le_nhds a)
(assume a' (h : {n : α | n ≤ a'} ∈ 𝓝 a), show a ≤ a', from @mem_of_mem_nhds α _ a _ h)
(assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ 𝓝 a), c < b, from
match dense_or_discrete a b with
| or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩
| or.inr ⟨_, h⟩ := ⟨a, (𝓝 a).sets_of_superset (gt_mem_nhds hba) h, hba⟩
end)
theorem Liminf_nhds : ∀ (a : α), Liminf (𝓝 a) = a :=
@Limsup_nhds (order_dual α) _ _ _
/-- If a filter is converging, its limsup coincides with its limit. -/
theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : f.Liminf = a :=
have hb_ge : is_bounded (≥) f, from (is_bounded_ge_nhds a).mono h,
have hb_le : is_bounded (≤) f, from (is_bounded_le_nhds a).mono h,
le_antisymm
(calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hb_le hb_ge
... ≤ (𝓝 a).Limsup :
Limsup_le_Limsup_of_le h hb_ge.is_cobounded_flip (is_bounded_le_nhds a)
... = a : Limsup_nhds a)
(calc a = (𝓝 a).Liminf : (Liminf_nhds a).symm
... ≤ f.Liminf :
Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) hb_le.is_cobounded_flip)
/-- If a filter is converging, its liminf coincides with its limit. -/
theorem Limsup_eq_of_le_nhds : ∀ {f : filter α} {a : α} [ne_bot f], f ≤ 𝓝 a → f.Limsup = a :=
@Liminf_eq_of_le_nhds (order_dual α) _ _ _
/-- If a function has a limit, then its limsup coincides with its limit. -/
theorem filter.tendsto.limsup_eq {f : filter β} {u : β → α} {a : α} [ne_bot f]
(h : tendsto u f (𝓝 a)) : limsup f u = a :=
Limsup_eq_of_le_nhds h
/-- If a function has a limit, then its liminf coincides with its limit. -/
theorem filter.tendsto.liminf_eq {f : filter β} {u : β → α} {a : α} [ne_bot f]
(h : tendsto u f (𝓝 a)) : liminf f u = a :=
Liminf_eq_of_le_nhds h
/-- If the liminf and the limsup of a function coincide, then the limit of the function
exists and has the same value -/
theorem tendsto_of_liminf_eq_limsup {f : filter β} {u : β → α} {a : α}
(hinf : liminf f u = a) (hsup : limsup f u = a)
(h : f.is_bounded_under (≤) u . is_bounded_default)
(h' : f.is_bounded_under (≥) u . is_bounded_default) :
tendsto u f (𝓝 a) :=
le_nhds_of_Limsup_eq_Liminf h h' hsup hinf
/-- If a number `a` is less than or equal to the `liminf` of a function `f` at some filter
and is greater than or equal to the `limsup` of `f`, then `f` tends to `a` along this filter. -/
theorem tendsto_of_le_liminf_of_limsup_le {f : filter β} {u : β → α} {a : α}
(hinf : a ≤ liminf f u) (hsup : limsup f u ≤ a)
(h : f.is_bounded_under (≤) u . is_bounded_default)
(h' : f.is_bounded_under (≥) u . is_bounded_default) :
tendsto u f (𝓝 a) :=
if hf : f = ⊥ then hf.symm ▸ tendsto_bot
else by haveI : ne_bot f := ⟨hf⟩; exact tendsto_of_liminf_eq_limsup
(le_antisymm (le_trans (liminf_le_limsup h h') hsup) hinf)
(le_antisymm hsup (le_trans hinf (liminf_le_limsup h h'))) h h'
/-- Assume that, for any `a < b`, a sequence can not be infinitely many times below `a` and
above `b`. If it is also ultimately bounded above and below, then it has to converge. This even
works if `a` and `b` are restricted to a dense subset.
-/
lemma tendsto_of_no_upcrossings [densely_ordered α]
{f : filter β} {u : β → α} {s : set α} (hs : dense s)
(H : ∀ (a ∈ s) (b ∈ s), a < b → ¬((∃ᶠ n in f, u n < a) ∧ (∃ᶠ n in f, b < u n)))
(h : f.is_bounded_under (≤) u . is_bounded_default)
(h' : f.is_bounded_under (≥) u . is_bounded_default) :
∃ (c : α), tendsto u f (𝓝 c) :=
begin
by_cases hbot : f = ⊥, { rw hbot, exact ⟨Inf ∅, tendsto_bot⟩ },
haveI : ne_bot f := ⟨hbot⟩,
refine ⟨limsup f u, _⟩,
apply tendsto_of_le_liminf_of_limsup_le _ le_rfl h h',
by_contra hlt,
push_neg at hlt,
obtain ⟨a, ⟨⟨la, au⟩, as⟩⟩ : ∃ a, (f.liminf u < a ∧ a < f.limsup u) ∧ a ∈ s :=
dense_iff_inter_open.1 hs (set.Ioo (f.liminf u) (f.limsup u)) is_open_Ioo
(set.nonempty_Ioo.2 hlt),
obtain ⟨b, ⟨⟨ab, bu⟩, bs⟩⟩ : ∃ b, (a < b ∧ b < f.limsup u) ∧ b ∈ s :=
dense_iff_inter_open.1 hs (set.Ioo a (f.limsup u)) is_open_Ioo
(set.nonempty_Ioo.2 au),
have A : ∃ᶠ n in f, u n < a :=
frequently_lt_of_liminf_lt (is_bounded.is_cobounded_ge h) la,
have B : ∃ᶠ n in f, b < u n :=
frequently_lt_of_lt_limsup (is_bounded.is_cobounded_le h') bu,
exact H a as b bs ab ⟨A, B⟩,
end
end conditionally_complete_linear_order
end liminf_limsup
|
1b9fcf8697d455b3be102f8e62e7edbeeb4e2d9c | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/ring_theory/polynomial_algebra.lean | a092a2f85301cc8058d5cc095ec98fc9caf3be85 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,005 | 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 ring_theory.matrix_algebra
import data.polynomial.algebra_map
/-!
# Algebra isomorphism between matrices of polynomials and polynomials of matrices
Given `[comm_ring R] [ring A] [algebra R A]`
we show `polynomial A ≃ₐ[R] (A ⊗[R] polynomial R)`.
Combining this with the isomorphism `matrix n n A ≃ₐ[R] (A ⊗[R] matrix n n R)` proved earlier
in `ring_theory.matrix_algebra`, we obtain the algebra isomorphism
```
def mat_poly_equiv :
matrix n n (polynomial R) ≃ₐ[R] polynomial (matrix n n R)
```
which is characterized by
```
coeff (mat_poly_equiv m) k i j = coeff (m i j) k
```
We will use this algebra isomorphism to prove the Cayley-Hamilton theorem.
-/
universes u v w
open_locale tensor_product
open polynomial
open tensor_product
open algebra.tensor_product (alg_hom_of_linear_map_tensor_product include_left)
noncomputable theory
variables (R A : Type*)
variables [comm_semiring R]
variables [semiring A] [algebra R A]
namespace poly_equiv_tensor
/--
(Implementation detail).
The bare function underlying `A ⊗[R] polynomial R →ₐ[R] polynomial A`, on pure tensors.
-/
def to_fun (a : A) (p : polynomial R) : polynomial A :=
p.sum (λ n r, monomial n (a * algebra_map R A r))
/--
(Implementation detail).
The function underlying `A ⊗[R] polynomial R →ₐ[R] polynomial A`,
as a linear map in the second factor.
-/
def to_fun_linear_right (a : A) : polynomial R →ₗ[R] polynomial A :=
{ to_fun := to_fun R A a,
map_smul' := λ r p,
begin
dsimp [to_fun],
rw sum_smul_index,
{ dsimp [sum_def],
rw finset.smul_sum,
apply finset.sum_congr rfl,
intros k hk,
rw [monomial_eq_smul_X, monomial_eq_smul_X, algebra.smul_def, ← C_mul', ← C_mul',
← mul_assoc],
congr' 1,
rw [← algebra.commutes, ← algebra.commutes],
simp only [ring_hom.map_mul, polynomial.algebra_map_apply, mul_assoc], },
{ intro i, simp only [ring_hom.map_zero, mul_zero, monomial_zero_right] },
end,
map_add' := λ p q,
begin
simp only [to_fun],
rw sum_add_index,
{ simp only [monomial_zero_right, forall_const, ring_hom.map_zero, mul_zero], },
{ intros i r s, simp only [ring_hom.map_add, mul_add, monomial_add], },
end, }
/--
(Implementation detail).
The function underlying `A ⊗[R] polynomial R →ₐ[R] polynomial A`,
as a bilinear function of two arguments.
-/
def to_fun_bilinear : A →ₗ[R] polynomial R →ₗ[R] polynomial A :=
{ to_fun := to_fun_linear_right R A,
map_smul' := by {
intros, unfold to_fun_linear_right,
congr, simp only [linear_map.coe_mk],
simp_rw [to_fun, sum_def, finset.smul_sum, smul_monomial, ← algebra.smul_mul_assoc],
refl },
map_add' := by {
intros, unfold to_fun_linear_right,
congr, simp only [linear_map.coe_mk],
simp_rw [to_fun, sum_def, ← finset.sum_add_distrib, ← monomial_add, ← add_mul],
refl } }
/--
(Implementation detail).
The function underlying `A ⊗[R] polynomial R →ₐ[R] polynomial A`,
as a linear map.
-/
def to_fun_linear : A ⊗[R] polynomial R →ₗ[R] polynomial A :=
tensor_product.lift (to_fun_bilinear R A)
-- We apparently need to provide the decidable instance here
-- in order to successfully rewrite by this lemma.
lemma to_fun_linear_mul_tmul_mul_aux_1
(p : polynomial R) (k : ℕ) (h : decidable (¬p.coeff k = 0)) (a : A) :
ite (¬coeff p k = 0) (a * (algebra_map R A) (coeff p k)) 0 = a * (algebra_map R A) (coeff p k) :=
by { classical, split_ifs; simp *, }
lemma to_fun_linear_mul_tmul_mul_aux_2 (k : ℕ) (a₁ a₂ : A) (p₁ p₂ : polynomial R) :
a₁ * a₂ * (algebra_map R A) ((p₁ * p₂).coeff k) =
(finset.nat.antidiagonal k).sum
(λ x, a₁ * (algebra_map R A) (coeff p₁ x.1) * (a₂ * (algebra_map R A) (coeff p₂ x.2))) :=
begin
simp_rw [mul_assoc, algebra.commutes, ←finset.mul_sum, mul_assoc, ←finset.mul_sum],
congr,
simp_rw [algebra.commutes (coeff p₂ _), coeff_mul, ring_hom.map_sum, ring_hom.map_mul],
end
lemma to_fun_linear_mul_tmul_mul (a₁ a₂ : A) (p₁ p₂ : polynomial R) :
(to_fun_linear R A) ((a₁ * a₂) ⊗ₜ[R] (p₁ * p₂)) =
(to_fun_linear R A) (a₁ ⊗ₜ[R] p₁) * (to_fun_linear R A) (a₂ ⊗ₜ[R] p₂) :=
begin
dsimp [to_fun_linear],
simp only [lift.tmul],
dsimp [to_fun_bilinear, to_fun_linear_right, to_fun],
ext k,
simp_rw [coeff_sum, coeff_monomial, sum_def, finset.sum_ite_eq', mem_support_iff, ne.def],
conv_rhs { rw [coeff_mul] },
simp_rw [finset_sum_coeff, coeff_monomial,
finset.sum_ite_eq', mem_support_iff, ne.def,
mul_ite, mul_zero, ite_mul, zero_mul],
simp_rw [ite_mul_zero_left (¬coeff p₁ _ = 0) (a₁ * (algebra_map R A) (coeff p₁ _))],
simp_rw [ite_mul_zero_right (¬coeff p₂ _ = 0) _ (_ * _)],
simp_rw [to_fun_linear_mul_tmul_mul_aux_1, to_fun_linear_mul_tmul_mul_aux_2],
end
lemma to_fun_linear_algebra_map_tmul_one (r : R) :
(to_fun_linear R A) ((algebra_map R A) r ⊗ₜ[R] 1) = (algebra_map R (polynomial A)) r :=
begin
dsimp [to_fun_linear],
simp only [lift.tmul],
dsimp [to_fun_bilinear, to_fun_linear_right, to_fun],
rw [← C_1, ←monomial_zero_left, sum_monomial_index];
simp [algebra_map_apply],
end
/--
(Implementation detail).
The algebra homomorphism `A ⊗[R] polynomial R →ₐ[R] polynomial A`.
-/
def to_fun_alg_hom : A ⊗[R] polynomial R →ₐ[R] polynomial A :=
alg_hom_of_linear_map_tensor_product
(to_fun_linear R A)
(to_fun_linear_mul_tmul_mul R A)
(to_fun_linear_algebra_map_tmul_one R A)
@[simp] lemma to_fun_alg_hom_apply_tmul (a : A) (p : polynomial R) :
to_fun_alg_hom R A (a ⊗ₜ[R] p) = p.sum (λ n r, monomial n (a * (algebra_map R A) r)) :=
by simp [to_fun_alg_hom, to_fun_linear, to_fun_bilinear, to_fun_linear_right, to_fun]
/--
(Implementation detail.)
The bare function `polynomial A → A ⊗[R] polynomial R`.
(We don't need to show that it's an algebra map, thankfully --- just that it's an inverse.)
-/
def inv_fun (p : polynomial A) : A ⊗[R] polynomial R :=
p.eval₂
(include_left : A →ₐ[R] A ⊗[R] polynomial R)
((1 : A) ⊗ₜ[R] (X : polynomial R))
@[simp]
lemma inv_fun_add {p q} : inv_fun R A (p + q) = inv_fun R A p + inv_fun R A q :=
by simp only [inv_fun, eval₂_add]
lemma inv_fun_monomial (n : ℕ) (a : A) :
inv_fun R A (monomial n a) = include_left a * ((1 : A) ⊗ₜ[R] (X : polynomial R)) ^ n :=
eval₂_monomial _ _
lemma left_inv (x : A ⊗ polynomial R) :
inv_fun R A ((to_fun_alg_hom R A) x) = x :=
begin
apply tensor_product.induction_on x,
{ simp [inv_fun], },
{ intros a p, dsimp only [inv_fun],
rw [to_fun_alg_hom_apply_tmul, eval₂_sum],
simp_rw [eval₂_monomial, alg_hom.coe_to_ring_hom, algebra.tensor_product.tmul_pow, one_pow,
algebra.tensor_product.include_left_apply, algebra.tensor_product.tmul_mul_tmul,
mul_one, one_mul, ←algebra.commutes, ←algebra.smul_def'', smul_tmul, sum_def, ←tmul_sum],
conv_rhs { rw [←sum_C_mul_X_eq p], },
simp only [algebra.smul_def''],
refl, },
{ intros p q hp hq,
simp only [alg_hom.map_add, inv_fun_add, hp, hq], },
end
lemma right_inv (x : polynomial A) :
(to_fun_alg_hom R A) (inv_fun R A x) = x :=
begin
apply polynomial.induction_on' x,
{ intros p q hp hq, simp only [inv_fun_add, alg_hom.map_add, hp, hq], },
{ intros n a,
rw [inv_fun_monomial, algebra.tensor_product.include_left_apply,
algebra.tensor_product.tmul_pow, one_pow, algebra.tensor_product.tmul_mul_tmul,
mul_one, one_mul, to_fun_alg_hom_apply_tmul, X_pow_eq_monomial, sum_monomial_index];
simp, }
end
/--
(Implementation detail)
The equivalence, ignoring the algebra structure, `(A ⊗[R] polynomial R) ≃ polynomial A`.
-/
def equiv : (A ⊗[R] polynomial R) ≃ polynomial A :=
{ to_fun := to_fun_alg_hom R A,
inv_fun := inv_fun R A,
left_inv := left_inv R A,
right_inv := right_inv R A, }
end poly_equiv_tensor
open poly_equiv_tensor
/--
The `R`-algebra isomorphism `polynomial A ≃ₐ[R] (A ⊗[R] polynomial R)`.
-/
def poly_equiv_tensor : polynomial A ≃ₐ[R] (A ⊗[R] polynomial R) :=
alg_equiv.symm
{ ..(poly_equiv_tensor.to_fun_alg_hom R A), ..(poly_equiv_tensor.equiv R A) }
@[simp]
lemma poly_equiv_tensor_apply (p : polynomial A) :
poly_equiv_tensor R A p =
p.eval₂ (include_left : A →ₐ[R] A ⊗[R] polynomial R) ((1 : A) ⊗ₜ[R] (X : polynomial R)) :=
rfl
@[simp]
lemma poly_equiv_tensor_symm_apply_tmul (a : A) (p : polynomial R) :
(poly_equiv_tensor R A).symm (a ⊗ₜ p) = p.sum (λ n r, monomial n (a * algebra_map R A r)) :=
begin
simp [poly_equiv_tensor, to_fun_alg_hom, alg_hom_of_linear_map_tensor_product, to_fun_linear],
refl,
end
open dmatrix matrix
open_locale big_operators
variables {R}
variables {n : Type w} [decidable_eq n] [fintype n]
/--
The algebra isomorphism stating "matrices of polynomials are the same as polynomials of matrices".
(You probably shouldn't attempt to use this underlying definition ---
it's an algebra equivalence, and characterised extensionally by the lemma
`mat_poly_equiv_coeff_apply` below.)
-/
noncomputable def mat_poly_equiv :
matrix n n (polynomial R) ≃ₐ[R] polynomial (matrix n n R) :=
(((matrix_equiv_tensor R (polynomial R) n)).trans
(algebra.tensor_product.comm R _ _)).trans
(poly_equiv_tensor R (matrix n n R)).symm
open finset
lemma mat_poly_equiv_coeff_apply_aux_1 (i j : n) (k : ℕ) (x : R) :
mat_poly_equiv (std_basis_matrix i j $ monomial k x) =
monomial k (std_basis_matrix i j x) :=
begin
simp only [mat_poly_equiv, alg_equiv.trans_apply,
matrix_equiv_tensor_apply_std_basis],
apply (poly_equiv_tensor R (matrix n n R)).injective,
simp only [alg_equiv.apply_symm_apply],
convert algebra.tensor_product.comm_tmul _ _ _ _ _,
simp only [poly_equiv_tensor_apply],
convert eval₂_monomial _ _,
simp only [algebra.tensor_product.tmul_mul_tmul, one_pow, one_mul, matrix.mul_one,
algebra.tensor_product.tmul_pow, algebra.tensor_product.include_left_apply, mul_eq_mul],
rw [monomial_eq_smul_X, ← tensor_product.smul_tmul],
congr' with i' j'; simp
end
lemma mat_poly_equiv_coeff_apply_aux_2
(i j : n) (p : polynomial R) (k : ℕ) :
coeff (mat_poly_equiv (std_basis_matrix i j p)) k =
std_basis_matrix i j (coeff p k) :=
begin
apply polynomial.induction_on' p,
{ intros p q hp hq, ext,
simp [hp, hq, coeff_add, add_apply, std_basis_matrix_add], },
{ intros k x,
simp only [mat_poly_equiv_coeff_apply_aux_1, coeff_monomial],
split_ifs; { funext, simp, }, }
end
@[simp] lemma mat_poly_equiv_coeff_apply
(m : matrix n n (polynomial R)) (k : ℕ) (i j : n) :
coeff (mat_poly_equiv m) k i j = coeff (m i j) k :=
begin
apply matrix.induction_on' m,
{ simp, },
{ intros p q hp hq, simp [hp, hq], },
{ intros i' j' x,
erw mat_poly_equiv_coeff_apply_aux_2,
dsimp [std_basis_matrix],
split_ifs,
{ rcases h with ⟨rfl, rfl⟩, simp [std_basis_matrix], },
{ simp [std_basis_matrix, h], }, },
end
@[simp] lemma mat_poly_equiv_symm_apply_coeff
(p : polynomial (matrix n n R)) (i j : n) (k : ℕ) :
coeff (mat_poly_equiv.symm p i j) k = coeff p k i j :=
begin
have t : p = mat_poly_equiv
(mat_poly_equiv.symm p) := by simp,
conv_rhs { rw t, },
simp only [mat_poly_equiv_coeff_apply],
end
lemma mat_poly_equiv_smul_one (p : polynomial R) :
mat_poly_equiv (p • 1) = p.map (algebra_map R (matrix n n R)) :=
begin
ext m i j,
simp only [coeff_map, one_apply, algebra_map_matrix_apply, mul_boole,
pi.smul_apply, mat_poly_equiv_coeff_apply],
split_ifs; simp,
end
lemma support_subset_support_mat_poly_equiv
(m : matrix n n (polynomial R)) (i j : n) :
support (m i j) ⊆ support (mat_poly_equiv m) :=
begin
assume k,
contrapose,
simp only [not_mem_support_iff],
assume hk,
rw [← mat_poly_equiv_coeff_apply, hk],
refl
end
|
10fcdf1a81002320c2dc8a09c2c56a10bfdd31d6 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/order/basic.lean | d5ed39b3f15f1090de8088bcfecf985f3ac8a3b8 | [
"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 | 27,664 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Mario Carneiro
-/
import data.prod
import data.subtype
/-!
# Basic definitions about `≤` and `<`
This file proves basic results about orders, provides extensive dot notation, defines useful order
classes and allows to transfer order instances.
## Type synonyms
* `order_dual α` : A type synonym reversing the meaning of all inequalities, with notation `αᵒᵈ`.
* `as_linear_order α`: A type synonym to promote `partial_order α` to `linear_order α` using
`is_total α (≤)`.
### Transfering orders
- `order.preimage`, `preorder.lift`: Transfers a (pre)order on `β` to an order on `α`
using a function `f : α → β`.
- `partial_order.lift`, `linear_order.lift`: Transfers a partial (resp., linear) order on `β` to a
partial (resp., linear) order on `α` using an injective function `f`.
### Extra class
- `densely_ordered`: An order with no gap, i.e. for any two elements `a < b` there exists `c` such
that `a < c < b`.
## Notes
`≤` and `<` are highly favored over `≥` and `>` in mathlib. The reason is that we can formulate all
lemmas using `≤`/`<`, and `rw` has trouble unifying `≤` and `≥`. Hence choosing one direction spares
us useless duplication. This is enforced by a linter. See Note [nolint_ge] for more infos.
Dot notation is particularly useful on `≤` (`has_le.le`) and `<` (`has_lt.lt`). To that end, we
provide many aliases to dot notation-less lemmas. For example, `le_trans` is aliased with
`has_le.le.trans` and can be used to construct `hab.trans hbc : a ≤ c` when `hab : a ≤ b`,
`hbc : b ≤ c`, `lt_of_le_of_lt` is aliased as `has_le.le.trans_lt` and can be used to construct
`hab.trans hbc : a < c` when `hab : a ≤ b`, `hbc : b < c`.
## TODO
- expand module docs
- automatic construction of dual definitions / theorems
## Tags
preorder, order, partial order, poset, linear order, chain
-/
open function
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop}
section preorder
variables [preorder α] {a b c : α}
lemma le_trans' : b ≤ c → a ≤ b → a ≤ c := flip le_trans
lemma lt_trans' : b < c → a < b → a < c := flip lt_trans
lemma lt_of_le_of_lt' : b ≤ c → a < b → a < c := flip lt_of_lt_of_le
lemma lt_of_lt_of_le' : b < c → a ≤ b → a < c := flip lt_of_le_of_lt
end preorder
section partial_order
variables [partial_order α] {a b : α}
lemma ge_antisymm : a ≤ b → b ≤ a → b = a := flip le_antisymm
lemma lt_of_le_of_ne' : a ≤ b → b ≠ a → a < b := λ h₁ h₂, lt_of_le_of_ne h₁ h₂.symm
lemma ne.lt_of_le : a ≠ b → a ≤ b → a < b := flip lt_of_le_of_ne
lemma ne.lt_of_le' : b ≠ a → a ≤ b → a < b := flip lt_of_le_of_ne'
end partial_order
attribute [simp] le_refl
attribute [ext] has_le
alias le_trans ← has_le.le.trans
alias le_trans' ← has_le.le.trans'
alias lt_of_le_of_lt ← has_le.le.trans_lt
alias lt_of_le_of_lt' ← has_le.le.trans_lt'
alias le_antisymm ← has_le.le.antisymm
alias ge_antisymm ← has_le.le.antisymm'
alias lt_of_le_of_ne ← has_le.le.lt_of_ne
alias lt_of_le_of_ne' ← has_le.le.lt_of_ne'
alias lt_of_le_not_le ← has_le.le.lt_of_not_le
alias lt_or_eq_of_le ← has_le.le.lt_or_eq
alias decidable.lt_or_eq_of_le ← has_le.le.lt_or_eq_dec
alias le_of_lt ← has_lt.lt.le
alias lt_trans ← has_lt.lt.trans
alias lt_trans' ← has_lt.lt.trans'
alias lt_of_lt_of_le ← has_lt.lt.trans_le
alias lt_of_lt_of_le' ← has_lt.lt.trans_le'
alias ne_of_lt ← has_lt.lt.ne
alias lt_asymm ← has_lt.lt.asymm has_lt.lt.not_lt
alias le_of_eq ← eq.le
attribute [nolint decidable_classical] has_le.le.lt_or_eq_dec
section
variables [preorder α] {a b c : α}
/-- A version of `le_refl` where the argument is implicit -/
lemma le_rfl : a ≤ a := le_refl a
@[simp] lemma lt_self_iff_false (x : α) : x < x ↔ false := ⟨lt_irrefl x, false.elim⟩
lemma le_of_le_of_eq (hab : a ≤ b) (hbc : b = c) : a ≤ c := hab.trans hbc.le
lemma le_of_eq_of_le (hab : a = b) (hbc : b ≤ c) : a ≤ c := hab.le.trans hbc
lemma lt_of_lt_of_eq (hab : a < b) (hbc : b = c) : a < c := hab.trans_le hbc.le
lemma lt_of_eq_of_lt (hab : a = b) (hbc : b < c) : a < c := hab.le.trans_lt hbc
lemma le_of_le_of_eq' : b ≤ c → a = b → a ≤ c := flip le_of_eq_of_le
lemma le_of_eq_of_le' : b = c → a ≤ b → a ≤ c := flip le_of_le_of_eq
lemma lt_of_lt_of_eq' : b < c → a = b → a < c := flip lt_of_eq_of_lt
lemma lt_of_eq_of_lt' : b = c → a < b → a < c := flip lt_of_lt_of_eq
alias le_of_le_of_eq ← has_le.le.trans_eq
alias le_of_le_of_eq' ← has_le.le.trans_eq'
alias lt_of_lt_of_eq ← has_lt.lt.trans_eq
alias lt_of_lt_of_eq' ← has_lt.lt.trans_eq'
alias le_of_eq_of_le ← eq.trans_le
alias le_of_eq_of_le' ← eq.trans_ge
alias lt_of_eq_of_lt ← eq.trans_lt
alias lt_of_eq_of_lt' ← eq.trans_gt
end
namespace eq
variables [preorder α] {x y z : α}
/-- If `x = y` then `y ≤ x`. Note: this lemma uses `y ≤ x` instead of `x ≥ y`, because `le` is used
almost exclusively in mathlib. -/
protected lemma ge (h : x = y) : y ≤ x := h.symm.le
lemma not_lt (h : x = y) : ¬ x < y := λ h', h'.ne h
lemma not_gt (h : x = y) : ¬ y < x := h.symm.not_lt
end eq
namespace has_le.le
@[nolint ge_or_gt] -- see Note [nolint_ge]
protected lemma ge [has_le α] {x y : α} (h : x ≤ y) : y ≥ x := h
lemma lt_iff_ne [partial_order α] {x y : α} (h : x ≤ y) : x < y ↔ x ≠ y := ⟨λ h, h.ne, h.lt_of_ne⟩
lemma le_iff_eq [partial_order α] {x y : α} (h : x ≤ y) : y ≤ x ↔ y = x :=
⟨λ h', h'.antisymm h, eq.le⟩
lemma lt_or_le [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a < c ∨ c ≤ b :=
(lt_or_ge a c).imp id $ λ hc, le_trans hc h
lemma le_or_lt [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a ≤ c ∨ c < b :=
(le_or_gt a c).imp id $ λ hc, lt_of_lt_of_le hc h
lemma le_or_le [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a ≤ c ∨ c ≤ b :=
(h.le_or_lt c).elim or.inl (λ h, or.inr $ le_of_lt h)
end has_le.le
namespace has_lt.lt
@[nolint ge_or_gt] -- see Note [nolint_ge]
protected lemma gt [has_lt α] {x y : α} (h : x < y) : y > x := h
protected lemma false [preorder α] {x : α} : x < x → false := lt_irrefl x
lemma ne' [preorder α] {x y : α} (h : x < y) : y ≠ x := h.ne.symm
lemma lt_or_lt [linear_order α] {x y : α} (h : x < y) (z : α) : x < z ∨ z < y :=
(lt_or_ge z y).elim or.inr (λ hz, or.inl $ h.trans_le hz)
end has_lt.lt
@[nolint ge_or_gt] -- see Note [nolint_ge]
protected lemma ge.le [has_le α] {x y : α} (h : x ≥ y) : y ≤ x := h
@[nolint ge_or_gt] -- see Note [nolint_ge]
protected lemma gt.lt [has_lt α] {x y : α} (h : x > y) : y < x := h
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem ge_of_eq [preorder α] {a b : α} (h : a = b) : a ≥ b := h.ge
@[simp, nolint ge_or_gt] -- see Note [nolint_ge]
lemma ge_iff_le [has_le α] {a b : α} : a ≥ b ↔ b ≤ a := iff.rfl
@[simp, nolint ge_or_gt] -- see Note [nolint_ge]
lemma gt_iff_lt [has_lt α] {a b : α} : a > b ↔ b < a := iff.rfl
lemma not_le_of_lt [preorder α] {a b : α} (h : a < b) : ¬ b ≤ a := (le_not_le_of_lt h).right
alias not_le_of_lt ← has_lt.lt.not_le
lemma not_lt_of_le [preorder α] {a b : α} (h : a ≤ b) : ¬ b < a := λ hba, hba.not_le h
alias not_lt_of_le ← has_le.le.not_lt
lemma ne_of_not_le [preorder α] {a b : α} (h : ¬ a ≤ b) : a ≠ b :=
λ hab, h (le_of_eq hab)
-- See Note [decidable namespace]
protected lemma decidable.le_iff_eq_or_lt [partial_order α] [@decidable_rel α (≤)]
{a b : α} : a ≤ b ↔ a = b ∨ a < b := decidable.le_iff_lt_or_eq.trans or.comm
lemma le_iff_eq_or_lt [partial_order α] {a b : α} : a ≤ b ↔ a = b ∨ a < b :=
le_iff_lt_or_eq.trans or.comm
lemma lt_iff_le_and_ne [partial_order α] {a b : α} : a < b ↔ a ≤ b ∧ a ≠ b :=
⟨λ h, ⟨le_of_lt h, ne_of_lt h⟩, λ ⟨h1, h2⟩, h1.lt_of_ne h2⟩
-- See Note [decidable namespace]
protected lemma decidable.eq_iff_le_not_lt [partial_order α] [@decidable_rel α (≤)]
{a b : α} : a = b ↔ a ≤ b ∧ ¬ a < b :=
⟨λ h, ⟨h.le, h ▸ lt_irrefl _⟩, λ ⟨h₁, h₂⟩, h₁.antisymm $
decidable.by_contradiction $ λ h₃, h₂ (h₁.lt_of_not_le h₃)⟩
lemma eq_iff_le_not_lt [partial_order α] {a b : α} : a = b ↔ a ≤ b ∧ ¬ a < b :=
by haveI := classical.dec; exact decidable.eq_iff_le_not_lt
lemma eq_or_lt_of_le [partial_order α] {a b : α} (h : a ≤ b) : a = b ∨ a < b := h.lt_or_eq.symm
lemma eq_or_gt_of_le [partial_order α] {a b : α} (h : a ≤ b) : b = a ∨ a < b :=
h.lt_or_eq.symm.imp eq.symm id
alias decidable.eq_or_lt_of_le ← has_le.le.eq_or_lt_dec
alias eq_or_lt_of_le ← has_le.le.eq_or_lt
alias eq_or_gt_of_le ← has_le.le.eq_or_gt
attribute [nolint decidable_classical] has_le.le.eq_or_lt_dec
lemma eq_of_le_of_not_lt [partial_order α] {a b : α} (hab : a ≤ b) (hba : ¬ a < b) : a = b :=
hab.eq_or_lt.resolve_right hba
lemma eq_of_ge_of_not_gt [partial_order α] {a b : α} (hab : a ≤ b) (hba : ¬ a < b) : b = a :=
(hab.eq_or_lt.resolve_right hba).symm
alias eq_of_le_of_not_lt ← has_le.le.eq_of_not_lt
alias eq_of_ge_of_not_gt ← has_le.le.eq_of_not_gt
lemma ne.le_iff_lt [partial_order α] {a b : α} (h : a ≠ b) : a ≤ b ↔ a < b :=
⟨λ h', lt_of_le_of_ne h' h, λ h, h.le⟩
lemma ne.not_le_or_not_le [partial_order α] {a b : α} (h : a ≠ b) : ¬ a ≤ b ∨ ¬ b ≤ a :=
not_and_distrib.1 $ le_antisymm_iff.not.1 h
-- See Note [decidable namespace]
protected lemma decidable.ne_iff_lt_iff_le [partial_order α] [decidable_eq α] {a b : α} :
(a ≠ b ↔ a < b) ↔ a ≤ b :=
⟨λ h, decidable.by_cases le_of_eq (le_of_lt ∘ h.mp), λ h, ⟨lt_of_le_of_ne h, ne_of_lt⟩⟩
@[simp] lemma ne_iff_lt_iff_le [partial_order α] {a b : α} : (a ≠ b ↔ a < b) ↔ a ≤ b :=
by haveI := classical.dec; exact decidable.ne_iff_lt_iff_le
lemma lt_of_not_le [linear_order α] {a b : α} (h : ¬ b ≤ a) : a < b :=
((le_total _ _).resolve_right h).lt_of_not_le h
lemma lt_iff_not_le [linear_order α] {x y : α} : x < y ↔ ¬ y ≤ x := ⟨not_le_of_lt, lt_of_not_le⟩
lemma ne.lt_or_lt [linear_order α] {x y : α} (h : x ≠ y) : x < y ∨ y < x := lt_or_gt_of_ne h
/-- A version of `ne_iff_lt_or_gt` with LHS and RHS reversed. -/
@[simp] lemma lt_or_lt_iff_ne [linear_order α] {x y : α} : x < y ∨ y < x ↔ x ≠ y :=
ne_iff_lt_or_gt.symm
lemma not_lt_iff_eq_or_lt [linear_order α] {a b : α} : ¬ a < b ↔ a = b ∨ b < a :=
not_lt.trans $ decidable.le_iff_eq_or_lt.trans $ or_congr eq_comm iff.rfl
lemma exists_ge_of_linear [linear_order α] (a b : α) : ∃ c, a ≤ c ∧ b ≤ c :=
match le_total a b with
| or.inl h := ⟨_, h, le_rfl⟩
| or.inr h := ⟨_, le_rfl, h⟩
end
lemma lt_imp_lt_of_le_imp_le {β} [linear_order α] [preorder β] {a b : α} {c d : β}
(H : a ≤ b → c ≤ d) (h : d < c) : b < a :=
lt_of_not_le $ λ h', (H h').not_lt h
lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} :
(a ≤ b → c ≤ d) ↔ (d < c → b < a) :=
⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩
lemma lt_iff_lt_of_le_iff_le' {β} [preorder α] [preorder β] {a b : α} {c d : β}
(H : a ≤ b ↔ c ≤ d) (H' : b ≤ a ↔ d ≤ c) : b < a ↔ d < c :=
lt_iff_le_not_le.trans $ (and_congr H' (not_congr H)).trans lt_iff_le_not_le.symm
lemma lt_iff_lt_of_le_iff_le {β} [linear_order α] [linear_order β] {a b : α} {c d : β}
(H : a ≤ b ↔ c ≤ d) : b < a ↔ d < c :=
not_le.symm.trans $ (not_congr H).trans $ not_le
lemma le_iff_le_iff_lt_iff_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} :
(a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) :=
⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ (not_congr H).trans $ not_lt⟩
lemma eq_of_forall_le_iff [partial_order α] {a b : α}
(H : ∀ c, c ≤ a ↔ c ≤ b) : a = b :=
((H _).1 le_rfl).antisymm ((H _).2 le_rfl)
lemma le_of_forall_le [preorder α] {a b : α}
(H : ∀ c, c ≤ a → c ≤ b) : a ≤ b :=
H _ le_rfl
lemma le_of_forall_le' [preorder α] {a b : α}
(H : ∀ c, a ≤ c → b ≤ c) : b ≤ a :=
H _ le_rfl
lemma le_of_forall_lt [linear_order α] {a b : α}
(H : ∀ c, c < a → c < b) : a ≤ b :=
le_of_not_lt $ λ h, lt_irrefl _ (H _ h)
lemma forall_lt_iff_le [linear_order α] {a b : α} :
(∀ ⦃c⦄, c < a → c < b) ↔ a ≤ b :=
⟨le_of_forall_lt, λ h c hca, lt_of_lt_of_le hca h⟩
lemma le_of_forall_lt' [linear_order α] {a b : α}
(H : ∀ c, a < c → b < c) : b ≤ a :=
le_of_not_lt $ λ h, lt_irrefl _ (H _ h)
lemma forall_lt_iff_le' [linear_order α] {a b : α} :
(∀ ⦃c⦄, a < c → b < c) ↔ b ≤ a :=
⟨le_of_forall_lt', λ h c hac, lt_of_le_of_lt h hac⟩
lemma eq_of_forall_ge_iff [partial_order α] {a b : α}
(H : ∀ c, a ≤ c ↔ b ≤ c) : a = b :=
((H _).2 le_rfl).antisymm ((H _).1 le_rfl)
/-- monotonicity of `≤` with respect to `→` -/
lemma le_implies_le_of_le_of_le {a b c d : α} [preorder α] (hca : c ≤ a) (hbd : b ≤ d) :
a ≤ b → c ≤ d :=
λ hab, (hca.trans hab).trans hbd
@[ext]
lemma preorder.to_has_le_injective {α : Type*} :
function.injective (@preorder.to_has_le α) :=
λ A B h, begin
cases A, cases B,
injection h with h_le,
have : A_lt = B_lt,
{ funext a b,
dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le h_le,
simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, h_le], },
congr',
end
@[ext]
lemma partial_order.to_preorder_injective {α : Type*} :
function.injective (@partial_order.to_preorder α) :=
λ A B h, by { cases A, cases B, injection h, congr' }
@[ext]
lemma linear_order.to_partial_order_injective {α : Type*} :
function.injective (@linear_order.to_partial_order α) :=
begin
intros A B h,
cases A, cases B, injection h,
obtain rfl : A_le = B_le := ‹_›, obtain rfl : A_lt = B_lt := ‹_›,
obtain rfl : A_decidable_le = B_decidable_le := subsingleton.elim _ _,
obtain rfl : A_max = B_max := A_max_def.trans B_max_def.symm,
obtain rfl : A_min = B_min := A_min_def.trans B_min_def.symm,
congr
end
theorem preorder.ext {α} {A B : preorder α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by { ext x y, exact H x y }
theorem partial_order.ext {α} {A B : partial_order α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by { ext x y, exact H x y }
theorem linear_order.ext {α} {A B : linear_order α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by { ext x y, exact H x y }
/-- Given a relation `R` on `β` and a function `f : α → β`, the preimage relation on `α` is defined
by `x ≤ y ↔ f x ≤ f y`. It is the unique relation on `α` making `f` a `rel_embedding` (assuming `f`
is injective). -/
@[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) : Prop := s (f x) (f y)
infix ` ⁻¹'o `:80 := order.preimage
/-- The preimage of a decidable order is decidable. -/
instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] :
decidable_rel (f ⁻¹'o s) :=
λ x y, H _ _
/-! ### Order dual -/
/-- Type synonym to equip a type with the dual order: `≤` means `≥` and `<` means `>`. `αᵒᵈ` is
notation for `order_dual α`. -/
def order_dual (α : Type*) : Type* := α
notation α `ᵒᵈ`:std.prec.max_plus := order_dual α
namespace order_dual
instance (α : Type*) [h : nonempty α] : nonempty αᵒᵈ := h
instance (α : Type*) [h : subsingleton α] : subsingleton αᵒᵈ := h
instance (α : Type*) [has_le α] : has_le αᵒᵈ := ⟨λ x y : α, y ≤ x⟩
instance (α : Type*) [has_lt α] : has_lt αᵒᵈ := ⟨λ x y : α, y < x⟩
instance (α : Type*) [has_zero α] : has_zero αᵒᵈ := ⟨(0 : α)⟩
-- `dual_le` and `dual_lt` should not be simp lemmas:
-- they cause a loop since `α` and `αᵒᵈ` are definitionally equal
lemma dual_le [has_le α] {a b : α} :
@has_le.le αᵒᵈ _ a b ↔ @has_le.le α _ b a := iff.rfl
lemma dual_lt [has_lt α] {a b : α} :
@has_lt.lt αᵒᵈ _ a b ↔ @has_lt.lt α _ b a := iff.rfl
instance (α : Type*) [preorder α] : preorder αᵒᵈ :=
{ le_refl := le_refl,
le_trans := λ a b c hab hbc, hbc.trans hab,
lt_iff_le_not_le := λ _ _, lt_iff_le_not_le,
.. order_dual.has_le α,
.. order_dual.has_lt α }
instance (α : Type*) [partial_order α] : partial_order αᵒᵈ :=
{ le_antisymm := λ a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α }
instance (α : Type*) [linear_order α] : linear_order αᵒᵈ :=
{ le_total := λ a b : α, le_total b a,
decidable_le := (infer_instance : decidable_rel (λ a b : α, b ≤ a)),
decidable_lt := (infer_instance : decidable_rel (λ a b : α, b < a)),
min := @max α _,
max := @min α _,
min_def := @linear_order.max_def α _,
max_def := @linear_order.min_def α _,
.. order_dual.partial_order α }
instance : Π [inhabited α], inhabited αᵒᵈ := id
theorem preorder.dual_dual (α : Type*) [H : preorder α] :
order_dual.preorder αᵒᵈ = H :=
preorder.ext $ λ _ _, iff.rfl
theorem partial_order.dual_dual (α : Type*) [H : partial_order α] :
order_dual.partial_order αᵒᵈ = H :=
partial_order.ext $ λ _ _, iff.rfl
theorem linear_order.dual_dual (α : Type*) [H : linear_order α] :
order_dual.linear_order αᵒᵈ = H :=
linear_order.ext $ λ _ _, iff.rfl
end order_dual
/-! ### Order instances on the function space -/
instance pi.has_le {ι : Type u} {α : ι → Type v} [∀ i, has_le (α i)] : has_le (Π i, α i) :=
{ le := λ x y, ∀ i, x i ≤ y i }
lemma pi.le_def {ι : Type u} {α : ι → Type v} [∀ i, has_le (α i)] {x y : Π i, α i} :
x ≤ y ↔ ∀ i, x i ≤ y i :=
iff.rfl
instance pi.preorder {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] : preorder (Π i, α i) :=
{ le_refl := λ a i, le_refl (a i),
le_trans := λ a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i),
..pi.has_le }
lemma pi.lt_def {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] {x y : Π i, α i} :
x < y ↔ x ≤ y ∧ ∃ i, x i < y i :=
by simp [lt_iff_le_not_le, pi.le_def] {contextual := tt}
lemma le_update_iff {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] [decidable_eq ι]
{x y : Π i, α i} {i : ι} {a : α i} :
x ≤ function.update y i a ↔ x i ≤ a ∧ ∀ j ≠ i, x j ≤ y j :=
function.forall_update_iff _ (λ j z, x j ≤ z)
lemma update_le_iff {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] [decidable_eq ι]
{x y : Π i, α i} {i : ι} {a : α i} :
function.update x i a ≤ y ↔ a ≤ y i ∧ ∀ j ≠ i, x j ≤ y j :=
function.forall_update_iff _ (λ j z, z ≤ y j)
lemma update_le_update_iff {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] [decidable_eq ι]
{x y : Π i, α i} {i : ι} {a b : α i} :
function.update x i a ≤ function.update y i b ↔ a ≤ b ∧ ∀ j ≠ i, x j ≤ y j :=
by simp [update_le_iff] {contextual := tt}
instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀ i, partial_order (α i)] :
partial_order (Π i, α i) :=
{ le_antisymm := λ f g h1 h2, funext (λ b, (h1 b).antisymm (h2 b)),
..pi.preorder }
/-! ### Lifts of order instances -/
/-- Transfer a `preorder` on `β` to a `preorder` on `α` using a function `f : α → β`.
See note [reducible non-instances]. -/
@[reducible] def preorder.lift {α β} [preorder β] (f : α → β) : preorder α :=
{ le := λ x y, f x ≤ f y,
le_refl := λ a, le_rfl,
le_trans := λ a b c, le_trans,
lt := λ x y, f x < f y,
lt_iff_le_not_le := λ a b, lt_iff_le_not_le }
/-- Transfer a `partial_order` on `β` to a `partial_order` on `α` using an injective
function `f : α → β`. See note [reducible non-instances]. -/
@[reducible] def partial_order.lift {α β} [partial_order β] (f : α → β) (inj : injective f) :
partial_order α :=
{ le_antisymm := λ a b h₁ h₂, inj (h₁.antisymm h₂), .. preorder.lift f }
/-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective
function `f : α → β`. See note [reducible non-instances]. -/
@[reducible] def linear_order.lift {α β} [linear_order β] (f : α → β) (inj : injective f) :
linear_order α :=
{ le_total := λ x y, le_total (f x) (f y),
decidable_le := λ x y, (infer_instance : decidable (f x ≤ f y)),
decidable_lt := λ x y, (infer_instance : decidable (f x < f y)),
decidable_eq := λ x y, decidable_of_iff _ inj.eq_iff,
.. partial_order.lift f inj }
/-! ### Subtype of an order -/
namespace subtype
instance [has_le α] {p : α → Prop} : has_le (subtype p) := ⟨λ x y, (x : α) ≤ y⟩
instance [has_lt α] {p : α → Prop} : has_lt (subtype p) := ⟨λ x y, (x : α) < y⟩
@[simp] lemma mk_le_mk [has_le α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} :
(⟨x, hx⟩ : subtype p) ≤ ⟨y, hy⟩ ↔ x ≤ y :=
iff.rfl
@[simp] lemma mk_lt_mk [has_lt α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} :
(⟨x, hx⟩ : subtype p) < ⟨y, hy⟩ ↔ x < y :=
iff.rfl
@[simp, norm_cast]
lemma coe_le_coe [has_le α] {p : α → Prop} {x y : subtype p} : (x : α) ≤ y ↔ x ≤ y := iff.rfl
@[simp, norm_cast]
lemma coe_lt_coe [has_lt α] {p : α → Prop} {x y : subtype p} : (x : α) < y ↔ x < y := iff.rfl
instance [preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift (coe : subtype p → α)
instance partial_order [partial_order α] (p : α → Prop) :
partial_order (subtype p) :=
partial_order.lift coe subtype.coe_injective
instance decidable_le [preorder α] [@decidable_rel α (≤)] {p : α → Prop} :
@decidable_rel (subtype p) (≤) :=
λ a b, decidable_of_iff _ subtype.coe_le_coe
instance decidable_lt [preorder α] [@decidable_rel α (<)] {p : α → Prop} :
@decidable_rel (subtype p) (<) :=
λ a b, decidable_of_iff _ subtype.coe_lt_coe
/-- A subtype of a linear order is a linear order. We explicitly give the proofs of decidable
equality and decidable order in order to ensure the decidability instances are all definitionally
equal. -/
instance [linear_order α] (p : α → Prop) : linear_order (subtype p) :=
{ decidable_eq := subtype.decidable_eq,
decidable_le := subtype.decidable_le,
decidable_lt := subtype.decidable_lt,
max_def := by { ext a b, convert rfl },
min_def := by { ext a b, convert rfl },
.. linear_order.lift coe subtype.coe_injective }
end subtype
/-!
### Pointwise order on `α × β`
The lexicographic order is defined in `order.lexicographic`, and the instances are available via the
type synonym `α ×ₗ β = α × β`.
-/
namespace prod
instance (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) :=
⟨λ p q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩
lemma le_def [has_le α] [has_le β] {x y : α × β} : x ≤ y ↔ x.1 ≤ y.1 ∧ x.2 ≤ y.2 := iff.rfl
@[simp] lemma mk_le_mk [has_le α] [has_le β] {x₁ x₂ : α} {y₁ y₂ : β} :
(x₁, y₁) ≤ (x₂, y₂) ↔ x₁ ≤ x₂ ∧ y₁ ≤ y₂ :=
iff.rfl
@[simp] lemma swap_le_swap [has_le α] [has_le β] {x y : α × β} : x.swap ≤ y.swap ↔ x ≤ y :=
and_comm _ _
instance (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) :=
{ le_refl := λ ⟨a, b⟩, ⟨le_refl a, le_refl b⟩,
le_trans := λ ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩,
⟨le_trans hac hce, le_trans hbd hdf⟩,
.. prod.has_le α β }
@[simp] lemma swap_lt_swap [preorder α] [preorder β] {x y : α × β} : x.swap < y.swap ↔ x < y :=
and_congr swap_le_swap (not_congr swap_le_swap)
lemma lt_iff [preorder α] [preorder β] {a b : α × β} :
a < b ↔ a.1 < b.1 ∧ a.2 ≤ b.2 ∨ a.1 ≤ b.1 ∧ a.2 < b.2 :=
begin
refine ⟨λ h, _, _⟩,
{ by_cases h₁ : b.1 ≤ a.1,
{ exact or.inr ⟨h.1.1, h.1.2.lt_of_not_le $ λ h₂, h.2 ⟨h₁, h₂⟩⟩ },
{ exact or.inl ⟨h.1.1.lt_of_not_le h₁, h.1.2⟩ } },
{ rintro (⟨h₁, h₂⟩ | ⟨h₁, h₂⟩),
{ exact ⟨⟨h₁.le, h₂⟩, λ h, h₁.not_le h.1⟩ },
{ exact ⟨⟨h₁, h₂.le⟩, λ h, h₂.not_le h.2⟩ } }
end
@[simp] lemma mk_lt_mk [preorder α] [preorder β] {x₁ x₂ : α} {y₁ y₂ : β} :
(x₁, y₁) < (x₂, y₂) ↔ x₁ < x₂ ∧ y₁ ≤ y₂ ∨ x₁ ≤ x₂ ∧ y₁ < y₂ :=
lt_iff
/-- The pointwise partial order on a product.
(The lexicographic ordering is defined in order/lexicographic.lean, and the instances are
available via the type synonym `α ×ₗ β = α × β`.) -/
instance (α : Type u) (β : Type v) [partial_order α] [partial_order β] :
partial_order (α × β) :=
{ le_antisymm := λ ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩,
prod.ext (hac.antisymm hca) (hbd.antisymm hdb),
.. prod.preorder α β }
end prod
/-! ### Additional order classes -/
/-- An order is dense if there is an element between any pair of distinct elements. -/
class densely_ordered (α : Type u) [has_lt α] : Prop :=
(dense : ∀ a₁ a₂ : α, a₁ < a₂ → ∃ a, a₁ < a ∧ a < a₂)
lemma exists_between [has_lt α] [densely_ordered α] :
∀ {a₁ a₂ : α}, a₁ < a₂ → ∃ a, a₁ < a ∧ a < a₂ :=
densely_ordered.dense
instance order_dual.densely_ordered (α : Type u) [has_lt α] [densely_ordered α] :
densely_ordered αᵒᵈ :=
⟨λ a₁ a₂ ha, (@exists_between α _ _ _ _ ha).imp $ λ a, and.symm⟩
lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h : ∀ a, a₂ < a → a₁ ≤ a) :
a₁ ≤ a₂ :=
le_of_not_gt $ λ ha,
let ⟨a, ha₁, ha₂⟩ := exists_between ha in
lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›)
lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h₁ : a₂ ≤ a₁) (h₂ : ∀ a, a₂ < a → a₁ ≤ a) : a₁ = a₂ :=
le_antisymm (le_of_forall_le_of_dense h₂) h₁
lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h : ∀ a₃ < a₁, a₃ ≤ a₂) :
a₁ ≤ a₂ :=
le_of_not_gt $ λ ha,
let ⟨a, ha₁, ha₂⟩ := exists_between ha in
lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a›
lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h₁ : a₂ ≤ a₁) (h₂ : ∀ a₃ < a₁, a₃ ≤ a₂) : a₁ = a₂ :=
(le_of_forall_ge_of_dense h₂).antisymm h₁
lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) :
(∃ a, a₁ < a ∧ a < a₂) ∨ ((∀ a, a₁ < a → a₂ ≤ a) ∧ (∀ a < a₂, a ≤ a₁)) :=
or_iff_not_imp_left.2 $ λ h,
⟨λ a ha₁, le_of_not_gt $ λ ha₂, h ⟨a, ha₁, ha₂⟩,
λ a ha₂, le_of_not_gt $ λ ha₁, h ⟨a, ha₁, ha₂⟩⟩
variables {s : β → β → Prop} {t : γ → γ → Prop}
/-! ### Linear order from a total partial order -/
/-- Type synonym to create an instance of `linear_order` from a `partial_order` and
`is_total α (≤)` -/
def as_linear_order (α : Type u) := α
instance {α} [inhabited α] : inhabited (as_linear_order α) :=
⟨ (default : α) ⟩
noncomputable instance as_linear_order.linear_order {α} [partial_order α] [is_total α (≤)] :
linear_order (as_linear_order α) :=
{ le_total := @total_of α (≤) _,
decidable_le := classical.dec_rel _,
.. (_ : partial_order α) }
|
069d0c897044bb130d9bcd64f3897fd02e4347eb | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/decidable.lean | d001eaec3c15cb11f28079f1610d19e834b43910 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 229 | lean | import standard data.unit
using bool unit decidable
constants a b c : bool
constants u v : unit
set_option pp.implicit true
check if ((a = b) ∧ (b = c) → ¬ (u = v) ∨ (a = c) → (a = c) ↔ a = tt ↔ true) then a else b
|
b5bca6ffffcfcf63ebcafd29263b721314413247 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /tests/lean/mvar1.lean | dd4adc971b479d3467b41cd115152ba01db326b3 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,084 | lean | import Lean.MetavarContext
open Lean
def check (b : Bool) : IO Unit :=
unless b (throw $ IO.userError "error")
def f := mkConst `f []
def g := mkConst `g []
def a := mkConst `a []
def b := mkConst `b []
def c := mkConst `c []
def b0 := mkBVar 0
def b1 := mkBVar 1
def b2 := mkBVar 2
def u := mkLevelParam `u
def typeE := mkSort levelOne
def natE := mkConst `Nat []
def boolE := mkConst `Bool []
def vecE := mkConst `Vec [levelZero]
def α := mkFVar `α
def x := mkFVar `x
def y := mkFVar `y
def z := mkFVar `z
def w := mkFVar `w
def m1 := mkMVar `m1
def m2 := mkMVar `m2
def m3 := mkMVar `m3
def m4 := mkMVar `m4
def m5 := mkMVar `m5
def m6 := mkMVar `m6
def bi := BinderInfo.default
def arrow (d b : Expr) := mkForall `_ bi d b
def lctx1 : LocalContext := {}
def lctx2 := lctx1.mkLocalDecl `α `α typeE
def lctx3 := lctx2.mkLocalDecl `x `x natE
def lctx4 := lctx3.mkLocalDecl `y `y α
def lctx5 := lctx4.mkLocalDecl `z `z (mkAppN vecE #[x])
def lctx6 := lctx5.mkLocalDecl `w `w (arrow natE (mkAppN m6 #[α, x, y]))
def t1 := lctx5.mkLambda #[α, x, y] $ mkAppN f #[α, mkAppN g #[x, y], lctx5.mkLambda #[z] (mkApp f z)]
#eval check (!t1.hasFVar)
#eval t1
def mctx1 : MetavarContext := {}
def mctx2 := mctx1.addExprMVarDecl `m1 `m1 lctx3 #[] natE
def mctx3 := mctx2.addExprMVarDecl `m2 `m2 lctx4 #[] α
def mctx4 := mctx3.addExprMVarDecl `m3 `m3 lctx4 #[] natE
def mctx5 := mctx4.addExprMVarDecl `m4 `m4 lctx1 #[] (arrow typeE (arrow natE (arrow α natE)))
def mctx6 := mctx5.addExprMVarDecl `m5 `m5 lctx5 #[] typeE
def mctx7 := mctx5.addExprMVarDecl `m6 `m6 lctx5 #[] (arrow typeE (arrow natE (arrow α natE)))
def mctx8 := mctx7.assignDelayed `m4 lctx4 #[α, x, y] m3
def mctx9 := mctx8.assignExpr `m3 (mkAppN g #[x, y])
def mctx10 := mctx9.assignExpr `m1 a
def t2 := lctx5.mkLambda #[α, x, y] $ mkAppN f #[mkAppN m4 #[α, x, y], x]
#eval check (!t2.hasFVar)
#eval t2
#eval (mctx6.instantiateMVars t2).1
#eval check (!(mctx9.instantiateMVars t2).1.hasMVar)
#eval check (!(mctx9.instantiateMVars t2).1.hasFVar)
#eval (mctx9.instantiateMVars t2).1
-- t3 is ill-formed since m3's localcontext contains ‵α`, `x` and `y`
def t3 := lctx5.mkLambda #[α, x, y] $ mkAppN f #[m3, x]
#eval check (mctx10.instantiateMVars t3).1.hasFVar
#eval (mctx7.instantiateMVars t3).1
def mkDiamond : Nat → Expr
| 0 => m1
| (n+1) => mkAppN f #[mkDiamond n, mkDiamond n]
#eval (mctx7.instantiateMVars (mkDiamond 3)).1
#eval (mctx10.instantiateMVars (mkDiamond 3)).1
#eval (mctx7.instantiateMVars (mkDiamond 100)).1.getAppFn
#eval (mctx10.instantiateMVars (mkDiamond 100)).1.getAppFn
def mctx11 := mctx10.assignDelayed `m6 lctx5 #[α, x, y] m5
def mctx12 := mctx11.assignExpr `m5 (arrow α α)
def t4 := lctx6.mkLambda #[α, x, y, w] $ mkAppN f #[mkAppN m4 #[α, x, y], x]
#eval t4
#eval (mctx9.instantiateMVars t4).1
#eval (mctx12.instantiateMVars t4).1
#eval check (mctx9.instantiateMVars t4).1.hasMVar
#eval check (!((mctx9.instantiateMVars t4).1.hasFVar))
#eval check (!(mctx12.instantiateMVars t4).1.hasMVar)
#eval check (!((mctx12.instantiateMVars t4).1.hasFVar))
|
aa3ae4750f1947c2aa7f4eb24d0aa753d898e3c9 | 952248371e69ccae722eb20bfe6815d8641554a8 | /src/interactive.lean | f22b08afe8244be5df87c4a04fe66f5cf9dc37a0 | [] | no_license | robertylewis/lean_polya | 5fd079031bf7114449d58d68ccd8c3bed9bcbc97 | 1da14d60a55ad6cd8af8017b1b64990fccb66ab7 | refs/heads/master | 1,647,212,226,179 | 1,558,108,354,000 | 1,558,108,354,000 | 89,933,264 | 1 | 2 | null | 1,560,964,118,000 | 1,493,650,551,000 | Lean | UTF-8 | Lean | false | false | 4,208 | lean | import .control
open polya monad native
meta structure polya_cache :=
(sum_cache : rb_set sum_form_comp_data)
(prod_cache : rb_set prod_form_comp_data)
(bb : blackboard)
meta def polya_tactic := state_t polya_cache tactic
namespace polya_tactic
meta instance : monad polya_tactic := state_t.monad
meta instance : monad_state polya_cache polya_tactic := state_t.monad_state
meta instance polya_tactic.of_tactic : has_monad_lift tactic polya_tactic :=
state_t.has_monad_lift
private meta def lift_polya_state (α) (m : polya_state α) : polya_tactic α :=
do
s ← get,
let (a, bb') := m.run s.bb,
put ⟨s.sum_cache, s.prod_cache, bb'⟩,
return a
meta instance polya_tactic.of_polya_state : has_monad_lift polya_state polya_tactic :=
⟨lift_polya_state⟩
meta instance tpt (α) : has_coe (tactic α) (polya_tactic α) :=
⟨monad_lift⟩
meta instance pst (α) : has_coe (polya_state α) (polya_tactic α) :=
⟨monad_lift⟩
meta instance : alternative polya_tactic := state_t.alternative
meta def step {α} (c : polya_tactic α) : polya_tactic unit :=
c >> return ()
meta def save_info (p : pos) : polya_tactic unit :=
return ()
meta def execute (c : polya_tactic unit) : tactic unit :=
do bb ← add_proof_to_blackboard blackboard.mk_empty `(rat_one_gt_zero),
let pc : polya_cache := ⟨mk_rb_set, mk_rb_set, bb⟩ in
c.run pc >> return ()
/-meta def istep {α} (line0 col0 line col : ℕ) (c : polya_tactic α) : polya_tactic unit :=
tactic.istep line0 col0 line col c-/
meta def assert_claims_with_names : list expr → list name → tactic unit
| [] _ := tactic.skip
| (h::hs) (n::ns) := tactic.note n none h >> assert_claims_with_names hs ns
| (h::hs) [] := do n ← tactic.mk_fresh_name, tactic.note n none h, assert_claims_with_names hs []
namespace interactive
open lean lean.parser interactive interactive.types
meta def add_expr (e : parse texpr) : polya_tactic unit :=
do
ps ← get,
bb' ← ↑(tactic.i_to_expr e >>= process_expr_tac ps.bb),
put ⟨ps.sum_cache, ps.prod_cache, bb'⟩
meta def add_comparison (e : parse texpr) : polya_tactic unit :=
do
ps ← get,
bb' ← ↑(tactic.i_to_expr e >>= add_proof_to_blackboard ps.bb),
put ⟨ps.sum_cache, ps.prod_cache, bb'⟩
meta def add_hypotheses (ns : parse (many ident)) : polya_tactic unit :=
do
ps ← get,
exps ← ns.mmap ↑tactic.get_local,
bb' ← add_proofs_to_blackboard ps.bb exps,
put ⟨ps.sum_cache, ps.prod_cache, bb'⟩
meta def additive : polya_tactic unit :=
do
ps ← get,
let (nsc, bb') := (sum_form.add_new_ineqs ps.sum_cache).run ps.bb in
put ⟨nsc, ps.prod_cache, bb'⟩
meta def multiplicative : polya_tactic unit :=
do
ps ← get,
let (nsc, bb') := (prod_form.add_new_ineqs ps.prod_cache).run ps.bb in
put ⟨ps.sum_cache, nsc, bb'⟩
meta def trace_exprs : polya_tactic unit :=
do
ps ← get,
ps.bb.trace_exprs
meta def trace_state : polya_tactic unit :=
do
ps ← get,
ps.bb.trace
meta def trace_contr : polya_tactic unit :=
do
ps ← get,
match ps.bb.contr with
| contrad.none := tactic.trace "no contradiction found"
| _ := tactic.trace "contradiction found"
end
meta def reconstruct : polya_tactic unit :=
do
ps ← get,
e ← ps.bb.contr.reconstruct,
_ ← tactic.apply e,
return ()
meta def extract_comparisons_between (lhs rhs : parse parser.pexpr) (nms : parse with_ident_list) : polya_tactic unit :=
do lhs' ← tactic.i_to_expr lhs,
rhs' ← tactic.i_to_expr rhs,
iqs ← get_ineqs lhs' rhs',
iqse ← iqs.data.mmap (λ iq, iq.prf.reconstruct),
assert_claims_with_names iqse nms
end interactive
end polya_tactic
open lean.parser interactive
--meta def tactic.interactive.add_comp_to_blackboard' (e : parse texpr) (b : blackboard) : tactic blackboard :=
--do e' ← i_to_expr e, add_comp_to_blackboard e' b
meta def tactic.interactive.polya (ns : parse (many ident)) : tactic unit :=
polya_on_hyps ns
meta def tactic.interactive.polya_l (ns : parse (many ident)) : tactic unit :=
polya_on_hyps ns ff
meta def tactic.interactive.polya_all (rct : parse (optional (tk "!"))) : tactic unit :=
polya_on_all_hyps rct.is_some
|
5b959c35d1d261081062984ac5be52a85bfefc56 | f98c49f30cbc7120b78f92246f22dedad3f11f62 | /lean/book/Theorem_Proving_in_Lean/TP_02_Dependent_Type_Theory.lean | b4c16491628cba75ac2f7c73f164861aae214d84 | [
"Unlicense"
] | permissive | haroldcarr/learn-haskell-coq-ml-etc | 5a88bbbb0e0f435798ee9cab29d9e9da854174e2 | a7247caa22097573cbfa1e95fa81debeb146c12a | refs/heads/master | 1,683,755,751,897 | 1,682,914,556,000 | 1,682,914,556,000 | 12,350,346 | 36 | 9 | null | null | null | null | UTF-8 | Lean | false | false | 23,853 | lean | /-
------------------------------------------------------------------------------
2. Dependent Type Theory
Dependent type theory is a language.
Lean based on version of dependent type theory known as the Calculus of Constructions,
with a countable hierarchy of non-cumulative universes and inductive types.
------------------------------------------------------------------------------
2.1. Simple Type Theory
Type theory gets its name from fact that all expressions have types.
-/
/- declare some constants -/
constant m : nat -- m is a natural number
constant n : nat
constants b1 b2 : bool -- declare two constants at once
/- check their types (Commands that query Lean for info begin with hash) -/
#check m -- output: nat
#check n
#check n + 0 -- nat
#check m * (n + 0) -- nat
#check b1 -- bool
#check b1 && b2 -- "&&" is boolean and
#check b1 || b2 -- boolean or
#check tt -- boolean "true"
/- Build new types out of others. -/
constant f : nat → nat -- type the arrow as "\to" or "\r"
constant f' : nat -> nat -- alternative ASCII notation
constant f'' : ℕ → ℕ -- alternative notation for nat
constant p : nat × nat -- type the product as "\times"
constant q : prod nat nat -- alternative notation
constant g : nat → nat → nat
constant g' : nat → (nat → nat) -- has the same type as g!
constant h : nat × nat → nat
constant F : (nat → nat) → nat -- a "functional"
#check f -- ℕ → ℕ
#check f n -- ℕ
#check g m n -- ℕ
#check g m -- ℕ → ℕ
#check (m, n) -- ℕ × ℕ
#check p.1 -- ℕ
#check p.2 -- ℕ
#check (m, n).1 -- ℕ
#check (p.1, n) -- ℕ × ℕ
#check F f -- ℕ
/-
ℕ \nat
× \times
lower-case greek letters (e.g, α, β, γ) fro types \a, \b, and \g
f x function application
type expressions, arrows associate to the right (enables partial application)
(m, n) ordered pair
p.1 projection
p.2 projection
------------------------------------------------------------------------------
2.2. Types as Objects
Dependent type theory extends simple type theory is that types are first-class citizens.
-/
#check nat -- Type
#check bool -- Type
#check nat → bool -- Type
#check nat × bool -- Type
#check nat → nat -- ...
#check nat × nat → nat
#check nat → nat → nat
#check nat → (nat → nat)
#check nat → nat → bool
#check (nat → nat) → nat
/- declare constants and constructors for types --/
constants α β : Type
constant F' : Type → Type
constant G : Type → Type → Type
#check α -- Type
#check F' α -- Type
#check F' nat -- Type
#check G α -- Type → Type
#check G α β -- Type
#check G α nat -- Type
-- cartesian product : Type → Type → Type
-- constants α β : Type
#check prod α β -- Type
#check prod nat nat -- Type
-- list of α
-- constant α : Type
#check list α -- Type
#check list nat -- Type
/-
Think of a type as a set. The elements of the type are the elements of the set.
What type does Type have?
-/
#check Type -- Type 1
-- Lean’s foundation has an infinite hierarchy of types:
#check Type -- Type 1
#check Type 1 -- Type 2
#check Type 2 -- Type 3
#check Type 3 -- Type 4
#check Type 4 -- Type 5
/-
Type 0 : universe of "small" or "ordinary" types.
Type 1 : universe that contains Type 0 as an element
Type 2 : universe that contains Type 1 as an element
...
-/
#check Type
#check Type 0
-- another type, Prop, with special properties (discussed in next chapter)
#check Prop -- Type
/-
Some operations are polymorphic over type universes,
e.g., list α, for any type α, no matter which type universe α lives in.
Thus the type of the function list:
-/
#check list -- Type u_1 → Type u_1
/-
u_1 is a variable ranging over type levels.
#check output says that whenever α has type Type n, list α also has type Type n.
function prod is similarly polymorphic:
-/
#check prod -- Type u_1 → Type u_2 → Type (max u_1 u_2)
-- define polymorphic constants and variables via declaring universe variables explicitly:
universe u'
constant α' : Type u'
#check α'
/-
Use polymorphism for constructions to have as much generality as possible.
Type constructors will be treated as instances of mathematical functions.
------------------------------------------------------------------------------
2.3. Function Abstraction and Evaluation
Given m n : nat, then (m, n) : nat × nat : create pairs of naturals.
Given p : nat × nat, then fst p : nat and snd p : nat. : extracting pairs two components.
APPLICATION
Given function f : α → β, then apply it to a : α to obtain f a : β.
ABSTRACTION: create a function
Suppose postulating variable x : α, then construct expression t : β.
Then the expression λ x : α, t, is an object (a "function") of type α → β.
e.g., λ x : nat, x + 5
-/
#check fun x : nat, x + 5
#check λ x : nat, x + 5
-- constants α β : Type
constants a1 a2 : α
constants b1' b2' : β
constant faa : α → α
constant gab : α → β
constant haba : α → β → α
constant paa : α → α → bool
#check fun x : α, faa x -- α → α
#check λ x : α, faa x -- α → α
#check λ x : α, faa (faa x) -- α → α
#check λ x : α, haba x b1' -- α → α
#check λ y : β, haba a1 y -- β → α
#check λ x : α, paa (faa (faa x)) (haba (faa a1) b2') -- α → bool
#check λ x : α, λ y : β , haba (faa x) y -- α → β → α
#check λ (x : α) (y : β), haba (faa x) y -- α → β → α
#check λ x y , haba (faa x) y -- α → β → α
-- constants α β γ : Type
constants γ : Type
constant fab' : α → β
constant gby' : β → γ
constant b : β
#check λ x : α, x -- α → α
#check λ x : α, b -- α → β
#check λ x : α, gby' (fab' x) -- α → γ
#check λ x , gby' (fab' x)
-- constant functions
#check λ b : β, λ x : α , x -- β → α → α
#check λ (b : β) (x : α), x -- β → α → α
-- composition
#check λ (g : β → γ) (f : α → β) (x : α), g (f x) -- (β → γ) → (α → β) → α → γ
-- abstract over types - using dependent products
#check λ (α β : Type) (b : β) (x : α) , x -- constant function
#check λ (α β γ : Type) (g : β → γ) (f : α → β) (x : α), g (f x) -- composition
/-
constant f : α → β
constant g : β → γ
-/
constant hidentity : α → α
constants (a' : α) (b' : β)
#reduce (λ x : α, x) a' -- a'
#reduce (λ x : α, b') a' -- b'
#reduce (λ x : α, b') (hidentity a') -- b'
#reduce (λ x : α, gby' (fab' x)) a' -- g (f a)
#reduce (λ (v : β → γ) (u : α → β) x, v (u x)) gby' fab' a' -- g (f a)
#reduce (λ (Q R S : Type) (v : R → S) (u : Q → R) (x : Q), v (u x)) α β γ gby' fab' a' -- g (f a)
/-
#reduce : evaluate/reduce to normal form : do all BETA reductions.
two terms that beta reduce to a common term are called beta equivalent
#reduce does other forms of reduction too:
-/
constants m' n' : nat
constant b'' : bool
#print "reducing pairs"
#reduce (m, n).1 -- m
#reduce (m, n).2 -- n
#print "reducing boolean expressions"
#reduce tt && ff -- ff
#reduce ff && b'' -- ff
#reduce b'' && ff -- bool.rec ff ff b
#print "reducing arithmetic expressions"
#reduce n + 0 -- n
#reduce n + 2 -- nat.succ (nat.succ n)
#reduce 2 + 3 -- 5
/-
Feature of dependent type theory: every term has computational behavior; supports reduction/normalization.
Two terms that reduce to the same value are called definitionally equal.
Considered "the same" by the logical framework.
Computational behavior makes it possible to use Lean as a programming language.
-/
#eval 12345 * 54321
/-
#reduce uses Lean’s trusted kernel : part responsible for checking/verifying correctness of exprs and proofs.
reduce is more trustworthy, but less efficient.
more about #eval in Chapter 11.
------------------------------------------------------------------------------
2.4. Introducing Definitions
def : defines new objects. : def foo : α := bar
-/
def foo : (ℕ → ℕ) → ℕ := λ f, f 0
#check foo -- (ℕ → ℕ) → ℕ
#print foo -- λ (f : ℕ → ℕ), f 0
-- can omit type when it can bre inferred
def foo' := λ f : ℕ → ℕ, f 0
-- alternative format : put abstracted variables before the colon and omits the lambda:
def double (x : ℕ) : ℕ := x + x
#print double
#check double 3
#reduce double 3 -- 6
def square (x : ℕ) := x * x
#print square
#check square 3
#reduce square 3 -- 9
def do_twice (f : ℕ → ℕ) (x : ℕ) : ℕ := f (f x)
#reduce do_twice double 2 -- 8
-- These definitions are equivalent to the following:
def double' : ℕ → ℕ := λ x, x + x
def square' : ℕ → ℕ := λ x, x * x
def do_twice' : (ℕ → ℕ) → ℕ → ℕ := λ f x, f (f x)
-- args that are types:
def compose (α β γ : Type) (g : β → γ) (f : α → β) (x : α) : γ := g (f x)
-- exercise
def hc_multiply_by_8 : ℕ → ℕ := λ x, double ((do_twice double) x)
#reduce hc_multiply_by_8 4 -- 32
-- exercise : define Do_Twice : ((ℕ → ℕ) → (ℕ → ℕ)) → (ℕ → ℕ) → (ℕ → ℕ)
-- that applies its argument twice
-- such that Do_Twice do_twice applies its input four times.
-- Then evaluate Do_Twice do_twice double 2.
def Do_Twice : ((ℕ → ℕ) → (ℕ → ℕ)) → (ℕ → ℕ) → (ℕ → ℕ) := λ f g, f (f g)
#reduce Do_Twice do_twice double 2
def curry (α β γ : Type) (f : α × β → γ) : α → β → γ := λ a b, f (a, b)
def uncurry (α β γ : Type) (f : α → β → γ) : (α × β) → γ := λ x , f x.1 x.2
------------------------------------------------------------------------------
-- 2.5. Local Definitions via LET
#check let y := 2 + 2 in y * y -- ℕ
#reduce let y := 2 + 2 in y * y -- 16
def t (x : ℕ) : ℕ := let y := x + x in y * y -- definitionally equal to the term (x + x) * (x + x)
#reduce t 2 -- 16
#check let y := 2 + 2, z := y + y in z * z -- ℕ
#reduce let y := 2 + 2, z := y + y in z * z -- 64
/-
1. let a := t1 in t2
similar to
2. (λ a, t2) t1
but not the same.
1. every instance of a in t2 is syntactic abbreviation for t1.
2. a is a variable. λ a, t2 must make sense independently of the value of a.
-/
def fooey := let a := nat in λ x : a, x + 2
/-
def bar := (λ a, λ x : a, x + 2) nat
-- above does not work because do not know type of a, so do not know how to handle '+'
-/
/-
------------------------------------------------------------------------------
2.6. Variables and Sections
constant : declare new objects in global context.
Warning: declaring a new constant is same to declaring an axiomatic extension of the foundational system.
It may result in inconsistency.
Avoid globals via LAMBDA.
-/
def compose' (α β γ : Type) (g : β → γ) (f : α → β) (x : α) : γ := g (f x)
def do_twice'' (α : Type) (h : α → α) (x : α) : α := h (h x)
def do_thrice (α : Type) (h : α → α) (x : α) : α := h (h (h x))
-- refactor via variable / variables
variables (α β γ : Type)
def compose'' (g : β → γ) (f : α → β) (x : α) : γ := g (f x)
def do_twice''' (h : α → α) (x : α) : α := h (h x)
def do_thrice' (h : α → α) (x : α) : α := h (h (h x))
-- declare variables of any type
-- variables (α β γ : Type)
variables (g : β → γ) (f : α → β) (h : α → α)
variable x : α
def compose''' := g (f x)
def do_twice'''' := h (h x)
def do_thrice'' := h (h (h x))
#print compose
#print do_twice
#print do_thrice
-- all three types of defs print the same
/-
variable / variables do NOT create permanent entities.
They instruct Lean to insert the declared variables as bound variables in definitions that refer to them.
a 'variable' stays in scope until the end of the file.
To limit the scope of a variable, use SECTION
-/
section useful
variables (α' β' γ' : Type)
variables (g' : β → γ) (f' : α → β) (h' : α → α)
variable x' : α
def compose'''' := g (f x)
def do_twice''''' := h (h x)
def do_thrice''' := h (h (h x))
end useful
/-
Do NOT have to name a section.
Sections can be nested.
-/
------------------------------------------------------------------------------
-- 2.7. nested hierachical Namespaces
namespace foo
def nsa : ℕ := 5
def nsf (x : ℕ) : ℕ := x + 7
def nsfa : ℕ := nsf nsa
def nsffa : ℕ := nsf (nsf nsa)
#print "inside foo"
#check nsa
#check nsf
#check nsfa
#check nsffa
#check foo.nsfa
end foo
#print "outside the namespace"
-- #check a -- error
-- #check f -- error
#check foo.nsa
#check foo.nsf
#check foo.nsfa
#check foo.nsffa
-- open brings unqualified names into current context
open foo
#print "opened foo"
#check nsa
#check nsf
#check nsfa
#check foo.nsfa
#check list.nil
#check list.cons
#check list.append
open list
#check nil
#check cons
#check append
-- namespaces can be nested
namespace foon
def na : ℕ := 5
def nf (x : ℕ) : ℕ := x + 7
def nfa : ℕ := nf na
namespace bar
def ffa : ℕ := nf (nf na)
#check nfa
#check ffa
end bar
#check nfa
#check bar.ffa
end foon
#check foon.nfa
#check foon.bar.ffa
open foon
#check nfa
#check bar.ffa
/-
------------------------------------------------------------------------------
2.8. Dependent Types
What makes dependent type theory dependent : types depend on parameters
(e.g., list α enables, list ℕ, list bool).
vec α n : α : Type (of elements) and n : ℕ (length).
cons : α → list α → list α.
What type should cons have?
Guess : Type → α → list α → list α.
NO: α does not refer to anything --- it should refer to the argument of type Type.
Assuming α : Type is the first argument to the function, the type of the next two elements are α and list α.
These types vary depending on the first argument, α.
This is an instance of a Pi type, or dependent function type.
Given α : Type and β : α → Type, think of β as a family of types over α, a type β a for each a : α.
The type Π x : α, β x denotes the type of functions f that, for each a : α, f a is an element of β a.
The type of the value returned by f depends on its input.
Π x : α, β makes sense for any expression β : Type.
When the value of β depends on x, Π x : α, β denotes a dependent function type.
When β doesn’t depend on x, Π x : α, β is no different from the type α → β.
In dependent type theory the Pi construction is fundamental
(α → β is just Π x : α, β when β does not depend on x).
(Π is \Pi)
Example : list operations:
-/
namespace hidden
universe u
constant list : Type u → Type u
constant cons : Π α : Type u, α → list α → list α
constant nil : Π α : Type u, list α
constant head : Π α : Type u, list α → α
constant tail : Π α : Type u, list α → list α
constant append : Π α : Type u, list α → list α → list α
end hidden
open list
#check list -- Type u_1 → Type u_1
#check @cons -- Π {α : Type u_1} , α → list α → list α
#check @nil -- Π {α : Type u_1} , list α
#check @head -- Π {α : Type u_1} [_inst_1 : inhabited α], list α → α
#check @tail -- Π {α : Type u_1} , list α → list α
#check @append -- Π {α : Type u_1} [c : has_append α] , α → α → α
-- head : type α required to have at least one element. when passed the empty list, must determine a default.
-- Vector operations
namespace vec
universe u
constant vec : Type u → ℕ → Type u
constant empty : Π α : Type u , vec α 0
constant cons : Π (α : Type u) (n : ℕ) , α → vec α n → vec α (n + 1)
constant append : Π (α : Type u) (n m : ℕ), vec α m → vec α n → vec α (n + m)
end vec
-- Sigma types
/-
Σ x : α, β x (aka dependent products) -- companions to Pi types.
Σ x : α, β x denotes the type of pairs sigma.mk a b where a : α and b : β a.
Just as Pi types Π x : α, β x generalize the notion of a function type α → β by allowing β to depend on α,
Sigma types Σ x : α, β x generalize the cartesian product α × β in the same way:
in the expression sigma.mk a b, the type of the second element of the pair, b : β a,
depends on the first element of the pair, a : α.
-/
namespace ss
variable sα : Type
variable sβ : sα → Type
variable sa : sα
variable sb : sβ sa
#check sigma.mk sa sb -- Σ (a : α), β a
#check (sigma.mk sa sb).1 -- α
#check (sigma.mk sa sb).2 -- β (sigma.fst (sigma.mk a b))
#reduce (sigma.mk sa sb).1 -- a
#reduce (sigma.mk sa sb).2 -- b
end ss
-- (sigma.mk a b).1 short for sigma.fst (sigma.mk a b)
-- (sigma.mk a b).2 sigma.snd (sigma.mk a b)
/-
------------------------------------------------------------------------------
2.9. Implicit Arguments
Suppose we have an implementation of lists as described above.
try it!
namespace hidden
universe u
constant list : Type u → Type u
namespace list
constant cons : Π α : Type u, α → list α → list α
constant nil : Π α : Type u, list α
constant append : Π α : Type u, list α → list α → list α
end list
end hidden
Then, given a type α, some elements of α, and some lists of elements of α, we can construct new lists using the constructors.
try it!
open hidden.list
variable α : Type
variable a : α
variables l1 l2 : list α
#check cons α a (nil α)
#check append α (cons α a (nil α)) l1
#check append α (append α (cons α a (nil α)) l1) l2
Because the constructors are polymorphic over types, we have to insert the type α as an argument repeatedly. But this information is redundant: one can infer the argument α in cons α a (nil α) from the fact that the second argument, a, has type α. One can similarly infer the argument in nil α, not from anything else in that expression, but from the fact that it is sent as an argument to the function cons, which expects an element of type list α in that position.
This is a central feature of dependent type theory: terms carry a lot of information, and often some of that information can be inferred from the context. In Lean, one uses an underscore, _, to specify that the system should fill in the information automatically. This is known as an “implicit argument.”
try it!
#check cons _ a (nil _)
#check append _ (cons _ a (nil _)) l1
#check append _ (append _ (cons _ a (nil _)) l1) l2
It is still tedious, however, to type all these underscores. When a function takes an argument that can generally be inferred from context, Lean allows us to specify that this argument should, by default, be left implicit. This is done by putting the arguments in curly braces, as follows:
try it!
namespace list
constant cons : Π {α : Type u}, α → list α → list α
constant nil : Π {α : Type u}, list α
constant append : Π {α : Type u}, list α → list α → list α
end list
open hidden.list
variable α : Type
variable a : α
variables l1 l2 : list α
#check cons a nil
#check append (cons a nil) l1
#check append (append (cons a nil) l1) l2
All that has changed are the braces around α : Type u in the declaration of the variables. We can also use this device in function definitions:
try it!
universe u
def ident {α : Type u} (x : α) := x
variables α β : Type u
variables (a : α) (b : β)
#check ident -- ?M_1 → ?M_1
#check ident a -- α
#check ident b -- β
This makes the first argument to ident implicit. Notationally, this hides the specification of the type, making it look as though ident simply takes an argument of any type. In fact, the function id is defined in the standard library in exactly this way. We have chosen a nontraditional name here only to avoid a clash of names.
Variables can also be specified as implicit when they are declared with the variables command:
try it!
universe u
section
variable {α : Type u}
variable x : α
def ident := x
end
variables α β : Type u
variables (a : α) (b : β)
#check ident
#check ident a
#check ident b
This definition of ident here has the same effect as the one above.
Lean has very complex mechanisms for instantiating implicit arguments, and we will see that they can be used to infer function types, predicates, and even proofs. The process of instantiating these “holes,” or “placeholders,” in a term is often known as elaboration. The presence of implicit arguments means that at times there may be insufficient information to fix the meaning of an expression precisely. An expression like id or list.nil is said to be polymorphic, because it can take on different meanings in different contexts.
One can always specify the type T of an expression e by writing (e : T). This instructs Lean’s elaborator to use the value T as the type of e when trying to resolve implicit arguments. In the second pair of examples below, this mechanism is used to specify the desired types of the expressions id and list.nil:
try it!
#check list.nil -- list ?M1
#check id -- ?M1 → ?M1
#check (list.nil : list ℕ) -- list ℕ
#check (id : ℕ → ℕ) -- ℕ → ℕ
Numerals are overloaded in Lean, but when the type of a numeral cannot be inferred, Lean assumes, by default, that it is a natural number. So the expressions in the first two #check commands below are elaborated in the same way, whereas the third #check command interprets 2 as an integer.
try it!
#check 2 -- ℕ
#check (2 : ℕ) -- ℕ
#check (2 : ℤ) -- ℤ
Sometimes, however, we may find ourselves in a situation where we have declared an argument to a function to be implicit, but now want to provide the argument explicitly. If foo is such a function, the notation @foo denotes the same function with all the arguments made explicit.
try it!
#check @id -- Π {α : Type u_1}, α → α
#check @id α -- α → α
#check @id β -- β → β
#check @id α a -- α
#check @id β b -- β
Notice that now the first #check command gives the type of the identifier, id, without inserting any placeholders. Moreover, the output indicates that the first argument is implicit.
2.10. Exercises
Define the function Do_Twice, as described in Section 2.4.
Define the functions curry and uncurry, as described in Section 2.4.
Above, we used the example vec α n for vectors of elements of type α of length n. Declare a constant vec_add that could represent a function that adds two vectors of natural numbers of the same length, and a constant vec_reverse that can represent a function that reverses its argument. Use implicit arguments for parameters that can be inferred. Declare some variables and check some expressions involving the constants that you have declared.
Similarly, declare a constant matrix so that matrix α m n could represent the type of m by n matrices. Declare some constants to represent functions on this type, such as matrix addition and multiplication, and (using vec) multiplication of a matrix by a vector. Once again, declare some variables and check some expressions involving the constants that you have declared.
-/
-/
|
0560d963be0616e15a5103f021d3134db06eff2d | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/list/nodup.lean | f1e94b3da337b6b071db7d09f4f29ab3c53ac9bc | [
"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 | 11,511 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau
-/
import data.list.pairwise
import data.list.forall2
universes u v
open nat function
variables {α : Type u} {β : Type v}
namespace list
/- no duplicates predicate -/
@[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l :=
⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩
@[simp] theorem nodup_nil : @nodup α [] := pairwise.nil
@[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l :=
by simp only [nodup, pairwise_cons, forall_mem_ne]
lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup
| _ _ forall₂.nil := by simp only [nodup_nil]
| _ _ (forall₂.cons hab h) :=
by simpa only [nodup_cons] using relator.rel_and (relator.rel_not (rel_mem hr hab h))
(rel_nodup h)
theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) :=
nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton (a : α) : nodup [a] :=
nodup_cons_of_nodup (not_mem_nil a) nodup_nil
theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l :=
(nodup_cons.1 h).2
theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l :=
(nodup_cons.1 h).1
theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) :=
imp_not_comm.1 not_mem_of_nodup_cons
theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ :=
pairwise_of_sublist
theorem not_nodup_pair (a : α) : ¬ nodup [a, a] :=
not_nodup_cons_of_mem $ mem_singleton_self _
theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l :=
⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin
induction l with a l IH; intro h, {exact nodup_nil},
exact nodup_cons_of_nodup
(λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al)
(IH $ λ a s, h a $ sublist_cons_of_sublist _ s)
end⟩
theorem nodup_iff_nth_le_inj {l : list α} :
nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j :=
pairwise_iff_nth_le.trans
⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _)
.resolve_left (λ h', H _ _ h₂ h' h))
.resolve_right (λ h', H _ _ h₁ h' h.symm),
λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩
@[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) :
index_of (nth_le l n h) l = n :=
nodup_iff_nth_le_inj.1 H _ _ _ h $
index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _
theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 :=
nodup_iff_sublist.trans $ forall_congr $ λ a,
have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm,
(not_congr this).trans not_lt
theorem nodup_repeat (a : α) : ∀ {n : ℕ}, nodup (repeat a n) ↔ n ≤ 1
| 0 := by simp [nat.zero_le]
| 1 := by simp
| (n+2) := iff_of_false
(λ H, nodup_iff_sublist.1 H a ((repeat_sublist_repeat _).2 (le_add_left 2 n)))
(not_le_of_lt $ le_add_left 2 n)
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α}
(d : nodup l) (h : a ∈ l) : count a l = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ :=
nodup_of_sublist (sublist_append_left l₁ l₂)
theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ :=
nodup_of_sublist (sublist_append_right l₁ l₂)
theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ :=
by simp only [nodup, pairwise_append, disjoint_iff_ne]
theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ :=
(nodup_append.1 d).2.2
theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂)
(dj : disjoint l₁ l₂) : nodup (l₁++l₂) :=
nodup_append.2 ⟨d₁, d₂, dj⟩
theorem nodup_append_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) :=
by simp only [nodup_append, and.left_comm, disjoint_comm]
theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) :=
by simp only [nodup_append, not_or_distrib, and.left_comm, and_assoc, nodup_cons, mem_append,
disjoint_cons_right]
theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l :=
pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f
theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y)
(d : nodup l) : nodup (map f l) :=
pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d)
theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) :=
nodup_map_on (assume x _ y _ h, hf h)
theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l :=
⟨nodup_of_nodup_map _, nodup_map hf⟩
@[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l :=
⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h,
λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩
theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) :=
by rw [pmap_eq_map_attach]; exact nodup_map
(λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h)
(nodup_attach.2 h)
theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) :=
pairwise_filter_of_pairwise p
@[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l :=
pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm]
theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) :
l.erase a = filter (≠ a) l :=
begin
induction d with b l m d IH, {refl},
by_cases b = a,
{ subst h, rw [erase_cons_head, filter_cons_of_neg],
symmetry, rw filter_eq_self, simpa only [ne.def, eq_comm] using m, exact not_not_intro rfl },
{ rw [erase_cons_tail _ h, filter_cons_of_pos, IH], exact h }
end
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_sublist (erase_sublist _ _)
theorem nodup_diff [decidable_eq α] : ∀ {l₁ l₂ : list α} (h : l₁.nodup), (l₁.diff l₂).nodup
| l₁ [] h := h
| l₁ (a::l₂) h := by rw diff_cons; exact nodup_diff (nodup_erase_of_nodup _ h)
theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw nodup_erase_eq_filter b d; simp only [mem_filter, and_comm]
theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a :=
λ H, ((mem_erase_iff_of_nodup h).1 H).1 rfl
theorem nodup_join {L : list (list α)} :
nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L :=
by simp only [nodup, pairwise_join, disjoint_left.symm, forall_mem_ne]
theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔
(∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ :=
by simp only [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm, mem_map,
exists_imp_distrib, and_imp];
rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔
(∀ (x : α), x ∈ l₁ → nodup (f x)),
from forall_swap.trans $ forall_congr $ λ_, forall_eq']
theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) :
nodup (product l₁ l₂) :=
nodup_bind.2
⟨λ a ma, nodup_map (left_inverse.injective (λ b, (rfl : (a,b).2 = b))) d₂,
d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin
rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩,
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩,
exact n rfl
end⟩
theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)}
(d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (l₁.sigma l₂) :=
nodup_bind.2
⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a),
d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin
rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩,
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩,
exact n rfl
end⟩
theorem nodup_filter_map {f : α → option β} {l : list α}
(H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') :
nodup l → nodup (filter_map f l) :=
pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm'
theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) :=
by rw concat_eq_append; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h)
theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) :=
if h' : a ∈ l then by rw [insert_of_mem h']; exact h
else by rw [insert_of_not_mem h', nodup_cons]; split; assumption
theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) :
nodup (l₁ ∪ l₂) :=
begin
induction l₁ with a l₁ ih generalizing l₂,
{ exact h },
apply nodup_insert,
exact ih h
end
theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) :=
nodup_filter _
@[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l :=
⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h),
λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩
@[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l :=
by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective,
nodup_sublists, nodup_reverse]
lemma nodup_sublists_len {α : Type*} (n) {l : list α}
(nd : nodup l) : (sublists_len n l).nodup :=
nodup_of_sublist (sublists_len_sublist_sublists' _ _) (nodup_sublists'.2 nd)
lemma diff_eq_filter_of_nodup [decidable_eq α] :
∀ {l₁ l₂ : list α} (hl₁ : l₁.nodup), l₁.diff l₂ = l₁.filter (∉ l₂)
| l₁ [] hl₁ := by simp
| l₁ (a::l₂) hl₁ :=
begin
rw [diff_cons, diff_eq_filter_of_nodup (nodup_erase_of_nodup _ hl₁),
nodup_erase_eq_filter _ hl₁, filter_filter],
simp only [mem_cons_iff, not_or_distrib, and.comm],
congr
end
lemma mem_diff_iff_of_nodup [decidable_eq α] {l₁ l₂ : list α} (hl₁ : l₁.nodup) {a : α} :
a ∈ l₁.diff l₂ ↔ a ∈ l₁ ∧ a ∉ l₂ :=
by rw [diff_eq_filter_of_nodup hl₁, mem_filter]
lemma nodup_update_nth : ∀ {l : list α} {n : ℕ} {a : α} (hl : l.nodup) (ha : a ∉ l),
(l.update_nth n a).nodup
| [] n a hl ha := nodup_nil
| (b::l) 0 a hl ha := nodup_cons.2 ⟨mt (mem_cons_of_mem _) ha, (nodup_cons.1 hl).2⟩
| (b::l) (n+1) a hl ha := nodup_cons.2
⟨λ h, (mem_or_eq_of_mem_update_nth h).elim
(nodup_cons.1 hl).1
(λ hba, ha (hba ▸ mem_cons_self _ _)),
nodup_update_nth (nodup_cons.1 hl).2 (mt (mem_cons_of_mem _) ha)⟩
end list
theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup
| none := list.nodup_nil
| (some x) := list.nodup_singleton x
|
4ea44edec8dd7a44dd80c31b08ed05b2bdd559cd | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/order/ring/canonical.lean | 93b3f65cb756db276711df3ab388f01bd1d217cc | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 4,766 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro
-/
import algebra.order.ring.defs
import algebra.order.sub.canonical
import group_theory.group_action.defs
/-!
# Canoncially ordered rings and semirings.
* `canonically_ordered_comm_semiring`
- `canonically_ordered_add_monoid` & multiplication & `*` respects `≤` & no zero divisors
- `comm_semiring` & `a ≤ b ↔ ∃ c, b = a + c` & no zero divisors
## TODO
We're still missing some typeclasses, like
* `canonically_ordered_semiring`
They have yet to come up in practice.
-/
open function
set_option old_structure_cmd true
universe u
variables {α : Type u} {β : Type*}
/-- A canonically ordered commutative semiring is an ordered, commutative semiring in which `a ≤ b`
iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but
not the integers or other ordered groups. -/
@[protect_proj, ancestor canonically_ordered_add_monoid comm_semiring]
class canonically_ordered_comm_semiring (α : Type*) extends
canonically_ordered_add_monoid α, comm_semiring α :=
(eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0)
section strict_ordered_semiring
variables [strict_ordered_semiring α] {a b c d : α}
section has_exists_add_of_le
variables [has_exists_add_of_le α]
/-- Binary **rearrangement inequality**. -/
lemma mul_add_mul_le_mul_add_mul (hab : a ≤ b) (hcd : c ≤ d) : a * d + b * c ≤ a * c + b * d :=
begin
obtain ⟨b, rfl⟩ := exists_add_of_le hab,
obtain ⟨d, rfl⟩ := exists_add_of_le hcd,
rw [mul_add, add_right_comm, mul_add, ←add_assoc],
exact add_le_add_left (mul_le_mul_of_nonneg_right hab $ (le_add_iff_nonneg_right _).1 hcd) _,
end
/-- Binary **rearrangement inequality**. -/
lemma mul_add_mul_le_mul_add_mul' (hba : b ≤ a) (hdc : d ≤ c) : a • d + b • c ≤ a • c + b • d :=
by { rw [add_comm (a • d), add_comm (a • c)], exact mul_add_mul_le_mul_add_mul hba hdc }
/-- Binary strict **rearrangement inequality**. -/
lemma mul_add_mul_lt_mul_add_mul (hab : a < b) (hcd : c < d) : a * d + b * c < a * c + b * d :=
begin
obtain ⟨b, rfl⟩ := exists_add_of_le hab.le,
obtain ⟨d, rfl⟩ := exists_add_of_le hcd.le,
rw [mul_add, add_right_comm, mul_add, ←add_assoc],
exact add_lt_add_left (mul_lt_mul_of_pos_right hab $ (lt_add_iff_pos_right _).1 hcd) _,
end
/-- Binary **rearrangement inequality**. -/
lemma mul_add_mul_lt_mul_add_mul' (hba : b < a) (hdc : d < c) : a • d + b • c < a • c + b • d :=
by { rw [add_comm (a • d), add_comm (a • c)], exact mul_add_mul_lt_mul_add_mul hba hdc }
end has_exists_add_of_le
end strict_ordered_semiring
namespace canonically_ordered_comm_semiring
variables [canonically_ordered_comm_semiring α] {a b : α}
@[priority 100] -- see Note [lower instance priority]
instance to_no_zero_divisors : no_zero_divisors α :=
⟨canonically_ordered_comm_semiring.eq_zero_or_eq_zero_of_mul_eq_zero⟩
@[priority 100] -- see Note [lower instance priority]
instance to_covariant_mul_le : covariant_class α α (*) (≤) :=
begin
refine ⟨λ a b c h, _⟩,
rcases exists_add_of_le h with ⟨c, rfl⟩,
rw mul_add,
apply self_le_add_right
end
@[priority 100] -- see Note [lower instance priority]
instance to_ordered_comm_semiring : ordered_comm_semiring α :=
{ zero_le_one := zero_le _,
mul_le_mul_of_nonneg_left := λ a b c h _, mul_le_mul_left' h _,
mul_le_mul_of_nonneg_right := λ a b c h _, mul_le_mul_right' h _,
..‹canonically_ordered_comm_semiring α› }
@[simp] lemma mul_pos : 0 < a * b ↔ (0 < a) ∧ (0 < b) :=
by simp only [pos_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib]
end canonically_ordered_comm_semiring
section sub
variables [canonically_ordered_comm_semiring α] {a b c : α}
variables [has_sub α] [has_ordered_sub α]
variables [is_total α (≤)]
namespace add_le_cancellable
protected lemma mul_tsub (h : add_le_cancellable (a * c)) :
a * (b - c) = a * b - a * c :=
begin
cases total_of (≤) b c with hbc hcb,
{ rw [tsub_eq_zero_iff_le.2 hbc, mul_zero, tsub_eq_zero_iff_le.2 (mul_le_mul_left' hbc a)] },
{ apply h.eq_tsub_of_add_eq, rw [← mul_add, tsub_add_cancel_of_le hcb] }
end
protected lemma tsub_mul (h : add_le_cancellable (b * c)) : (a - b) * c = a * c - b * c :=
by { simp only [mul_comm _ c] at *, exact h.mul_tsub }
end add_le_cancellable
variables [contravariant_class α α (+) (≤)]
lemma mul_tsub (a b c : α) : a * (b - c) = a * b - a * c :=
contravariant.add_le_cancellable.mul_tsub
lemma tsub_mul (a b c : α) : (a - b) * c = a * c - b * c :=
contravariant.add_le_cancellable.tsub_mul
end sub
|
760625b6cadd4fa6ffe82eda103b6a4e1cfc67c6 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/number_theory/legendre_symbol/quadratic_reciprocity.lean | af92628a7b20ce008df0941853d355d91d02e086 | [
"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 | 14,402 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Michael Stoll
-/
import number_theory.legendre_symbol.quadratic_char
/-!
# Legendre symbol and quadratic reciprocity.
This file contains results about quadratic residues modulo a prime number.
We define the Legendre symbol $\Bigl(\frac{a}{p}\Bigr)$ as `legendre_sym p a`.
Note the order of arguments! The advantage of this form is that then `legendre_sym p`
is a multiplicative map.
The Legendre symbol is used to define the Jacobi symbol, `jacobi_sym a b`, for integers `a`
and (odd) natural numbers `b`, which extends the Legendre symbol.
## Main results
We prove the law of quadratic reciprocity, see `legendre_sym.quadratic_reciprocity` and
`legendre_sym.quadratic_reciprocity'`, as well as the
interpretations in terms of existence of square roots depending on the congruence mod 4,
`zmod.exists_sq_eq_prime_iff_of_mod_four_eq_one`, and
`zmod.exists_sq_eq_prime_iff_of_mod_four_eq_three`.
We also prove the supplementary laws that give conditions for when `-1` or `2`
(or `-2`) is a square modulo a prime `p`:
`legendre_sym.at_neg_one` and `zmod.exists_sq_eq_neg_one_iff` for `-1`,
`legendre_sym.at_two` and `zmod.exists_sq_eq_two_iff` for `2`,
`legendre_sym.at_neg_two` and `zmod.exists_sq_eq_neg_two_iff` for `-2`.
## Implementation notes
The proofs use results for quadratic characters on arbitrary finite fields
from `number_theory.legendre_symbol.quadratic_char`, which in turn are based on
properties of quadratic Gauss sums as provided by `number_theory.legendre_symbol.gauss_sum`.
## Tags
quadratic residue, quadratic nonresidue, Legendre symbol, quadratic reciprocity
-/
open nat
section euler
namespace zmod
variables (p : ℕ) [fact p.prime]
/-- Euler's Criterion: A unit `x` of `zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/
lemma euler_criterion_units (x : (zmod p)ˣ) : (∃ y : (zmod p)ˣ, y ^ 2 = x) ↔ x ^ (p / 2) = 1 :=
begin
by_cases hc : p = 2,
{ substI hc,
simp only [eq_iff_true_of_subsingleton, exists_const], },
{ have h₀ := finite_field.unit_is_square_iff (by rwa ring_char_zmod_n) x,
have hs : (∃ y : (zmod p)ˣ, y ^ 2 = x) ↔ is_square(x) :=
by { rw is_square_iff_exists_sq x,
simp_rw eq_comm, },
rw hs,
rwa card p at h₀, },
end
/-- Euler's Criterion: a nonzero `a : zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/
lemma euler_criterion {a : zmod p} (ha : a ≠ 0) : is_square (a : zmod p) ↔ a ^ (p / 2) = 1 :=
begin
apply (iff_congr _ (by simp [units.ext_iff])).mp (euler_criterion_units p (units.mk0 a ha)),
simp only [units.ext_iff, sq, units.coe_mk0, units.coe_mul],
split, { rintro ⟨y, hy⟩, exact ⟨y, hy.symm⟩ },
{ rintro ⟨y, rfl⟩,
have hy : y ≠ 0, { rintro rfl, simpa [zero_pow] using ha, },
refine ⟨units.mk0 y hy, _⟩, simp, }
end
/-- If `a : zmod p` is nonzero, then `a^(p/2)` is either `1` or `-1`. -/
lemma pow_div_two_eq_neg_one_or_one {a : zmod p} (ha : a ≠ 0) :
a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 :=
begin
cases prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd,
{ substI p, revert a ha, dec_trivial },
rw [← mul_self_eq_one_iff, ← pow_add, ← two_mul, two_mul_odd_div_two hp_odd],
exact pow_card_sub_one_eq_one ha
end
end zmod
end euler
section legendre
/-!
### Definition of the Legendre symbol and basic properties
-/
open zmod
variables (p : ℕ) [fact p.prime]
/-- The Legendre symbol of `a : ℤ` and a prime `p`, `legendre_sym p a`,
is an integer defined as
* `0` if `a` is `0` modulo `p`;
* `1` if `a` is a nonzero square modulo `p`
* `-1` otherwise.
Note the order of the arguments! The advantage of the order chosen here is
that `legendre_sym p` is a multiplicative function `ℤ → ℤ`.
-/
def legendre_sym (a : ℤ) : ℤ := quadratic_char (zmod p) a
namespace legendre_sym
/-- We have the congruence `legendre_sym p a ≡ a ^ (p / 2) mod p`. -/
lemma eq_pow (a : ℤ) : (legendre_sym p a : zmod p) = a ^ (p / 2) :=
begin
cases eq_or_ne (ring_char (zmod p)) 2 with hc hc,
{ by_cases ha : (a : zmod p) = 0,
{ rw [legendre_sym, ha, quadratic_char_zero,
zero_pow (nat.div_pos (fact.out p.prime).two_le (succ_pos 1))],
norm_cast, },
{ have := (ring_char_zmod_n p).symm.trans hc, -- p = 2
substI p,
rw [legendre_sym, quadratic_char_eq_one_of_char_two hc ha],
revert ha,
generalize : (a : zmod 2) = b, revert b, dec_trivial } },
{ convert quadratic_char_eq_pow_of_char_ne_two' hc (a : zmod p),
exact (card p).symm },
end
/-- If `p ∤ a`, then `legendre_sym p a` is `1` or `-1`. -/
lemma eq_one_or_neg_one {a : ℤ} (ha : (a : zmod p) ≠ 0) :
legendre_sym p a = 1 ∨ legendre_sym p a = -1 :=
quadratic_char_dichotomy ha
lemma eq_neg_one_iff_not_one {a : ℤ} (ha : (a : zmod p) ≠ 0) :
legendre_sym p a = -1 ↔ ¬ legendre_sym p a = 1 :=
quadratic_char_eq_neg_one_iff_not_one ha
/-- The Legendre symbol of `p` and `a` is zero iff `p ∣ a`. -/
lemma eq_zero_iff (a : ℤ) : legendre_sym p a = 0 ↔ (a : zmod p) = 0 :=
quadratic_char_eq_zero_iff
@[simp] lemma at_zero : legendre_sym p 0 = 0 :=
by rw [legendre_sym, int.cast_zero, mul_char.map_zero]
@[simp] lemma at_one : legendre_sym p 1 = 1 :=
by rw [legendre_sym, int.cast_one, mul_char.map_one]
/-- The Legendre symbol is multiplicative in `a` for `p` fixed. -/
protected
lemma mul (a b : ℤ) : legendre_sym p (a * b) = legendre_sym p a * legendre_sym p b :=
by simp only [legendre_sym, int.cast_mul, map_mul]
/-- The Legendre symbol is a homomorphism of monoids with zero. -/
@[simps] def hom : ℤ →*₀ ℤ :=
{ to_fun := legendre_sym p,
map_zero' := at_zero p,
map_one' := at_one p,
map_mul' := legendre_sym.mul p }
/-- The square of the symbol is 1 if `p ∤ a`. -/
theorem sq_one {a : ℤ} (ha : (a : zmod p) ≠ 0) : (legendre_sym p a) ^ 2 = 1 :=
quadratic_char_sq_one ha
/-- The Legendre symbol of `a^2` at `p` is 1 if `p ∤ a`. -/
theorem sq_one' {a : ℤ} (ha : (a : zmod p) ≠ 0) : legendre_sym p (a ^ 2) = 1 :=
by exact_mod_cast quadratic_char_sq_one' ha
/-- The Legendre symbol depends only on `a` mod `p`. -/
protected
theorem mod (a : ℤ) : legendre_sym p a = legendre_sym p (a % p) :=
by simp only [legendre_sym, int_cast_mod]
/-- When `p ∤ a`, then `legendre_sym p a = 1` iff `a` is a square mod `p`. -/
lemma eq_one_iff {a : ℤ} (ha0 : (a : zmod p) ≠ 0) :
legendre_sym p a = 1 ↔ is_square (a : zmod p) :=
quadratic_char_one_iff_is_square ha0
lemma eq_one_iff' {a : ℕ} (ha0 : (a : zmod p) ≠ 0) :
legendre_sym p a = 1 ↔ is_square (a : zmod p) :=
by {rw eq_one_iff, norm_cast, exact_mod_cast ha0}
/-- `legendre_sym p a = -1` iff `a` is a nonsquare mod `p`. -/
lemma eq_neg_one_iff {a : ℤ} : legendre_sym p a = -1 ↔ ¬ is_square (a : zmod p) :=
quadratic_char_neg_one_iff_not_is_square
lemma eq_neg_one_iff' {a : ℕ} : legendre_sym p a = -1 ↔ ¬ is_square (a : zmod p) :=
by {rw eq_neg_one_iff, norm_cast}
/-- The number of square roots of `a` modulo `p` is determined by the Legendre symbol. -/
lemma card_sqrts (hp : p ≠ 2) (a : ℤ) :
↑{x : zmod p | x^2 = a}.to_finset.card = legendre_sym p a + 1 :=
quadratic_char_card_sqrts ((ring_char_zmod_n p).substr hp) a
end legendre_sym
end legendre
section values
/-!
### The value of the Legendre symbol at `-1`
See `jacobi_sym.at_neg_one` for the corresponding statement for the Jacobi symbol.
-/
variables {p : ℕ} [fact p.prime]
open zmod
/-- `legendre_sym p (-1)` is given by `χ₄ p`. -/
lemma legendre_sym.at_neg_one (hp : p ≠ 2) : legendre_sym p (-1) = χ₄ p :=
by simp only [legendre_sym, card p, quadratic_char_neg_one ((ring_char_zmod_n p).substr hp),
int.cast_neg, int.cast_one]
namespace zmod
/-- `-1` is a square in `zmod p` iff `p` is not congruent to `3` mod `4`. -/
lemma exists_sq_eq_neg_one_iff : is_square (-1 : zmod p) ↔ p % 4 ≠ 3 :=
by rw [finite_field.is_square_neg_one_iff, card p]
lemma mod_four_ne_three_of_sq_eq_neg_one {y : zmod p} (hy : y ^ 2 = -1) : p % 4 ≠ 3 :=
exists_sq_eq_neg_one_iff.1 ⟨y, hy ▸ pow_two y⟩
/-- If two nonzero squares are negatives of each other in `zmod p`, then `p % 4 ≠ 3`. -/
lemma mod_four_ne_three_of_sq_eq_neg_sq' {x y : zmod p} (hy : y ≠ 0) (hxy : x ^ 2 = - y ^ 2) :
p % 4 ≠ 3 :=
@mod_four_ne_three_of_sq_eq_neg_one p _ (x / y) begin
apply_fun (λ z, z / y ^ 2) at hxy,
rwa [neg_div, ←div_pow, ←div_pow, div_self hy, one_pow] at hxy
end
lemma mod_four_ne_three_of_sq_eq_neg_sq {x y : zmod p} (hx : x ≠ 0) (hxy : x ^ 2 = - y ^ 2) :
p % 4 ≠ 3 :=
mod_four_ne_three_of_sq_eq_neg_sq' hx (neg_eq_iff_eq_neg.mpr hxy).symm
end zmod
/-!
### The value of the Legendre symbol at `2` and `-2`
See `jacobi_sym.at_two` and `jacobi_sym.at_neg_two` for the corresponding statements
for the Jacobi symbol.
-/
namespace legendre_sym
variables (hp : p ≠ 2)
include hp
/-- `legendre_sym p 2` is given by `χ₈ p`. -/
lemma at_two : legendre_sym p 2 = χ₈ p :=
by simp only [legendre_sym, card p, quadratic_char_two ((ring_char_zmod_n p).substr hp),
int.cast_bit0, int.cast_one]
/-- `legendre_sym p (-2)` is given by `χ₈' p`. -/
lemma at_neg_two : legendre_sym p (-2) = χ₈' p :=
by simp only [legendre_sym, card p, quadratic_char_neg_two ((ring_char_zmod_n p).substr hp),
int.cast_bit0, int.cast_one, int.cast_neg]
end legendre_sym
namespace zmod
variables (hp : p ≠ 2)
include hp
/-- `2` is a square modulo an odd prime `p` iff `p` is congruent to `1` or `7` mod `8`. -/
lemma exists_sq_eq_two_iff : is_square (2 : zmod p) ↔ p % 8 = 1 ∨ p % 8 = 7 :=
begin
rw [finite_field.is_square_two_iff, card p],
have h₁ := prime.mod_two_eq_one_iff_ne_two.mpr hp,
rw [← mod_mod_of_dvd p (by norm_num : 2 ∣ 8)] at h₁,
have h₂ := mod_lt p (by norm_num : 0 < 8),
revert h₂ h₁,
generalize hm : p % 8 = m, unfreezingI {clear_dependent p},
dec_trivial!,
end
/-- `-2` is a square modulo an odd prime `p` iff `p` is congruent to `1` or `3` mod `8`. -/
lemma exists_sq_eq_neg_two_iff : is_square (-2 : zmod p) ↔ p % 8 = 1 ∨ p % 8 = 3 :=
begin
rw [finite_field.is_square_neg_two_iff, card p],
have h₁ := prime.mod_two_eq_one_iff_ne_two.mpr hp,
rw [← mod_mod_of_dvd p (by norm_num : 2 ∣ 8)] at h₁,
have h₂ := mod_lt p (by norm_num : 0 < 8),
revert h₂ h₁,
generalize hm : p % 8 = m, unfreezingI {clear_dependent p},
dec_trivial!,
end
end zmod
end values
section reciprocity
/-!
### The Law of Quadratic Reciprocity
See `jacobi_sym.quadratic_reciprocity` and variants for a version of Quadratic Reciprocity
for the Jacobi symbol.
-/
variables {p q : ℕ} [fact p.prime] [fact q.prime]
namespace legendre_sym
open zmod
/-- The Law of Quadratic Reciprocity: if `p` and `q` are distinct odd primes, then
`(q / p) * (p / q) = (-1)^((p-1)(q-1)/4)`. -/
theorem quadratic_reciprocity (hp : p ≠ 2) (hq : q ≠ 2) (hpq : p ≠ q) :
legendre_sym q p * legendre_sym p q = (-1) ^ ((p / 2) * (q / 2)) :=
begin
have hp₁ := (prime.eq_two_or_odd $ fact.out p.prime).resolve_left hp,
have hq₁ := (prime.eq_two_or_odd $ fact.out q.prime).resolve_left hq,
have hq₂ := (ring_char_zmod_n q).substr hq,
have h := quadratic_char_odd_prime ((ring_char_zmod_n p).substr hp) hq
((ring_char_zmod_n p).substr hpq),
rw [card p] at h,
have nc : ∀ (n r : ℕ), ((n : ℤ) : zmod r) = n := λ n r, by norm_cast,
have nc' : (((-1) ^ (p / 2) : ℤ) : zmod q) = (-1) ^ (p / 2) := by norm_cast,
rw [legendre_sym, legendre_sym, nc, nc, h, map_mul, mul_rotate', mul_comm (p / 2), ← pow_two,
quadratic_char_sq_one (prime_ne_zero q p hpq.symm), mul_one, pow_mul, χ₄_eq_neg_one_pow hp₁,
nc', map_pow, quadratic_char_neg_one hq₂, card q, χ₄_eq_neg_one_pow hq₁],
end
/-- The Law of Quadratic Reciprocity: if `p` and `q` are odd primes, then
`(q / p) = (-1)^((p-1)(q-1)/4) * (p / q)`. -/
theorem quadratic_reciprocity' (hp : p ≠ 2) (hq : q ≠ 2) :
legendre_sym q p = (-1) ^ ((p / 2) * (q / 2)) * legendre_sym p q :=
begin
cases eq_or_ne p q with h h,
{ substI p,
rw [(eq_zero_iff q q).mpr (by exact_mod_cast nat_cast_self q), mul_zero] },
{ have qr := congr_arg (* legendre_sym p q) (quadratic_reciprocity hp hq h),
have : ((q : ℤ) : zmod p) ≠ 0 := by exact_mod_cast prime_ne_zero p q h,
simpa only [mul_assoc, ← pow_two, sq_one p this, mul_one] using qr }
end
/-- The Law of Quadratic Reciprocity: if `p` and `q` are odd primes and `p % 4 = 1`,
then `(q / p) = (p / q)`. -/
theorem quadratic_reciprocity_one_mod_four (hp : p % 4 = 1) (hq : q ≠ 2) :
legendre_sym q p = legendre_sym p q :=
by rw [quadratic_reciprocity' (prime.mod_two_eq_one_iff_ne_two.mp
(odd_of_mod_four_eq_one hp)) hq,
pow_mul, neg_one_pow_div_two_of_one_mod_four hp, one_pow, one_mul]
/-- The Law of Quadratic Reciprocity: if `p` and `q` are primes that are both congruent
to `3` mod `4`, then `(q / p) = -(p / q)`. -/
theorem quadratic_reciprocity_three_mod_four (hp : p % 4 = 3) (hq : q % 4 = 3):
legendre_sym q p = -legendre_sym p q :=
let nop := @neg_one_pow_div_two_of_three_mod_four in begin
rw [quadratic_reciprocity', pow_mul, nop hp, nop hq, neg_one_mul];
rwa [← prime.mod_two_eq_one_iff_ne_two, odd_of_mod_four_eq_three],
end
end legendre_sym
namespace zmod
open legendre_sym
/-- If `p` and `q` are odd primes and `p % 4 = 1`, then `q` is a square mod `p` iff
`p` is a square mod `q`. -/
lemma exists_sq_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) (hq1 : q ≠ 2) :
is_square (q : zmod p) ↔ is_square (p : zmod q) :=
begin
cases eq_or_ne p q with h h,
{ substI p },
{ rw [← eq_one_iff' p (prime_ne_zero p q h), ← eq_one_iff' q (prime_ne_zero q p h.symm),
quadratic_reciprocity_one_mod_four hp1 hq1], }
end
/-- If `p` and `q` are distinct primes that are both congruent to `3` mod `4`, then `q` is
a square mod `p` iff `p` is a nonsquare mod `q`. -/
lemma exists_sq_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3)
(hpq : p ≠ q) :
is_square (q : zmod p) ↔ ¬ is_square (p : zmod q) :=
by rw [← eq_one_iff' p (prime_ne_zero p q hpq), ← eq_neg_one_iff' q,
quadratic_reciprocity_three_mod_four hp3 hq3, neg_inj]
end zmod
end reciprocity
|
c4b8a68e4041331ac8dc7a36fc13b569ab32ede9 | f57749ca63d6416f807b770f67559503fdb21001 | /hott/types/eq.hlean | c3cb79d910c6c22402c4fe3bedf81516fc282571 | [
"Apache-2.0"
] | permissive | aliassaf/lean | bd54e85bed07b1ff6f01396551867b2677cbc6ac | f9b069b6a50756588b309b3d716c447004203152 | refs/heads/master | 1,610,982,152,948 | 1,438,916,029,000 | 1,438,916,029,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,118 | hlean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Partially ported from Coq HoTT
Theorems about path types (identity types)
-/
open eq sigma sigma.ops equiv is_equiv equiv.ops
-- TODO: Rename transport_eq_... and pathover_eq_... to eq_transport_... and eq_pathover_...
namespace eq
/- Path spaces -/
variables {A B : Type} {a a₁ a₂ a₃ a₄ a' : A} {b b1 b2 : B} {f g : A → B} {h : B → A}
{p p' p'' : a₁ = a₂}
/- The path spaces of a path space are not, of course, determined; they are just the
higher-dimensional structure of the original space. -/
/- some lemmas about whiskering or other higher paths -/
theorem whisker_left_con_right (p : a₁ = a₂) {q q' q'' : a₂ = a₃} (r : q = q') (s : q' = q'')
: whisker_left p (r ⬝ s) = whisker_left p r ⬝ whisker_left p s :=
begin
induction p, induction r, induction s, reflexivity
end
theorem whisker_right_con_right (q : a₂ = a₃) (r : p = p') (s : p' = p'')
: whisker_right (r ⬝ s) q = whisker_right r q ⬝ whisker_right s q :=
begin
induction q, induction r, induction s, reflexivity
end
theorem whisker_left_con_left (p : a₁ = a₂) (p' : a₂ = a₃) {q q' : a₃ = a₄} (r : q = q')
: whisker_left (p ⬝ p') r = !con.assoc ⬝ whisker_left p (whisker_left p' r) ⬝ !con.assoc' :=
begin
induction p', induction p, induction r, induction q, reflexivity
end
theorem whisker_right_con_left {p p' : a₁ = a₂} (q : a₂ = a₃) (q' : a₃ = a₄) (r : p = p')
: whisker_right r (q ⬝ q') = !con.assoc' ⬝ whisker_right (whisker_right r q) q' ⬝ !con.assoc :=
begin
induction q', induction q, induction r, induction p, reflexivity
end
theorem whisker_left_inv_left (p : a₂ = a₁) {q q' : a₂ = a₃} (r : q = q')
: !con_inv_cancel_left⁻¹ ⬝ whisker_left p (whisker_left p⁻¹ r) ⬝ !con_inv_cancel_left = r :=
begin
induction p, induction r, induction q, reflexivity
end
theorem whisker_left_inv (p : a₁ = a₂) {q q' : a₂ = a₃} (r : q = q')
: whisker_left p r⁻¹ = (whisker_left p r)⁻¹ :=
by induction r; reflexivity
theorem whisker_right_inv {p p' : a₁ = a₂} (q : a₂ = a₃) (r : p = p')
: whisker_right r⁻¹ q = (whisker_right r q)⁻¹ :=
by induction r; reflexivity
theorem ap_eq_ap10 {f g : A → B} (p : f = g) (a : A) : ap (λh, h a) p = ap10 p a :=
by induction p;reflexivity
theorem inverse2_right_inv (r : p = p') : r ◾ inverse2 r ⬝ con.right_inv p' = con.right_inv p :=
by induction r;induction p;reflexivity
theorem inverse2_left_inv (r : p = p') : inverse2 r ◾ r ⬝ con.left_inv p' = con.left_inv p :=
by induction r;induction p;reflexivity
theorem ap_con_right_inv (f : A → B) (p : a₁ = a₂)
: ap_con f p p⁻¹ ⬝ whisker_left _ (ap_inv f p) ⬝ con.right_inv (ap f p)
= ap (ap f) (con.right_inv p) :=
by induction p;reflexivity
theorem ap_con_left_inv (f : A → B) (p : a₁ = a₂)
: ap_con f p⁻¹ p ⬝ whisker_right (ap_inv f p) _ ⬝ con.left_inv (ap f p)
= ap (ap f) (con.left_inv p) :=
by induction p;reflexivity
theorem idp_con_whisker_left {q q' : a₂ = a₃} (r : q = q') :
!idp_con⁻¹ ⬝ whisker_left idp r = r ⬝ !idp_con⁻¹ :=
by induction r;induction q;reflexivity
theorem whisker_left_idp_con {q q' : a₂ = a₃} (r : q = q') :
whisker_left idp r ⬝ !idp_con = !idp_con ⬝ r :=
by induction r;induction q;reflexivity
theorem idp_con_idp {p : a = a} (q : p = idp) : idp_con p ⬝ q = ap (λp, idp ⬝ p) q :=
by cases q;reflexivity
definition ap_weakly_constant [unfold 8] {A B : Type} {f : A → B} {b : B} (p : Πx, f x = b)
{x y : A} (q : x = y) : ap f q = p x ⬝ (p y)⁻¹ :=
by induction q;exact !con.right_inv⁻¹
definition inv2_inv {p q : a = a'} (r : p = q) : inverse2 r⁻¹ = (inverse2 r)⁻¹ :=
by induction r;reflexivity
definition inv2_con {p p' p'' : a = a'} (r : p = p') (r' : p' = p'')
: inverse2 (r ⬝ r') = inverse2 r ⬝ inverse2 r' :=
by induction r';induction r;reflexivity
definition con2_inv {p₁ q₁ : a₁ = a₂} {p₂ q₂ : a₂ = a₃} (r₁ : p₁ = q₁) (r₂ : p₂ = q₂)
: (r₁ ◾ r₂)⁻¹ = r₁⁻¹ ◾ r₂⁻¹ :=
by induction r₁;induction r₂;reflexivity
theorem eq_con_inv_of_con_eq_whisker_left {A : Type} {a a₂ a₃ : A}
{p : a = a₂} {q q' : a₂ = a₃} {r : a = a₃} (s' : q = q') (s : p ⬝ q' = r) :
eq_con_inv_of_con_eq (whisker_left p s' ⬝ s)
= eq_con_inv_of_con_eq s ⬝ whisker_left r (inverse2 s')⁻¹ :=
by induction s';induction q;induction s;reflexivity
theorem right_inv_eq_idp {A : Type} {a : A} {p : a = a} (r : p = idpath a) :
con.right_inv p = r ◾ inverse2 r :=
by cases r;reflexivity
/- Transporting in path spaces.
There are potentially a lot of these lemmas, so we adopt a uniform naming scheme:
- `l` means the left endpoint varies
- `r` means the right endpoint varies
- `F` means application of a function to that (varying) endpoint.
-/
definition transport_eq_l (p : a₁ = a₂) (q : a₁ = a₃)
: transport (λx, x = a₃) p q = p⁻¹ ⬝ q :=
by induction p; induction q; reflexivity
definition transport_eq_r (p : a₂ = a₃) (q : a₁ = a₂)
: transport (λx, a₁ = x) p q = q ⬝ p :=
by induction p; induction q; reflexivity
definition transport_eq_lr (p : a₁ = a₂) (q : a₁ = a₁)
: transport (λx, x = x) p q = p⁻¹ ⬝ q ⬝ p :=
by induction p; rewrite [▸*,idp_con]
definition transport_eq_Fl (p : a₁ = a₂) (q : f a₁ = b)
: transport (λx, f x = b) p q = (ap f p)⁻¹ ⬝ q :=
by induction p; induction q; reflexivity
definition transport_eq_Fr (p : a₁ = a₂) (q : b = f a₁)
: transport (λx, b = f x) p q = q ⬝ (ap f p) :=
by induction p; reflexivity
definition transport_eq_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁)
: transport (λx, f x = g x) p q = (ap f p)⁻¹ ⬝ q ⬝ (ap g p) :=
by induction p; rewrite [▸*,idp_con]
definition transport_eq_FlFr_D {B : A → Type} {f g : Πa, B a}
(p : a₁ = a₂) (q : f a₁ = g a₁)
: transport (λx, f x = g x) p q = (apd f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apd g p) :=
by induction p; rewrite [▸*,idp_con,ap_id]
definition transport_eq_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁)
: transport (λx, h (f x) = x) p q = (ap h (ap f p))⁻¹ ⬝ q ⬝ p :=
by induction p; rewrite [▸*,idp_con]
definition transport_eq_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁))
: transport (λx, x = h (f x)) p q = p⁻¹ ⬝ q ⬝ (ap h (ap f p)) :=
by induction p; rewrite [▸*,idp_con]
/- Pathovers -/
-- In the comment we give the fibration of the pathover
-- we should probably try to do everything just with pathover_eq (defined in cubical.square),
-- the following definitions may be removed in future.
definition pathover_eq_l (p : a₁ = a₂) (q : a₁ = a₃) : q =[p] p⁻¹ ⬝ q := /-(λx, x = a₃)-/
by induction p; induction q; exact idpo
definition pathover_eq_r (p : a₂ = a₃) (q : a₁ = a₂) : q =[p] q ⬝ p := /-(λx, a₁ = x)-/
by induction p; induction q; exact idpo
definition pathover_eq_lr (p : a₁ = a₂) (q : a₁ = a₁) : q =[p] p⁻¹ ⬝ q ⬝ p := /-(λx, x = x)-/
by induction p; rewrite [▸*,idp_con]; exact idpo
definition pathover_eq_Fl (p : a₁ = a₂) (q : f a₁ = b) : q =[p] (ap f p)⁻¹ ⬝ q := /-(λx, f x = b)-/
by induction p; induction q; exact idpo
definition pathover_eq_Fr (p : a₁ = a₂) (q : b = f a₁) : q =[p] q ⬝ (ap f p) := /-(λx, b = f x)-/
by induction p; exact idpo
definition pathover_eq_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) : q =[p] (ap f p)⁻¹ ⬝ q ⬝ (ap g p) :=
/-(λx, f x = g x)-/
by induction p; rewrite [▸*,idp_con]; exact idpo
definition pathover_eq_FlFr_D {B : A → Type} {f g : Πa, B a} (p : a₁ = a₂) (q : f a₁ = g a₁)
: q =[p] (apd f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apd g p) := /-(λx, f x = g x)-/
by induction p; rewrite [▸*,idp_con,ap_id];exact idpo
definition pathover_eq_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) : q =[p] (ap h (ap f p))⁻¹ ⬝ q ⬝ p :=
/-(λx, h (f x) = x)-/
by induction p; rewrite [▸*,idp_con];exact idpo
definition pathover_eq_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) : q =[p] p⁻¹ ⬝ q ⬝ (ap h (ap f p)) :=
/-(λx, x = h (f x))-/
by induction p; rewrite [▸*,idp_con];exact idpo
definition pathover_eq_r_idp (p : a₁ = a₂) : idp =[p] p := /-(λx, a₁ = x)-/
by induction p; exact idpo
definition pathover_eq_l_idp (p : a₁ = a₂) : idp =[p] p⁻¹ := /-(λx, x = a₁)-/
by induction p; exact idpo
definition pathover_eq_l_idp' (p : a₁ = a₂) : idp =[p⁻¹] p := /-(λx, x = a₂)-/
by induction p; exact idpo
-- The Functorial action of paths is [ap].
/- Equivalences between path spaces -/
/- [ap_closed] is in init.equiv -/
definition equiv_ap (f : A → B) [H : is_equiv f] (a₁ a₂ : A)
: (a₁ = a₂) ≃ (f a₁ = f a₂) :=
equiv.mk (ap f) _
/- Path operations are equivalences -/
definition is_equiv_eq_inverse (a₁ a₂ : A) : is_equiv (inverse : a₁ = a₂ → a₂ = a₁) :=
is_equiv.mk inverse inverse inv_inv inv_inv (λp, eq.rec_on p idp)
local attribute is_equiv_eq_inverse [instance]
definition eq_equiv_eq_symm (a₁ a₂ : A) : (a₁ = a₂) ≃ (a₂ = a₁) :=
equiv.mk inverse _
definition is_equiv_concat_left [constructor] [instance] (p : a₁ = a₂) (a₃ : A)
: is_equiv (concat p : a₂ = a₃ → a₁ = a₃) :=
is_equiv.mk (concat p) (concat p⁻¹)
(con_inv_cancel_left p)
(inv_con_cancel_left p)
(λq, by induction p;induction q;reflexivity)
local attribute is_equiv_concat_left [instance]
definition equiv_eq_closed_left [constructor] (a₃ : A) (p : a₁ = a₂) : (a₁ = a₃) ≃ (a₂ = a₃) :=
equiv.mk (concat p⁻¹) _
definition is_equiv_concat_right [constructor] [instance] (p : a₂ = a₃) (a₁ : A)
: is_equiv (λq : a₁ = a₂, q ⬝ p) :=
is_equiv.mk (λq, q ⬝ p) (λq, q ⬝ p⁻¹)
(λq, inv_con_cancel_right q p)
(λq, con_inv_cancel_right q p)
(λq, by induction p;induction q;reflexivity)
local attribute is_equiv_concat_right [instance]
definition equiv_eq_closed_right [constructor] (a₁ : A) (p : a₂ = a₃) : (a₁ = a₂) ≃ (a₁ = a₃) :=
equiv.mk (λq, q ⬝ p) _
definition eq_equiv_eq_closed [constructor] (p : a₁ = a₂) (q : a₃ = a₄) : (a₁ = a₃) ≃ (a₂ = a₄) :=
equiv.trans (equiv_eq_closed_left a₃ p) (equiv_eq_closed_right a₂ q)
definition is_equiv_whisker_left (p : a₁ = a₂) (q r : a₂ = a₃)
: is_equiv (whisker_left p : q = r → p ⬝ q = p ⬝ r) :=
begin
fapply adjointify,
{intro s, apply (!cancel_left s)},
{intro s,
apply concat, {apply whisker_left_con_right},
apply concat, rotate_left 1, apply (whisker_left_inv_left p s),
apply concat2,
{apply concat, {apply whisker_left_con_right},
apply concat2,
{induction p, induction q, reflexivity},
{reflexivity}},
{induction p, induction r, reflexivity}},
{intro s, induction s, induction q, induction p, reflexivity}
end
definition eq_equiv_con_eq_con_left (p : a₁ = a₂) (q r : a₂ = a₃) : (q = r) ≃ (p ⬝ q = p ⬝ r) :=
equiv.mk _ !is_equiv_whisker_left
definition is_equiv_whisker_right {p q : a₁ = a₂} (r : a₂ = a₃)
: is_equiv (λs, whisker_right s r : p = q → p ⬝ r = q ⬝ r) :=
begin
fapply adjointify,
{intro s, apply (!cancel_right s)},
{intro s, induction r, cases s, induction q, reflexivity},
{intro s, induction s, induction r, induction p, reflexivity}
end
definition eq_equiv_con_eq_con_right (p q : a₁ = a₂) (r : a₂ = a₃) : (p = q) ≃ (p ⬝ r = q ⬝ r) :=
equiv.mk _ !is_equiv_whisker_right
/-
The following proofs can be simplified a bit by concatenating previous equivalences.
However, these proofs have the advantage that the inverse is definitionally equal to
what we would expect
-/
definition is_equiv_con_eq_of_eq_inv_con (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (con_eq_of_eq_inv_con : p = r⁻¹ ⬝ q → r ⬝ p = q) :=
begin
fapply adjointify,
{ apply eq_inv_con_of_con_eq},
{ intro s, induction r, rewrite [↑[con_eq_of_eq_inv_con,eq_inv_con_of_con_eq],
con.assoc,con.assoc,con.left_inv,▸*,-con.assoc,con.right_inv,▸* at *,idp_con s]},
{ intro s, induction r, rewrite [↑[con_eq_of_eq_inv_con,eq_inv_con_of_con_eq],
con.assoc,con.assoc,con.right_inv,▸*,-con.assoc,con.left_inv,▸* at *,idp_con s] },
end
definition eq_inv_con_equiv_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: (p = r⁻¹ ⬝ q) ≃ (r ⬝ p = q) :=
equiv.mk _ !is_equiv_con_eq_of_eq_inv_con
definition is_equiv_con_eq_of_eq_con_inv (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (con_eq_of_eq_con_inv : r = q ⬝ p⁻¹ → r ⬝ p = q) :=
begin
fapply adjointify,
{ apply eq_con_inv_of_con_eq},
{ intro s, induction p, rewrite [↑[con_eq_of_eq_con_inv,eq_con_inv_of_con_eq]]},
{ intro s, induction p, rewrite [↑[con_eq_of_eq_con_inv,eq_con_inv_of_con_eq]] },
end
definition eq_con_inv_equiv_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: (r = q ⬝ p⁻¹) ≃ (r ⬝ p = q) :=
equiv.mk _ !is_equiv_con_eq_of_eq_con_inv
definition is_equiv_inv_con_eq_of_eq_con (p : a₁ = a₃) (q : a₂ = a₃) (r : a₁ = a₂)
: is_equiv (inv_con_eq_of_eq_con : p = r ⬝ q → r⁻¹ ⬝ p = q) :=
begin
fapply adjointify,
{ apply eq_con_of_inv_con_eq},
{ intro s, induction r, rewrite [↑[inv_con_eq_of_eq_con,eq_con_of_inv_con_eq],
con.assoc,con.assoc,con.left_inv,▸*,-con.assoc,con.right_inv,▸* at *,idp_con s]},
{ intro s, induction r, rewrite [↑[inv_con_eq_of_eq_con,eq_con_of_inv_con_eq],
con.assoc,con.assoc,con.right_inv,▸*,-con.assoc,con.left_inv,▸* at *,idp_con s] },
end
definition eq_con_equiv_inv_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₁ = a₂)
: (p = r ⬝ q) ≃ (r⁻¹ ⬝ p = q) :=
equiv.mk _ !is_equiv_inv_con_eq_of_eq_con
definition is_equiv_con_inv_eq_of_eq_con (p : a₃ = a₁) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (con_inv_eq_of_eq_con : r = q ⬝ p → r ⬝ p⁻¹ = q) :=
begin
fapply adjointify,
{ apply eq_con_of_con_inv_eq},
{ intro s, induction p, rewrite [↑[con_inv_eq_of_eq_con,eq_con_of_con_inv_eq]]},
{ intro s, induction p, rewrite [↑[con_inv_eq_of_eq_con,eq_con_of_con_inv_eq]] },
end
definition eq_con_equiv_con_inv_eq (p : a₃ = a₁) (q : a₂ = a₃) (r : a₂ = a₁)
: (r = q ⬝ p) ≃ (r ⬝ p⁻¹ = q) :=
equiv.mk _ !is_equiv_con_inv_eq_of_eq_con
local attribute is_equiv_inv_con_eq_of_eq_con
is_equiv_con_inv_eq_of_eq_con
is_equiv_con_eq_of_eq_con_inv
is_equiv_con_eq_of_eq_inv_con [instance]
definition is_equiv_eq_con_of_inv_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (eq_con_of_inv_con_eq : r⁻¹ ⬝ q = p → q = r ⬝ p) :=
is_equiv_inv inv_con_eq_of_eq_con
definition is_equiv_eq_con_of_con_inv_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (eq_con_of_con_inv_eq : q ⬝ p⁻¹ = r → q = r ⬝ p) :=
is_equiv_inv con_inv_eq_of_eq_con
definition is_equiv_eq_con_inv_of_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (eq_con_inv_of_con_eq : r ⬝ p = q → r = q ⬝ p⁻¹) :=
is_equiv_inv con_eq_of_eq_con_inv
definition is_equiv_eq_inv_con_of_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (eq_inv_con_of_con_eq : r ⬝ p = q → p = r⁻¹ ⬝ q) :=
is_equiv_inv con_eq_of_eq_inv_con
/- Pathover Equivalences -/
definition pathover_eq_equiv_l (p : a₁ = a₂) (q : a₁ = a₃) (r : a₂ = a₃) : q =[p] r ≃ q = p ⬝ r :=
/-(λx, x = a₃)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_r (p : a₂ = a₃) (q : a₁ = a₂) (r : a₁ = a₃) : q =[p] r ≃ q ⬝ p = r :=
/-(λx, a₁ = x)-/
by induction p; apply pathover_idp
definition pathover_eq_equiv_lr (p : a₁ = a₂) (q : a₁ = a₁) (r : a₂ = a₂)
: q =[p] r ≃ q ⬝ p = p ⬝ r := /-(λx, x = x)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_Fl (p : a₁ = a₂) (q : f a₁ = b) (r : f a₂ = b)
: q =[p] r ≃ q = ap f p ⬝ r := /-(λx, f x = b)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_Fr (p : a₁ = a₂) (q : b = f a₁) (r : b = f a₂)
: q =[p] r ≃ q ⬝ ap f p = r := /-(λx, b = f x)-/
by induction p; apply pathover_idp
definition pathover_eq_equiv_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) (r : f a₂ = g a₂)
: q =[p] r ≃ q ⬝ ap g p = ap f p ⬝ r := /-(λx, f x = g x)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) (r : h (f a₂) = a₂)
: q =[p] r ≃ q ⬝ p = ap h (ap f p) ⬝ r :=
/-(λx, h (f x) = x)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) (r : a₂ = h (f a₂))
: q =[p] r ≃ q ⬝ ap h (ap f p) = p ⬝ r :=
/-(λx, x = h (f x))-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
-- a lot of this library still needs to be ported from Coq HoTT
end eq
|
dfb7d58aeb6daa793c31d7b481b4dc31f1eba201 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/algebra/algebra/operations.lean | 02ed4b842e6e2e6175b1a099c34ca9054cf74363 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 24,428 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.algebra.bilinear
import algebra.module.submodule.pointwise
import algebra.module.submodule.bilinear
import algebra.module.opposites
import data.finset.pointwise
import data.set.semiring
import group_theory.group_action.sub_mul_action.pointwise
/-!
# Multiplication and division of submodules of an algebra.
An interface for multiplication and division of sub-R-modules of an R-algebra A is developed.
## Main definitions
Let `R` be a commutative ring (or semiring) and let `A` be an `R`-algebra.
* `1 : submodule R A` : the R-submodule R of the R-algebra A
* `has_mul (submodule R A)` : multiplication of two sub-R-modules M and N of A is defined to be
the smallest submodule containing all the products `m * n`.
* `has_div (submodule R A)` : `I / J` is defined to be the submodule consisting of all `a : A` such
that `a • J ⊆ I`
It is proved that `submodule R A` is a semiring, and also an algebra over `set A`.
Additionally, in the `pointwise` locale we promote `submodule.pointwise_distrib_mul_action` to a
`mul_semiring_action` as `submodule.pointwise_mul_semiring_action`.
## Tags
multiplication of submodules, division of submodules, submodule semiring
-/
universes uι u v
open algebra set mul_opposite
open_locale big_operators
open_locale pointwise
namespace sub_mul_action
variables {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
lemma algebra_map_mem (r : R) : algebra_map R A r ∈ (1 : sub_mul_action R A) :=
⟨r, (algebra_map_eq_smul_one r).symm⟩
lemma mem_one' {x : A} : x ∈ (1 : sub_mul_action R A) ↔ ∃ y, algebra_map R A y = x :=
exists_congr $ λ r, by rw algebra_map_eq_smul_one
end sub_mul_action
namespace submodule
variables {ι : Sort uι}
variables {R : Type u} [comm_semiring R]
section ring
variables {A : Type v} [semiring A] [algebra R A]
variables (S T : set A) {M N P Q : submodule R A} {m n : A}
/-- `1 : submodule R A` is the submodule R of A. -/
instance : has_one (submodule R A) :=
⟨(algebra.linear_map R A).range⟩
theorem one_eq_range :
(1 : submodule R A) = (algebra.linear_map R A).range := rfl
lemma le_one_to_add_submonoid :
1 ≤ (1 : submodule R A).to_add_submonoid :=
begin
rintros x ⟨n, rfl⟩,
exact ⟨n, map_nat_cast (algebra_map R A) n⟩,
end
lemma algebra_map_mem (r : R) : algebra_map R A r ∈ (1 : submodule R A) :=
linear_map.mem_range_self _ _
@[simp] lemma mem_one {x : A} : x ∈ (1 : submodule R A) ↔ ∃ y, algebra_map R A y = x :=
iff.rfl
@[simp] lemma to_sub_mul_action_one : (1 : submodule R A).to_sub_mul_action = 1 :=
set_like.ext $ λ x, mem_one.trans sub_mul_action.mem_one'.symm
theorem one_eq_span : (1 : submodule R A) = R ∙ 1 :=
begin
apply submodule.ext,
intro a,
simp only [mem_one, mem_span_singleton, algebra.smul_def, mul_one]
end
theorem one_eq_span_one_set : (1 : submodule R A) = span R 1 := one_eq_span
theorem one_le : (1 : submodule R A) ≤ P ↔ (1 : A) ∈ P :=
by simpa only [one_eq_span, span_le, set.singleton_subset_iff]
protected lemma map_one {A'} [semiring A'] [algebra R A'] (f : A →ₐ[R] A') :
map f.to_linear_map (1 : submodule R A) = 1 :=
by { ext, simp }
@[simp] lemma map_op_one :
map (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) (1 : submodule R A) = 1 :=
by { ext, induction x using mul_opposite.rec, simp }
@[simp] lemma comap_op_one :
comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) (1 : submodule R Aᵐᵒᵖ) = 1 :=
by { ext, simp }
@[simp] lemma map_unop_one :
map (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A) (1 : submodule R Aᵐᵒᵖ) = 1 :=
by rw [←comap_equiv_eq_map_symm, comap_op_one]
@[simp] lemma comap_unop_one :
comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A) (1 : submodule R A) = 1 :=
by rw [←map_equiv_eq_comap_symm, map_op_one]
/-- Multiplication of sub-R-modules of an R-algebra A. The submodule `M * N` is the
smallest R-submodule of `A` containing the elements `m * n` for `m ∈ M` and `n ∈ N`. -/
instance : has_mul (submodule R A) := ⟨submodule.map₂ $ linear_map.mul R A⟩
theorem mul_mem_mul (hm : m ∈ M) (hn : n ∈ N) : m * n ∈ M * N := apply_mem_map₂ _ hm hn
theorem mul_le : M * N ≤ P ↔ ∀ (m ∈ M) (n ∈ N), m * n ∈ P := map₂_le
lemma mul_to_add_submonoid (M N : submodule R A) :
(M * N).to_add_submonoid = M.to_add_submonoid * N.to_add_submonoid :=
begin
dsimp [has_mul.mul],
simp_rw [←linear_map.mul_left_to_add_monoid_hom R, linear_map.mul_left, ←map_to_add_submonoid _ N,
map₂],
rw supr_to_add_submonoid,
refl,
end
@[elab_as_eliminator] protected theorem mul_induction_on
{C : A → Prop} {r : A} (hr : r ∈ M * N)
(hm : ∀ (m ∈ M) (n ∈ N), C (m * n)) (ha : ∀ x y, C x → C y → C (x + y)) : C r :=
begin
rw [←mem_to_add_submonoid, mul_to_add_submonoid] at hr,
exact add_submonoid.mul_induction_on hr hm ha,
end
/-- A dependent version of `mul_induction_on`. -/
@[elab_as_eliminator] protected theorem mul_induction_on'
{C : Π r, r ∈ M * N → Prop}
(hm : ∀ (m ∈ M) (n ∈ N), C (m * n) (mul_mem_mul ‹_› ‹_›))
(ha : ∀ x hx y hy, C x hx → C y hy → C (x + y) (add_mem ‹_› ‹_›))
{r : A} (hr : r ∈ M * N) : C r hr :=
begin
refine exists.elim _ (λ (hr : r ∈ M * N) (hc : C r hr), hc),
exact submodule.mul_induction_on hr
(λ x hx y hy, ⟨_, hm _ hx _ hy⟩) (λ x y ⟨_, hx⟩ ⟨_, hy⟩, ⟨_, ha _ _ _ _ hx hy⟩),
end
variables R
theorem span_mul_span : span R S * span R T = span R (S * T) := map₂_span_span _ _ _ _
variables {R}
variables (M N P Q)
@[simp] theorem mul_bot : M * ⊥ = ⊥ := map₂_bot_right _ _
@[simp] theorem bot_mul : ⊥ * M = ⊥ := map₂_bot_left _ _
@[simp] protected theorem one_mul : (1 : submodule R A) * M = M :=
by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, one_mul, span_eq] }
@[simp] protected theorem mul_one : M * 1 = M :=
by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, mul_one, span_eq] }
variables {M N P Q}
@[mono] theorem mul_le_mul (hmp : M ≤ P) (hnq : N ≤ Q) : M * N ≤ P * Q := map₂_le_map₂ hmp hnq
theorem mul_le_mul_left (h : M ≤ N) : M * P ≤ N * P := map₂_le_map₂_left h
theorem mul_le_mul_right (h : N ≤ P) : M * N ≤ M * P := map₂_le_map₂_right h
variables (M N P)
theorem mul_sup : M * (N ⊔ P) = M * N ⊔ M * P := map₂_sup_right _ _ _ _
theorem sup_mul : (M ⊔ N) * P = M * P ⊔ N * P := map₂_sup_left _ _ _ _
lemma mul_subset_mul : (↑M : set A) * (↑N : set A) ⊆ (↑(M * N) : set A) :=
image2_subset_map₂ (algebra.lmul R A).to_linear_map M N
protected lemma map_mul {A'} [semiring A'] [algebra R A'] (f : A →ₐ[R] A') :
map f.to_linear_map (M * N) = map f.to_linear_map M * map f.to_linear_map N :=
calc map f.to_linear_map (M * N)
= ⨆ (i : M), (N.map (linear_map.mul R A i)).map f.to_linear_map : map_supr _ _
... = map f.to_linear_map M * map f.to_linear_map N :
begin
apply congr_arg Sup,
ext S,
split; rintros ⟨y, hy⟩,
{ use [f y, mem_map.mpr ⟨y.1, y.2, rfl⟩],
refine trans _ hy,
ext,
simp },
{ obtain ⟨y', hy', fy_eq⟩ := mem_map.mp y.2,
use [y', hy'],
refine trans _ hy,
rw f.to_linear_map_apply at fy_eq,
ext,
simp [fy_eq] }
end
lemma map_op_mul :
map (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) (M * N) =
map (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) N *
map (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) M :=
begin
apply le_antisymm,
{ simp_rw map_le_iff_le_comap,
refine mul_le.2 (λ m hm n hn, _),
rw [mem_comap, map_equiv_eq_comap_symm, map_equiv_eq_comap_symm],
show op n * op m ∈ _,
exact mul_mem_mul hn hm },
{ refine mul_le.2 (mul_opposite.rec $ λ m hm, mul_opposite.rec $ λ n hn, _),
rw submodule.mem_map_equiv at ⊢ hm hn,
exact mul_mem_mul hn hm, }
end
lemma comap_unop_mul :
comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A) (M * N) =
comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A) N *
comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A) M :=
by simp_rw [←map_equiv_eq_comap_symm, map_op_mul]
lemma map_unop_mul (M N : submodule R Aᵐᵒᵖ) :
map (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A) (M * N) =
map (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A) N *
map (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A) M :=
have function.injective (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) :=
linear_equiv.injective _,
map_injective_of_injective this $
by rw [← map_comp, map_op_mul, ←map_comp, ←map_comp, linear_equiv.comp_coe,
linear_equiv.symm_trans_self, linear_equiv.refl_to_linear_map, map_id, map_id, map_id]
lemma comap_op_mul (M N : submodule R Aᵐᵒᵖ) :
comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) (M * N) =
comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) N *
comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) M :=
by simp_rw [comap_equiv_eq_map_symm, map_unop_mul]
section
open_locale pointwise
/-- `submodule.has_pointwise_neg` distributes over multiplication.
This is available as an instance in the `pointwise` locale. -/
protected def has_distrib_pointwise_neg {A} [ring A] [algebra R A] :
has_distrib_neg (submodule R A) :=
to_add_submonoid_injective.has_distrib_neg _ neg_to_add_submonoid mul_to_add_submonoid
localized "attribute [instance] submodule.has_distrib_pointwise_neg" in pointwise
end
section decidable_eq
open_locale classical
lemma mem_span_mul_finite_of_mem_span_mul
{R A} [semiring R] [add_comm_monoid A] [has_mul A] [module R A]
{S : set A} {S' : set A} {x : A} (hx : x ∈ span R (S * S')) :
∃ (T T' : finset A), ↑T ⊆ S ∧ ↑T' ⊆ S' ∧ x ∈ span R (T * T' : set A) :=
begin
obtain ⟨U, h, hU⟩ := mem_span_finite_of_mem_span hx,
obtain ⟨T, T', hS, hS', h⟩ := finset.subset_mul h,
use [T, T', hS, hS'],
have h' : (U : set A) ⊆ T * T', { assumption_mod_cast, },
have h'' := span_mono h' hU,
assumption,
end
end decidable_eq
lemma mul_eq_span_mul_set (s t : submodule R A) : s * t = span R ((s : set A) * (t : set A)) :=
map₂_eq_span_image2 _ s t
lemma supr_mul (s : ι → submodule R A) (t : submodule R A) : (⨆ i, s i) * t = ⨆ i, s i * t :=
map₂_supr_left _ s t
lemma mul_supr (t : submodule R A) (s : ι → submodule R A) : t * (⨆ i, s i) = ⨆ i, t * s i :=
map₂_supr_right _ t s
lemma mem_span_mul_finite_of_mem_mul {P Q : submodule R A} {x : A} (hx : x ∈ P * Q) :
∃ (T T' : finset A), (T : set A) ⊆ P ∧ (T' : set A) ⊆ Q ∧ x ∈ span R (T * T' : set A) :=
submodule.mem_span_mul_finite_of_mem_span_mul
(by rwa [← submodule.span_eq P, ← submodule.span_eq Q, submodule.span_mul_span] at hx)
variables {M N P}
/-- Sub-R-modules of an R-algebra form a semiring. -/
instance : semiring (submodule R A) :=
{ one_mul := submodule.one_mul,
mul_one := submodule.mul_one,
zero_mul := bot_mul,
mul_zero := mul_bot,
left_distrib := mul_sup,
right_distrib := sup_mul,
..to_add_submonoid_injective.semigroup _ (λ m n : submodule R A, mul_to_add_submonoid m n),
..add_monoid_with_one.unary,
..submodule.pointwise_add_comm_monoid,
..submodule.has_one,
..submodule.has_mul }
variables (M)
lemma span_pow (s : set A) : ∀ n : ℕ, span R s ^ n = span R (s ^ n)
| 0 := by rw [pow_zero, pow_zero, one_eq_span_one_set]
| (n + 1) := by rw [pow_succ, pow_succ, span_pow, span_mul_span]
lemma pow_eq_span_pow_set (n : ℕ) : M ^ n = span R ((M : set A) ^ n) := by rw [←span_pow, span_eq]
lemma pow_subset_pow {n : ℕ} : (↑M : set A)^n ⊆ ↑(M^n : submodule R A) :=
(pow_eq_span_pow_set M n).symm ▸ subset_span
lemma pow_mem_pow {x : A} (hx : x ∈ M) (n : ℕ) : x ^ n ∈ M ^ n :=
pow_subset_pow _ $ set.pow_mem_pow hx _
lemma pow_to_add_submonoid {n : ℕ} (h : n ≠ 0) :
(M ^ n).to_add_submonoid = M.to_add_submonoid ^ n :=
begin
induction n with n ih,
{ exact (h rfl).elim },
{ rw [pow_succ, pow_succ, mul_to_add_submonoid],
cases n,
{ rw [pow_zero, pow_zero, mul_one, ←mul_to_add_submonoid, mul_one] },
{ rw ih n.succ_ne_zero } },
end
lemma le_pow_to_add_submonoid {n : ℕ} :
M.to_add_submonoid ^ n ≤ (M ^ n).to_add_submonoid :=
begin
obtain rfl | hn := decidable.eq_or_ne n 0,
{ rw [pow_zero, pow_zero], exact le_one_to_add_submonoid },
{ exact (pow_to_add_submonoid M hn).ge }
end
/-- Dependent version of `submodule.pow_induction_on_left`. -/
@[elab_as_eliminator] protected theorem pow_induction_on_left'
{C : Π (n : ℕ) x, x ∈ M ^ n → Prop}
(hr : ∀ r : R, C 0 (algebra_map _ _ r) (algebra_map_mem r))
(hadd : ∀ x y i hx hy, C i x hx → C i y hy → C i (x + y) (add_mem ‹_› ‹_›))
(hmul : ∀ (m ∈ M) i x hx, C i x hx → C (i.succ) (m * x) (mul_mem_mul H hx))
{x : A} {n : ℕ} (hx : x ∈ M ^ n) : C n x hx :=
begin
induction n with n n_ih generalizing x,
{ rw pow_zero at hx,
obtain ⟨r, rfl⟩ := hx,
exact hr r, },
exact submodule.mul_induction_on'
(λ m hm x ih, hmul _ hm _ _ _ (n_ih ih))
(λ x hx y hy Cx Cy, hadd _ _ _ _ _ Cx Cy) hx,
end
/-- Dependent version of `submodule.pow_induction_on_right`. -/
@[elab_as_eliminator] protected theorem pow_induction_on_right'
{C : Π (n : ℕ) x, x ∈ M ^ n → Prop}
(hr : ∀ r : R, C 0 (algebra_map _ _ r) (algebra_map_mem r))
(hadd : ∀ x y i hx hy, C i x hx → C i y hy → C i (x + y) (add_mem ‹_› ‹_›))
(hmul : ∀ i x hx, C i x hx → ∀ m ∈ M,
C (i.succ) (x * m) ((pow_succ' M i).symm ▸ mul_mem_mul hx H))
{x : A} {n : ℕ} (hx : x ∈ M ^ n) : C n x hx :=
begin
induction n with n n_ih generalizing x,
{ rw pow_zero at hx,
obtain ⟨r, rfl⟩ := hx,
exact hr r, },
revert hx,
simp_rw pow_succ',
intro hx,
exact submodule.mul_induction_on'
(λ m hm x ih, hmul _ _ hm (n_ih _) _ ih)
(λ x hx y hy Cx Cy, hadd _ _ _ _ _ Cx Cy) hx,
end
/-- To show a property on elements of `M ^ n` holds, it suffices to show that it holds for scalars,
is closed under addition, and holds for `m * x` where `m ∈ M` and it holds for `x` -/
@[elab_as_eliminator] protected theorem pow_induction_on_left
{C : A → Prop}
(hr : ∀ r : R, C (algebra_map _ _ r))
(hadd : ∀ x y, C x → C y → C (x + y))
(hmul : ∀ (m ∈ M) x, C x → C (m * x))
{x : A} {n : ℕ} (hx : x ∈ M ^ n) : C x :=
submodule.pow_induction_on_left' M
(by exact hr) (λ x y i hx hy, hadd x y) (λ m hm i x hx, hmul _ hm _) hx
/-- To show a property on elements of `M ^ n` holds, it suffices to show that it holds for scalars,
is closed under addition, and holds for `x * m` where `m ∈ M` and it holds for `x` -/
@[elab_as_eliminator] protected theorem pow_induction_on_right
{C : A → Prop}
(hr : ∀ r : R, C (algebra_map _ _ r))
(hadd : ∀ x y, C x → C y → C (x + y))
(hmul : ∀ x, C x → ∀ (m ∈ M), C (x * m))
{x : A} {n : ℕ} (hx : x ∈ M ^ n) : C x :=
submodule.pow_induction_on_right' M
(by exact hr) (λ x y i hx hy, hadd x y) (λ i x hx, hmul _) hx
/-- `submonoid.map` as a `monoid_with_zero_hom`, when applied to `alg_hom`s. -/
@[simps]
def map_hom {A'} [semiring A'] [algebra R A'] (f : A →ₐ[R] A') :
submodule R A →*₀ submodule R A' :=
{ to_fun := map f.to_linear_map,
map_zero' := submodule.map_bot _,
map_one' := submodule.map_one _,
map_mul' := λ _ _, submodule.map_mul _ _ _}
/-- The ring of submodules of the opposite algebra is isomorphic to the opposite ring of
submodules. -/
@[simps apply symm_apply]
def equiv_opposite : submodule R Aᵐᵒᵖ ≃+* (submodule R A)ᵐᵒᵖ :=
{ to_fun := λ p, op $ p.comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ),
inv_fun := λ p, p.unop.comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A),
left_inv := λ p, set_like.coe_injective $ rfl,
right_inv := λ p, unop_injective $ set_like.coe_injective rfl,
map_add' := λ p q, by simp [comap_equiv_eq_map_symm, ←op_add],
map_mul' := λ p q, congr_arg op $ comap_op_mul _ _ }
protected lemma map_pow {A'} [semiring A'] [algebra R A'] (f : A →ₐ[R] A') (n : ℕ) :
map f.to_linear_map (M ^ n) = map f.to_linear_map M ^ n :=
map_pow (map_hom f) M n
lemma comap_unop_pow (n : ℕ) :
comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A) (M ^ n) =
comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A) M ^ n :=
(equiv_opposite : submodule R Aᵐᵒᵖ ≃+* _).symm.map_pow (op M) n
lemma comap_op_pow (n : ℕ) (M : submodule R Aᵐᵒᵖ) :
comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) (M ^ n) =
comap (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) M ^ n :=
op_injective $ (equiv_opposite : submodule R Aᵐᵒᵖ ≃+* _).map_pow M n
lemma map_op_pow (n : ℕ) :
map (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) (M ^ n) =
map (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ) : A →ₗ[R] Aᵐᵒᵖ) M ^ n :=
by rw [map_equiv_eq_comap_symm, map_equiv_eq_comap_symm, comap_unop_pow]
lemma map_unop_pow (n : ℕ) (M : submodule R Aᵐᵒᵖ) :
map (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A) (M ^ n) =
map (↑(op_linear_equiv R : A ≃ₗ[R] Aᵐᵒᵖ).symm : Aᵐᵒᵖ →ₗ[R] A) M ^ n :=
by rw [←comap_equiv_eq_map_symm, ←comap_equiv_eq_map_symm, comap_op_pow]
/-- `span` is a semiring homomorphism (recall multiplication is pointwise multiplication of subsets
on either side). -/
def span.ring_hom : set_semiring A →+* submodule R A :=
{ to_fun := submodule.span R,
map_zero' := span_empty,
map_one' := one_eq_span.symm,
map_add' := span_union,
map_mul' := λ s t, by erw [span_mul_span, ← image_mul_prod] }
section
variables {α : Type*} [monoid α] [mul_semiring_action α A] [smul_comm_class α R A]
/-- The action on a submodule corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale.
This is a stronger version of `submodule.pointwise_distrib_mul_action`. -/
protected def pointwise_mul_semiring_action : mul_semiring_action α (submodule R A) :=
{ smul_mul := λ r x y, submodule.map_mul x y $ mul_semiring_action.to_alg_hom R A r,
smul_one := λ r, submodule.map_one $ mul_semiring_action.to_alg_hom R A r,
..submodule.pointwise_distrib_mul_action }
localized "attribute [instance] submodule.pointwise_mul_semiring_action" in pointwise
end
end ring
section comm_ring
variables {A : Type v} [comm_semiring A] [algebra R A]
variables {M N : submodule R A} {m n : A}
theorem mul_mem_mul_rev (hm : m ∈ M) (hn : n ∈ N) : n * m ∈ M * N :=
mul_comm m n ▸ mul_mem_mul hm hn
variables (M N)
protected theorem mul_comm : M * N = N * M :=
le_antisymm (mul_le.2 $ λ r hrm s hsn, mul_mem_mul_rev hsn hrm)
(mul_le.2 $ λ r hrn s hsm, mul_mem_mul_rev hsm hrn)
/-- Sub-R-modules of an R-algebra A form a semiring. -/
instance : comm_semiring (submodule R A) :=
{ mul_comm := submodule.mul_comm,
.. submodule.semiring }
lemma prod_span {ι : Type*} (s : finset ι) (M : ι → set A) :
(∏ i in s, submodule.span R (M i)) = submodule.span R (∏ i in s, M i) :=
begin
letI := classical.dec_eq ι,
refine finset.induction_on s _ _,
{ simp [one_eq_span, set.singleton_one] },
{ intros _ _ H ih,
rw [finset.prod_insert H, finset.prod_insert H, ih, span_mul_span] }
end
lemma prod_span_singleton {ι : Type*} (s : finset ι) (x : ι → A) :
(∏ i in s, span R ({x i} : set A)) = span R {∏ i in s, x i} :=
by rw [prod_span, set.finset_prod_singleton]
variables (R A)
/-- R-submodules of the R-algebra A are a module over `set A`. -/
instance module_set : module (set_semiring A) (submodule R A) :=
{ smul := λ s P, span R s * P,
smul_add := λ _ _ _, mul_add _ _ _,
add_smul := λ s t P, show span R (s ⊔ t) * P = _, by { erw [span_union, right_distrib] },
mul_smul := λ s t P, show _ = _ * (_ * _),
by { rw [← mul_assoc, span_mul_span, ← image_mul_prod] },
one_smul := λ P, show span R {(1 : A)} * P = _,
by { conv_lhs {erw ← span_eq P}, erw [span_mul_span, one_mul, span_eq] },
zero_smul := λ P, show span R ∅ * P = ⊥, by erw [span_empty, bot_mul],
smul_zero := λ _, mul_bot _ }
variables {R A}
lemma smul_def {s : set_semiring A} {P : submodule R A} : s • P = span R s * P := rfl
lemma smul_le_smul {s t : set_semiring A} {M N : submodule R A} (h₁ : s.down ≤ t.down)
(h₂ : M ≤ N) : s • M ≤ t • N :=
mul_le_mul (span_mono h₁) h₂
lemma smul_singleton (a : A) (M : submodule R A) :
({a} : set A).up • M = M.map (linear_map.mul_left _ a) :=
begin
conv_lhs {rw ← span_eq M},
change span _ _ * span _ _ = _,
rw [span_mul_span],
apply le_antisymm,
{ rw span_le,
rintros _ ⟨b, m, hb, hm, rfl⟩,
rw [set_like.mem_coe, mem_map, set.mem_singleton_iff.mp hb],
exact ⟨m, hm, rfl⟩ },
{ rintros _ ⟨m, hm, rfl⟩, exact subset_span ⟨a, m, set.mem_singleton a, hm, rfl⟩ }
end
section quotient
/-- The elements of `I / J` are the `x` such that `x • J ⊆ I`.
In fact, we define `x ∈ I / J` to be `∀ y ∈ J, x * y ∈ I` (see `mem_div_iff_forall_mul_mem`),
which is equivalent to `x • J ⊆ I` (see `mem_div_iff_smul_subset`), but nicer to use in proofs.
This is the general form of the ideal quotient, traditionally written $I : J$.
-/
instance : has_div (submodule R A) :=
⟨ λ I J,
{ carrier := { x | ∀ y ∈ J, x * y ∈ I },
zero_mem' := λ y hy, by { rw zero_mul, apply submodule.zero_mem },
add_mem' := λ a b ha hb y hy, by { rw add_mul, exact submodule.add_mem _ (ha _ hy) (hb _ hy) },
smul_mem' := λ r x hx y hy, by { rw algebra.smul_mul_assoc,
exact submodule.smul_mem _ _ (hx _ hy) } } ⟩
lemma mem_div_iff_forall_mul_mem {x : A} {I J : submodule R A} :
x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I :=
iff.refl _
lemma mem_div_iff_smul_subset {x : A} {I J : submodule R A} : x ∈ I / J ↔ x • (J : set A) ⊆ I :=
⟨ λ h y ⟨y', hy', xy'_eq_y⟩, by { rw ← xy'_eq_y, apply h, assumption },
λ h y hy, h (set.smul_mem_smul_set hy) ⟩
lemma le_div_iff {I J K : submodule R A} : I ≤ J / K ↔ ∀ (x ∈ I) (z ∈ K), x * z ∈ J := iff.refl _
lemma le_div_iff_mul_le {I J K : submodule R A} : I ≤ J / K ↔ I * K ≤ J :=
by rw [le_div_iff, mul_le]
@[simp] lemma one_le_one_div {I : submodule R A} :
1 ≤ 1 / I ↔ I ≤ 1 :=
begin
split, all_goals {intro hI},
{rwa [le_div_iff_mul_le, one_mul] at hI},
{rwa [le_div_iff_mul_le, one_mul]},
end
lemma le_self_mul_one_div {I : submodule R A} (hI : I ≤ 1) :
I ≤ I * (1 / I) :=
begin
rw [← mul_one I] {occs := occurrences.pos [1]},
apply mul_le_mul_right (one_le_one_div.mpr hI),
end
lemma mul_one_div_le_one {I : submodule R A} : I * (1 / I) ≤ 1 :=
begin
rw submodule.mul_le,
intros m hm n hn,
rw [submodule.mem_div_iff_forall_mul_mem] at hn,
rw mul_comm,
exact hn m hm,
end
@[simp] protected lemma map_div {B : Type*} [comm_semiring B] [algebra R B]
(I J : submodule R A) (h : A ≃ₐ[R] B) :
(I / J).map h.to_linear_map = I.map h.to_linear_map / J.map h.to_linear_map :=
begin
ext x,
simp only [mem_map, mem_div_iff_forall_mul_mem],
split,
{ rintro ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩,
exact ⟨x * y, hx _ hy, h.map_mul x y⟩ },
{ rintro hx,
refine ⟨h.symm x, λ z hz, _, h.apply_symm_apply x⟩,
obtain ⟨xz, xz_mem, hxz⟩ := hx (h z) ⟨z, hz, rfl⟩,
convert xz_mem,
apply h.injective,
erw [h.map_mul, h.apply_symm_apply, hxz] }
end
end quotient
end comm_ring
end submodule
|
edbe5bc3888ecb1daa949450b718bc8f7a6405a5 | d29d82a0af640c937e499f6be79fc552eae0aa13 | /src/data/real/basic.lean | b39793229824187f101399affa286e7f114641df | [
"Apache-2.0"
] | permissive | AbdulMajeedkhurasani/mathlib | 835f8a5c5cf3075b250b3737172043ab4fa1edf6 | 79bc7323b164aebd000524ebafd198eb0e17f956 | refs/heads/master | 1,688,003,895,660 | 1,627,788,521,000 | 1,627,788,521,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,949 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn
-/
import order.conditionally_complete_lattice
import data.real.cau_seq_completion
import algebra.archimedean
import algebra.star.basic
/-!
# Real numbers from Cauchy sequences
This file defines `ℝ` as the type of equivalence classes of Cauchy sequences of rational numbers.
This choice is motivated by how easy it is to prove that `ℝ` is a commutative ring, by simply
lifting everything to `ℚ`.
-/
/-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational
numbers. -/
structure real := of_cauchy ::
(cauchy : @cau_seq.completion.Cauchy ℚ _ _ _ abs _)
notation `ℝ` := real
attribute [pp_using_anonymous_constructor] real
namespace real
open cau_seq cau_seq.completion
variables {x y : ℝ}
lemma ext_cauchy_iff : ∀ {x y : real}, x = y ↔ x.cauchy = y.cauchy
| ⟨a⟩ ⟨b⟩ := by split; cc
lemma ext_cauchy {x y : real} : x.cauchy = y.cauchy → x = y :=
ext_cauchy_iff.2
/-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/
def equiv_Cauchy : ℝ ≃ cau_seq.completion.Cauchy :=
⟨real.cauchy, real.of_cauchy, λ ⟨_⟩, rfl, λ _, rfl⟩
-- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511
@[irreducible] private def zero : ℝ := ⟨0⟩
@[irreducible] private def one : ℝ := ⟨1⟩
@[irreducible] private def add : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩
@[irreducible] private def neg : ℝ → ℝ | ⟨a⟩ := ⟨-a⟩
@[irreducible] private def mul : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩
instance : has_zero ℝ := ⟨zero⟩
instance : has_one ℝ := ⟨one⟩
instance : has_add ℝ := ⟨add⟩
instance : has_neg ℝ := ⟨neg⟩
instance : has_mul ℝ := ⟨mul⟩
lemma zero_cauchy : (⟨0⟩ : ℝ) = 0 := show _ = zero, by rw zero
lemma one_cauchy : (⟨1⟩ : ℝ) = 1 := show _ = one, by rw one
lemma add_cauchy {a b} : (⟨a⟩ + ⟨b⟩ : ℝ) = ⟨a + b⟩ := show add _ _ = _, by rw add
lemma neg_cauchy {a} : (-⟨a⟩ : ℝ) = ⟨-a⟩ := show neg _ = _, by rw neg
lemma mul_cauchy {a b} : (⟨a⟩ * ⟨b⟩ : ℝ) = ⟨a * b⟩ := show mul _ _ = _, by rw mul
instance : comm_ring ℝ :=
begin
refine_struct { zero := 0,
one := 1,
mul := (*),
add := (+),
neg := @has_neg.neg ℝ _,
sub := λ a b, a + (-b),
npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩,
nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩,
gsmul := @gsmul_rec _ ⟨0⟩ ⟨(+)⟩ ⟨@has_neg.neg ℝ _⟩ };
repeat { rintro ⟨_⟩, };
try { refl };
simp [← zero_cauchy, ← one_cauchy, add_cauchy, neg_cauchy, mul_cauchy];
apply add_assoc <|> apply add_comm <|> apply mul_assoc <|> apply mul_comm <|>
apply left_distrib <|> apply right_distrib <|> apply sub_eq_add_neg <|> skip
end
/-! Extra instances to short-circuit type class resolution.
These short-circuits have an additional property of ensuring that a computable path is found; if
`field ℝ` is found first, then decaying it to these typeclasses would result in a `noncomputable`
version of them. -/
instance : ring ℝ := by apply_instance
instance : comm_semiring ℝ := by apply_instance
instance : semiring ℝ := by apply_instance
instance : add_comm_group ℝ := by apply_instance
instance : add_group ℝ := by apply_instance
instance : add_comm_monoid ℝ := by apply_instance
instance : add_monoid ℝ := by apply_instance
instance : add_left_cancel_semigroup ℝ := by apply_instance
instance : add_right_cancel_semigroup ℝ := by apply_instance
instance : add_comm_semigroup ℝ := by apply_instance
instance : add_semigroup ℝ := by apply_instance
instance : comm_monoid ℝ := by apply_instance
instance : monoid ℝ := by apply_instance
instance : comm_semigroup ℝ := by apply_instance
instance : semigroup ℝ := by apply_instance
instance : has_sub ℝ := by apply_instance
instance : module ℝ ℝ := by apply_instance
instance : inhabited ℝ := ⟨0⟩
/-- The real numbers are a `*`-ring, with the trivial `*`-structure. -/
instance : star_ring ℝ := star_ring_of_comm
/-- Coercion `ℚ` → `ℝ` as a `ring_hom`. Note that this
is `cau_seq.completion.of_rat`, not `rat.cast`. -/
def of_rat : ℚ →+* ℝ :=
by refine_struct { to_fun := of_cauchy ∘ of_rat };
simp [of_rat_one, of_rat_zero, of_rat_mul, of_rat_add,
one_cauchy, zero_cauchy, ← mul_cauchy, ← add_cauchy]
lemma of_rat_apply (x : ℚ) : of_rat x = of_cauchy (cau_seq.completion.of_rat x) := rfl
/-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/
def mk (x : cau_seq ℚ abs) : ℝ := ⟨cau_seq.completion.mk x⟩
theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g :=
ext_cauchy_iff.trans mk_eq
@[irreducible]
private def lt : ℝ → ℝ → Prop | ⟨x⟩ ⟨y⟩ :=
quotient.lift_on₂ x y (<) $
λ f₁ g₁ f₂ g₂ hf hg, propext $
⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg),
λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩
instance : has_lt ℝ := ⟨lt⟩
lemma lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _, by rw lt; refl
@[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g :=
lt_cauchy
lemma mk_zero : mk 0 = 0 := by rw ← zero_cauchy; refl
lemma mk_one : mk 1 = 1 := by rw ← one_cauchy; refl
lemma mk_add {f g : cau_seq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, add_cauchy]
lemma mk_mul {f g : cau_seq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, mul_cauchy]
lemma mk_neg {f : cau_seq ℚ abs} : mk (-f) = -mk f := by simp [mk, neg_cauchy]
@[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f :=
by rw [← mk_zero, mk_lt]; exact iff_of_eq (congr_arg pos (sub_zero f))
@[irreducible] private def le (x y : ℝ) : Prop := x < y ∨ x = y
instance : has_le ℝ := ⟨le⟩
private lemma le_def {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y := show le _ _ ↔ _, by rw le
@[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g :=
by simp [le_def, mk_eq]; refl
@[elab_as_eliminator]
protected lemma ind_mk {C : real → Prop} (x : real) (h : ∀ y, C (mk y)) : C x :=
begin
cases x with x,
induction x using quot.induction_on with x,
exact h x
end
theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b :=
begin
induction a using real.ind_mk,
induction b using real.ind_mk,
induction c using real.ind_mk,
simp only [mk_lt, ← mk_add],
show pos _ ↔ pos _, rw add_sub_add_left_eq_sub
end
instance : partial_order ℝ :=
{ le := (≤), lt := (<),
lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b,
by simpa using lt_iff_le_not_le,
le_refl := λ a, a.ind_mk (by intro a; rw mk_le),
le_trans := λ a b c, real.ind_mk a $ λ a, real.ind_mk b $ λ b, real.ind_mk c $ λ c,
by simpa using le_trans,
lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b,
by simpa using lt_iff_le_not_le,
le_antisymm := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b,
by simpa [mk_eq] using @cau_seq.le_antisymm _ _ a b }
instance : preorder ℝ := by apply_instance
theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y :=
begin
rw [mk_lt] {md := tactic.transparency.semireducible},
exact const_lt
end
protected theorem zero_lt_one : (0 : ℝ) < 1 :=
by convert of_rat_lt.2 zero_lt_one; simp
protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b :=
begin
induction a using real.ind_mk with a,
induction b using real.ind_mk with b,
simpa only [mk_lt, mk_pos, ← mk_mul] using cau_seq.mul_pos
end
instance : ordered_ring ℝ :=
{ add_le_add_left :=
begin
simp only [le_iff_eq_or_lt],
rintros a b ⟨rfl, h⟩,
{ simp },
{ exact λ c, or.inr ((add_lt_add_iff_left c).2 ‹_›) }
end,
zero_le_one := le_of_lt real.zero_lt_one,
mul_pos := @real.mul_pos,
.. real.comm_ring, .. real.partial_order, .. real.semiring }
instance : ordered_semiring ℝ := by apply_instance
instance : ordered_add_comm_group ℝ := by apply_instance
instance : ordered_cancel_add_comm_monoid ℝ := by apply_instance
instance : ordered_add_comm_monoid ℝ := by apply_instance
instance : nontrivial ℝ := ⟨⟨0, 1, ne_of_lt real.zero_lt_one⟩⟩
open_locale classical
noncomputable instance : linear_order ℝ :=
{ le_total := begin
intros a b,
induction a using real.ind_mk with a,
induction b using real.ind_mk with b,
simpa using le_total a b,
end,
decidable_le := by apply_instance,
.. real.partial_order }
noncomputable instance : linear_ordered_comm_ring ℝ :=
{ .. real.nontrivial, .. real.ordered_ring, .. real.comm_ring, .. real.linear_order }
/- Extra instances to short-circuit type class resolution -/
noncomputable instance : linear_ordered_ring ℝ := by apply_instance
noncomputable instance : linear_ordered_semiring ℝ := by apply_instance
instance : domain ℝ :=
{ .. real.nontrivial, .. real.comm_ring, .. linear_ordered_ring.to_domain }
/-- The real numbers are an ordered `*`-ring, with the trivial `*`-structure. -/
instance : star_ordered_ring ℝ :=
{ star_mul_self_nonneg := λ r, mul_self_nonneg r, }
@[irreducible] private noncomputable def inv' : ℝ → ℝ | ⟨a⟩ := ⟨a⁻¹⟩
noncomputable instance : has_inv ℝ := ⟨inv'⟩
lemma inv_cauchy {f} : (⟨f⟩ : ℝ)⁻¹ = ⟨f⁻¹⟩ := show inv' _ = _, by rw inv'
noncomputable instance : linear_ordered_field ℝ :=
{ inv := has_inv.inv,
mul_inv_cancel := begin
rintros ⟨a⟩ h,
rw mul_comm,
simp only [inv_cauchy, mul_cauchy, ← one_cauchy, ← zero_cauchy, ne.def] at *,
exact cau_seq.completion.inv_mul_cancel h,
end,
inv_zero := by simp [← zero_cauchy, inv_cauchy],
..real.linear_ordered_comm_ring,
..real.domain }
/- Extra instances to short-circuit type class resolution -/
noncomputable instance : linear_ordered_add_comm_group ℝ := by apply_instance
noncomputable instance field : field ℝ := by apply_instance
noncomputable instance : division_ring ℝ := by apply_instance
noncomputable instance : integral_domain ℝ := by apply_instance
noncomputable instance : distrib_lattice ℝ := by apply_instance
noncomputable instance : lattice ℝ := by apply_instance
noncomputable instance : semilattice_inf ℝ := by apply_instance
noncomputable instance : semilattice_sup ℝ := by apply_instance
noncomputable instance : has_inf ℝ := by apply_instance
noncomputable instance : has_sup ℝ := by apply_instance
noncomputable instance decidable_lt (a b : ℝ) : decidable (a < b) := by apply_instance
noncomputable instance decidable_le (a b : ℝ) : decidable (a ≤ b) := by apply_instance
noncomputable instance decidable_eq (a b : ℝ) : decidable (a = b) := by apply_instance
open rat
@[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x :=
of_rat.eq_rat_cast
theorem le_mk_of_forall_le {f : cau_seq ℚ abs} :
(∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f :=
begin
intro h,
induction x using real.ind_mk with x,
apply le_of_not_lt,
rw mk_lt,
rintro ⟨K, K0, hK⟩,
obtain ⟨i, H⟩ := exists_forall_ge_and h
(exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0)),
apply not_lt_of_le (H _ (le_refl _)).1,
rw ← of_rat_eq_cast,
rw [mk_lt] {md := tactic.transparency.semireducible},
refine ⟨_, half_pos K0, i, λ j ij, _⟩,
have := add_le_add (H _ ij).2.1
(le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1),
rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this
end
theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ}
(h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) : mk f ≤ x :=
begin
cases h with i H,
rw [← neg_le_neg_iff, ← mk_neg],
exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩
end
theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ}
(H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $
H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1,
sub_le.1 $ le_mk_of_forall_le $
H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩
instance : archimedean ℝ :=
archimedean_iff_rat_le.2 $ λ x, real.ind_mk x $ λ f,
let ⟨M, M0, H⟩ := f.bounded' 0 in
⟨M, mk_le_of_forall_le ⟨0, λ i _,
rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩
noncomputable instance : floor_ring ℝ := archimedean.floor_ring _
theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) :=
⟨λ H ε ε0,
let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in
(H _ δ0).imp $ λ i hi j ij, lt_trans
(by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε,
λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $
λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩
theorem of_near (f : ℕ → ℚ) (x : ℝ)
(h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) :
∃ h', real.mk ⟨f, h'⟩ = x :=
⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h),
sub_eq_zero.1 $ abs_eq_zero.1 $
eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0,
mk_near_of_forall_near $
(h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩
theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧
∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub :=
int.exists_greatest_of_bdd
(let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h',
int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩)
(let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩)
theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) →
∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y
| ⟨L, hL⟩ ⟨U, hU⟩ := begin
choose f hf using begin
refine λ d : ℕ, @int.exists_greatest_of_bdd
(λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _,
{ cases exists_int_gt U with k hk,
refine ⟨k * d, λ z h, _⟩,
rcases h with ⟨y, yS, hy⟩,
refine int.cast_le.1 (le_trans hy _),
simp,
exact mul_le_mul_of_nonneg_right
(le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) },
{ exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ }
end,
have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0,
let ⟨y, yS, hy⟩ := (hf n).1 in
⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩,
have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ),
{ intros n n0 y yS,
have := lt_of_lt_of_le (sub_one_lt_floor _)
(int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩),
simp [-sub_eq_add_neg],
rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel],
exact ne_of_gt (nat.cast_pos.2 n0) },
suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩,
refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩,
{ refine le_of_forall_ge_of_dense (λ z xz, _),
cases exists_nat_gt (x - z)⁻¹ with K hK,
refine le_mk_of_forall_le ⟨K, λ n nK, _⟩,
replace xz := sub_pos.2 xz,
replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK),
have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 xz) hK),
refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS),
rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] },
{ exact mk_le_of_forall_le ⟨1, λ n n1,
let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ },
intros ε ε0,
suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε,
{ refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩,
rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij },
intros j k ij ik,
replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij),
replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik),
have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ij),
have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ik),
rcases hf₁ _ j0 with ⟨y, yS, hy⟩,
refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _)
((inv_le ε0 (nat.cast_pos.2 k0)).1 ik),
simpa using sub_lt_iff_lt_add'.2
(lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS)
end
noncomputable instance : has_Sup ℝ :=
⟨λ S, if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x)
then classical.some (exists_sup S h.1 h.2) else 0⟩
lemma Sup_def (S : set ℝ) :
Sup S = if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x)
then classical.some (exists_sup S h.1 h.2) else 0 := rfl
theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x)
{y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y :=
by simp [Sup_def, h₁, h₂]; exact
classical.some_spec (exists_sup S h₁ h₂) y
theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x)
{y} : y < Sup S ↔ ∃ z ∈ S, y < z :=
by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y)
theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S :=
(Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS
theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub :=
(Sup_le S h₁ ⟨_, h₂⟩).2 h₂
protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) :
is_lub s (Sup s) :=
⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs,
λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩
noncomputable instance : has_Inf ℝ := ⟨λ S, -Sup {x | -x ∈ S}⟩
lemma Inf_def (S : set ℝ) : Inf S = -Sup {x | -x ∈ S} := rfl
theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y)
{y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z :=
begin
refine le_neg.trans ((Sup_le _ _ _).trans _),
{ cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ },
{ cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ },
split; intros H z hz,
{ exact neg_le_neg_iff.1 (H _ $ by simp [hz]) },
{ exact le_neg.2 (H _ hz) }
end
section
-- this proof times out without this
local attribute [instance, priority 1000] classical.prop_decidable
theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y)
{y} : Inf S < y ↔ ∃ z ∈ S, z < y :=
by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y)
end
theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x :=
(le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS
theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S :=
(le_Inf S h₁ ⟨_, h₂⟩).2 h₂
noncomputable instance : conditionally_complete_linear_order ℝ :=
{ Sup := has_Sup.Sup,
Inf := has_Inf.Inf,
le_cSup :=
assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s),
show a ≤ Sup s,
from le_Sup s ‹bdd_above s› ‹a ∈ s›,
cSup_le :=
assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, b ≤ a),
show Sup s ≤ a,
from Sup_le_ub s ‹s.nonempty› H,
cInf_le :=
assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s),
show Inf s ≤ a,
from Inf_le s ‹bdd_below s› ‹a ∈ s›,
le_cInf :=
assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, a ≤ b),
show a ≤ Inf s,
from lb_le_Inf s ‹s.nonempty› H,
..real.linear_order, ..real.lattice}
lemma lt_Inf_add_pos {s : set ℝ} (h : bdd_below s) (h' : s.nonempty) {ε : ℝ} (hε : 0 < ε) :
∃ a ∈ s, a < Inf s + ε :=
(Inf_lt _ h' h).1 $ lt_add_of_pos_right _ hε
lemma add_neg_lt_Sup {s : set ℝ} (h : bdd_above s) (h' : s.nonempty) {ε : ℝ} (hε : ε < 0) :
∃ a ∈ s, Sup s + ε < a :=
(real.lt_Sup _ h' h).1 $ add_lt_iff_neg_left.mpr hε
lemma Inf_le_iff {s : set ℝ} (h : bdd_below s) (h' : s.nonempty) {a : ℝ} :
Inf s ≤ a ↔ ∀ ε, 0 < ε → ∃ x ∈ s, x < a + ε :=
begin
rw le_iff_forall_pos_lt_add,
split; intros H ε ε_pos,
{ exact exists_lt_of_cInf_lt h' (H ε ε_pos) },
{ rcases H ε ε_pos with ⟨x, x_in, hx⟩,
exact cInf_lt_of_lt h x_in hx }
end
lemma le_Sup_iff {s : set ℝ} (h : bdd_above s) (h' : s.nonempty) {a : ℝ} :
a ≤ Sup s ↔ ∀ ε, ε < 0 → ∃ x ∈ s, a + ε < x :=
begin
rw le_iff_forall_pos_lt_add,
refine ⟨λ H ε ε_neg, _, λ H ε ε_pos, _⟩,
{ exact exists_lt_of_lt_cSup h' (lt_sub_iff_add_lt.mp (H _ (neg_pos.mpr ε_neg))) },
{ rcases H _ (neg_lt_zero.mpr ε_pos) with ⟨x, x_in, hx⟩,
exact sub_lt_iff_lt_add.mp (lt_cSup_of_lt h x_in hx) }
end
@[simp] theorem Sup_empty : Sup (∅ : set ℝ) = 0 := dif_neg $ by simp
theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : Sup s = 0 :=
dif_neg $ assume h, hs h.2
theorem Sup_univ : Sup (@set.univ ℝ) = 0 :=
real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _)
@[simp] theorem Inf_empty : Inf (∅ : set ℝ) = 0 :=
by simp [Inf_def, Sup_empty]
theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : Inf s = 0 :=
have bdd_above {x | -x ∈ s} → bdd_below s, from
assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb $ by simp [hxs]⟩,
have ¬ bdd_above {x | -x ∈ s}, from mt this hs,
neg_eq_zero.2 $ Sup_of_not_bdd_above $ this
/--
As `0` is the default value for `real.Sup` of the empty set or sets which are not bounded above, it
suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`.
-/
lemma Sup_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Sup S :=
begin
rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩,
{ exact Sup_empty.ge },
{ apply dite _ (λ h, le_cSup_of_le h hy $ hS y hy) (λ h, (Sup_of_not_bdd_above h).ge) }
end
/--
As `0` is the default value for `real.Sup` of the empty set, it suffices to show that `S` is
bounded above by `0` to show that `Sup S ≤ 0`.
-/
lemma Sup_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Sup S ≤ 0 :=
begin
rcases S.eq_empty_or_nonempty with rfl | hS₂,
exacts [Sup_empty.le, Sup_le_ub _ hS₂ hS],
end
/--
As `0` is the default value for `real.Inf` of the empty set, it suffices to show that `S` is
bounded below by `0` to show that `0 ≤ Inf S`.
-/
lemma Inf_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Inf S :=
begin
rcases S.eq_empty_or_nonempty with rfl | hS₂,
exacts [Inf_empty.ge, lb_le_Inf S hS₂ hS]
end
/--
As `0` is the default value for `real.Inf` of the empty set or sets which are not bounded below, it
suffices to show that `S` is bounded above by `0` to show that `Inf S ≤ 0`.
-/
lemma Inf_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Inf S ≤ 0 :=
begin
rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩,
{ exact Inf_empty.le },
{ apply dite _ (λ h, cInf_le_of_le h hy $ hS y hy) (λ h, (Inf_of_not_bdd_below h).le) }
end
lemma Inf_le_Sup (s : set ℝ) (h₁ : bdd_below s) (h₂ : bdd_above s) : Inf s ≤ Sup s :=
begin
rcases s.eq_empty_or_nonempty with rfl | hne,
{ rw [Inf_empty, Sup_empty] },
{ exact cInf_le_cSup h₁ h₂ hne }
end
theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x :=
begin
let S := {x : ℝ | const abs x < f},
have lb : ∃ x, x ∈ S := exists_lt f,
have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x :=
λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h,
have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub',
refine ⟨Sup S,
((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩,
{ rcases h with ⟨ε, ε0, i, ih⟩,
refine not_lt_of_le (Sup_le_ub S lb (ub' _ _))
(sub_lt_self _ (half_pos ε0)),
refine ⟨_, half_pos ε0, i, λ j ij, _⟩,
rw [sub_apply, const_apply, sub_right_comm,
le_sub_iff_add_le, add_halves],
exact ih _ ij },
{ rcases h with ⟨ε, ε0, i, ih⟩,
refine not_lt_of_le (le_Sup S ub _)
((lt_add_iff_pos_left _).2 (half_pos ε0)),
refine ⟨_, half_pos ε0, i, λ j ij, _⟩,
rw [sub_apply, const_apply, add_comm, ← sub_sub,
le_sub_iff_add_le, add_halves],
exact ih _ ij }
end
noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩
end real
|
c968a37760d23cfad16b7e6f882d0e5e51566d6b | a721fe7446524f18ba361625fc01033d9c8b7a78 | /elaborate/concat_empty_nat.lean | 8b5118670dfbf1e9a93b17aebc55cb7f3e6f2352 | [] | no_license | Sterrs/leaning | 8fd80d1f0a6117a220bb2e57ece639b9a63deadc | 3901cc953694b33adda86cb88ca30ba99594db31 | refs/heads/master | 1,627,023,822,744 | 1,616,515,221,000 | 1,616,515,221,000 | 245,512,190 | 2 | 0 | null | 1,616,429,050,000 | 1,583,527,118,000 | Lean | UTF-8 | Lean | false | false | 2,140 | lean | λ {lst : mylist mynat},
mylist.rec
(eq.rec true.intro
(eq.rec (eq.refl (empty = empty))
(eq.rec (eq.refl (empty = empty))
(propext {mp := λ (hl : empty = empty), true.intro, mpr := λ (hr : true), eq.refl empty}))))
(λ (lst_head : mynat) (lst_tail : mylist mynat) (lst_ih : lst_tail ++ empty = lst_tail),
eq.rec true.intro
(eq.rec (eq.refl (lst_head :: (lst_tail ++ empty) = lst_head :: lst_tail))
(eq.rec
(eq.rec
(eq.rec
(eq.rec (eq.refl (lst_head :: (lst_tail ++ empty) = lst_head :: lst_tail))
(eq.rec (eq.refl (eq (lst_head :: (lst_tail ++ empty))))
(eq.rec (eq.refl (lst_head :: (lst_tail ++ empty)))
(eq.rec (eq.refl (lst_head :: (lst_tail ++ empty))) lst_ih))))
(propext
{mp := λ (h : lst_head :: lst_tail = lst_head :: lst_tail),
⟨eq.refl lst_head, eq.refl lst_tail⟩,
mpr := λ (a : lst_head = lst_head ∧ lst_tail = lst_tail),
and.rec
(λ (left : lst_head = lst_head) (right : lst_tail = lst_tail)
(«_» : lst_head = lst_head ∧ lst_tail = lst_tail),
eq.refl (lst_head :: lst_tail))
a
a}))
(eq.rec
(eq.rec (eq.refl (lst_head = lst_head ∧ lst_tail = lst_tail))
(propext
{mp := λ (hl : lst_tail = lst_tail), true.intro, mpr := λ (hr : true), eq.refl lst_tail}))
(eq.rec (eq.refl (and (lst_head = lst_head)))
(propext
{mp := λ (hl : lst_head = lst_head), true.intro,
mpr := λ (hr : true), eq.refl lst_head}))))
(propext {mp := and.left true, mpr := λ (h : true), ⟨h, h⟩}))))
lst
|
50b0a809c7f1bf876f520bb3fd3e75f9940d3f8b | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/algebra/geom_sum.lean | dd792ac2d41c2357ec2cce054679e311b46db358 | [
"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 | 15,382 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland
-/
import algebra.group_with_zero.power
import algebra.big_operators.order
import algebra.big_operators.ring
import algebra.big_operators.intervals
/-!
# Partial sums of geometric series
This file determines the values of the geometric series $\sum_{i=0}^{n-1} x^i$ and
$\sum_{i=0}^{n-1} x^i y^{n-1-i}$ and variants thereof. We also provide some bounds on the
"geometric" sum of `a/b^i` where `a b : ℕ`.
## Main definitions
* `geom_sum` defines for each $x$ in a semiring and each natural number $n$ the partial sum
$\sum_{i=0}^{n-1} x^i$ of the geometric series.
* `geom_sum₂` defines for each $x,y$ in a semiring and each natural number $n$ the partial sum
$\sum_{i=0}^{n-1} x^i y^{n-1-i}$ of the geometric series.
## Main statements
* `geom_sum_Ico` proves that $\sum_{i=m}^{n-1} x^i=\frac{x^n-x^m}{x-1}$ in a division ring.
* `geom_sum₂_Ico` proves that $\sum_{i=m}^{n-1} x^i=\frac{x^n-y^{n-m}x^m}{x-y}$ in a field.
Several variants are recorded, generalising in particular to the case of a noncommutative ring in
which `x` and `y` commute. Even versions not using division or subtraction, valid in each semiring,
are recorded.
-/
universe u
variable {α : Type u}
open finset opposite
open_locale big_operators
/-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i$. -/
def geom_sum [semiring α] (x : α) (n : ℕ) :=
∑ i in range n, x ^ i
theorem geom_sum_def [semiring α] (x : α) (n : ℕ) :
geom_sum x n = ∑ i in range n, x ^ i := rfl
@[simp] theorem geom_sum_zero [semiring α] (x : α) :
geom_sum x 0 = 0 := rfl
@[simp] theorem geom_sum_one [semiring α] (x : α) :
geom_sum x 1 = 1 :=
by { rw [geom_sum_def, sum_range_one, pow_zero] }
@[simp] lemma op_geom_sum [ring α] (x : α) (n : ℕ) :
op (geom_sum x n) = geom_sum (op x) n :=
by simp [geom_sum_def]
/-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i y^{n-1-i}$. -/
def geom_sum₂ [semiring α] (x y : α) (n : ℕ) :=
∑ i in range n, x ^ i * (y ^ (n - 1 - i))
theorem geom_sum₂_def [semiring α] (x y : α) (n : ℕ) :
geom_sum₂ x y n = ∑ i in range n, x ^ i * y ^ (n - 1 - i) := rfl
@[simp] theorem geom_sum₂_zero [semiring α] (x y : α) :
geom_sum₂ x y 0 = 0 := rfl
@[simp] theorem geom_sum₂_one [semiring α] (x y : α) :
geom_sum₂ x y 1 = 1 :=
by { have : 1 - 1 - 0 = 0 := rfl,
rw [geom_sum₂_def, sum_range_one, this, pow_zero, pow_zero, mul_one] }
@[simp] lemma op_geom_sum₂ [ring α] (x y : α) (n : ℕ) :
op (geom_sum₂ x y n) = geom_sum₂ (op y) (op x) n :=
begin
simp only [geom_sum₂_def, op_sum, op_mul, op_pow],
rw ← sum_range_reflect,
refine sum_congr rfl (λ j j_in, _),
rw [mem_range, nat.lt_iff_add_one_le] at j_in,
congr,
apply nat.sub_sub_self,
exact nat.le_sub_right_of_add_le j_in
end
@[simp] theorem geom_sum₂_with_one [semiring α] (x : α) (n : ℕ) :
geom_sum₂ x 1 n = geom_sum x n :=
sum_congr rfl (λ i _, by { rw [one_pow, mul_one] })
/-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/
protected theorem commute.geom_sum₂_mul_add [semiring α] {x y : α} (h : commute x y) (n : ℕ) :
(geom_sum₂ (x + y) y n) * x + y ^ n = (x + y) ^ n :=
begin
let f := λ (m i : ℕ), (x + y) ^ i * y ^ (m - 1 - i),
change (∑ i in range n, (f n) i) * x + y ^ n = (x + y) ^ n,
induction n with n ih,
{ rw [range_zero, sum_empty, zero_mul, zero_add, pow_zero, pow_zero] },
{ have f_last : f (n + 1) n = (x + y) ^ n :=
by { dsimp [f],
rw [nat.sub_sub, nat.add_comm, nat.sub_self, pow_zero, mul_one] },
have f_succ : ∀ i, i ∈ range n → f (n + 1) i = y * f n i :=
λ i hi, by {
dsimp [f],
have : commute y ((x + y) ^ i) :=
(h.symm.add_right (commute.refl y)).pow_right i,
rw [← mul_assoc, this.eq, mul_assoc, ← pow_succ y (n - 1 - i)],
congr' 2,
rw [nat.add_sub_cancel, nat.sub_sub, add_comm 1 i],
have : i + 1 + (n - (i + 1)) = n := nat.add_sub_of_le (mem_range.mp hi),
rw [add_comm (i + 1)] at this,
rw [← this, nat.add_sub_cancel, add_comm i 1, ← add_assoc,
nat.add_sub_cancel] },
rw [pow_succ (x + y), add_mul, sum_range_succ_comm, add_mul, f_last, add_assoc],
rw (((commute.refl x).add_right h).pow_right n).eq,
congr' 1,
rw [sum_congr rfl f_succ, ← mul_sum, pow_succ y, mul_assoc, ← mul_add y, ih] }
end
theorem geom_sum₂_self {α : Type*} [comm_ring α] (x : α) (n : ℕ) :
geom_sum₂ x x n = n * x ^ (n-1) :=
calc ∑ i in finset.range n, x ^ i * x ^ (n - 1 - i)
= ∑ i in finset.range n, x ^ (i + (n - 1 - i)) : by simp_rw [← pow_add]
... = ∑ i in finset.range n, x ^ (n - 1) : finset.sum_congr rfl
(λ i hi, congr_arg _ $ nat.add_sub_cancel' $ nat.le_pred_of_lt $ finset.mem_range.1 hi)
... = (finset.range n).card • (x ^ (n - 1)) : finset.sum_const _
... = n * x ^ (n - 1) : by rw [finset.card_range, nsmul_eq_mul]
/-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/
theorem geom_sum₂_mul_add [comm_semiring α] (x y : α) (n : ℕ) :
(geom_sum₂ (x + y) y n) * x + y ^ n = (x + y) ^ n :=
(commute.all x y).geom_sum₂_mul_add n
theorem geom_sum_mul_add [semiring α] (x : α) (n : ℕ) :
(geom_sum (x + 1) n) * x + 1 = (x + 1) ^ n :=
begin
have := (commute.one_right x).geom_sum₂_mul_add n,
rw [one_pow, geom_sum₂_with_one] at this,
exact this
end
protected theorem commute.geom_sum₂_mul [ring α] {x y : α} (h : commute x y) (n : ℕ) :
(geom_sum₂ x y n) * (x - y) = x ^ n - y ^ n :=
begin
have := (h.sub_left (commute.refl y)).geom_sum₂_mul_add n,
rw [sub_add_cancel] at this,
rw [← this, add_sub_cancel]
end
lemma commute.mul_neg_geom_sum₂ [ring α] {x y : α} (h : commute x y) (n : ℕ) :
(y - x) * (geom_sum₂ x y n) = y ^ n - x ^ n :=
begin
rw ← op_inj_iff,
simp only [op_mul, op_sub, op_geom_sum₂, op_pow],
exact (commute.op h.symm).geom_sum₂_mul n
end
lemma commute.mul_geom_sum₂ [ring α] {x y : α} (h : commute x y) (n : ℕ) :
(x - y) * (geom_sum₂ x y n) = x ^ n - y ^ n :=
by rw [← neg_sub (y ^ n), ← h.mul_neg_geom_sum₂, ← neg_mul_eq_neg_mul_symm, neg_sub]
theorem geom_sum₂_mul [comm_ring α] (x y : α) (n : ℕ) :
(geom_sum₂ x y n) * (x - y) = x ^ n - y ^ n :=
(commute.all x y).geom_sum₂_mul n
theorem geom_sum_mul [ring α] (x : α) (n : ℕ) :
(geom_sum x n) * (x - 1) = x ^ n - 1 :=
begin
have := (commute.one_right x).geom_sum₂_mul n,
rw [one_pow, geom_sum₂_with_one] at this,
exact this
end
lemma mul_geom_sum [ring α] (x : α) (n : ℕ) :
(x - 1) * (geom_sum x n) = x ^ n - 1 :=
begin
rw ← op_inj_iff,
simpa using geom_sum_mul (op x) n,
end
theorem geom_sum_mul_neg [ring α] (x : α) (n : ℕ) :
(geom_sum x n) * (1 - x) = 1 - x ^ n :=
begin
have := congr_arg has_neg.neg (geom_sum_mul x n),
rw [neg_sub, ← mul_neg_eq_neg_mul_symm, neg_sub] at this,
exact this
end
lemma mul_neg_geom_sum [ring α] (x : α) (n : ℕ) :
(1 - x) * (geom_sum x n) = 1 - x ^ n :=
begin
rw ← op_inj_iff,
simpa using geom_sum_mul_neg (op x) n,
end
protected theorem commute.geom_sum₂ [division_ring α] {x y : α} (h' : commute x y) (h : x ≠ y)
(n : ℕ) : (geom_sum₂ x y n) = (x ^ n - y ^ n) / (x - y) :=
have x - y ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *,
by rw [← h'.geom_sum₂_mul, mul_div_cancel _ this]
theorem geom₂_sum [field α] {x y : α} (h : x ≠ y) (n : ℕ) :
(geom_sum₂ x y n) = (x ^ n - y ^ n) / (x - y) :=
(commute.all x y).geom_sum₂ h n
theorem geom_sum_eq [division_ring α] {x : α} (h : x ≠ 1) (n : ℕ) :
(geom_sum x n) = (x ^ n - 1) / (x - 1) :=
have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *,
by rw [← geom_sum_mul, mul_div_cancel _ this]
protected theorem commute.mul_geom_sum₂_Ico [ring α] {x y : α} (h : commute x y) {m n : ℕ}
(hmn : m ≤ n) :
(x - y) * (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) = x ^ n - x ^ m * y ^ (n - m) :=
begin
rw [sum_Ico_eq_sub _ hmn, ← geom_sum₂_def],
have : ∑ k in range m, x ^ k * y ^ (n - 1 - k)
= ∑ k in range m, x ^ k * (y ^ (n - m) * y ^ (m - 1 - k)),
{ refine sum_congr rfl (λ j j_in, _),
rw ← pow_add,
congr,
rw [mem_range, nat.lt_iff_add_one_le, add_comm] at j_in,
have h' : n - m + (m - (1 + j)) = n - (1 + j) := nat.sub_add_sub_cancel hmn j_in,
rw [nat.sub_sub m, h', nat.sub_sub] },
rw this,
simp_rw pow_mul_comm y (n-m) _,
simp_rw ← mul_assoc,
rw [← sum_mul, ← geom_sum₂_def, mul_sub, h.mul_geom_sum₂, ← mul_assoc,
h.mul_geom_sum₂, sub_mul, ← pow_add, nat.add_sub_of_le hmn,
sub_sub_sub_cancel_right (x ^ n) (x ^ m * y ^ (n - m)) (y ^ n)],
end
protected theorem commute.geom_sum₂_succ_eq {α : Type u} [ring α] {x y : α}
(h : commute x y) {n : ℕ} :
geom_sum₂ x y (n + 1) = x ^ n + y * (geom_sum₂ x y n) :=
begin
simp_rw [geom_sum₂, mul_sum, sum_range_succ_comm, nat.add_succ_sub_one, add_zero, nat.sub_self,
pow_zero, mul_one, add_right_inj, ←mul_assoc, (h.symm.pow_right _).eq, mul_assoc, ←pow_succ],
refine sum_congr rfl (λ i hi, _),
suffices : n - 1 - i + 1 = n - i, { rw this },
cases n,
{ exact absurd (list.mem_range.mp hi) i.not_lt_zero },
{ rw [nat.sub_add_eq_add_sub (nat.le_pred_of_lt (list.mem_range.mp hi)),
nat.sub_add_cancel (nat.succ_le_iff.mpr n.succ_pos)] },
end
theorem geom_sum₂_succ_eq {α : Type u} [comm_ring α] (x y : α) {n : ℕ} :
geom_sum₂ x y (n + 1) = x ^ n + y * (geom_sum₂ x y n) :=
(commute.all x y).geom_sum₂_succ_eq
theorem mul_geom_sum₂_Ico [comm_ring α] (x y : α) {m n : ℕ} (hmn : m ≤ n) :
(x - y) * (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) = x ^ n - x ^ m * y ^ (n - m) :=
(commute.all x y).mul_geom_sum₂_Ico hmn
protected theorem commute.geom_sum₂_Ico_mul [ring α] {x y : α} (h : commute x y) {m n : ℕ}
(hmn : m ≤ n) :
(∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) * (x - y) = x ^ n - y ^ (n - m) * x ^ m :=
begin
rw ← op_inj_iff,
simp only [op_sub, op_mul, op_pow, op_sum],
have : ∑ k in Ico m n, op y ^ (n - 1 - k) * op x ^ k
= ∑ k in Ico m n, op x ^ k * op y ^ (n - 1 - k),
{ refine sum_congr rfl (λ k k_in, _),
apply commute.pow_pow (commute.op h.symm) },
rw this,
exact (commute.op h).mul_geom_sum₂_Ico hmn
end
theorem geom_sum_Ico_mul [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) :
(∑ i in finset.Ico m n, x ^ i) * (x - 1) = x^n - x^m :=
by rw [sum_Ico_eq_sub _ hmn, ← geom_sum_def, ← geom_sum_def, sub_mul,
geom_sum_mul, geom_sum_mul, sub_sub_sub_cancel_right]
theorem geom_sum_Ico_mul_neg [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) :
(∑ i in finset.Ico m n, x ^ i) * (1 - x) = x^m - x^n :=
by rw [sum_Ico_eq_sub _ hmn, ← geom_sum_def, ← geom_sum_def, sub_mul,
geom_sum_mul_neg, geom_sum_mul_neg, sub_sub_sub_cancel_left]
protected theorem commute.geom_sum₂_Ico [division_ring α] {x y : α} (h : commute x y) (hxy : x ≠ y)
{m n : ℕ} (hmn : m ≤ n) :
∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i) = (x ^ n - y ^ (n - m) * x ^ m ) / (x - y) :=
have x - y ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *,
by rw [← h.geom_sum₂_Ico_mul hmn, mul_div_cancel _ this]
theorem geom_sum₂_Ico [field α] {x y : α} (hxy : x ≠ y) {m n : ℕ} (hmn : m ≤ n) :
∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i) = (x ^ n - y ^ (n - m) * x ^ m ) / (x - y) :=
(commute.all x y).geom_sum₂_Ico hxy hmn
theorem geom_sum_Ico [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) :
∑ i in finset.Ico m n, x ^ i = (x ^ n - x ^ m) / (x - 1) :=
by simp only [sum_Ico_eq_sub _ hmn, (geom_sum_def _ _).symm, geom_sum_eq hx, div_sub_div_same,
sub_sub_sub_cancel_right]
theorem geom_sum_Ico' [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) :
∑ i in finset.Ico m n, x ^ i = (x ^ m - x ^ n) / (1 - x) :=
by { simp only [geom_sum_Ico hx hmn], convert neg_div_neg_eq (x^m - x^n) (1-x); abel }
lemma geom_sum_inv [division_ring α] {x : α} (hx1 : x ≠ 1) (hx0 : x ≠ 0) (n : ℕ) :
(geom_sum x⁻¹ n) = (x - 1)⁻¹ * (x - x⁻¹ ^ n * x) :=
have h₁ : x⁻¹ ≠ 1, by rwa [inv_eq_one_div, ne.def, div_eq_iff_mul_eq hx0, one_mul],
have h₂ : x⁻¹ - 1 ≠ 0, from mt sub_eq_zero.1 h₁,
have h₃ : x - 1 ≠ 0, from mt sub_eq_zero.1 hx1,
have h₄ : x * (x ^ n)⁻¹ = (x ^ n)⁻¹ * x :=
nat.rec_on n (by simp)
(λ n h, by rw [pow_succ, mul_inv_rev', ←mul_assoc, h, mul_assoc, mul_inv_cancel hx0, mul_assoc,
inv_mul_cancel hx0]),
begin
rw [geom_sum_eq h₁, div_eq_iff_mul_eq h₂, ← mul_right_inj' h₃,
← mul_assoc, ← mul_assoc, mul_inv_cancel h₃],
simp [mul_add, add_mul, mul_inv_cancel hx0, mul_assoc, h₄, sub_eq_add_neg, add_comm,
add_left_comm],
end
variables {β : Type*}
theorem ring_hom.map_geom_sum [semiring α] [semiring β] (x : α) (n : ℕ) (f : α →+* β) :
f (geom_sum x n) = geom_sum (f x) n :=
by simp [geom_sum_def, f.map_sum]
theorem ring_hom.map_geom_sum₂ [semiring α] [semiring β] (x y : α) (n : ℕ) (f : α →+* β) :
f (geom_sum₂ x y n) = geom_sum₂ (f x) (f y) n :=
by simp [geom_sum₂_def, f.map_sum]
/-! ### Geometric sum with `ℕ`-division -/
lemma nat.pred_mul_geom_sum_le (a b n : ℕ) :
(b - 1) * ∑ i in range n.succ, a/b^i ≤ a * b - a/b^n :=
calc
(b - 1) * (∑ i in range n.succ, a/b^i)
= ∑ i in range n, a/b^(i + 1) * b + a * b
- (∑ i in range n, a/b^i + a/b^n)
: by rw [nat.mul_sub_right_distrib, mul_comm, sum_mul, one_mul, sum_range_succ',
sum_range_succ, pow_zero, nat.div_one]
... ≤ ∑ i in range n, a/b^i + a * b - (∑ i in range n, a/b^i + a/b^n)
: begin
refine nat.sub_le_sub_right (add_le_add_right (sum_le_sum $ λ i _, _) _) _,
rw [pow_succ', ←nat.div_div_eq_div_mul],
exact nat.div_mul_le_self _ _,
end
... = a * b - a/b^n : nat.add_sub_add_left _ _ _
lemma nat.geom_sum_le {b : ℕ} (hb : 2 ≤ b) (a n : ℕ) :
∑ i in range n, a/b^i ≤ a * b/(b - 1) :=
begin
refine (nat.le_div_iff_mul_le _ _ $ nat.sub_pos_of_lt hb).2 _,
cases n,
{ rw [sum_range_zero, zero_mul],
exact nat.zero_le _ },
rw mul_comm,
exact (nat.pred_mul_geom_sum_le a b n).trans (nat.sub_le_self _ _),
end
lemma nat.geom_sum_Ico_le {b : ℕ} (hb : 2 ≤ b) (a n : ℕ) :
∑ i in Ico 1 n, a/b^i ≤ a/(b - 1) :=
begin
cases n,
{ rw [Ico.eq_empty_of_le zero_le_one, sum_empty],
exact nat.zero_le _ },
rw ←add_le_add_iff_left a,
calc
a + ∑ (i : ℕ) in Ico 1 n.succ, a/b^i
= a/b^0 + ∑ (i : ℕ) in Ico 1 n.succ, a/b^i : by rw [pow_zero, nat.div_one]
... = ∑ i in range n.succ, a/b^i : begin
rw [range_eq_Ico, ←finset.Ico.insert_succ_bot (nat.succ_pos _), sum_insert],
exact λ h, zero_lt_one.not_le (Ico.mem.1 h).1,
end
... ≤ a * b/(b - 1) : nat.geom_sum_le hb a _
... = (a * 1 + a * (b - 1))/(b - 1)
: by rw [←mul_add, nat.add_sub_cancel' (one_le_two.trans hb)]
... = a + a/(b - 1)
: by rw [mul_one, nat.add_mul_div_right _ _ (nat.sub_pos_of_lt hb), add_comm]
end
|
dfea31040c9669669ec64c81189842a68a5a4a4a | ec62863c729b7eedee77b86d974f2c529fa79d25 | /25/a.lean | de477c52f07f8aca272534fa915a293e1b92f987 | [] | no_license | rwbarton/advent-of-lean-4 | 2ac9b17ba708f66051e3d8cd694b0249bc433b65 | 417c7e2718253ba7148c0279fcb251b6fc291477 | refs/heads/main | 1,675,917,092,057 | 1,609,864,581,000 | 1,609,864,581,000 | 317,700,289 | 24 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 438 | lean | @[reducible, inline] def modulus := 20201227
def main : IO Unit := do
let input ← IO.FS.lines "a.in"
let pub₁ := input[0].toNat!
let pub₂ := input[1].toNat!
let mut dlog : Array Nat := Array.mkArray modulus 0
let mut pow := 1
for j in [0:modulus-1] do
dlog := dlog.set! pow j
pow := (7 * pow) % modulus
let priv₁ := dlog[pub₁]
let mut key := 1
for j in [0:priv₁] do
key := (pub₂ * key) % modulus
IO.print s!"{key}\n"
|
fcad944771ebfd64d8b9c04e85f1a7cc18874fe5 | 4fa118f6209450d4e8d058790e2967337811b2b5 | /src/examples/padics.lean | ab1b4e06b651377c262fb2f199e6164d1bf2a2aa | [
"Apache-2.0"
] | permissive | leanprover-community/lean-perfectoid-spaces | 16ab697a220ed3669bf76311daa8c466382207f7 | 95a6520ce578b30a80b4c36e36ab2d559a842690 | refs/heads/master | 1,639,557,829,139 | 1,638,797,866,000 | 1,638,797,866,000 | 135,769,296 | 96 | 10 | Apache-2.0 | 1,638,797,866,000 | 1,527,892,754,000 | Lean | UTF-8 | Lean | false | false | 11,553 | lean | import data.padics
import for_mathlib.ideal_operations
import for_mathlib.normed_spaces
import for_mathlib.nnreal
import for_mathlib.padics
import adic_space
/-!
# The p-adics form a Huber ring
In this file we show that ℤ_[p] and ℚ_[p] are Huber rings.
They are the fundamental examples of Huber rings.
We also show that (ℚ_[p], ℤ_[p]) is a Huber pair,
and that its adic spectrum is a singleton,
consisting of the standard p-adic valuation on ℚ_[p].
-/
noncomputable theory
open_locale classical
local postfix `⁺` : 66 := λ A : Huber_pair, A.plus
open local_ring
local attribute [instance] padic_int.algebra
variables (p : ℕ) [nat.prime p]
namespace padic_int
/-- The topology on ℤ_[p] is adic with respect to the maximal ideal.-/
lemma is_adic : is_ideal_adic (nonunits_ideal ℤ_[p]) :=
begin
rw is_ideal_adic_iff,
split,
{ intro n,
show is_open (↑(_ : ideal ℤ_[p]) : set ℤ_[p]),
rw power_nonunits_ideal_eq_norm_le_pow,
simp only [norm_le_pow_iff_norm_lt_pow_succ],
rw ← ball_0_eq,
exact metric.is_open_ball },
{ intros s hs,
rcases metric.mem_nhds_iff.mp hs with ⟨ε, ε_pos, hε⟩,
obtain ⟨n, hn⟩ : ∃ n : ℕ, (p : ℝ)^-(n:ℤ) < ε,
{ have hp : (1:ℝ) < p := by exact_mod_cast nat.prime.one_lt ‹_›,
obtain ⟨n, hn⟩ : ∃ (n:ℕ), ε⁻¹ < p^n := pow_unbounded_of_one_lt ε⁻¹ hp,
use n,
have hp' : (0:ℝ) < p^n,
{ rw ← fpow_of_nat, apply fpow_pos_of_pos, exact_mod_cast nat.prime.pos ‹_› },
rw [inv_lt ε_pos hp', inv_eq_one_div] at hn,
rwa [fpow_neg, fpow_of_nat], },
use n, show (↑(_ : ideal ℤ_[p]) : set ℤ_[p]) ⊆ _,
refine set.subset.trans _ hε,
rw power_nonunits_ideal_eq_norm_le_pow,
rw ball_0_eq,
intros x hx,
rw set.mem_set_of_eq at *,
exact lt_of_le_of_lt hx hn }
end
section
open polynomial
lemma is_integrally_closed : is_integrally_closed ℤ_[p] ℚ_[p] :=
{ inj := subtype.val_injective,
closed :=
begin
rintros x ⟨f, f_monic, hf⟩,
have bleh : eval₂ (algebra_map ℚ_[p]) x ((finset.range (nat_degree f)).sum (λ (i : ℕ), C (coeff f i) * X^i)) =
((finset.range (nat_degree f)).sum (λ (i : ℕ), eval₂ (algebra_map ℚ_[p]) x $ C (coeff f i) * X^i)),
{ exact (finset.sum_hom _ _).symm },
erw subtype.val_range,
show ∥x∥ ≤ 1,
rw [f_monic.as_sum, aeval_def, eval₂_add, eval₂_pow, eval₂_X] at hf,
rw [bleh] at hf,
replace hf := congr_arg (@has_norm.norm ℚ_[p] _) hf,
contrapose! hf with H,
apply ne_of_gt,
rw [norm_zero, padic_norm_e.add_eq_max_of_ne],
{ apply lt_of_lt_of_le _ (le_max_left _ _),
rw [← fpow_of_nat, normed_field.norm_fpow],
apply fpow_pos_of_pos,
exact lt_trans zero_lt_one H, },
{ apply ne_of_gt,
apply lt_of_le_of_lt (padic.norm_sum _ _),
rw finset.fold_max_lt,
split,
{ rw [← fpow_of_nat, normed_field.norm_fpow], apply fpow_pos_of_pos, exact lt_trans zero_lt_one H },
{ intros i hi,
suffices : ∥algebra_map ℚ_[p] (coeff f i)∥ * ∥x∥ ^ i < ∥x∥ ^ nat_degree f,
by simpa [eval₂_pow],
refine lt_of_le_of_lt (mul_le_of_le_one_left _ _ : _ ≤ ∥x∥ ^ i) _,
{ rw [← fpow_of_nat], apply fpow_nonneg_of_nonneg, exact norm_nonneg _ },
{ exact (coeff f i).property },
{ rw [← fpow_of_nat, ← fpow_of_nat, (fpow_strict_mono H).lt_iff_lt],
rw finset.mem_range at hi, exact_mod_cast hi, } } }
end }
end
/-- The p-adic integers (ℤ_[p])form a Huber ring.-/
instance : Huber_ring ℤ_[p] :=
{ pod := ⟨ℤ_[p], infer_instance, infer_instance, by apply_instance,
⟨{ emb := open_embedding_id,
J := (nonunits_ideal _),
fin := nonunits_ideal_fg p,
top := is_adic p,
.. algebra.id ℤ_[p] }⟩⟩ }
end padic_int
section
--move this
variables {α : Type*} {β : Type*} [topological_space α] [topological_space β]
lemma is_open_map.image_nhds {f : α → β} (hf : is_open_map f)
{x : α} {U : set α} (hU : U ∈ nhds x) : f '' U ∈ nhds (f x) :=
begin
apply (is_open_map_iff_nhds_le).mp hf x,
change f ⁻¹' (f '' U) ∈ nhds x,
filter_upwards [hU],
exact set.subset_preimage_image f U
end
end
open local_ring set padic_int
/-- The p-adic numbers (ℚ_[p]) form a Huber ring.-/
instance padic.Huber_ring : Huber_ring ℚ_[p] :=
{ pod := ⟨ℤ_[p], infer_instance, infer_instance, by apply_instance,
⟨{ emb := coe_open_embedding,
J := (nonunits_ideal _),
fin := nonunits_ideal_fg p,
top := is_adic p,
.. padic_int.algebra }⟩⟩ }
/-- The p-adic numbers form a Huber pair (with the p-adic integers as power bounded subring).-/
@[reducible] def padic.Huber_pair : Huber_pair :=
{ plus := ℤ_[p],
carrier := ℚ_[p],
intel :=
{ is_power_bounded :=
begin
-- this entire goal ought to follow from some is_bounded.map lemma
-- but we didn't prove that.
suffices : is_bounded {x : ℚ_[p] | ∥x∥ ≤ 1},
{ rintro _ ⟨x, rfl⟩,
show is_power_bounded (x:ℚ_[p]),
refine is_bounded.subset _ this,
rintro y ⟨n, rfl⟩,
show ∥(x:ℚ_[p])^n∥ ≤ 1,
rw normed_field.norm_pow,
exact pow_le_one _ (norm_nonneg _) x.property, },
have bnd := is_adic.is_bounded ⟨_, is_adic p⟩,
intros U hU,
rcases bnd ((coe : ℤ_[p] → ℚ_[p]) ⁻¹' U) _ with ⟨V, hV, H⟩,
{ use [(coe : ℤ_[p] → ℚ_[p]) '' V,
coe_open_embedding.is_open_map.image_nhds hV],
rintros _ ⟨v, v_in, rfl⟩ b hb,
specialize H v v_in ⟨b, hb⟩ (mem_univ _),
rwa [mem_preimage, coe_mul] at H },
{ rw ← coe_zero at hU,
exact continuous_coe.continuous_at hU }
end
.. coe_open_embedding,
.. is_integrally_closed p } }
.
-- Valuations take values in a linearly ordered monoid with a minimal element 0,
-- whereas norms in mathlib are defined to take values in ℝ.
-- This is a repackaging of the p-adic norm as a valuation with values in the non-negative reals.
/-- The standard p-adic valuation. -/
def padic.bundled_valuation : valuation ℚ_[p] nnreal :=
{ to_fun := λ x, ⟨∥x∥, norm_nonneg _⟩,
map_zero' := subtype.val_injective norm_zero,
map_one' := subtype.val_injective normed_field.norm_one,
map_mul' := λ x y, subtype.val_injective $ normed_field.norm_mul _ _,
map_add' := λ x y,
begin
apply le_trans (padic_norm_e.nonarchimedean x y),
rw max_le_iff,
simp [nnreal.coe_max],
split,
{ apply le_trans (le_max_left ∥x∥ ∥y∥),
apply le_of_eq, symmetry, convert nnreal.coe_max _ _,
delta classical.DLO nnreal.decidable_linear_order real.decidable_linear_order,
congr, },
{ apply le_trans (le_max_right ∥x∥ ∥y∥),
apply le_of_eq, symmetry, convert nnreal.coe_max _ _,
delta classical.DLO nnreal.decidable_linear_order real.decidable_linear_order,
congr, },
end }
namespace valuation
variables {R : Type*} [comm_ring R]
variables {K : Type*} [discrete_field K]
variables {L : Type*} [discrete_field L] [topological_space L]
variables {Γ₀ : Type*} [linear_ordered_comm_group_with_zero Γ₀]
variables {Γ'₀ : Type*} [linear_ordered_comm_group_with_zero Γ'₀]
--move this
-- This is a hack, to avoid an fpow diamond.
lemma map_fpow_eq_one_iff {v : valuation K Γ₀} {x : K} (n : ℤ) (hn : n ≠ 0) :
v (x^n) = 1 ↔ v x = 1 :=
begin
have helper : ∀ x (n : ℕ), n ≠ 0 → (v (x^n) = 1 ↔ v x = 1),
{ clear hn n x, intros x n hn,
erw [is_monoid_hom.map_pow v.to_monoid_hom],
cases n, { contradiction, },
show (v x)^(n+1) = 1 ↔ v x = 1,
by_cases hx : x = 0, { rw [hx, v.map_zero, pow_succ, zero_mul], },
change x ≠ 0 at hx,
rw ← v.ne_zero_iff at hx,
let u : units Γ₀ := group_with_zero.mk₀ _ hx,
suffices : u^(n+1) = 1 ↔ u = 1,
{ rwa [units.ext_iff, units.ext_iff, units.coe_pow] at this, },
split; intro h,
{ exact linear_ordered_structure.eq_one_of_pow_eq_one (nat.succ_ne_zero _) h },
{ rw [h, one_pow], } },
by_cases hn' : 0 ≤ n,
{ lift n to ℕ using hn', rw [fpow_of_nat], norm_cast at hn, solve_by_elim },
{ push_neg at hn', rw ← neg_pos at hn',
lift -n to ℕ using le_of_lt hn' with m hm,
have hm' : m ≠ 0, { apply ne_of_gt, exact_mod_cast hn' },
rw [← neg_neg n, ← mul_neg_one, fpow_mul, fpow_inv, v.map_inv, ← inv_one',
inv_inj'', ← hm, inv_one'], solve_by_elim }
end
end valuation
--move this
lemma padic.not_discrete : ¬ discrete_topology ℚ_[p] :=
nondiscrete_normed_field.nondiscrete
--move this
lemma padic_int.not_discrete : ¬ discrete_topology ℤ_[p] :=
begin
assume h,
replace h := topological_add_group.discrete_iff_open_zero.mp h,
apply padic.not_discrete p,
refine topological_add_group.discrete_iff_open_zero.mpr _,
have := coe_open_embedding.is_open_map _ h,
rw image_singleton at this,
exact_mod_cast this
end
/-- The adic spectrum Spa(ℚ_p, ℤ_p) is inhabited. -/
def padic.Spa_inhabited : inhabited (Spa $ padic.Huber_pair p) :=
{ default := ⟨Spv.mk (padic.bundled_valuation p),
begin
refine mk_mem_spa.mpr _,
split,
{ rw valuation.is_continuous_iff,
rintro y,
change is_open {x : ℚ_[p] | ∥x∥ < ∥y∥ },
rw ← ball_0_eq,
exact metric.is_open_ball },
{ intro x, change ℤ_[p] at x, exact x.property },
end⟩ }
/-- The adic spectrum Spa(ℚ_p, ℤ_p) is a singleton:
the only element is the standard p-adic valuation. -/
def padic.Spa_unique : unique (Spa $ padic.Huber_pair p) :=
{ uniq :=
begin
intros v,
change spa (padic.Huber_pair p) at v,
ext,
refine valuation.is_equiv.trans _ (Spv.out_mk _).symm,
apply valuation.is_equiv_of_val_le_one,
intros x, change ℚ_[p] at x,
split; intro h,
{ by_cases hx : ∃ y : ℤ_[p], x = y,
{ rcases hx with ⟨x, rfl⟩, exact x.property },
{ push_neg at hx,
contrapose! h,
obtain ⟨y, hy⟩ : ∃ y : ℤ_[p], x⁻¹ = y,
{ refine ⟨⟨x⁻¹, _⟩, rfl⟩, rw normed_field.norm_inv, apply inv_le_one, apply le_of_lt, exact h },
refine (linear_ordered_structure.inv_lt_inv _ _).mp _,
{ rw valuation.ne_zero_iff, contrapose! hx, use [0, hx] },
{ exact one_ne_zero },
{ rw [inv_one', ← valuation.map_inv, hy],
refine lt_of_le_of_ne (v.map_plus y) _,
assume H,
apply padic.not_discrete p,
apply (valuation.is_continuous_iff_discrete_of_is_trivial _ _).mp v.is_continuous,
rw valuation.is_trivial_iff_val_le_one,
intro z,
by_cases hx' : x = 0, { contrapose! h, simp [hx'], },
rcases padic.exists_repr x hx' with ⟨u, m, rfl⟩, clear hx',
by_cases hz : z = 0, { simp [hz], },
rcases padic.exists_repr z hz with ⟨v, n, rfl⟩, clear hz,
erw [valuation.map_mul, spa.map_unit, one_mul],
by_cases hn : n = 0, { erw [hn, fpow_zero, valuation.map_one], },
erw [← hy, valuation.map_inv, valuation.map_mul, spa.map_unit,
one_mul, ← inv_one', inv_inj'',
valuation.map_fpow_eq_one_iff, ← valuation.map_fpow_eq_one_iff n hn] at H,
{ exact le_of_eq H, },
contrapose! h,
rw [h, fpow_zero, mul_one, ← nnreal.coe_le], apply le_of_eq,
erw ← padic_int.is_unit_iff, exact is_unit_unit _, } } },
{ exact spa.map_plus v ⟨x, h⟩, }
end,
.. padic.Spa_inhabited p }
|
c5e4c9b002eb6ff040e6373b3ffdfedd69c04481 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/monoidal/limits.lean | 89112c519d5239f6cbfed339c576d25be0d1fc2f | [] | 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,234 | 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.functorial
import Mathlib.category_theory.monoidal.functor_category
import Mathlib.category_theory.limits.limits
import Mathlib.PostPort
universes u v
namespace Mathlib
/-!
# `lim : (J ⥤ C) ⥤ C` is lax monoidal when `C` is a monoidal category.
When `C` is a monoidal category, the functorial association `F ↦ limit F` is lax monoidal,
i.e. there are morphisms
* `lim_lax.ε : (𝟙_ C) → limit (𝟙_ (J ⥤ C))`
* `lim_lax.μ : limit F ⊗ limit G ⟶ limit (F ⊗ G)`
satisfying the laws of a lax monoidal functor.
-/
namespace category_theory.limits
protected instance limit_functorial {J : Type v} [small_category J] {C : Type u} [category C] [has_limits C] : functorial fun (F : J ⥤ C) => limit F :=
functorial.mk (functor.map lim)
@[simp] theorem limit_functorial_map {J : Type v} [small_category J] {C : Type u} [category C] [has_limits C] {F : J ⥤ C} {G : J ⥤ C} (α : F ⟶ G) : map (fun (F : J ⥤ C) => limit F) α = functor.map lim α :=
rfl
protected instance limit_lax_monoidal {J : Type v} [small_category J] {C : Type u} [category C] [has_limits C] [monoidal_category C] : lax_monoidal fun (F : J ⥤ C) => limit F :=
lax_monoidal.mk (limit.lift (functor.obj (functor.const J) 𝟙_) (cone.mk 𝟙_ (nat_trans.mk fun (j : J) => 𝟙)))
fun (F G : J ⥤ C) =>
limit.lift (F ⊗ G) (cone.mk (limit F ⊗ limit G) (nat_trans.mk fun (j : J) => limit.π F j ⊗ limit.π G j))
/-- The limit functor `F ↦ limit F` bundled as a lax monoidal functor. -/
def lim_lax {J : Type v} [small_category J] {C : Type u} [category C] [has_limits C] [monoidal_category C] : lax_monoidal_functor (J ⥤ C) C :=
lax_monoidal_functor.of fun (F : J ⥤ C) => limit F
@[simp] theorem lim_lax_obj {J : Type v} [small_category J] {C : Type u} [category C] [has_limits C] [monoidal_category C] (F : J ⥤ C) : functor.obj (lax_monoidal_functor.to_functor lim_lax) F = limit F :=
rfl
theorem lim_lax_obj' {J : Type v} [small_category J] {C : Type u} [category C] [has_limits C] [monoidal_category C] (F : J ⥤ C) : functor.obj (lax_monoidal_functor.to_functor lim_lax) F = functor.obj lim F :=
rfl
@[simp] theorem lim_lax_map {J : Type v} [small_category J] {C : Type u} [category C] [has_limits C] [monoidal_category C] {F : J ⥤ C} {G : J ⥤ C} (α : F ⟶ G) : functor.map (lax_monoidal_functor.to_functor lim_lax) α = functor.map lim α :=
rfl
@[simp] theorem lim_lax_ε {J : Type v} [small_category J] {C : Type u} [category C] [has_limits C] [monoidal_category C] : lax_monoidal_functor.ε lim_lax =
limit.lift (functor.obj (functor.const J) 𝟙_) (cone.mk 𝟙_ (nat_trans.mk fun (j : J) => 𝟙)) :=
rfl
@[simp] theorem lim_lax_μ {J : Type v} [small_category J] {C : Type u} [category C] [has_limits C] [monoidal_category C] (F : J ⥤ C) (G : J ⥤ C) : lax_monoidal_functor.μ lim_lax F G =
limit.lift (F ⊗ G) (cone.mk (limit F ⊗ limit G) (nat_trans.mk fun (j : J) => limit.π F j ⊗ limit.π G j)) :=
rfl
|
bebcf7b33e81b002ecfb06a8cb68e435ff7d9042 | c09f5945267fd905e23a77be83d9a78580e04a4a | /src/ring_theory/localization.lean | aca005974cffd6e985c3e0985a94a9eddba60be8 | [
"Apache-2.0"
] | permissive | OHIHIYA20/mathlib | 023a6df35355b5b6eb931c404f7dd7535dccfa89 | 1ec0a1f49db97d45e8666a3bf33217ff79ca1d87 | refs/heads/master | 1,587,964,529,965 | 1,551,819,319,000 | 1,551,819,319,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,410 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro
-/
import tactic.ring data.quot ring_theory.ideal_operations group_theory.submonoid
universes u v
namespace localization
variables (α : Type u) [comm_ring α] (S : set α) [is_submonoid S]
def r (x y : α × S) : Prop :=
∃ t ∈ S, ((x.2 : α) * y.1 - y.2 * x.1) * t = 0
local infix ≈ := r α S
section
variables {α S}
theorem r_of_eq {a₀ a₁ : α × S} (h : (a₀.2 : α) * a₁.1 = a₁.2 * a₀.1) : a₀ ≈ a₁ :=
⟨1, is_submonoid.one_mem S, by rw [h, sub_self, mul_one]⟩
end
theorem refl (x : α × S) : x ≈ x := r_of_eq rfl
theorem symm (x y : α × S) : x ≈ y → y ≈ x :=
λ ⟨t, hts, ht⟩, ⟨t, hts, by rw [← neg_sub, ← neg_mul_eq_neg_mul, ht, neg_zero]⟩
theorem trans : ∀ (x y z : α × S), x ≈ y → y ≈ z → x ≈ z :=
λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨t, hts, ht⟩ ⟨t', hts', ht'⟩,
⟨s₂ * t' * t, is_submonoid.mul_mem (is_submonoid.mul_mem hs₂ hts') hts,
calc (s₁ * r₃ - s₃ * r₁) * (s₂ * t' * t) =
t' * s₃ * ((s₁ * r₂ - s₂ * r₁) * t) + t * s₁ * ((s₂ * r₃ - s₃ * r₂) * t') :
by simp [mul_left_comm, mul_add, mul_comm]
... = 0 : by simp only [subtype.coe_mk] at ht ht'; rw [ht, ht']; simp⟩
instance : setoid (α × S) :=
⟨r α S, refl α S, symm α S, trans α S⟩
def loc := quotient $ localization.setoid α S
instance : has_add (loc α S) :=
⟨quotient.lift₂
(λ x y : α × S, (⟦⟨x.2 * y.1 + y.2 * x.1, x.2 * y.2⟩⟧ : loc α S)) $
λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩,
quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅,
calc (s₁ * s₂ * (s₃ * r₄ + s₄ * r₃) - s₃ * s₄ * (s₁ * r₂ + s₂ * r₁)) * (t₆ * t₅) =
s₁ * s₃ * ((s₂ * r₄ - s₄ * r₂) * t₆) * t₅ + s₂ * s₄ * ((s₁ * r₃ - s₃ * r₁) * t₅) * t₆ : by ring
... = 0 : by simp only [subtype.coe_mk] at ht₅ ht₆; rw [ht₆, ht₅]; simp⟩⟩
instance : has_neg (loc α S) :=
⟨quotient.lift (λ x : α × S, (⟦⟨-x.1, x.2⟩⟧ : loc α S)) $
λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩,
quotient.sound ⟨t, hts,
calc (s₁ * -r₂ - s₂ * -r₁) * t = -((s₁ * r₂ - s₂ * r₁) * t) : by ring
... = 0 : by simp only [subtype.coe_mk] at ht; rw ht; simp⟩⟩
instance : has_mul (loc α S) :=
⟨quotient.lift₂
(λ x y : α × S, (⟦⟨x.1 * y.1, x.2 * y.2⟩⟧ : loc α S)) $
λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩,
quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅,
calc ((s₁ * s₂) * (r₃ * r₄) - (s₃ * s₄) * (r₁ * r₂)) * (t₆ * t₅) =
t₆ * ((s₁ * r₃ - s₃ * r₁) * t₅) * r₂ * s₄ + t₅ * ((s₂ * r₄ - s₄ * r₂) * t₆) * r₃ * s₁ :
by simp [mul_left_comm, mul_add, mul_comm]
... = 0 : by simp only [subtype.coe_mk] at ht₅ ht₆; rw [ht₅, ht₆]; simp⟩⟩
variables {α S}
def mk (r : α) (s : S) : loc α S := ⟦(r, s)⟧
def of (r : α) : loc α S := mk r 1
instance : comm_ring (loc α S) :=
by refine
{ add := has_add.add,
add_assoc := λ m n k, quotient.induction_on₃ m n k _,
zero := of 0,
zero_add := quotient.ind _,
add_zero := quotient.ind _,
neg := has_neg.neg,
add_left_neg := quotient.ind _,
add_comm := quotient.ind₂ _,
mul := has_mul.mul,
mul_assoc := λ m n k, quotient.induction_on₃ m n k _,
one := of 1,
one_mul := quotient.ind _,
mul_one := quotient.ind _,
left_distrib := λ m n k, quotient.induction_on₃ m n k _,
right_distrib := λ m n k, quotient.induction_on₃ m n k _,
mul_comm := quotient.ind₂ _ };
{ intros,
try {rcases a with ⟨r₁, s₁, hs₁⟩},
try {rcases b with ⟨r₂, s₂, hs₂⟩},
try {rcases c with ⟨r₃, s₃, hs₃⟩},
refine (quotient.sound $ r_of_eq _),
simp [mul_left_comm, mul_add, mul_comm] }
instance of.is_ring_hom : is_ring_hom (of : α → loc α S) :=
{ map_add := λ x y, quotient.sound $ by simp,
map_mul := λ x y, quotient.sound $ by simp,
map_one := rfl }
variables {S}
instance : has_coe α (loc α S) := ⟨of⟩
instance coe.is_ring_hom : is_ring_hom (coe : α → loc α S) :=
localization.of.is_ring_hom
section
variables (α S) (x y : α) (n : ℕ)
@[simp] lemma of_zero : (of 0 : loc α S) = 0 := rfl
@[simp] lemma of_one : (of 1 : loc α S) = 1 := rfl
@[simp] lemma of_add : (of (x + y) : loc α S) = of x + of y :=
by apply is_ring_hom.map_add
@[simp] lemma of_sub : (of (x - y) : loc α S) = of x - of y :=
by apply is_ring_hom.map_sub
@[simp] lemma of_mul : (of (x * y) : loc α S) = of x * of y :=
by apply is_ring_hom.map_mul
@[simp] lemma of_neg : (of (-x) : loc α S) = -of x :=
by apply is_ring_hom.map_neg
@[simp] lemma of_pow : (of (x ^ n) : loc α S) = (of x) ^ n :=
by apply is_semiring_hom.map_pow
@[simp] lemma coe_zero : ((0 : α) : loc α S) = 0 := rfl
@[simp] lemma coe_one : ((1 : α) : loc α S) = 1 := rfl
@[simp] lemma coe_add : (↑(x + y) : loc α S) = x + y := of_add _ _ _ _
@[simp] lemma coe_sub : (↑(x - y) : loc α S) = x - y := of_sub _ _ _ _
@[simp] lemma coe_mul : (↑(x * y) : loc α S) = x * y := of_mul _ _ _ _
@[simp] lemma coe_neg : (↑(-x) : loc α S) = -x := of_neg _ _ _
@[simp] lemma coe_pow : (↑(x ^ n) : loc α S) = x ^ n := of_pow _ _ _ _
end
@[simp] lemma mk_self {x : α} {hx : x ∈ S} :
(mk x ⟨x, hx⟩ : loc α S) = 1 :=
quotient.sound ⟨1, is_submonoid.one_mem S,
by simp only [subtype.coe_mk, is_submonoid.coe_one, mul_one, one_mul, sub_self]⟩
@[simp] lemma mk_self' {s : S} :
(mk s s : loc α S) = 1 :=
by cases s; exact mk_self
@[simp] lemma mk_self'' {s : S} :
(mk s.1 s : loc α S) = 1 :=
mk_self'
@[simp] lemma coe_mul_mk (x y : α) (s : S) :
↑x * mk y s = mk (x * y) s :=
quotient.sound $ r_of_eq $ by rw one_mul
lemma mk_eq_mul_mk_one (r : α) (s : S) :
mk r s = r * mk 1 s :=
by rw [coe_mul_mk, mul_one]
@[simp] lemma mk_mul_mk (x y : α) (s t : S) :
mk x s * mk y t = mk (x * y) (s * t) := rfl
@[simp] lemma mk_mul_cancel_left (r : α) (s : S) :
mk (↑s * r) s = r :=
by rw [mk_eq_mul_mk_one, mul_comm ↑s, coe_mul,
mul_assoc, ← mk_eq_mul_mk_one, mk_self', mul_one]
@[simp] lemma mk_mul_cancel_right (r : α) (s : S) :
mk (r * s) s = r :=
by rw [mul_comm, mk_mul_cancel_left]
@[elab_as_eliminator]
protected theorem induction_on {C : loc α S → Prop} (x : loc α S)
(ih : ∀ r s, C (mk r s : loc α S)) : C x :=
by rcases x with ⟨r, s⟩; exact ih r s
@[elab_with_expected_type]
protected def rec {β : Type v} [comm_ring β]
(f : α → β) [hf : is_ring_hom f] (g : S → units β) (hg : ∀ s, (g s : β) = f s)
(x : loc α S) : β :=
quotient.lift_on x (λ p, f p.1 * ((g p.2)⁻¹ : units β)) $ λ ⟨r₁, s₁⟩ ⟨r₂, s₂⟩ ⟨t, hts, ht⟩,
show f r₁ * ↑(g s₁)⁻¹ = f r₂ * ↑(g s₂)⁻¹, from
calc f r₁ * ↑(g s₁)⁻¹
= (f r₁ * g s₂ + ((g s₁ * f r₂ - g s₂ * f r₁) * g ⟨t, hts⟩) * ↑(g ⟨t, hts⟩)⁻¹) * ↑(g s₁)⁻¹ * ↑(g s₂)⁻¹ :
by simp only [hg, subtype.coe_mk, (is_ring_hom.map_mul f).symm, (is_ring_hom.map_sub f).symm, ht, is_ring_hom.map_zero f,
zero_mul, add_zero]; rw [is_ring_hom.map_mul f, ← hg, mul_right_comm, mul_assoc (f r₁), ← units.coe_mul, mul_inv_self];
rw [units.coe_one, mul_one]
... = f r₂ * ↑(g s₂)⁻¹ :
by rw [mul_assoc, mul_assoc, ← units.coe_mul, mul_inv_self, units.coe_one, mul_one, mul_comm ↑(g s₂), add_sub_cancel'_right];
rw [mul_comm ↑(g s₁), ← mul_assoc, mul_assoc (f r₂), ← units.coe_mul, mul_inv_self, units.coe_one, mul_one]
instance rec.is_ring_hom {β : Type v} [comm_ring β]
(f : α → β) [hf : is_ring_hom f] (g : S → units β) (hg : ∀ s, (g s : β) = f s) :
is_ring_hom (localization.rec f g hg) :=
{ map_one := have g 1 = 1, from units.ext (by rw hg; exact is_ring_hom.map_one f),
show f 1 * ↑(g 1)⁻¹ = 1, by rw [this, one_inv, units.coe_one, mul_one, is_ring_hom.map_one f],
map_mul := λ x y, localization.induction_on x $ λ r₁ s₁,
localization.induction_on y $ λ r₂ s₂,
have g (s₁ * s₂) = g s₁ * g s₂, from units.ext (by simp only [hg, units.coe_mul]; exact is_ring_hom.map_mul f),
show _ * ↑(g (_ * _))⁻¹ = (_ * _) * (_ * _),
by simp only [subtype.coe_mk, mul_one, one_mul, subtype.coe_eta, this, mul_inv_rev];
rw [is_ring_hom.map_mul f, units.coe_mul, ← mul_assoc, ← mul_assoc];
simp only [mul_right_comm],
map_add := λ x y, localization.induction_on x $ λ r₁ s₁,
localization.induction_on y $ λ r₂ s₂,
have g (s₁ * s₂) = g s₁ * g s₂, from units.ext (by simp only [hg, units.coe_mul]; exact is_ring_hom.map_mul f),
show _ * ↑(g (_ * _))⁻¹ = _ * _ + _ * _,
by simp only [subtype.coe_mk, mul_one, one_mul, subtype.coe_eta, this, mul_inv_rev];
simp only [is_ring_hom.map_mul f, is_ring_hom.map_add f, add_mul, (hg _).symm];
simp only [mul_assoc, mul_comm, mul_left_comm, (units.coe_mul _ _).symm];
rw [mul_inv_cancel_left, mul_left_comm, ← mul_assoc, mul_inv_cancel_right, add_comm] }
@[reducible] def away (x : α) := loc α (powers x)
@[simp] def away.inv_self (x : α) : away x :=
mk 1 ⟨x, 1, pow_one x⟩
@[elab_with_expected_type]
protected noncomputable def away.rec {x : α} {β : Type v} [comm_ring β]
(f : α → β) [hf : is_ring_hom f] (hfx : is_unit (f x)) : away x → β :=
localization.rec f (λ s, classical.some hfx ^ classical.some s.2) $ λ s,
by rw [units.coe_pow, ← classical.some_spec hfx, ← is_semiring_hom.map_pow f, classical.some_spec s.2]; refl
noncomputable def away_to_away_right (x y : α) : away x → away (x * y) :=
localization.away.rec coe $
is_unit_of_mul_one x (y * away.inv_self (x * y)) $
by rw [away.inv_self, coe_mul_mk, coe_mul_mk, mul_one, mk_self]
instance away.rec.is_ring_hom {x : α} {β : Type v} [comm_ring β]
(f : α → β) [hf : is_ring_hom f] (hfx : is_unit (f x)) :
is_ring_hom (localization.away.rec f hfx) :=
rec.is_ring_hom _ _ _
instance away_to_away_right.is_ring_hom (x y : α) :
is_ring_hom (away_to_away_right x y) :=
away.rec.is_ring_hom _ _
section at_prime
variables (P : ideal α) [hp : ideal.is_prime P]
include hp
instance prime.is_submonoid :
is_submonoid (-P : set α) :=
{ one_mem := P.ne_top_iff_one.1 hp.1,
mul_mem := λ x y hnx hny hxy, or.cases_on (hp.2 hxy) hnx hny }
@[reducible] def at_prime := loc α (-P)
instance at_prime.local_ring : is_local_ring (at_prime P) :=
local_of_nonunits_ideal
(λ hze,
let ⟨t, hts, ht⟩ := quotient.exact hze in
hts $ have htz : t = 0, by simpa using ht,
suffices (0:α) ∈ P, by rwa htz,
P.zero_mem)
(begin
rintro ⟨⟨r₁, s₁, hs₁⟩⟩ ⟨⟨r₂, s₂, hs₂⟩⟩ hx hy hu,
rcases is_unit_iff_exists_inv.1 hu with ⟨⟨⟨r₃, s₃, hs₃⟩⟩, hz⟩,
rcases quotient.exact hz with ⟨t, hts, ht⟩,
simp at ht,
have : ∀ {r s hs}, (⟦⟨r, s, hs⟩⟧ : at_prime P) ∈ nonunits (at_prime P) → r ∈ P,
{ haveI := classical.dec,
exact λ r s hs, not_imp_comm.1 (λ nr,
is_unit_iff_exists_inv.2 ⟨⟦⟨s, r, nr⟩⟧,
quotient.sound $ r_of_eq $ by simp [mul_comm]⟩) },
have hr₃ := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right hts,
have := (ideal.add_mem_iff_left _ _).1 hr₃,
{ exact not_or (mt hp.mem_or_mem (not_or hs₁ hs₂)) hs₃ (hp.mem_or_mem this) },
{ exact P.neg_mem (P.mul_mem_right
(P.add_mem (P.mul_mem_left (this hy)) (P.mul_mem_left (this hx)))) }
end)
end at_prime
variable (α)
def non_zero_divisors : set α := {x | ∀ z, z * x = 0 → z = 0}
instance non_zero_divisors.is_submonoid : is_submonoid (non_zero_divisors α) :=
{ one_mem := λ z hz, by rwa mul_one at hz,
mul_mem := λ x₁ x₂ hx₁ hx₂ z hz,
have z * x₁ * x₂ = 0, by rwa mul_assoc,
hx₁ z $ hx₂ (z * x₁) this }
@[reducible] def fraction_ring := loc α (non_zero_divisors α)
section fraction_ring
variables {β : Type u} [integral_domain β] [decidable_eq β]
lemma ne_zero_of_mem_non_zero_divisors {x : β}
(hm : x ∈ non_zero_divisors β) : x ≠ 0 | hz :=
zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm
lemma eq_zero_of_ne_zero_of_mul_eq_zero {x y : β} :
x ≠ 0 → y * x = 0 → y = 0 :=
λ hnx hxy, or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx
lemma mem_non_zero_divisors_of_ne_zero {x : β} :
x ≠ 0 → x ∈ non_zero_divisors β :=
λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx
variable (β)
def inv_aux (x : β × (non_zero_divisors β)) : fraction_ring β :=
if h : x.1 = 0 then 0 else ⟦⟨x.2, x.1, mem_non_zero_divisors_of_ne_zero h⟩⟧
instance : has_inv (fraction_ring β) :=
⟨quotient.lift (inv_aux β) $
λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩,
begin
have hrs : s₁ * r₂ = 0 + s₂ * r₁,
from sub_eq_iff_eq_add.1 (hts _ ht),
by_cases hr₁ : r₁ = 0;
by_cases hr₂ : r₂ = 0;
simp [hr₁, hr₂] at hrs; simp [inv_aux, hr₁, hr₂],
{ exfalso,
exact ne_zero_of_mem_non_zero_divisors hs₁ hrs },
{ exfalso,
exact ne_zero_of_mem_non_zero_divisors hs₂ hrs },
{ apply r_of_eq,
simpa [mul_comm] using hrs.symm }
end⟩
instance : decidable_eq (fraction_ring β) :=
@quotient.decidable_eq (β × non_zero_divisors β) (localization.setoid β (non_zero_divisors β)) $
λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩, show decidable (∃ t ∈ non_zero_divisors β, (s₁ * r₂ - s₂ * r₁) * t = 0),
from decidable_of_iff (s₁ * r₂ - s₂ * r₁ = 0)
⟨λ H, ⟨1, λ y, (mul_one y).symm ▸ id, H.symm ▸ zero_mul _⟩,
λ ⟨t, ht1, ht2⟩, or.resolve_right (mul_eq_zero.1 ht2) $ λ ht,
one_ne_zero (ht1 1 ((one_mul t).symm ▸ ht))⟩
instance fraction_ring.field : discrete_field (fraction_ring β) :=
by refine
{ inv := has_inv.inv,
zero_ne_one := λ hzo,
let ⟨t, hts, ht⟩ := quotient.exact hzo in
zero_ne_one (by simpa using hts _ ht : 0 = 1),
mul_inv_cancel := quotient.ind _,
inv_mul_cancel := quotient.ind _,
has_decidable_eq := localization.decidable_eq β,
inv_zero := dif_pos rfl,
.. localization.comm_ring };
{ intros x hnx,
rcases x with ⟨x, z, hz⟩,
have : x ≠ 0,
from assume hx, hnx (quotient.sound $ r_of_eq $ by simp [hx]),
simp only [has_inv.inv, inv_aux, quotient.lift_beta, dif_neg this],
exact (quotient.sound $ r_of_eq $ by simp [mul_comm]) }
@[simp] lemma mk_eq_div {r s} : (mk r s : fraction_ring β) = (r / s : fraction_ring β) :=
show _ = _ * dite (s.1 = 0) _ _, by rw [dif_neg (ne_zero_of_mem_non_zero_divisors s.2)];
exact localization.mk_eq_mul_mk_one _ _
variables {β}
lemma eq_zero_of (x : β) (h : (of x : fraction_ring β) = 0) : x = 0 :=
begin
rcases quotient.exact h with ⟨t, ht, ht'⟩,
simpa [ne_zero_of_mem_non_zero_divisors ht] using ht'
end
lemma of.injective : function.injective (of : β → fraction_ring β) :=
(is_add_group_hom.injective_iff _).mpr eq_zero_of
end fraction_ring
section ideals
theorem map_comap (J : ideal (loc α S)) :
ideal.map coe (ideal.comap (coe : α → loc α S) J) = J :=
le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x,
localization.induction_on x $ λ r s hJ, (submodule.mem_coe _).2 $
mul_one r ▸ coe_mul_mk r 1 s ▸ (ideal.mul_mem_right _ $ ideal.mem_map_of_mem $
have _ := @ideal.mul_mem_left (loc α S) _ _ s _ hJ,
by rwa [coe_coe, coe_mul_mk, mk_mul_cancel_left] at this)
def le_order_embedding :
((≤) : ideal (loc α S) → ideal (loc α S) → Prop) ≼o
((≤) : ideal α → ideal α → Prop) :=
{ to_fun := λ J, ideal.comap coe J,
inj := function.injective_of_left_inverse (map_comap α),
ord := λ J₁ J₂, ⟨ideal.comap_mono, λ hJ,
map_comap α J₁ ▸ map_comap α J₂ ▸ ideal.map_mono hJ⟩ }
end ideals
end localization
|
286ba2a85ca30fafd34d1cf482e7377bfa3242fa | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/set_theory/ordinal_arithmetic.lean | 1f0bb5ae44234d54fe7f7c66144cf3ad0a23325e | [
"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 | 69,921 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import set_theory.ordinal
/-!
# Ordinal arithmetic
Ordinals have an addition (corresponding to disjoint union) that turns them into an additive
monoid, and a multiplication (corresponding to the lexicographic order on the product) that turns
them into a monoid. One can also define correspondingly a subtraction, a division, a successor
function, a power function and a logarithm function.
We also define limit ordinals and prove the basic induction principle on ordinals separating
successor ordinals and limit ordinals, in `limit_rec_on`.
## Main definitions and results
* `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that
every element of `o₁` is smaller than every element of `o₂`.
* `o₁ - o₂` is the unique ordinal `o` such that `o₂ + o = o₁`, when `o₂ ≤ o₁`.
* `o₁ * o₂` is the lexicographic order on `o₂ × o₁`.
* `o₁ / o₂` is the ordinal `o` such that `o₁ = o₂ * o + o'` with `o' < o₂`. We also define the
divisibility predicate, and a modulo operation.
* `succ o = o + 1` is the successor of `o`.
* `pred o` if the predecessor of `o`. If `o` is not a successor, we set `pred o = o`.
We also define the power function and the logarithm function on ordinals, and discuss the properties
of casts of natural numbers of and of `omega` with respect to these operations.
Some properties of the operations are also used to discuss general tools on ordinals:
* `is_limit o`: an ordinal is a limit ordinal if it is neither `0` nor a successor.
* `limit_rec_on` is the main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals.
* `is_normal`: a function `f : ordinal → ordinal` satisfies `is_normal` if it is strictly increasing
and order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`.
* `nfp f a`: the next fixed point of a function `f` on ordinals, above `a`. It behaves well
for normal functions.
* `CNF b o` is the Cantor normal form of the ordinal `o` in base `b`.
* `sup`: the supremum of an indexed family of ordinals in `Type u`, as an ordinal in `Type u`.
* `bsup`: the supremum of a set of ordinals indexed by ordinals less than a given ordinal `o`.
-/
noncomputable theory
open function cardinal set equiv
open_locale classical cardinal
universes u v w
variables {α : Type*} {β : Type*} {γ : Type*}
{r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
namespace ordinal
/-! ### Further properties of addition on ordinals -/
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans
(rel_iso.sum_lex_congr (rel_iso.preimage equiv.ulift _)
(rel_iso.preimage equiv.ulift _)).symm⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
by unfold succ; simp only [lift_add, lift_one]
theorem add_le_add_iff_left (a) {b c : ordinal} : a + b ≤ a + c ↔ b ≤ c :=
⟨induction_on a $ λ α r hr, induction_on b $ λ β₁ s₁ hs₁, induction_on c $ λ β₂ s₂ hs₂ ⟨f⟩, ⟨
have fl : ∀ a, f (sum.inl a) = sum.inl a := λ a,
by simpa only [initial_seg.trans_apply, initial_seg.le_add_apply]
using @initial_seg.eq _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr hs₂)
((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r s₂) a,
have ∀ b, {b' // f (sum.inr b) = sum.inr b'}, begin
intro b, cases e : f (sum.inr b),
{ rw ← fl at e, have := f.inj' e, contradiction },
{ exact ⟨_, rfl⟩ }
end,
let g (b) := (this b).1 in
have fr : ∀ b, f (sum.inr b) = sum.inr (g b), from λ b, (this b).2,
⟨⟨⟨g, λ x y h, by injection f.inj'
(by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩,
λ a b, by simpa only [sum.lex_inr_inr, fr, rel_embedding.coe_fn_to_embedding,
initial_seg.coe_fn_to_rel_embedding, function.embedding.coe_fn_mk]
using @rel_embedding.map_rel_iff _ _ _ _ f.to_rel_embedding (sum.inr a) (sum.inr b)⟩,
λ a b H, begin
rcases f.init' (by rw fr; exact sum.lex_inr_inr.2 H) with ⟨a'|a', h⟩,
{ rw fl at h, cases h },
{ rw fr at h, exact ⟨a', sum.inr.inj h⟩ }
end⟩⟩,
λ h, add_le_add_left h _⟩
theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) :=
(add_assoc _ _ _).symm
@[simp] theorem succ_zero : succ 0 = 1 := zero_add _
theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o :=
by rw [← succ_zero, succ_le]
theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 :=
by rw [one_le_iff_pos, pos_iff_ne_zero]
theorem succ_pos (o : ordinal) : 0 < succ o :=
lt_of_le_of_lt (zero_le _) (lt_succ_self _)
theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 :=
ne_of_gt $ succ_pos o
@[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 :=
by simp only [succ, card_add, card_one]
theorem nat_cast_succ (n : ℕ) : (succ n : ordinal) = n.succ := rfl
theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c :=
by simp only [le_antisymm_iff, add_le_add_iff_left]
theorem lt_succ {a b : ordinal} : a < succ b ↔ a ≤ b :=
by rw [← not_le, succ_le, not_lt]
theorem add_lt_add_iff_left (a) {b c : ordinal} : a + b < a + c ↔ b < c :=
by rw [← not_le, ← not_le, add_le_add_iff_left]
theorem lt_of_add_lt_add_right {a b c : ordinal} : a + b < c + b → a < c :=
lt_imp_lt_of_le_imp_le (λ h, add_le_add_right h _)
@[simp] theorem succ_lt_succ {a b : ordinal} : succ a < succ b ↔ a < b :=
by rw [lt_succ, succ_le]
@[simp] theorem succ_le_succ {a b : ordinal} : succ a ≤ succ b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 succ_lt_succ
theorem succ_inj {a b : ordinal} : succ a = succ b ↔ a = b :=
by simp only [le_antisymm_iff, succ_le_succ]
theorem add_le_add_iff_right {a b : ordinal} (n : ℕ) : a + n ≤ b + n ↔ a ≤ b :=
by induction n with n ih; [rw [nat.cast_zero, add_zero, add_zero],
rw [← nat_cast_succ, add_succ, add_succ, succ_le_succ, ih]]
theorem add_right_cancel {a b : ordinal} (n : ℕ) : a + n = b + n ↔ a = b :=
by simp only [le_antisymm_iff, add_le_add_iff_right]
/-! ### The zero ordinal -/
@[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 :=
⟨induction_on o $ λ α r _ h, begin
refine le_antisymm (le_of_not_lt $
λ hn, ne_zero_iff_nonempty.2 _ h) (zero_le _),
rw [← succ_le, succ_zero] at hn, cases hn with f,
exact ⟨f punit.star⟩
end, λ e, by simp only [e, card_zero]⟩
theorem type_ne_zero_iff_nonempty [is_well_order α r] : type r ≠ 0 ↔ nonempty α :=
(not_congr (@card_eq_zero (type r))).symm.trans ne_zero_iff_nonempty
@[simp] theorem type_eq_zero_iff_empty [is_well_order α r] : type r = 0 ↔ ¬ nonempty α :=
(not_iff_comm.1 type_ne_zero_iff_nonempty).symm
protected lemma one_ne_zero : (1 : ordinal) ≠ 0 :=
type_ne_zero_iff_nonempty.2 ⟨punit.star⟩
instance : nontrivial ordinal.{u} :=
⟨⟨1, 0, ordinal.one_ne_zero⟩⟩
theorem zero_lt_one : (0 : ordinal) < 1 :=
lt_iff_le_and_ne.2 ⟨zero_le _, ne.symm $ ordinal.one_ne_zero⟩
/-! ### The predecessor of an ordinal -/
/-- The ordinal predecessor of `o` is `o'` if `o = succ o'`,
and `o` otherwise. -/
def pred (o : ordinal.{u}) : ordinal.{u} :=
if h : ∃ a, o = succ a then classical.some h else o
@[simp] theorem pred_succ (o) : pred (succ o) = o :=
by have h : ∃ a, succ o = succ a := ⟨_, rfl⟩;
simpa only [pred, dif_pos h] using (succ_inj.1 $ classical.some_spec h).symm
theorem pred_le_self (o) : pred o ≤ o :=
if h : ∃ a, o = succ a then let ⟨a, e⟩ := h in
by rw [e, pred_succ]; exact le_of_lt (lt_succ_self _)
else by rw [pred, dif_neg h]
theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬ ∃ a, o = succ a :=
⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact ne_of_lt (lt_succ_self _) e,
λ h, dif_neg h⟩
theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a :=
iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le])
(iff_not_comm.1 pred_eq_iff_not_succ).symm
theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a :=
⟨λ e, ⟨_, e.symm⟩, λ ⟨a, e⟩, by simp only [e, pred_succ]⟩
theorem succ_lt_of_not_succ {o} (h : ¬ ∃ a, o = succ a) {b} : succ b < o ↔ b < o :=
⟨lt_trans (lt_succ_self _), λ l,
lt_of_le_of_ne (succ_le.2 l) (λ e, h ⟨_, e.symm⟩)⟩
theorem lt_pred {a b} : a < pred b ↔ succ a < b :=
if h : ∃ a, b = succ a then let ⟨c, e⟩ := h in
by rw [e, pred_succ, succ_lt_succ]
else by simp only [pred, dif_neg h, succ_lt_of_not_succ h]
theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b :=
le_iff_le_iff_lt_iff_lt.2 lt_pred
@[simp] theorem lift_is_succ {o} : (∃ a, lift o = succ a) ↔ (∃ a, o = succ a) :=
⟨λ ⟨a, h⟩,
let ⟨b, e⟩ := lift_down $ show a ≤ lift o, from le_of_lt $
h.symm ▸ lt_succ_self _ in
⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩,
λ ⟨a, h⟩, ⟨lift a, by simp only [h, lift_succ]⟩⟩
@[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) :=
if h : ∃ a, o = succ a then
by cases h with a e; simp only [e, pred_succ, lift_succ]
else by rw [pred_eq_iff_not_succ.2 h,
pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)]
/-! ### Limit ordinals -/
/-- A limit ordinal is an ordinal which is not zero and not a successor. -/
def is_limit (o : ordinal) : Prop := o ≠ 0 ∧ ∀ a < o, succ a < o
theorem not_zero_is_limit : ¬ is_limit 0
| ⟨h, _⟩ := h rfl
theorem not_succ_is_limit (o) : ¬ is_limit (succ o)
| ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ_self _))
theorem not_succ_of_is_limit {o} (h : is_limit o) : ¬ ∃ a, o = succ a
| ⟨a, e⟩ := not_succ_is_limit a (e ▸ h)
theorem succ_lt_of_is_limit {o} (h : is_limit o) {a} : succ a < o ↔ a < o :=
⟨lt_trans (lt_succ_self _), h.2 _⟩
theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≤ succ a ↔ o ≤ a :=
le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h
theorem limit_le {o} (h : is_limit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a :=
⟨λ h x l, le_trans (le_of_lt l) h,
λ H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ λ hn,
not_lt_of_le (H _ hn) (lt_succ_self _)⟩
theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ ∃ x < o, a < x :=
by simpa only [not_ball, not_le] using not_congr (@limit_le _ h a)
@[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o :=
and_congr (not_congr $ by simpa only [lift_zero] using @lift_inj o 0)
⟨λ H a h, lift_lt.1 $ by simpa only [lift_succ] using H _ (lift_lt.2 h),
λ H a h, let ⟨a', e⟩ := lift_down (le_of_lt h) in
by rw [← e, ← lift_succ, lift_lt];
rw [← e, lift_lt] at h; exact H a' h⟩
theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o :=
lt_of_le_of_ne (zero_le _) h.1.symm
theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o :=
by simpa only [succ_zero] using h.2 _ h.pos
theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o
| 0 := h.pos
| (n+1) := h.2 _ (is_limit.nat_lt n)
theorem zero_or_succ_or_limit (o : ordinal) :
o = 0 ∨ (∃ a, o = succ a) ∨ is_limit o :=
if o0 : o = 0 then or.inl o0 else
if h : ∃ a, o = succ a then or.inr (or.inl h) else
or.inr $ or.inr ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩
/-- Main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals. -/
@[elab_as_eliminator] def limit_rec_on {C : ordinal → Sort*}
(o : ordinal) (H₁ : C 0) (H₂ : ∀ o, C o → C (succ o))
(H₃ : ∀ o, is_limit o → (∀ o' < o, C o') → C o) : C o :=
wf.fix (λ o IH,
if o0 : o = 0 then by rw o0; exact H₁ else
if h : ∃ a, o = succ a then
by rw ← succ_pred_iff_is_succ.2 h; exact
H₂ _ (IH _ $ pred_lt_iff_is_succ.2 h)
else H₃ _ ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ IH) o
@[simp] theorem limit_rec_on_zero {C} (H₁ H₂ H₃) : @limit_rec_on C 0 H₁ H₂ H₃ = H₁ :=
by rw [limit_rec_on, well_founded.fix_eq, dif_pos rfl]; refl
@[simp] theorem limit_rec_on_succ {C} (o H₁ H₂ H₃) :
@limit_rec_on C (succ o) H₁ H₂ H₃ = H₂ o (@limit_rec_on C o H₁ H₂ H₃) :=
begin
have h : ∃ a, succ o = succ a := ⟨_, rfl⟩,
rw [limit_rec_on, well_founded.fix_eq,
dif_neg (succ_ne_zero o), dif_pos h],
generalize : limit_rec_on._proof_2 (succ o) h = h₂,
generalize : limit_rec_on._proof_3 (succ o) h = h₃,
revert h₂ h₃, generalize e : pred (succ o) = o', intros,
rw pred_succ at e, subst o', refl
end
@[simp] theorem limit_rec_on_limit {C} (o H₁ H₂ H₃ h) :
@limit_rec_on C o H₁ H₂ H₃ = H₃ o h (λ x h, @limit_rec_on C x H₁ H₂ H₃) :=
by rw [limit_rec_on, well_founded.fix_eq,
dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl
lemma has_succ_of_is_limit {α} {r : α → α → Prop} [wo : is_well_order α r]
(h : (type r).is_limit) (x : α) : ∃y, r x y :=
begin
use enum r (typein r x).succ (h.2 _ (typein_lt_type r x)),
convert (enum_lt (typein_lt_type r x) _).mpr (lt_succ_self _), rw [enum_typein]
end
lemma type_subrel_lt (o : ordinal.{u}) :
type (subrel (<) {o' : ordinal | o' < o}) = ordinal.lift.{u u+1} o :=
begin
refine quotient.induction_on o _,
rintro ⟨α, r, wo⟩, resetI, apply quotient.sound,
constructor, symmetry, refine (rel_iso.preimage equiv.ulift r).trans (typein_iso r)
end
lemma mk_initial_seg (o : ordinal.{u}) :
#{o' : ordinal | o' < o} = cardinal.lift.{u u+1} o.card :=
by rw [lift_card, ←type_subrel_lt, card_type]
/-! ### Normal ordinal functions -/
/-- A normal ordinal function is a strictly increasing function which is
order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`. -/
def is_normal (f : ordinal → ordinal) : Prop :=
(∀ o, f o < f (succ o)) ∧ ∀ o, is_limit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a
theorem is_normal.limit_le {f} (H : is_normal f) : ∀ {o}, is_limit o →
∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a := H.2
theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} :
a < f o ↔ ∃ b < o, a < f b :=
not_iff_not.1 $ by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a
theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b :=
strict_mono.lt_iff_lt $ λ a b,
limit_rec_on b (not.elim (not_lt_of_le $ zero_le _))
(λ b IH h, (lt_or_eq_of_le (lt_succ.1 h)).elim
(λ h, lt_trans (IH h) (H.1 _))
(λ e, e ▸ H.1 _))
(λ b l IH h, lt_of_lt_of_le (H.1 a)
((H.2 _ l _).1 (le_refl _) _ (l.2 _ h)))
theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≤ f b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_iff
theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b :=
by simp only [le_antisymm_iff, H.le_iff]
theorem is_normal.le_self {f} (H : is_normal f) (a) : a ≤ f a :=
limit_rec_on a (zero_le _)
(λ a IH, succ_le.2 $ lt_of_le_of_lt IH (H.1 _))
(λ a l IH, (limit_le l).2 $ λ b h,
le_trans (IH b h) $ H.le_iff.2 $ le_of_lt h)
theorem is_normal.le_set {f} (H : is_normal f) (p : ordinal → Prop)
(p0 : ∃ x, p x) (S)
(H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → a ≤ o) {o} :
f S ≤ o ↔ ∀ a, p a → f a ≤ o :=
⟨λ h a pa, le_trans (H.le_iff.2 ((H₂ _).1 (le_refl _) _ pa)) h,
λ h, begin
revert H₂, apply limit_rec_on S,
{ intro H₂,
cases p0 with x px,
have := le_zero.1 ((H₂ _).1 (zero_le _) _ px),
rw this at px, exact h _ px },
{ intros S _ H₂,
rcases not_ball.1 (mt (H₂ S).2 $ not_le_of_lt $ lt_succ_self _) with ⟨a, h₁, h₂⟩,
exact le_trans (H.le_iff.2 $ succ_le.2 $ not_le.1 h₂) (h _ h₁) },
{ intros S L _ H₂, apply (H.2 _ L _).2, intros a h',
rcases not_ball.1 (mt (H₂ a).2 (not_le.2 h')) with ⟨b, h₁, h₂⟩,
exact le_trans (H.le_iff.2 $ le_of_lt $ not_le.1 h₂) (h _ h₁) }
end⟩
theorem is_normal.le_set' {f} (H : is_normal f) (p : α → Prop) (g : α → ordinal)
(p0 : ∃ x, p x) (S)
(H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → g a ≤ o) {o} :
f S ≤ o ↔ ∀ a, p a → f (g a) ≤ o :=
(H.le_set (λ x, ∃ y, p y ∧ x = g y)
(let ⟨x, px⟩ := p0 in ⟨_, _, px, rfl⟩) _
(λ o, (H₂ o).trans ⟨λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1,
λ H a h1, H (g a) ⟨a, h1, rfl⟩⟩)).trans
⟨λ H a h, H (g a) ⟨a, h, rfl⟩, λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1⟩
theorem is_normal.refl : is_normal id :=
⟨λ x, lt_succ_self _, λ o l a, limit_le l⟩
theorem is_normal.trans {f g} (H₁ : is_normal f) (H₂ : is_normal g) :
is_normal (λ x, f (g x)) :=
⟨λ x, H₁.lt_iff.2 (H₂.1 _),
λ o l a, H₁.le_set' (< o) g ⟨_, l.pos⟩ _ (λ c, H₂.2 _ l _)⟩
theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) :
is_limit (f o) :=
⟨ne_of_gt $ lt_of_le_of_lt (zero_le _) $ H.lt_iff.2 l.pos,
λ a h, let ⟨b, h₁, h₂⟩ := (H.limit_lt l).1 h in
lt_of_le_of_lt (succ_le.2 h₂) (H.lt_iff.2 h₁)⟩
theorem add_le_of_limit {a b c : ordinal.{u}}
(h : is_limit b) : a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c :=
⟨λ h b' l, le_trans (add_le_add_left (le_of_lt l) _) h,
λ H, le_of_not_lt $
induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin
resetI,
suffices : ∀ x : β, sum.lex r s (sum.inr x) (enum _ _ l),
{ cases enum _ _ l with x x,
{ cases this (enum s 0 h.pos) },
{ exact irrefl _ (this _) } },
intros x,
rw [← typein_lt_typein (sum.lex r s), typein_enum],
have := H _ (h.2 _ (typein_lt_type s x)),
rw [add_succ, succ_le] at this,
refine lt_of_le_of_lt (type_le'.2
⟨rel_embedding.of_monotone (λ a, _) (λ a b, _)⟩) this,
{ rcases a with ⟨a | b, h⟩,
{ exact sum.inl a },
{ exact sum.inr ⟨b, by cases h; assumption⟩ } },
{ rcases a with ⟨a | a, h₁⟩; rcases b with ⟨b | b, h₂⟩; cases h₁; cases h₂;
rintro ⟨⟩; constructor; assumption }
end) h H⟩
theorem add_is_normal (a : ordinal) : is_normal ((+) a) :=
⟨λ b, (add_lt_add_iff_left a).2 (lt_succ_self _),
λ b l c, add_le_of_limit l⟩
theorem add_is_limit (a) {b} : is_limit b → is_limit (a + b) :=
(add_is_normal a).is_limit
/-! ### Subtraction on ordinals-/
/-- `a - b` is the unique ordinal satisfying
`b + (a - b) = a` when `b ≤ a`. -/
def sub (a b : ordinal.{u}) : ordinal.{u} :=
omin {o | a ≤ b+o} ⟨a, le_add_left _ _⟩
instance : has_sub ordinal := ⟨sub⟩
theorem le_add_sub (a b : ordinal) : a ≤ b + (a - b) :=
omin_mem {o | a ≤ b+o} _
theorem sub_le {a b c : ordinal} : a - b ≤ c ↔ a ≤ b + c :=
⟨λ h, le_trans (le_add_sub a b) (add_le_add_left h _),
λ h, omin_le h⟩
theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b :=
lt_iff_lt_of_le_iff_le sub_le
theorem add_sub_cancel (a b : ordinal) : a + b - a = b :=
le_antisymm (sub_le.2 $ le_refl _)
((add_le_add_iff_left a).1 $ le_add_sub _ _)
theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b :=
h ▸ add_sub_cancel _ _
theorem sub_le_self (a b : ordinal) : a - b ≤ a :=
sub_le.2 $ le_add_left _ _
theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≤ a) : b + (a - b) = a :=
le_antisymm begin
rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l,
{ simp only [e, add_zero, h] },
{ rw [e, add_succ, succ_le, ← lt_sub, e], apply lt_succ_self },
{ exact (add_le_of_limit l).2 (λ c l, le_of_lt (lt_sub.1 l)) }
end (le_add_sub _ _)
@[simp] theorem sub_zero (a : ordinal) : a - 0 = a :=
by simpa only [zero_add] using add_sub_cancel 0 a
@[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 :=
by rw ← le_zero; apply sub_le_self
@[simp] theorem sub_self (a : ordinal) : a - a = 0 :=
by simpa only [add_zero] using add_sub_cancel a 0
theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≤ b :=
⟨λ h, by simpa only [h, add_zero] using le_add_sub a b,
λ h, by rwa [← le_zero, sub_le, add_zero]⟩
theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) :=
eq_of_forall_ge_iff $ λ d, by rw [sub_le, sub_le, sub_le, add_assoc]
theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c :=
by rw [← sub_sub, add_sub_cancel]
theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) :=
⟨ne_of_gt $ lt_sub.2 $ by rwa add_zero,
λ c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩
@[simp] theorem one_add_omega : 1 + omega.{u} = omega :=
begin
refine le_antisymm _ (le_add_left _ _),
rw [omega, one_eq_lift_type_unit, ← lift_add, lift_le, type_add],
have : is_well_order unit empty_relation := by apply_instance,
refine ⟨rel_embedding.collapse (rel_embedding.of_monotone _ _)⟩,
{ apply sum.rec, exact λ _, 0, exact nat.succ },
{ intros a b, cases a; cases b; intro H; cases H with _ _ H _ _ H;
[cases H, exact nat.succ_pos _, exact nat.succ_lt_succ H] }
end
@[simp, priority 990]
theorem one_add_of_omega_le {o} (h : omega ≤ o) : 1 + o = o :=
by rw [← add_sub_cancel_of_le h, ← add_assoc, one_add_omega]
/-! ### Multiplication of ordinals-/
/-- The multiplication of ordinals `o₁` and `o₂` is the (well founded) lexicographic order on
`o₂ × o₁`. -/
instance : monoid ordinal.{u} :=
{ mul := λ a b, quotient.lift_on₂ a b
(λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β × α, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧
: Well_order → Well_order → ordinal) $
λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩,
quot.sound ⟨rel_iso.prod_lex_congr g f⟩,
one := 1,
mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩,
eq.symm $ quotient.sound ⟨⟨prod_assoc _ _ _, λ a b, begin
rcases a with ⟨⟨a₁, a₂⟩, a₃⟩,
rcases b with ⟨⟨b₁, b₂⟩, b₃⟩,
simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc]
end⟩⟩,
mul_one := λ a, induction_on a $ λ α r _, quotient.sound
⟨⟨punit_prod _, λ a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩;
simp only [prod.lex_def, empty_relation, false_or];
simp only [eq_self_iff_true, true_and]; refl⟩⟩,
one_mul := λ a, induction_on a $ λ α r _, quotient.sound
⟨⟨prod_punit _, λ a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩;
simp only [prod.lex_def, empty_relation, and_false, or_false]; refl⟩⟩ }
@[simp] theorem type_mul {α β : Type u} (r : α → α → Prop) (s : β → β → Prop)
[is_well_order α r] [is_well_order β s] : type r * type s = type (prod.lex s r) := rfl
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans
(rel_iso.prod_lex_congr (rel_iso.preimage equiv.ulift _)
(rel_iso.preimage equiv.ulift _)).symm⟩
@[simp] theorem card_mul (a b) : card (a * b) = card a * card b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
mul_comm (mk β) (mk α)
@[simp] theorem mul_zero (a : ordinal) : a * 0 = 0 :=
induction_on a $ λ α _ _, by exactI
type_eq_zero_iff_empty.2 (λ ⟨⟨e, _⟩⟩, e.elim)
@[simp] theorem zero_mul (a : ordinal) : 0 * a = 0 :=
induction_on a $ λ α _ _, by exactI
type_eq_zero_iff_empty.2 (λ ⟨⟨_, e⟩⟩, e.elim)
theorem mul_add (a b c : ordinal) : a * (b + c) = a * b + a * c :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩,
quotient.sound ⟨⟨sum_prod_distrib _ _ _, begin
rintro ⟨a₁|a₁, a₂⟩ ⟨b₁|b₁, b₂⟩; simp only [prod.lex_def,
sum.lex_inl_inl, sum.lex.sep, sum.lex_inr_inl, sum.lex_inr_inr,
sum_prod_distrib_apply_left, sum_prod_distrib_apply_right];
simp only [sum.inl.inj_iff, true_or, false_and, false_or]
end⟩⟩
@[simp] theorem mul_add_one (a b : ordinal) : a * (b + 1) = a * b + a :=
by simp only [mul_add, mul_one]
@[simp] theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one _ _
theorem mul_le_mul_left {a b} (c : ordinal) : a ≤ b → c * a ≤ c * b :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin
resetI,
refine type_le'.2 ⟨rel_embedding.of_monotone
(λ a, (f a.1, a.2))
(λ a b h, _)⟩, clear_,
cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h',
{ exact prod.lex.left _ _ (f.to_rel_embedding.map_rel_iff.1 h') },
{ exact prod.lex.right _ h' }
end
theorem mul_le_mul_right {a b} (c : ordinal) : a ≤ b → a * c ≤ b * c :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin
resetI,
refine type_le'.2 ⟨rel_embedding.of_monotone
(λ a, (a.1, f a.2))
(λ a b h, _)⟩,
cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h',
{ exact prod.lex.left _ _ h' },
{ exact prod.lex.right _ (f.to_rel_embedding.map_rel_iff.1 h') }
end
theorem mul_le_mul {a b c d : ordinal} (h₁ : a ≤ c) (h₂ : b ≤ d) : a * b ≤ c * d :=
le_trans (mul_le_mul_left _ h₂) (mul_le_mul_right _ h₁)
private lemma mul_le_of_limit_aux {α β r s} [is_well_order α r] [is_well_order β s]
{c} (h : is_limit (type s)) (H : ∀ b' < type s, type r * b' ≤ c)
(l : c < type r * type s) : false :=
begin
suffices : ∀ a b, prod.lex s r (b, a) (enum _ _ l),
{ cases enum _ _ l with b a, exact irrefl _ (this _ _) },
intros a b,
rw [← typein_lt_typein (prod.lex s r), typein_enum],
have := H _ (h.2 _ (typein_lt_type s b)),
rw [mul_succ] at this,
have := lt_of_lt_of_le ((add_lt_add_iff_left _).2
(typein_lt_type _ a)) this,
refine lt_of_le_of_lt _ this,
refine (type_le'.2 _),
constructor,
refine rel_embedding.of_monotone (λ a, _) (λ a b, _),
{ rcases a with ⟨⟨b', a'⟩, h⟩,
by_cases e : b = b',
{ refine sum.inr ⟨a', _⟩,
subst e, cases h with _ _ _ _ h _ _ _ h,
{ exact (irrefl _ h).elim },
{ exact h } },
{ refine sum.inl (⟨b', _⟩, a'),
cases h with _ _ _ _ h _ _ _ h,
{ exact h }, { exact (e rfl).elim } } },
{ rcases a with ⟨⟨b₁, a₁⟩, h₁⟩,
rcases b with ⟨⟨b₂, a₂⟩, h₂⟩,
intro h, by_cases e₁ : b = b₁; by_cases e₂ : b = b₂,
{ substs b₁ b₂,
simpa only [subrel_val, prod.lex_def, @irrefl _ s _ b, true_and, false_or, eq_self_iff_true,
dif_pos, sum.lex_inr_inr] using h },
{ subst b₁,
simp only [subrel_val, prod.lex_def, e₂, prod.lex_def, dif_pos, subrel_val, eq_self_iff_true,
or_false, dif_neg, not_false_iff, sum.lex_inr_inl, false_and] at h ⊢,
cases h₂; [exact asymm h h₂_h, exact e₂ rfl] },
{ simp only [e₂, dif_pos, eq_self_iff_true, dif_neg e₁, not_false_iff, sum.lex.sep] },
{ simpa only [dif_neg e₁, dif_neg e₂, prod.lex_def, subrel_val, subtype.mk_eq_mk,
sum.lex_inl_inl] using h } }
end
theorem mul_le_of_limit {a b c : ordinal.{u}}
(h : is_limit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c :=
⟨λ h b' l, le_trans (mul_le_mul_left _ (le_of_lt l)) h,
λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _,
by exactI mul_le_of_limit_aux) h H⟩
theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) :=
⟨λ b, by rw mul_succ; simpa only [add_zero] using (add_lt_add_iff_left (a*b)).2 h,
λ b l c, mul_le_of_limit l⟩
theorem lt_mul_of_limit {a b c : ordinal.{u}}
(h : is_limit c) : a < b * c ↔ ∃ c' < c, a < b * c' :=
by simpa only [not_ball, not_le] using not_congr (@mul_le_of_limit b c a h)
theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c :=
(mul_is_normal a0).lt_iff
theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c :=
(mul_is_normal a0).le_iff
theorem mul_lt_mul_of_pos_left {a b c : ordinal}
(h : a < b) (c0 : 0 < c) : c * a < c * b :=
(mul_lt_mul_iff_left c0).2 h
theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b :=
by simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁
theorem mul_ne_zero {a b : ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 :=
by simpa only [pos_iff_ne_zero] using mul_pos
theorem le_of_mul_le_mul_left {a b c : ordinal}
(h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b :=
le_imp_le_of_lt_imp_lt (λ h', mul_lt_mul_of_pos_left h' h0) h
theorem mul_right_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c :=
(mul_is_normal a0).inj
theorem mul_is_limit {a b : ordinal}
(a0 : 0 < a) : is_limit b → is_limit (a * b) :=
(mul_is_normal a0).is_limit
theorem mul_is_limit_left {a b : ordinal}
(l : is_limit a) (b0 : 0 < b) : is_limit (a * b) :=
begin
rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb,
{ exact (lt_irrefl _).elim b0 },
{ rw mul_succ, exact add_is_limit _ l },
{ exact mul_is_limit l.pos lb }
end
/-! ### Division on ordinals -/
protected lemma div_aux (a b : ordinal.{u}) (h : b ≠ 0) : set.nonempty {o | a < b * succ o} :=
⟨a, succ_le.1 $
by simpa only [succ_zero, one_mul]
using mul_le_mul_right (succ a) (succ_le.2 (pos_iff_ne_zero.2 h))⟩
/-- `a / b` is the unique ordinal `o` satisfying
`a = b * o + o'` with `o' < b`. -/
protected def div (a b : ordinal.{u}) : ordinal.{u} :=
if h : b = 0 then 0 else omin {o | a < b * succ o} (ordinal.div_aux a b h)
instance : has_div ordinal := ⟨ordinal.div⟩
@[simp] theorem div_zero (a : ordinal) : a / 0 = 0 := dif_pos rfl
lemma div_def (a) {b : ordinal} (h : b ≠ 0) :
a / b = omin {o | a < b * succ o} (ordinal.div_aux a b h) := dif_neg h
theorem lt_mul_succ_div (a) {b : ordinal} (h : b ≠ 0) : a < b * succ (a / b) :=
by rw div_def a h; exact omin_mem {o | a < b * succ o} _
theorem lt_mul_div_add (a) {b : ordinal} (h : b ≠ 0) : a < b * (a / b) + b :=
by simpa only [mul_succ] using lt_mul_succ_div a h
theorem div_le {a b c : ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c :=
⟨λ h, lt_of_lt_of_le (lt_mul_succ_div a b0) (mul_le_mul_left _ $ succ_le_succ.2 h),
λ h, by rw div_def a b0; exact omin_le h⟩
theorem lt_div {a b c : ordinal} (c0 : c ≠ 0) : a < b / c ↔ c * succ a ≤ b :=
by rw [← not_le, div_le c0, not_lt]
theorem le_div {a b c : ordinal} (c0 : c ≠ 0) :
a ≤ b / c ↔ c * a ≤ b :=
begin
apply limit_rec_on a,
{ simp only [mul_zero, zero_le] },
{ intros, rw [succ_le, lt_div c0] },
{ simp only [mul_le_of_limit, limit_le, iff_self, forall_true_iff] {contextual := tt} }
end
theorem div_lt {a b c : ordinal} (b0 : b ≠ 0) :
a / b < c ↔ a < b * c :=
lt_iff_lt_of_le_iff_le $ le_div b0
theorem div_le_of_le_mul {a b c : ordinal} (h : a ≤ b * c) : a / b ≤ c :=
if b0 : b = 0 then by simp only [b0, div_zero, zero_le] else
(div_le b0).2 $ lt_of_le_of_lt h $
mul_lt_mul_of_pos_left (lt_succ_self _) (pos_iff_ne_zero.2 b0)
theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c → c * a < b :=
lt_imp_lt_of_le_imp_le div_le_of_le_mul
@[simp] theorem zero_div (a : ordinal) : 0 / a = 0 :=
le_zero.1 $ div_le_of_le_mul $ zero_le _
theorem mul_div_le (a b : ordinal) : b * (a / b) ≤ a :=
if b0 : b = 0 then by simp only [b0, zero_mul, zero_le] else (le_div b0).1 (le_refl _)
theorem mul_add_div (a) {b : ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b :=
begin
apply le_antisymm,
{ apply (div_le b0).2,
rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left],
apply lt_mul_div_add _ b0 },
{ rw [le_div b0, mul_add, add_le_add_iff_left],
apply mul_div_le }
end
theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 :=
by rw [← le_zero, div_le $ pos_iff_ne_zero.1 $ lt_of_le_of_lt (zero_le _) h];
simpa only [succ_zero, mul_one] using h
@[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b ≠ 0) : b * a / b = a :=
by simpa only [add_zero, zero_div] using mul_add_div a b0 0
@[simp] theorem div_one (a : ordinal) : a / 1 = a :=
by simpa only [one_mul] using mul_div_cancel a ordinal.one_ne_zero
@[simp] theorem div_self {a : ordinal} (h : a ≠ 0) : a / a = 1 :=
by simpa only [mul_one] using mul_div_cancel 1 h
theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c :=
if a0 : a = 0 then by simp only [a0, zero_mul, sub_self] else
eq_of_forall_ge_iff $ λ d,
by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0]
theorem is_limit_add_iff {a b} : is_limit (a + b) ↔ is_limit b ∨ (b = 0 ∧ is_limit a) :=
begin
split; intro h,
{ by_cases h' : b = 0,
{ rw [h', add_zero] at h, right, exact ⟨h', h⟩ },
left, rw [←add_sub_cancel a b], apply sub_is_limit h,
suffices : a + 0 < a + b, simpa only [add_zero],
rwa [add_lt_add_iff_left, pos_iff_ne_zero] },
rcases h with h|⟨rfl, h⟩, exact add_is_limit a h, simpa only [add_zero]
end
theorem dvd_add_iff : ∀ {a b c : ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c)
| a _ c ⟨b, rfl⟩ :=
⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩,
λ ⟨d, e⟩, by { rw [e, ← mul_add], apply dvd_mul_right }⟩
theorem dvd_add {a b c : ordinal} (h₁ : a ∣ b) : a ∣ c → a ∣ b + c :=
(dvd_add_iff h₁).2
theorem dvd_zero (a : ordinal) : a ∣ 0 := ⟨_, (mul_zero _).symm⟩
theorem zero_dvd {a : ordinal} : 0 ∣ a ↔ a = 0 :=
⟨λ ⟨h, e⟩, by simp only [e, zero_mul], λ e, e.symm ▸ dvd_zero _⟩
theorem one_dvd (a : ordinal) : 1 ∣ a := ⟨a, (one_mul _).symm⟩
theorem div_mul_cancel : ∀ {a b : ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b
| a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0]
theorem le_of_dvd : ∀ {a b : ordinal}, b ≠ 0 → a ∣ b → a ≤ b
| a _ b0 ⟨b, rfl⟩ := by simpa only [mul_one] using mul_le_mul_left a
(one_le_iff_ne_zero.2 (λ h : b = 0, by simpa only [h, mul_zero] using b0))
theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b :=
if a0 : a = 0 then by subst a; exact (zero_dvd.1 h₁).symm else
if b0 : b = 0 then by subst b; exact zero_dvd.1 h₂ else
le_antisymm (le_of_dvd b0 h₁) (le_of_dvd a0 h₂)
/-- `a % b` is the unique ordinal `o'` satisfying
`a = b * o + o'` with `o' < b`. -/
instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩
theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl
@[simp] theorem mod_zero (a : ordinal) : a % 0 = a :=
by simp only [mod_def, div_zero, zero_mul, sub_zero]
theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a :=
by simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero]
@[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 :=
by simp only [mod_def, zero_div, mul_zero, sub_self]
theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a :=
add_sub_cancel_of_le $ mul_div_le _ _
theorem mod_lt (a) {b : ordinal} (h : b ≠ 0) : a % b < b :=
(add_lt_add_iff_left (b * (a / b))).1 $
by rw div_add_mod; exact lt_mul_div_add a h
@[simp] theorem mod_self (a : ordinal) : a % a = 0 :=
if a0 : a = 0 then by simp only [a0, zero_mod] else
by simp only [mod_def, div_self a0, mul_one, sub_self]
@[simp] theorem mod_one (a : ordinal) : a % 1 = 0 :=
by simp only [mod_def, div_one, one_mul, sub_self]
/-! ### Supremum of a family of ordinals -/
/-- The supremum of a family of ordinals -/
def sup {ι} (f : ι → ordinal) : ordinal :=
omin {c | ∀ i, f i ≤ c}
⟨(sup (cardinal.succ ∘ card ∘ f)).ord, λ i, le_of_lt $
cardinal.lt_ord.2 (lt_of_lt_of_le (cardinal.lt_succ_self _) (le_sup _ _))⟩
theorem le_sup {ι} (f : ι → ordinal) : ∀ i, f i ≤ sup f :=
omin_mem {c | ∀ i, f i ≤ c} _
theorem sup_le {ι} {f : ι → ordinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
⟨λ h i, le_trans (le_sup _ _) h, λ h, omin_le h⟩
theorem lt_sup {ι} {f : ι → ordinal} {a} : a < sup f ↔ ∃ i, a < f i :=
by simpa only [not_forall, not_le] using not_congr (@sup_le _ f a)
theorem is_normal.sup {f} (H : is_normal f)
{ι} {g : ι → ordinal} (h : nonempty ι) : f (sup g) = sup (f ∘ g) :=
eq_of_forall_ge_iff $ λ a,
by rw [sup_le, comp, H.le_set' (λ_:ι, true) g (let ⟨i⟩ := h in ⟨i, ⟨⟩⟩)];
intros; simp only [sup_le, true_implies_iff]
theorem sup_ord {ι} (f : ι → cardinal) : sup (λ i, (f i).ord) = (cardinal.sup f).ord :=
eq_of_forall_ge_iff $ λ a, by simp only [sup_le, cardinal.ord_le, cardinal.sup_le]
lemma sup_succ {ι} (f : ι → ordinal) : sup (λ i, succ (f i)) ≤ succ (sup f) :=
by { rw [ordinal.sup_le], intro i, rw ordinal.succ_le_succ, apply ordinal.le_sup }
lemma unbounded_range_of_sup_ge {α β : Type u} (r : α → α → Prop) [is_well_order α r] (f : β → α)
(h : type r ≤ sup.{u u} (typein r ∘ f)) : unbounded r (range f) :=
begin
apply (not_bounded_iff _).mp, rintro ⟨x, hx⟩, apply not_lt_of_ge h,
refine lt_of_le_of_lt _ (typein_lt_type r x), rw [sup_le], intro y,
apply le_of_lt, rw typein_lt_typein, apply hx, apply mem_range_self
end
/-- The supremum of a family of ordinals indexed by the set
of ordinals less than some `o : ordinal.{u}`.
(This is not a special case of `sup` over the subtype,
because `{a // a < o} : Type (u+1)` and `sup` only works over
families in `Type u`.) -/
def bsup (o : ordinal.{u}) : (Π a < o, ordinal.{max u v}) → ordinal.{max u v} :=
match o, o.out, o.out_eq with
| _, ⟨α, r, _⟩, rfl, f := by exactI sup (λ a, f (typein r a) (typein_lt_type _ _))
end
theorem bsup_le {o f a} : bsup.{u v} o f ≤ a ↔ ∀ i h, f i h ≤ a :=
match o, o.out, o.out_eq, f :
∀ o w (e : ⟦w⟧ = o) (f : Π (a : ordinal.{u}), a < o → ordinal.{(max u v)}),
bsup._match_1 o w e f ≤ a ↔ ∀ i h, f i h ≤ a with
| _, ⟨α, r, _⟩, rfl, f := by rw [bsup._match_1, sup_le]; exactI
⟨λ H i h, by simpa only [typein_enum] using H (enum r i h), λ H b, H _ _⟩
end
theorem bsup_type (r : α → α → Prop) [is_well_order α r] (f) :
bsup (type r) f = sup (λ a, f (typein r a) (typein_lt_type _ _)) :=
eq_of_forall_ge_iff $ λ o,
by rw [bsup_le, sup_le]; exact
⟨λ H b, H _ _, λ H i h, by simpa only [typein_enum] using H (enum r i h)⟩
theorem le_bsup {o} (f : Π a < o, ordinal) (i h) : f i h ≤ bsup o f :=
bsup_le.1 (le_refl _) _ _
theorem lt_bsup {o : ordinal} {f : Π a < o, ordinal}
(hf : ∀{a a'} (ha : a < o) (ha' : a' < o), a < a' → f a ha < f a' ha')
(ho : o.is_limit) (i h) : f i h < bsup o f :=
lt_of_lt_of_le (hf _ _ $ lt_succ_self i) (le_bsup f i.succ $ ho.2 _ h)
theorem bsup_id {o} (ho : is_limit o) : bsup.{u u} o (λ x _, x) = o :=
begin
apply le_antisymm, rw [bsup_le], intro i, apply le_of_lt,
rw [←not_lt], intro h, apply lt_irrefl (bsup.{u u} o (λ x _, x)),
apply lt_of_le_of_lt _ (lt_bsup _ ho _ h), refl, intros, assumption
end
theorem is_normal.bsup {f} (H : is_normal f)
{o : ordinal} : ∀ (g : Π a < o, ordinal) (h : o ≠ 0),
f (bsup o g) = bsup o (λ a h, f (g a h)) :=
induction_on o $ λ α r _ g h,
by resetI; rw [bsup_type,
H.sup (type_ne_zero_iff_nonempty.1 h), bsup_type]
theorem is_normal.bsup_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) :
bsup.{u} o (λx _, f x) = f o :=
by { rw [←is_normal.bsup.{u u} H (λ x _, x) h.1, bsup_id h] }
/-! ### Ordinal exponential -/
/-- The ordinal exponential, defined by transfinite recursion. -/
def power (a b : ordinal) : ordinal :=
if a = 0 then 1 - b else
limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b)
instance : has_pow ordinal ordinal := ⟨power⟩
local infixr ^ := @pow ordinal ordinal ordinal.has_pow
theorem zero_power' (a : ordinal) : 0 ^ a = 1 - a :=
by simp only [pow, power, if_pos rfl]
@[simp] theorem zero_power {a : ordinal} (a0 : a ≠ 0) : 0 ^ a = 0 :=
by rwa [zero_power', sub_eq_zero_iff_le, one_le_iff_ne_zero]
@[simp] theorem power_zero (a : ordinal) : a ^ 0 = 1 :=
by by_cases a = 0; [simp only [pow, power, if_pos h, sub_zero],
simp only [pow, power, if_neg h, limit_rec_on_zero]]
@[simp] theorem power_succ (a b : ordinal) : a ^ succ b = a ^ b * a :=
if h : a = 0 then by subst a; simp only [zero_power (succ_ne_zero _), mul_zero]
else by simp only [pow, power, limit_rec_on_succ, if_neg h]
theorem power_limit {a b : ordinal} (a0 : a ≠ 0) (h : is_limit b) :
a ^ b = bsup.{u u} b (λ c _, a ^ c) :=
by simp only [pow, power, if_neg a0]; rw limit_rec_on_limit _ _ _ _ h; refl
theorem power_le_of_limit {a b c : ordinal} (a0 : a ≠ 0) (h : is_limit b) :
a ^ b ≤ c ↔ ∀ b' < b, a ^ b' ≤ c :=
by rw [power_limit a0 h, bsup_le]
theorem lt_power_of_limit {a b c : ordinal} (b0 : b ≠ 0) (h : is_limit c) :
a < b ^ c ↔ ∃ c' < c, a < b ^ c' :=
by rw [← not_iff_not, not_exists]; simp only [not_lt, power_le_of_limit b0 h, exists_prop, not_and]
@[simp] theorem power_one (a : ordinal) : a ^ 1 = a :=
by rw [← succ_zero, power_succ]; simp only [power_zero, one_mul]
@[simp] theorem one_power (a : ordinal) : 1 ^ a = 1 :=
begin
apply limit_rec_on a,
{ simp only [power_zero] },
{ intros _ ih, simp only [power_succ, ih, mul_one] },
refine λ b l IH, eq_of_forall_ge_iff (λ c, _),
rw [power_le_of_limit ordinal.one_ne_zero l],
exact ⟨λ H, by simpa only [power_zero] using H 0 l.pos,
λ H b' h, by rwa IH _ h⟩,
end
theorem power_pos {a : ordinal} (b)
(a0 : 0 < a) : 0 < a ^ b :=
begin
have h0 : 0 < a ^ 0, {simp only [power_zero, zero_lt_one]},
apply limit_rec_on b,
{ exact h0 },
{ intros b IH, rw [power_succ],
exact mul_pos IH a0 },
{ exact λ b l _, (lt_power_of_limit (pos_iff_ne_zero.1 a0) l).2
⟨0, l.pos, h0⟩ },
end
theorem power_ne_zero {a : ordinal} (b)
(a0 : a ≠ 0) : a ^ b ≠ 0 :=
pos_iff_ne_zero.1 $ power_pos b $ pos_iff_ne_zero.2 a0
theorem power_is_normal {a : ordinal} (h : 1 < a) : is_normal ((^) a) :=
have a0 : 0 < a, from lt_trans zero_lt_one h,
⟨λ b, by simpa only [mul_one, power_succ] using
(mul_lt_mul_iff_left (power_pos b a0)).2 h,
λ b l c, power_le_of_limit (ne_of_gt a0) l⟩
theorem power_lt_power_iff_right {a b c : ordinal}
(a1 : 1 < a) : a ^ b < a ^ c ↔ b < c :=
(power_is_normal a1).lt_iff
theorem power_le_power_iff_right {a b c : ordinal}
(a1 : 1 < a) : a ^ b ≤ a ^ c ↔ b ≤ c :=
(power_is_normal a1).le_iff
theorem power_right_inj {a b c : ordinal}
(a1 : 1 < a) : a ^ b = a ^ c ↔ b = c :=
(power_is_normal a1).inj
theorem power_is_limit {a b : ordinal}
(a1 : 1 < a) : is_limit b → is_limit (a ^ b) :=
(power_is_normal a1).is_limit
theorem power_is_limit_left {a b : ordinal}
(l : is_limit a) (hb : b ≠ 0) : is_limit (a ^ b) :=
begin
rcases zero_or_succ_or_limit b with e|⟨b,rfl⟩|l',
{ exact absurd e hb },
{ rw power_succ,
exact mul_is_limit (power_pos _ l.pos) l },
{ exact power_is_limit l.one_lt l' }
end
theorem power_le_power_right {a b c : ordinal}
(h₁ : 0 < a) (h₂ : b ≤ c) : a ^ b ≤ a ^ c :=
begin
cases lt_or_eq_of_le (one_le_iff_pos.2 h₁) with h₁ h₁,
{ exact (power_le_power_iff_right h₁).2 h₂ },
{ subst a, simp only [one_power] }
end
theorem power_le_power_left {a b : ordinal} (c)
(ab : a ≤ b) : a ^ c ≤ b ^ c :=
begin
by_cases a0 : a = 0,
{ subst a, by_cases c0 : c = 0,
{ subst c, simp only [power_zero] },
{ simp only [zero_power c0, zero_le] } },
{ apply limit_rec_on c,
{ simp only [power_zero] },
{ intros c IH, simpa only [power_succ] using mul_le_mul IH ab },
{ exact λ c l IH, (power_le_of_limit a0 l).2
(λ b' h, le_trans (IH _ h) (power_le_power_right
(lt_of_lt_of_le (pos_iff_ne_zero.2 a0) ab) (le_of_lt h))) } }
end
theorem le_power_self {a : ordinal} (b) (a1 : 1 < a) : b ≤ a ^ b :=
(power_is_normal a1).le_self _
theorem power_lt_power_left_of_succ {a b c : ordinal}
(ab : a < b) : a ^ succ c < b ^ succ c :=
by rw [power_succ, power_succ]; exact
lt_of_le_of_lt
(mul_le_mul_right _ $ power_le_power_left _ $ le_of_lt ab)
(mul_lt_mul_of_pos_left ab (power_pos _ (lt_of_le_of_lt (zero_le _) ab)))
theorem power_add (a b c : ordinal) : a ^ (b + c) = a ^ b * a ^ c :=
begin
by_cases a0 : a = 0,
{ subst a,
by_cases c0 : c = 0, {simp only [c0, add_zero, power_zero, mul_one]},
have : b+c ≠ 0 := ne_of_gt (lt_of_lt_of_le
(pos_iff_ne_zero.2 c0) (le_add_left _ _)),
simp only [zero_power c0, zero_power this, mul_zero] },
cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1,
{ subst a1, simp only [one_power, mul_one] },
apply limit_rec_on c,
{ simp only [add_zero, power_zero, mul_one] },
{ intros c IH,
rw [add_succ, power_succ, IH, power_succ, mul_assoc] },
{ intros c l IH,
refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans
(add_is_normal b)).limit_le l).trans _),
simp only [IH] {contextual := tt},
exact (((mul_is_normal $ power_pos b (pos_iff_ne_zero.2 a0)).trans
(power_is_normal a1)).limit_le l).symm }
end
theorem power_dvd_power (a) {b c : ordinal}
(h : b ≤ c) : a ^ b ∣ a ^ c :=
by { rw [← add_sub_cancel_of_le h, power_add], apply dvd_mul_right }
theorem power_dvd_power_iff {a b c : ordinal}
(a1 : 1 < a) : a ^ b ∣ a ^ c ↔ b ≤ c :=
⟨λ h, le_of_not_lt $ λ hn,
not_le_of_lt ((power_lt_power_iff_right a1).2 hn) $
le_of_dvd (power_ne_zero _ $ one_le_iff_ne_zero.1 $ le_of_lt a1) h,
power_dvd_power _⟩
theorem power_mul (a b c : ordinal) : a ^ (b * c) = (a ^ b) ^ c :=
begin
by_cases b0 : b = 0, {simp only [b0, zero_mul, power_zero, one_power]},
by_cases a0 : a = 0,
{ subst a,
by_cases c0 : c = 0, {simp only [c0, mul_zero, power_zero]},
simp only [zero_power b0, zero_power c0, zero_power (mul_ne_zero b0 c0)] },
cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1,
{ subst a1, simp only [one_power] },
apply limit_rec_on c,
{ simp only [mul_zero, power_zero] },
{ intros c IH,
rw [mul_succ, power_add, IH, power_succ] },
{ intros c l IH,
refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans
(mul_is_normal (pos_iff_ne_zero.2 b0))).limit_le l).trans _),
simp only [IH] {contextual := tt},
exact (power_le_of_limit (power_ne_zero _ a0) l).symm }
end
/-! ### Ordinal logarithm -/
/-- The ordinal logarithm is the solution `u` to the equation
`x = b ^ u * v + w` where `v < b` and `w < b`. -/
def log (b : ordinal) (x : ordinal) : ordinal :=
if h : 1 < b then pred $
omin {o | x < b^o} ⟨succ x, succ_le.1 (le_power_self _ h)⟩
else 0
@[simp] theorem log_not_one_lt {b : ordinal} (b1 : ¬ 1 < b) (x : ordinal) : log b x = 0 :=
by simp only [log, dif_neg b1]
theorem log_def {b : ordinal} (b1 : 1 < b) (x : ordinal) : log b x =
pred (omin {o | x < b^o} (log._proof_1 b x b1)) :=
by simp only [log, dif_pos b1]
@[simp] theorem log_zero (b : ordinal) : log b 0 = 0 :=
if b1 : 1 < b then
by rw [log_def b1, ← le_zero, pred_le];
apply omin_le; change 0<b^succ 0;
rw [succ_zero, power_one];
exact lt_trans zero_lt_one b1
else by simp only [log_not_one_lt b1]
theorem succ_log_def {b x : ordinal} (b1 : 1 < b) (x0 : 0 < x) : succ (log b x) =
omin {o | x < b^o} (log._proof_1 b x b1) :=
begin
let t := omin {o | x < b^o} (log._proof_1 b x b1),
have : x < b ^ t := omin_mem {o | x < b^o} _,
rcases zero_or_succ_or_limit t with h|h|h,
{ refine (not_lt_of_le (one_le_iff_pos.2 x0) _).elim,
simpa only [h, power_zero] },
{ rw [show log b x = pred t, from log_def b1 x,
succ_pred_iff_is_succ.2 h] },
{ rcases (lt_power_of_limit (ne_of_gt $ lt_trans zero_lt_one b1) h).1 this with ⟨a, h₁, h₂⟩,
exact (not_le_of_lt h₁).elim (le_omin.1 (le_refl t) a h₂) }
end
theorem lt_power_succ_log {b : ordinal} (b1 : 1 < b) (x : ordinal) :
x < b ^ succ (log b x) :=
begin
cases lt_or_eq_of_le (zero_le x) with x0 x0,
{ rw [succ_log_def b1 x0], exact omin_mem {o | x < b^o} _ },
{ subst x, apply power_pos _ (lt_trans zero_lt_one b1) }
end
theorem power_log_le (b) {x : ordinal} (x0 : 0 < x) :
b ^ log b x ≤ x :=
begin
by_cases b0 : b = 0,
{ rw [b0, zero_power'],
refine le_trans (sub_le_self _ _) (one_le_iff_pos.2 x0) },
cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1,
{ refine le_of_not_lt (λ h, not_le_of_lt (lt_succ_self (log b x)) _),
have := @omin_le {o | x < b^o} _ _ h,
rwa ← succ_log_def b1 x0 at this },
{ rw [← b1, one_power], exact one_le_iff_pos.2 x0 }
end
theorem le_log {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) :
c ≤ log b x ↔ b ^ c ≤ x :=
⟨λ h, le_trans ((power_le_power_iff_right b1).2 h) (power_log_le b x0),
λ h, le_of_not_lt $ λ hn,
not_le_of_lt (lt_power_succ_log b1 x) $
le_trans ((power_le_power_iff_right b1).2 (succ_le.2 hn)) h⟩
theorem log_lt {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) :
log b x < c ↔ x < b ^ c :=
lt_iff_lt_of_le_iff_le (le_log b1 x0)
theorem log_le_log (b) {x y : ordinal} (xy : x ≤ y) :
log b x ≤ log b y :=
if x0 : x = 0 then by simp only [x0, log_zero, zero_le] else
have x0 : 0 < x, from pos_iff_ne_zero.2 x0,
if b1 : 1 < b then
(le_log b1 (lt_of_lt_of_le x0 xy)).2 $ le_trans (power_log_le _ x0) xy
else by simp only [log_not_one_lt b1, zero_le]
theorem log_le_self (b x : ordinal) : log b x ≤ x :=
if x0 : x = 0 then by simp only [x0, log_zero, zero_le] else
if b1 : 1 < b then
le_trans (le_power_self _ b1) (power_log_le b (pos_iff_ne_zero.2 x0))
else by simp only [log_not_one_lt b1, zero_le]
/-! ### The Cantor normal form -/
theorem CNF_aux {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) :
o % b ^ log b o < o :=
lt_of_lt_of_le
(mod_lt _ $ power_ne_zero _ b0)
(power_log_le _ $ pos_iff_ne_zero.2 o0)
/-- Proving properties of ordinals by induction over their Cantor normal form. -/
@[elab_as_eliminator] noncomputable def CNF_rec {b : ordinal} (b0 : b ≠ 0)
{C : ordinal → Sort*}
(H0 : C 0)
(H : ∀ o, o ≠ 0 → o % b ^ log b o < o → C (o % b ^ log b o) → C o)
: ∀ o, C o
| o :=
if o0 : o = 0 then by rw o0; exact H0 else
have _, from CNF_aux b0 o0,
H o o0 this (CNF_rec (o % b ^ log b o))
using_well_founded {dec_tac := `[assumption]}
@[simp] theorem CNF_rec_zero {b} (b0) {C H0 H} : @CNF_rec b b0 C H0 H 0 = H0 :=
by rw [CNF_rec, dif_pos rfl]; refl
@[simp] theorem CNF_rec_ne_zero {b} (b0) {C H0 H o} (o0) :
@CNF_rec b b0 C H0 H o = H o o0 (CNF_aux b0 o0) (@CNF_rec b b0 C H0 H _) :=
by rw [CNF_rec, dif_neg o0]
/-- The Cantor normal form of an ordinal is the list of coefficients
in the base-`b` expansion of `o`.
CNF b (b ^ u₁ * v₁ + b ^ u₂ * v₂) = [(u₁, v₁), (u₂, v₂)] -/
noncomputable def CNF (b := omega) (o : ordinal) : list (ordinal × ordinal) :=
if b0 : b = 0 then [] else
CNF_rec b0 [] (λ o o0 h IH, (log b o, o / b ^ log b o) :: IH) o
@[simp] theorem zero_CNF (o) : CNF 0 o = [] :=
dif_pos rfl
@[simp] theorem CNF_zero (b) : CNF b 0 = [] :=
if b0 : b = 0 then dif_pos b0 else
(dif_neg b0).trans $ CNF_rec_zero _
theorem CNF_ne_zero {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) :
CNF b o = (log b o, o / b ^ log b o) :: CNF b (o % b ^ log b o) :=
by unfold CNF; rw [dif_neg b0, dif_neg b0, CNF_rec_ne_zero b0 o0]
theorem one_CNF {o : ordinal} (o0 : o ≠ 0) :
CNF 1 o = [(0, o)] :=
by rw [CNF_ne_zero ordinal.one_ne_zero o0, log_not_one_lt (lt_irrefl _), power_zero, mod_one,
CNF_zero, div_one]
theorem CNF_foldr {b : ordinal} (b0 : b ≠ 0) (o) :
(CNF b o).foldr (λ p r, b ^ p.1 * p.2 + r) 0 = o :=
CNF_rec b0 (by rw CNF_zero; refl)
(λ o o0 h IH, by rw [CNF_ne_zero b0 o0, list.foldr_cons, IH, div_add_mod]) o
theorem CNF_pairwise_aux (b := omega) (o) :
(∀ p ∈ CNF b o, prod.fst p ≤ log b o) ∧
(CNF b o).pairwise (λ p q, q.1 < p.1) :=
begin
by_cases b0 : b = 0,
{ simp only [b0, zero_CNF, list.pairwise.nil, and_true], exact λ _, false.elim },
cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1,
{ refine CNF_rec b0 _ _ o,
{ simp only [CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim },
intros o o0 H IH, cases IH with IH₁ IH₂,
simp only [CNF_ne_zero b0 o0, list.forall_mem_cons, list.pairwise_cons, IH₂, and_true],
refine ⟨⟨le_refl _, λ p m, _⟩, λ p m, _⟩,
{ exact le_trans (IH₁ p m) (log_le_log _ $ le_of_lt H) },
{ refine lt_of_le_of_lt (IH₁ p m) ((log_lt b1 _).2 _),
{ rw pos_iff_ne_zero, intro e,
rw e at m, simpa only [CNF_zero] using m },
{ exact mod_lt _ (power_ne_zero _ b0) } } },
{ by_cases o0 : o = 0,
{ simp only [o0, CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim },
rw [← b1, one_CNF o0],
simp only [list.mem_singleton, log_not_one_lt (lt_irrefl _), forall_eq, le_refl, true_and, list.pairwise_singleton] }
end
theorem CNF_pairwise (b := omega) (o) :
(CNF b o).pairwise (λ p q, prod.fst q < p.1) :=
(CNF_pairwise_aux _ _).2
theorem CNF_fst_le_log (b := omega) (o) :
∀ p ∈ CNF b o, prod.fst p ≤ log b o :=
(CNF_pairwise_aux _ _).1
theorem CNF_fst_le (b := omega) (o) (p ∈ CNF b o) : prod.fst p ≤ o :=
le_trans (CNF_fst_le_log _ _ p H) (log_le_self _ _)
theorem CNF_snd_lt {b : ordinal} (b1 : 1 < b) (o) :
∀ p ∈ CNF b o, prod.snd p < b :=
begin
have b0 := ne_of_gt (lt_trans zero_lt_one b1),
refine CNF_rec b0 (λ _, by rw [CNF_zero]; exact false.elim) _ o,
intros o o0 H IH,
simp only [CNF_ne_zero b0 o0, list.mem_cons_iff, forall_eq_or_imp, iff_true_intro IH, and_true],
rw [div_lt (power_ne_zero _ b0), ← power_succ],
exact lt_power_succ_log b1 _,
end
theorem CNF_sorted (b := omega) (o) :
((CNF b o).map prod.fst).sorted (>) :=
by rw [list.sorted, list.pairwise_map]; exact CNF_pairwise b o
/-! ### Casting naturals into ordinals, compatibility with operations -/
@[simp] theorem nat_cast_mul {m n : ℕ} : ((m * n : ℕ) : ordinal) = m * n :=
by induction n with n IH; [simp only [nat.cast_zero, nat.mul_zero, mul_zero],
rw [nat.mul_succ, nat.cast_add, IH, nat.cast_succ, mul_add_one]]
@[simp] theorem nat_cast_power {m n : ℕ} : ((pow m n : ℕ) : ordinal) = m ^ n :=
by induction n with n IH; [simp only [pow_zero, nat.cast_zero, power_zero, nat.cast_one],
rw [pow_succ', nat_cast_mul, IH, nat.cast_succ, ← succ_eq_add_one, power_succ]]
@[simp] theorem nat_cast_le {m n : ℕ} : (m : ordinal) ≤ n ↔ m ≤ n :=
by rw [← cardinal.ord_nat, ← cardinal.ord_nat,
cardinal.ord_le_ord, cardinal.nat_cast_le]
@[simp] theorem nat_cast_lt {m n : ℕ} : (m : ordinal) < n ↔ m < n :=
by simp only [lt_iff_le_not_le, nat_cast_le]
@[simp] theorem nat_cast_inj {m n : ℕ} : (m : ordinal) = n ↔ m = n :=
by simp only [le_antisymm_iff, nat_cast_le]
@[simp] theorem nat_cast_eq_zero {n : ℕ} : (n : ordinal) = 0 ↔ n = 0 :=
@nat_cast_inj n 0
theorem nat_cast_ne_zero {n : ℕ} : (n : ordinal) ≠ 0 ↔ n ≠ 0 :=
not_congr nat_cast_eq_zero
@[simp] theorem nat_cast_pos {n : ℕ} : (0 : ordinal) < n ↔ 0 < n :=
@nat_cast_lt 0 n
@[simp] theorem nat_cast_sub {m n : ℕ} : ((m - n : ℕ) : ordinal) = m - n :=
(_root_.le_total m n).elim
(λ h, by rw [nat.sub_eq_zero_iff_le.2 h, sub_eq_zero_iff_le.2 (nat_cast_le.2 h)]; refl)
(λ h, (add_left_cancel n).1 $ by rw [← nat.cast_add,
nat.add_sub_cancel' h, add_sub_cancel_of_le (nat_cast_le.2 h)])
@[simp] theorem nat_cast_div {m n : ℕ} : ((m / n : ℕ) : ordinal) = m / n :=
if n0 : n = 0 then by simp only [n0, nat.div_zero, nat.cast_zero, div_zero] else
have n0':_, from nat_cast_ne_zero.2 n0,
le_antisymm
(by rw [le_div n0', ← nat_cast_mul, nat_cast_le, mul_comm];
apply nat.div_mul_le_self)
(by rw [div_le n0', succ, ← nat.cast_succ, ← nat_cast_mul,
nat_cast_lt, mul_comm, ← nat.div_lt_iff_lt_mul _ _ (nat.pos_of_ne_zero n0)];
apply nat.lt_succ_self)
@[simp] theorem nat_cast_mod {m n : ℕ} : ((m % n : ℕ) : ordinal) = m % n :=
by rw [← add_left_cancel (n*(m/n)), div_add_mod, ← nat_cast_div, ← nat_cast_mul, ← nat.cast_add,
add_comm, nat.mod_add_div]
@[simp] theorem nat_le_card {o} {n : ℕ} : (n : cardinal) ≤ card o ↔ (n : ordinal) ≤ o :=
⟨λ h, by rwa [← cardinal.ord_le, cardinal.ord_nat] at h,
λ h, card_nat n ▸ card_le_card h⟩
@[simp] theorem nat_lt_card {o} {n : ℕ} : (n : cardinal) < card o ↔ (n : ordinal) < o :=
by rw [← succ_le, ← cardinal.succ_le, ← cardinal.nat_succ, nat_le_card]; refl
@[simp] theorem card_lt_nat {o} {n : ℕ} : card o < n ↔ o < n :=
lt_iff_lt_of_le_iff_le nat_le_card
@[simp] theorem card_le_nat {o} {n : ℕ} : card o ≤ n ↔ o ≤ n :=
le_iff_le_iff_lt_iff_lt.2 nat_lt_card
@[simp] theorem card_eq_nat {o} {n : ℕ} : card o = n ↔ o = n :=
by simp only [le_antisymm_iff, card_le_nat, nat_le_card]
@[simp] theorem type_fin (n : ℕ) : @type (fin n) (<) _ = n :=
by rw [← card_eq_nat, card_type, mk_fin]
@[simp] theorem lift_nat_cast (n : ℕ) : lift n = n :=
by induction n with n ih; [simp only [nat.cast_zero, lift_zero],
simp only [nat.cast_succ, lift_add, ih, lift_one]]
theorem lift_type_fin (n : ℕ) : lift (@type (fin n) (<) _) = n :=
by simp only [type_fin, lift_nat_cast]
theorem fintype_card (r : α → α → Prop) [is_well_order α r] [fintype α] : type r = fintype.card α :=
by rw [← card_eq_nat, card_type, fintype_card]
end ordinal
/-! ### Properties of `omega` -/
namespace cardinal
open ordinal
@[simp] theorem ord_omega : ord.{u} omega = ordinal.omega :=
le_antisymm (ord_le.2 $ le_refl _) $
le_of_forall_lt $ λ o h, begin
rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩,
rw [lt_ord, ← lift_card, ← lift_omega.{0 u},
lift_lt, ← typein_enum (<) h'],
exact lt_omega_iff_fintype.2 ⟨set.fintype_lt_nat _⟩
end
@[simp] theorem add_one_of_omega_le {c} (h : omega ≤ c) : c + 1 = c :=
by rw [add_comm, ← card_ord c, ← card_one,
← card_add, one_add_of_omega_le];
rwa [← ord_omega, ord_le_ord]
end cardinal
namespace ordinal
theorem lt_omega {o : ordinal.{u}} : o < omega ↔ ∃ n : ℕ, o = n :=
by rw [← cardinal.ord_omega, cardinal.lt_ord, lt_omega]; simp only [card_eq_nat]
theorem nat_lt_omega (n : ℕ) : (n : ordinal) < omega :=
lt_omega.2 ⟨_, rfl⟩
theorem omega_pos : 0 < omega := nat_lt_omega 0
theorem omega_ne_zero : omega ≠ 0 := ne_of_gt omega_pos
theorem one_lt_omega : 1 < omega := by simpa only [nat.cast_one] using nat_lt_omega 1
theorem omega_is_limit : is_limit omega :=
⟨omega_ne_zero, λ o h,
let ⟨n, e⟩ := lt_omega.1 h in
by rw [e]; exact nat_lt_omega (n+1)⟩
theorem omega_le {o : ordinal.{u}} : omega ≤ o ↔ ∀ n : ℕ, (n : ordinal) ≤ o :=
⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h,
λ H, le_of_forall_lt $ λ a h,
let ⟨n, e⟩ := lt_omega.1 h in
by rw [e, ← succ_le]; exact H (n+1)⟩
theorem nat_lt_limit {o} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o
| 0 := lt_of_le_of_ne (zero_le o) h.1.symm
| (n+1) := h.2 _ (nat_lt_limit n)
theorem omega_le_of_is_limit {o} (h : is_limit o) : omega ≤ o :=
omega_le.2 $ λ n, le_of_lt $ nat_lt_limit h n
theorem add_omega {a : ordinal} (h : a < omega) : a + omega = omega :=
begin
rcases lt_omega.1 h with ⟨n, rfl⟩,
clear h, induction n with n IH,
{ rw [nat.cast_zero, zero_add] },
{ rw [nat.cast_succ, add_assoc, one_add_of_omega_le (le_refl _), IH] }
end
theorem add_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a + b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega
end
theorem mul_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a * b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_mul]; apply nat_lt_omega
end
theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a ≠ 0 ∧ omega ∣ a :=
begin
refine ⟨λ l, ⟨l.1, ⟨a / omega, le_antisymm _ (mul_div_le _ _)⟩⟩, λ h, _⟩,
{ refine (limit_le l).2 (λ x hx, le_of_lt _),
rw [← div_lt omega_ne_zero, ← succ_le, le_div omega_ne_zero,
mul_succ, add_le_of_limit omega_is_limit],
intros b hb,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
exact le_trans (add_le_add_right (mul_div_le _ _) _)
(le_of_lt $ lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _) },
{ rcases h with ⟨a0, b, rfl⟩,
refine mul_is_limit_left omega_is_limit
(pos_iff_ne_zero.2 $ mt _ a0),
intro e, simp only [e, mul_zero] }
end
local infixr ^ := @pow ordinal ordinal ordinal.has_pow
theorem power_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_power]; apply nat_lt_omega
end
theorem add_omega_power {a b : ordinal} (h : a < omega ^ b) : a + omega ^ b = omega ^ b :=
begin
refine le_antisymm _ (le_add_left _ _),
revert h, apply limit_rec_on b,
{ intro h, rw [power_zero, ← succ_zero, lt_succ, le_zero] at h,
rw [h, zero_add] },
{ intros b _ h, rw [power_succ] at h,
rcases (lt_mul_of_limit omega_is_limit).1 h with ⟨x, xo, ax⟩,
refine le_trans (add_le_add_right (le_of_lt ax) _) _,
rw [power_succ, ← mul_add, add_omega xo] },
{ intros b l IH h, rcases (lt_power_of_limit omega_ne_zero l).1 h with ⟨x, xb, ax⟩,
refine (((add_is_normal a).trans (power_is_normal one_lt_omega))
.limit_le l).2 (λ y yb, _),
let z := max x y,
have := IH z (max_lt xb yb)
(lt_of_lt_of_le ax $ power_le_power_right omega_pos (le_max_left _ _)),
exact le_trans (add_le_add_left (power_le_power_right omega_pos (le_max_right _ _)) _)
(le_trans this (power_le_power_right omega_pos $ le_of_lt $ max_lt xb yb)) }
end
theorem add_lt_omega_power {a b c : ordinal} (h₁ : a < omega ^ c) (h₂ : b < omega ^ c) :
a + b < omega ^ c :=
by rwa [← add_omega_power h₁, add_lt_add_iff_left]
theorem add_absorp {a b c : ordinal} (h₁ : a < omega ^ b) (h₂ : omega ^ b ≤ c) : a + c = c :=
by rw [← add_sub_cancel_of_le h₂, ← add_assoc, add_omega_power h₁]
theorem add_absorp_iff {o : ordinal} (o0 : 0 < o) : (∀ a < o, a + o = o) ↔ ∃ a, o = omega ^ a :=
⟨λ H, ⟨log omega o, begin
refine ((lt_or_eq_of_le (power_log_le _ o0))
.resolve_left $ λ h, _).symm,
have := H _ h,
have := lt_power_succ_log one_lt_omega o,
rw [power_succ, lt_mul_of_limit omega_is_limit] at this,
rcases this with ⟨a, ao, h'⟩,
rcases lt_omega.1 ao with ⟨n, rfl⟩, clear ao,
revert h', apply not_lt_of_le,
suffices e : omega ^ log omega o * ↑n + o = o,
{ simpa only [e] using le_add_right (omega ^ log omega o * ↑n) o },
induction n with n IH, {simp only [nat.cast_zero, mul_zero, zero_add]},
simp only [nat.cast_succ, mul_add_one, add_assoc, this, IH]
end⟩,
λ ⟨b, e⟩, e.symm ▸ λ a, add_omega_power⟩
theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a)
(l : is_limit c)
(IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) :
(a + b) * c = a * c :=
le_antisymm
((mul_le_of_limit l).2 $ λ c' h, begin
apply le_trans (mul_le_mul_left _ (le_of_lt $ lt_succ_self _)),
rw IH _ h,
apply le_trans (add_le_add_left _ _),
{ rw ← mul_succ, exact mul_le_mul_left _ (succ_le.2 $ l.2 _ h) },
{ rw ← ba, exact le_add_right _ _ }
end)
(mul_le_mul_right _ (le_add_right _ _))
theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) :
(a + b) * succ c = a * succ c + b :=
begin
apply limit_rec_on c,
{ simp only [succ_zero, mul_one] },
{ intros c IH,
rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] },
{ intros c l IH,
have := add_mul_limit_aux ba l IH,
rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] }
end
theorem add_mul_limit {a b c : ordinal} (ba : b + a = a)
(l : is_limit c) : (a + b) * c = a * c :=
add_mul_limit_aux ba l (λ c' _, add_mul_succ c' ba)
theorem mul_omega {a : ordinal} (a0 : 0 < a) (ha : a < omega) : a * omega = omega :=
le_antisymm
((mul_le_of_limit omega_is_limit).2 $ λ b hb, le_of_lt (mul_lt_omega ha hb))
(by simpa only [one_mul] using mul_le_mul_right omega (one_le_iff_pos.2 a0))
theorem mul_lt_omega_power {a b c : ordinal}
(c0 : 0 < c) (ha : a < omega ^ c) (hb : b < omega) : a * b < omega ^ c :=
if b0 : b = 0 then by simp only [b0, mul_zero, power_pos _ omega_pos] else begin
rcases zero_or_succ_or_limit c with rfl|⟨c,rfl⟩|l,
{ exact (lt_irrefl _).elim c0 },
{ rw power_succ at ha,
rcases ((mul_is_normal $ power_pos _ omega_pos).limit_lt
omega_is_limit).1 ha with ⟨n, hn, an⟩,
refine lt_of_le_of_lt (mul_le_mul_right _ (le_of_lt an)) _,
rw [power_succ, mul_assoc, mul_lt_mul_iff_left (power_pos _ omega_pos)],
exact mul_lt_omega hn hb },
{ rcases ((power_is_normal one_lt_omega).limit_lt l).1 ha with ⟨x, hx, ax⟩,
refine lt_of_le_of_lt (mul_le_mul (le_of_lt ax) (le_of_lt hb)) _,
rw [← power_succ, power_lt_power_iff_right one_lt_omega],
exact l.2 _ hx }
end
theorem mul_omega_dvd {a : ordinal}
(a0 : 0 < a) (ha : a < omega) : ∀ {b}, omega ∣ b → a * b = b
| _ ⟨b, rfl⟩ := by rw [← mul_assoc, mul_omega a0 ha]
theorem mul_omega_power_power {a b : ordinal} (a0 : 0 < a) (h : a < omega ^ omega ^ b) :
a * omega ^ omega ^ b = omega ^ omega ^ b :=
begin
by_cases b0 : b = 0, {rw [b0, power_zero, power_one] at h ⊢, exact mul_omega a0 h},
refine le_antisymm _ (by simpa only [one_mul] using mul_le_mul_right (omega^omega^b) (one_le_iff_pos.2 a0)),
rcases (lt_power_of_limit omega_ne_zero (power_is_limit_left omega_is_limit b0)).1 h
with ⟨x, xb, ax⟩,
refine le_trans (mul_le_mul_right _ (le_of_lt ax)) _,
rw [← power_add, add_omega_power xb]
end
theorem power_omega {a : ordinal} (a1 : 1 < a) (h : a < omega) : a ^ omega = omega :=
le_antisymm
((power_le_of_limit (one_le_iff_ne_zero.1 $ le_of_lt a1) omega_is_limit).2
(λ b hb, le_of_lt (power_lt_omega h hb)))
(le_power_self _ a1)
/-! ### Fixed points of normal functions -/
/-- The next fixed point function, the least fixed point of the
normal function `f` above `a`. -/
def nfp (f : ordinal → ordinal) (a : ordinal) :=
sup (λ n : ℕ, f^[n] a)
theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a :=
le_sup _ n
theorem le_nfp_self (f a) : a ≤ nfp f a :=
iterate_le_nfp f a 0
theorem is_normal.lt_nfp {f} (H : is_normal f) {a b} :
f b < nfp f a ↔ b < nfp f a :=
lt_sup.trans $ iff.trans
(by exact
⟨λ ⟨n, h⟩, ⟨n, lt_of_le_of_lt (H.le_self _) h⟩,
λ ⟨n, h⟩, ⟨n+1, by rw iterate_succ'; exact H.lt_iff.2 h⟩⟩)
lt_sup.symm
theorem is_normal.nfp_le {f} (H : is_normal f) {a b} :
nfp f a ≤ f b ↔ nfp f a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_nfp
theorem is_normal.nfp_le_fp {f} (H : is_normal f) {a b}
(ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b :=
sup_le.2 $ λ i, begin
induction i with i IH generalizing a, {exact ab},
exact IH (le_trans (H.le_iff.2 ab) h),
end
theorem is_normal.nfp_fp {f} (H : is_normal f) (a) : f (nfp f a) = nfp f a :=
begin
refine le_antisymm _ (H.le_self _),
cases le_or_lt (f a) a with aa aa,
{ rwa le_antisymm (H.nfp_le_fp (le_refl _) aa) (le_nfp_self _ _) },
rcases zero_or_succ_or_limit (nfp f a) with e|⟨b, e⟩|l,
{ refine @le_trans _ _ _ (f a) _ (H.le_iff.2 _) (iterate_le_nfp f a 1),
simp only [e, zero_le] },
{ have : f b < nfp f a := H.lt_nfp.2 (by simp only [e, lt_succ_self]),
rw [e, lt_succ] at this,
have ab : a ≤ b,
{ rw [← lt_succ, ← e],
exact lt_of_lt_of_le aa (iterate_le_nfp f a 1) },
refine le_trans (H.le_iff.2 (H.nfp_le_fp ab this))
(le_trans this (le_of_lt _)),
simp only [e, lt_succ_self] },
{ exact (H.2 _ l _).2 (λ b h, le_of_lt (H.lt_nfp.2 h)) }
end
theorem is_normal.le_nfp {f} (H : is_normal f) {a b} :
f b ≤ nfp f a ↔ b ≤ nfp f a :=
⟨le_trans (H.le_self _), λ h,
by simpa only [H.nfp_fp] using H.le_iff.2 h⟩
theorem nfp_eq_self {f : ordinal → ordinal} {a} (h : f a = a) : nfp f a = a :=
le_antisymm (sup_le.mpr $ λ i, by rw [iterate_fixed h]) (le_nfp_self f a)
/-- The derivative of a normal function `f` is
the sequence of fixed points of `f`. -/
def deriv (f : ordinal → ordinal) (o : ordinal) : ordinal :=
limit_rec_on o (nfp f 0)
(λ a IH, nfp f (succ IH))
(λ a l, bsup.{u u} a)
@[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := limit_rec_on_zero _ _ _
@[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) :=
limit_rec_on_succ _ _ _ _
theorem deriv_limit (f) {o} : is_limit o →
deriv f o = bsup.{u u} o (λ a _, deriv f a) :=
limit_rec_on_limit _ _ _ _
theorem deriv_is_normal (f) : is_normal (deriv f) :=
⟨λ o, by rw [deriv_succ, ← succ_le]; apply le_nfp_self,
λ o l a, by rw [deriv_limit _ l, bsup_le]⟩
theorem is_normal.deriv_fp {f} (H : is_normal f) (o) : f (deriv.{u} f o) = deriv f o :=
begin
apply limit_rec_on o,
{ rw [deriv_zero, H.nfp_fp] },
{ intros o ih, rw [deriv_succ, H.nfp_fp] },
intros o l IH,
rw [deriv_limit _ l, is_normal.bsup.{u u u} H _ l.1],
refine eq_of_forall_ge_iff (λ c, _),
simp only [bsup_le, IH] {contextual:=tt}
end
theorem is_normal.fp_iff_deriv {f} (H : is_normal f)
{a} : f a ≤ a ↔ ∃ o, a = deriv f o :=
⟨λ ha, begin
suffices : ∀ o (_:a ≤ deriv f o), ∃ o, a = deriv f o,
from this a ((deriv_is_normal _).le_self _),
intro o, apply limit_rec_on o,
{ intros h₁,
refine ⟨0, le_antisymm h₁ _⟩,
rw deriv_zero,
exact H.nfp_le_fp (zero_le _) ha },
{ intros o IH h₁,
cases le_or_lt a (deriv f o), {exact IH h},
refine ⟨succ o, le_antisymm h₁ _⟩,
rw deriv_succ,
exact H.nfp_le_fp (succ_le.2 h) ha },
{ intros o l IH h₁,
cases eq_or_lt_of_le h₁, {exact ⟨_, h⟩},
rw [deriv_limit _ l, ← not_le, bsup_le, not_ball] at h,
exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) }
end, λ ⟨o, e⟩, e.symm ▸ le_of_eq (H.deriv_fp _)⟩
end ordinal
|
3ca2acce662a5e0889dd3e0e7ddda0cb394221fc | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/set/default.lean | ca6ef04fcd3cc1b730261240fc326f6da0a28d8a | [
"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 | 49 | lean | import data.set.finite
import data.set.intervals
|
b81b99fba8e9b16be93bdb41d1e3bdbe1bab8f89 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/set/intervals/ord_connected.lean | 51a0a0d0dcbfea77971be5bffa1d827d2ed87f99 | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,757 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import data.set.intervals.unordered_interval
import data.set.lattice
/-!
# Order-connected sets
We say that a set `s : set α` is `ord_connected` if for all `x y ∈ s` it includes the
interval `[x, y]`. If `α` is a `densely_ordered` `conditionally_complete_linear_order` with
the `order_topology`, then this condition is equivalent to `is_preconnected s`. If `α` is a
`linear_ordered_field`, then this condition is also equivalent to `convex α s`.
In this file we prove that intersection of a family of `ord_connected` sets is `ord_connected` and
that all standard intervals are `ord_connected`.
-/
namespace set
variables {α : Type*} [preorder α] {s t : set α}
/--
We say that a set `s : set α` is `ord_connected` if for all `x y ∈ s` it includes the
interval `[x, y]`. If `α` is a `densely_ordered` `conditionally_complete_linear_order` with
the `order_topology`, then this condition is equivalent to `is_preconnected s`. If `α` is a
`linear_ordered_field`, then this condition is also equivalent to `convex α s`.
-/
class ord_connected (s : set α) : Prop :=
(out' ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s) : Icc x y ⊆ s)
lemma ord_connected.out (h : ord_connected s) :
∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), Icc x y ⊆ s := h.1
lemma ord_connected_def : ord_connected s ↔ ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), Icc x y ⊆ s :=
⟨λ h, h.1, λ h, ⟨h⟩⟩
/-- It suffices to prove `[x, y] ⊆ s` for `x y ∈ s`, `x ≤ y`. -/
lemma ord_connected_iff : ord_connected s ↔ ∀ (x ∈ s) (y ∈ s), x ≤ y → Icc x y ⊆ s :=
ord_connected_def.trans
⟨λ hs x hx y hy hxy, hs hx hy, λ H x hx y hy z hz, H x hx y hy (le_trans hz.1 hz.2) hz⟩
lemma ord_connected_of_Ioo {α : Type*} [partial_order α] {s : set α}
(hs : ∀ (x ∈ s) (y ∈ s), x < y → Ioo x y ⊆ s) :
ord_connected s :=
begin
rw ord_connected_iff,
intros x hx y hy hxy,
rcases eq_or_lt_of_le hxy with rfl|hxy', { simpa },
have := hs x hx y hy hxy',
rw [← union_diff_cancel Ioo_subset_Icc_self],
simp [*, insert_subset]
end
protected lemma Icc_subset (s : set α) [hs : ord_connected s] {x y} (hx : x ∈ s) (hy : y ∈ s) :
Icc x y ⊆ s := hs.out hx hy
lemma ord_connected.inter {s t : set α} (hs : ord_connected s) (ht : ord_connected t) :
ord_connected (s ∩ t) :=
⟨λ x hx y hy, subset_inter (hs.out hx.1 hy.1) (ht.out hx.2 hy.2)⟩
instance ord_connected.inter' {s t : set α} [ord_connected s] [ord_connected t] :
ord_connected (s ∩ t) :=
ord_connected.inter ‹_› ‹_›
lemma ord_connected.dual {s : set α} (hs : ord_connected s) :
ord_connected (order_dual.of_dual ⁻¹' s) :=
⟨λ x hx y hy z hz, hs.out hy hx ⟨hz.2, hz.1⟩⟩
lemma ord_connected_dual {s : set α} : ord_connected (order_dual.of_dual ⁻¹' s) ↔ ord_connected s :=
⟨λ h, by simpa only [ord_connected_def] using h.dual, λ h, h.dual⟩
lemma ord_connected_sInter {S : set (set α)} (hS : ∀ s ∈ S, ord_connected s) :
ord_connected (⋂₀ S) :=
⟨λ x hx y hy, subset_sInter $ λ s hs, (hS s hs).out (hx s hs) (hy s hs)⟩
lemma ord_connected_Inter {ι : Sort*} {s : ι → set α} (hs : ∀ i, ord_connected (s i)) :
ord_connected (⋂ i, s i) :=
ord_connected_sInter $ forall_range_iff.2 hs
instance ord_connected_Inter' {ι : Sort*} {s : ι → set α} [∀ i, ord_connected (s i)] :
ord_connected (⋂ i, s i) :=
ord_connected_Inter ‹_›
lemma ord_connected_bInter {ι : Sort*} {p : ι → Prop} {s : Π (i : ι) (hi : p i), set α}
(hs : ∀ i hi, ord_connected (s i hi)) :
ord_connected (⋂ i hi, s i hi) :=
ord_connected_Inter $ λ i, ord_connected_Inter $ hs i
lemma ord_connected_pi {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] {s : set ι}
{t : Π i, set (α i)} (h : ∀ i ∈ s, ord_connected (t i)) : ord_connected (s.pi t) :=
⟨λ x hx y hy z hz i hi, (h i hi).out (hx i hi) (hy i hi) ⟨hz.1 i, hz.2 i⟩⟩
instance ord_connected_pi' {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] {s : set ι}
{t : Π i, set (α i)} [h : ∀ i, ord_connected (t i)] : ord_connected (s.pi t) :=
ord_connected_pi $ λ i hi, h i
@[instance] lemma ord_connected_Ici {a : α} : ord_connected (Ici a) :=
⟨λ x hx y hy z hz, le_trans hx hz.1⟩
@[instance] lemma ord_connected_Iic {a : α} : ord_connected (Iic a) :=
⟨λ x hx y hy z hz, le_trans hz.2 hy⟩
@[instance] lemma ord_connected_Ioi {a : α} : ord_connected (Ioi a) :=
⟨λ x hx y hy z hz, lt_of_lt_of_le hx hz.1⟩
@[instance] lemma ord_connected_Iio {a : α} : ord_connected (Iio a) :=
⟨λ x hx y hy z hz, lt_of_le_of_lt hz.2 hy⟩
@[instance] lemma ord_connected_Icc {a b : α} : ord_connected (Icc a b) :=
ord_connected_Ici.inter ord_connected_Iic
@[instance] lemma ord_connected_Ico {a b : α} : ord_connected (Ico a b) :=
ord_connected_Ici.inter ord_connected_Iio
@[instance] lemma ord_connected_Ioc {a b : α} : ord_connected (Ioc a b) :=
ord_connected_Ioi.inter ord_connected_Iic
@[instance] lemma ord_connected_Ioo {a b : α} : ord_connected (Ioo a b) :=
ord_connected_Ioi.inter ord_connected_Iio
@[instance] lemma ord_connected_singleton {α : Type*} [partial_order α] {a : α} :
ord_connected ({a} : set α) :=
by { rw ← Icc_self, exact ord_connected_Icc }
@[instance] lemma ord_connected_empty : ord_connected (∅ : set α) := ⟨λ x, false.elim⟩
@[instance] lemma ord_connected_univ : ord_connected (univ : set α) := ⟨λ _ _ _ _, subset_univ _⟩
/-- In a dense order `α`, the subtype from an `ord_connected` set is also densely ordered. -/
instance [densely_ordered α] {s : set α} [hs : ord_connected s] :
densely_ordered s :=
⟨ begin
intros a₁ a₂ ha,
have ha' : ↑a₁ < ↑a₂ := ha,
obtain ⟨x, ha₁x, hxa₂⟩ := exists_between ha',
refine ⟨⟨x, _⟩, ⟨ha₁x, hxa₂⟩⟩,
exact (hs.out a₁.2 a₂.2) (Ioo_subset_Icc_self ⟨ha₁x, hxa₂⟩),
end ⟩
variables {β : Type*} [linear_order β]
@[instance] lemma ord_connected_interval {a b : β} : ord_connected (interval a b) :=
ord_connected_Icc
lemma ord_connected.interval_subset {s : set β} (hs : ord_connected s)
⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s) :
interval x y ⊆ s :=
by cases le_total x y; simp only [interval_of_le, interval_of_ge, *]; apply hs.out; assumption
lemma ord_connected_iff_interval_subset {s : set β} :
ord_connected s ↔ ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), interval x y ⊆ s :=
⟨λ h, h.interval_subset,
λ h, ord_connected_iff.2 $ λ x hx y hy hxy, by simpa only [interval_of_le hxy] using h hx hy⟩
end set
|
726ed38805b3adb00efa55c91d339861163ceb02 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /tests/playground/deriving.lean | 286b3195b73658610f3fcbfcb131ed3164f5973a | [
"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,299 | lean | import Lean
mutual
inductive Vect (α : Type u) (β : Type v) : Nat → Nat → Type max u v where
| nil : Vect α β 0 0
| lst : List (Array (Vect α β 0 0)) → Vect α β 0 0
| cons1 : {n m : Nat} → TreeV α β n → Vect α β n m → Vect α β (n+1) m
| cons2 : {n m : Nat} → TreeV α β m → Vect α β n m → Vect α β n (m+1)
inductive TreeV (α : Type u) (β : Type v) : Nat → Type max u v where
| diag : {n : Nat} → Vect α β n n → TreeV α β n
| lower : {n m : Nat} → n < m → Vect α β n m → TreeV α β m
end
mutual
partial def aux1 {α β m n} [ToString α] [ToString β] (s : Vect α β m n) : String :=
let inst1 {m' n' : Nat} : ToString (Vect α β m' n') := ⟨aux1⟩
let inst1 {n' : Nat} : ToString (TreeV α β n') := ⟨aux2⟩
match m, n, s with
| _, _, Vect.nil => "nil"
| _, _, Vect.lst xs => "lst " ++ toString xs
| _, _, Vect.cons1 t v => "cons1 " ++ toString t ++ " " ++ toString v
| _, _, Vect.cons2 t v => "cons2 " ++ toString t ++ " " ++ toString v
partial def aux2 {α β n} [ToString α] [ToString β] (s : TreeV α β n) : String :=
let inst1 {m' n' : Nat} : ToString (Vect α β m' n') := ⟨aux1⟩
let inst1 {n' : Nat} : ToString (TreeV α β n') := ⟨aux2⟩
match n, s with
| _, TreeV.diag v => "diag " ++ toString v
| _, TreeV.lower _ v => "lower " ++ "<proof>" ++ " " ++ toString v
end
instance {α β m n} [ToString α] [ToString β] : ToString (Vect α β m n) where
toString := aux1
instance {α β n} [ToString α] [ToString β] : ToString (TreeV α β n) where
toString := aux2
namespace Test
mutual
inductive Foo (α : Type) where
| mk : List (Bla α) → Foo α
| leaf : α → Foo α
inductive Bla (α : Type) where
| nil : Bla α
| cons : Foo α → Bla α → Bla α
end
open Lean
open Lean.Meta
def tst : MetaM Unit := do
let info ← getConstInfoInduct `Test.Bla
trace[Meta.debug]! "nested: {info.isNested}"
pure ()
#eval tst
mutual
partial def fooToString {α : Type} [ToString α] (s : Foo α) : String :=
let inst1 : ToString (Bla α) := ⟨blaToString⟩
match s with
| Foo.mk bs => "Foo.mk " ++ toString bs
| Foo.leaf a => "Foo.leaf " ++ toString a
partial def blaToString {α : Type} [ToString α] (s : Bla α) : String :=
let inst1 : ToString (Bla α) := ⟨blaToString⟩
let inst2 : ToString (Foo α) := ⟨fooToString⟩
match s with
| Bla.nil => "Bla.nil"
| Bla.cons h t => "Bla.cons (" ++ toString h ++ ") " ++ toString t
end
instance [ToString α] : ToString (Foo α) where
toString := fooToString
instance [ToString α] : ToString (Bla α) where
toString := blaToString
#eval Foo.mk [Bla.cons (Foo.leaf 10) Bla.nil]
end Test
namespace Lean.Elab
open Meta
namespace Deriving
/- For type classes such as BEq, ToString, Format -/
namespace Default
structure ContextCore where
classInfo : ConstantInfo
typeInfos : Array InductiveVal
auxFunNames : Array Name
usePartial : Bool
resultType : Syntax
structure Header where
binders : Array Syntax
argNames : Array Name
targetName : Name
abbrev MkAltRhs :=
ContextCore → (ctorName : Name) → (ctorArgs : Array (Syntax × Expr)) → TermElabM Syntax
structure Context extends ContextCore where
mkAltRhs : MkAltRhs
def mkContext (className : Name) (typeName : Name) (resultType : Syntax) (mkAltRhs : MkAltRhs) : TermElabM Context := do
let indVal ← getConstInfoInduct typeName
let mut typeInfos := #[]
for typeName in indVal.all do
typeInfos ← typeInfos.push (← getConstInfoInduct typeName)
let classInfo ← getConstInfo className
let mut auxFunNames := #[]
for typeName in indVal.all do
match className.eraseMacroScopes, typeName.eraseMacroScopes with
| Name.str _ c _, Name.str _ t _ => auxFunNames := auxFunNames.push (← mkFreshUserName <| Name.mkSimple <| c.decapitalize ++ t)
| _, _ => auxFunNames := auxFunNames.push (← mkFreshUserName `instFn)
trace[Meta.debug]! "{auxFunNames}"
let usePartial := indVal.isNested || typeInfos.size > 1
return {
classInfo := classInfo
typeInfos := typeInfos
auxFunNames := auxFunNames
usePartial := usePartial
resultType := resultType
mkAltRhs := mkAltRhs
}
def mkInductArgNames (indVal : InductiveVal) : TermElabM (Array Name) := do
forallTelescopeReducing indVal.type fun xs _ => do
let mut argNames := #[]
for x in xs do
let localDecl ← getLocalDecl x.fvarId!
let paramName ← mkFreshUserName localDecl.userName.eraseMacroScopes
argNames := argNames.push paramName
pure argNames
def mkInductiveApp (indVal : InductiveVal) (argNames : Array Name) : TermElabM Syntax :=
let f := mkIdent indVal.name
let args := argNames.map mkIdent
`(@$f $args*)
def implicitBinderF := Parser.Term.implicitBinder
def instBinderF := Parser.Term.instBinder
def explicitBinderF := Parser.Term.explicitBinder
def mkImplicitBinders (argNames : Array Name) : TermElabM (Array Syntax) :=
argNames.mapM fun argName =>
`(implicitBinderF| { $(mkIdent argName) })
def mkInstImplicitBinders (ctx : Context) (indVal : InductiveVal) (argNames : Array Name) : TermElabM (Array Syntax) :=
forallBoundedTelescope indVal.type indVal.nparams fun xs _ => do
let mut binders := #[]
for i in [:xs.size] do
try
let x := xs[i]
let clsName := ctx.classInfo.name
let c ← mkAppM clsName #[x]
if (← isTypeCorrect c) then
let argName := argNames[i]
let binder ← `(instBinderF| [ $(mkIdent clsName):ident $(mkIdent argName):ident ])
binders := binders.push binder
catch _ =>
pure ()
return binders
def mkHeader (ctx : Context) (indVal : InductiveVal) : TermElabM Header := do
let argNames ← mkInductArgNames indVal
let binders ← mkImplicitBinders argNames
let targetType ← mkInductiveApp indVal argNames
let targetName ← mkFreshUserName `x
let targetBinder ← `(explicitBinderF| ($(mkIdent targetName) : $targetType))
let binders := binders ++ (← mkInstImplicitBinders ctx indVal argNames)
let binders := binders.push targetBinder
return {
binders := binders
argNames := argNames
targetName := targetName
}
def mkLocalInstanceLetDecls (ctx : Context) (argNames : Array Name) : TermElabM (Array Syntax) := do
let mut letDecls := #[]
for i in [:ctx.typeInfos.size] do
let indVal := ctx.typeInfos[i]
let auxFunName := ctx.auxFunNames[i]
let currArgNames ← mkInductArgNames indVal
let numParams := indVal.nparams
let currIndices := currArgNames[numParams:]
let binders ← mkImplicitBinders currIndices
let argNamesNew := argNames[:numParams] ++ currIndices
let indType ← mkInductiveApp indVal argNamesNew
let type ← `($(mkIdent ctx.classInfo.name) $indType)
let val ← `(⟨$(mkIdent auxFunName)⟩)
let instName ← mkFreshUserName `localinst
let letDecl ← `(Parser.Term.letDecl| $(mkIdent instName):ident $binders:implicitBinder* : $type := $val)
letDecls := letDecls.push letDecl
return letDecls
def mkLet (letDecls : Array Syntax) (body : Syntax) : TermElabM Syntax :=
letDecls.foldrM (init := body) fun letDecl body =>
`(let $letDecl:letDecl; $body)
def matchAltExpr := Parser.Term.matchAlt
def mkMatch (ctx : Context) (header : Header) (indVal : InductiveVal) (argNames : Array Name) : TermElabM Syntax := do
let discrs ← mkDiscrs
let alts ← mkAlts
`(match $[$discrs],* with | $[$alts:matchAlt]|*)
where
mkDiscr (varName : Name) : TermElabM Syntax :=
`(Parser.Term.matchDiscr| $(mkIdent varName):term)
mkDiscrs : TermElabM (Array Syntax) := do
let mut discrs := #[]
-- add indices
for argName in argNames[indVal.nparams:] do
discrs := discrs.push (← mkDiscr argName)
return discrs.push (← mkDiscr header.targetName)
mkAlts : TermElabM (Array Syntax) := do
let mut alts := #[]
for ctorName in indVal.ctors do
let mut patterns := #[]
-- add `_` pattern for indices
for i in [:indVal.nindices] do
patterns := patterns.push (← `(_))
let ctorInfo ← getConstInfoCtor ctorName
let mut ctorArgs := #[]
-- add `_` for inductive parameters, they are inaccessible
for i in [:indVal.nparams] do
ctorArgs := ctorArgs.push (← `(_))
for i in [:ctorInfo.nfields] do
ctorArgs := ctorArgs.push (mkIdent (← mkFreshUserName `y))
patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs:term*))
let altRhs ← forallTelescopeReducing ctorInfo.type fun xs _ =>
ctx.mkAltRhs ctx.toContextCore ctorName (Array.zip ctorArgs xs)
let alt ← `(matchAltExpr| $[$patterns:term],* => $altRhs:term)
alts := alts.push alt
return alts
def mkAuxFunction (ctx : Context) (i : Nat) : TermElabM Syntax := do
let auxFunName ← ctx.auxFunNames[i]
let indVal ← ctx.typeInfos[i]
let header ← mkHeader ctx indVal
let mut body ← mkMatch ctx header indVal header.argNames
if ctx.usePartial then
let letDecls ← mkLocalInstanceLetDecls ctx header.argNames
body ← mkLet letDecls body
let binders := header.binders
if ctx.usePartial then
`(private partial def $(mkIdent auxFunName):ident $binders:explicitBinder* : $ctx.resultType:term := $body:term)
else
`(private def $(mkIdent auxFunName):ident $binders:explicitBinder* : $ctx.resultType:term := $body:term)
def mkMutualBlock (ctx : Context) : TermElabM Syntax := do
let mut auxDefs := #[]
for i in [:ctx.typeInfos.size] do
auxDefs := auxDefs.push (← mkAuxFunction ctx i)
`(mutual $auxDefs:command* end)
def mkInstanceCmds (ctx : Context) : TermElabM (Array Syntax) := do
let mut instances := #[]
for i in [:ctx.typeInfos.size] do
let indVal := ctx.typeInfos[i]
let auxFunName := ctx.auxFunNames[i]
let argNames ← mkInductArgNames indVal
let binders ← mkImplicitBinders argNames
let binders := binders ++ (← mkInstImplicitBinders ctx indVal argNames)
let indType ← mkInductiveApp indVal argNames
let type ← `($(mkIdent ctx.classInfo.name) $indType)
let val ← `(⟨$(mkIdent auxFunName)⟩)
let instCmd ← `(instance $binders:implicitBinder* : $type := $val)
trace[Meta.debug]! "\n{instCmd}"
instances := instances.push instCmd
return instances
open Command
def mkDeriving (className : Name) (typeName : Name) (resultType : Syntax) (mkAltRhs : MkAltRhs) : CommandElabM Unit := do
let cmds ← liftTermElabM none do
let ctx ← mkContext className typeName resultType mkAltRhs
let block ← mkMutualBlock ctx
trace[Meta.debug]! "\n{block}"
return #[block] ++ (← mkInstanceCmds ctx)
cmds.forM elabCommand
def mkDerivingToString (typeName : Name) : CommandElabM Unit := do
mkDeriving `ToString typeName (← `(String)) fun ctx ctorName ctorArgs =>
quote (toString ctorName) -- TODO
syntax[runTstKind] "runTst" : command
@[commandElab runTstKind] def elabTst : CommandElab := fun stx =>
mkDerivingToString `Test.Foo
set_option trace.Meta.debug true
runTst
|
9f2835d2affd31731a2ac4e1821c843f7a525c8d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/induction.lean | c2b6e7cbda8d34a1721edd052e311f3834967ff2 | [
"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 | 55,031 | lean | /-
Copyright (c) 2020 Jannis Limperg. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jannis Limperg
-/
import tactic.clear
import tactic.dependencies
import tactic.fresh_names
import tactic.generalizes
import tactic.has_variable_names
import tactic.unify_equations
/-!
# A better tactic for induction and case analysis
This module defines the tactics `tactic.interactive.induction'` and
`tactic.interactive.cases'`, which are variations on Lean's builtin `induction`
and `cases`. The primed variants feature various improvements over the builtin
tactics; in particular, they generate more human-friendly names and `induction'`
deals much better with indexed inductive types. See the tactics' documentation
for more details. We also provide corresponding non-interactive induction
tactics `tactic.eliminate_hyp` and `tactic.eliminate_expr`.
The design and implementation of these tactics is described in a
[draft paper](https://limperg.de/paper/cpp2021-induction/).
-/
open expr native
open tactic.interactive (case_tag.from_tag_hyps)
namespace tactic
namespace eliminate
/-!
## Tracing
We set up two tracing functions to be used by `eliminate_hyp` and its supporting
tactics. Their output is enabled by setting `trace.eliminate_hyp` to `true`.
-/
declare_trace eliminate_hyp
/--
`trace_eliminate_hyp msg` traces `msg` if the option `trace.eliminate_hyp` is
`true`.
-/
meta def trace_eliminate_hyp {α} [has_to_format α] (msg : thunk α) : tactic unit :=
when_tracing `eliminate_hyp $ trace $ to_fmt "eliminate_hyp: " ++ to_fmt (msg ())
/--
`trace_state_eliminate_hyp msg` traces `msg` followed by the tactic state if the
option `trace.eliminate_hyp` is `true`.
-/
meta def trace_state_eliminate_hyp {α} [has_to_format α] (msg : thunk α) :
tactic unit := do
state ← read,
trace_eliminate_hyp $ format.join
[to_fmt (msg ()), "\n-----\n", to_fmt state, "\n-----"]
/-!
## Information Gathering
We define data structures for information relevant to the induction, and
functions to collect this information for a specific goal.
-/
/--
Information about a constructor argument. E.g. given the declaration
```
induction ℕ : Type
| zero : ℕ
| suc (n : ℕ) : ℕ
```
the `zero` constructor has no arguments and the `suc` constructor has one
argument, `n`.
We record the following information:
- `aname`: the argument's name. If the argument was not explicitly named in the
declaration, the elaborator generates a name for it.
- `type` : the argument's type.
- `dependent`: whether the argument is dependent, i.e. whether it occurs in the
remainder of the constructor type.
- `index_occurrences`: the index arguments of the constructor's return type
in which this argument occurs. If the constructor return type is
`I i₀ ... iₙ` and the argument under consideration is `a`, and `a` occurs in
`i₁` and `i₂`, then the `index_occurrences` are `1, 2`. As an additional
requirement, for `iⱼ` to be considered an index occurrences,
the type of `iⱼ` must match that of `a` according to
`index_occurrence_type_match`.
- `recursive_leading_pis`: `none` if this constructor is not recursive.
Otherwise, the argument has type `Π (x₁ : T₁) ... (xₙ : Tₙ), I ...`
where `I` is the inductive type to which this constructor belongs. In this
case, `recursive_leading_pis` is `some n` with `n` the number of leading Π
binders in the argument's type.
-/
@[derive has_reflect]
meta structure constructor_argument_info :=
(aname : name)
(type : expr)
(dependent : bool)
(index_occurrences : list ℕ)
(recursive_leading_pis : option ℕ)
namespace constructor_argument_info
/--
`is_recursive c` is true iff the constructor argument described by `c` is
recursive.
-/
meta def is_recursive (c : constructor_argument_info) :=
c.recursive_leading_pis.is_some
end constructor_argument_info
/--
Information about a constructor. Contains:
- `cname`: the constructor's name.
- `non_param_args`: information about the arguments of the constructor,
excluding the arguments induced by the parameters of the inductive type.
- `num_non_param_args`: the length of `non_param_args`.
- `rec_args`: the subset of `non_param_args` which are recursive constructor
arguments.
- `num_rec_args`: the length of `rec_args`.
For example, take the constructor
```
list.cons : ∀ {α} (x : α) (xs : list α), list α
```
`α` is a parameter of `list`, so `non_param_args` contains information about `x`
and `xs`. `rec_args` contains information about `xs`.
-/
@[derive has_reflect]
meta structure constructor_info :=
(cname : name)
(non_param_args : list constructor_argument_info)
(num_non_param_args : ℕ)
(rec_args : list constructor_argument_info)
(num_rec_args : ℕ)
/--
When we construct the goal for the minor premise of a given constructor, this is
the number of hypotheses we must name.
-/
meta def constructor_info.num_nameable_hypotheses (c : constructor_info) : ℕ :=
c.num_non_param_args + c.num_rec_args
/--
Information about an inductive type. Contains:
- `iname`: the type's name.
- `constructors`: information about the type's constructors.
- `num_constructors`: the length of `constructors`.
- `type`: the type's type.
- `num_param`: the type's number of parameters.
- `num_indices`: the type's number of indices.
-/
@[derive has_reflect]
meta structure inductive_info :=
(iname : name)
(constructors : list constructor_info)
(num_constructors : ℕ)
(type : expr)
(num_params : ℕ)
(num_indices : ℕ)
/--
Information about a major premise (i.e. the hypothesis on which we are
performing induction). Contains:
- `mpname`: the major premise's name.
- `mpexpr`: the major premise itself.
- `type`: the type of `mpexpr`.
- `args`: the arguments of the major premise. The major premise has type
`I x₀ ... xₙ`, where `I` is an inductive type. `args` is the map
`[0 → x₀, ..., n → xₙ]`.
-/
meta structure major_premise_info :=
(mpname : name)
(mpexpr : expr)
(type : expr)
(args : rb_map ℕ expr)
/--
`index_occurrence_type_match t s` is true iff `t` and `s` are definitionally
equal.
-/
-- We could extend this check to be more permissive. E.g. if a constructor
-- argument has type `list α` and the index has type `list β`, we may want to
-- consider these types sufficiently similar to inherit the name. Same (but even
-- more obvious) with `vec α n` and `vec α (n + 1)`.
meta def index_occurrence_type_match (t s : expr) : tactic bool :=
succeeds $ is_def_eq t s
/--
From the return type of a constructor `C` of an inductive type `I`, determine
the index occurrences of the constructor arguments of `C`.
Input:
- `num_params:` the number of parameters of `I`.
- `ret_type`: the return type of `C`. `e` must be of the form `I x₁ ... xₙ`.
Output: A map associating each local constant `c` that appears in any of the `xᵢ`
with the set of indexes `j` such that `c` appears in `xⱼ` and `xⱼ`'s type
matches that of `c` according to `tactic.index_occurrence_type_match`.
-/
meta def get_index_occurrences (num_params : ℕ) (ret_type : expr) :
tactic (rb_lmap expr ℕ) := do
ret_args ← get_app_args_whnf ret_type,
ret_args.mfoldl_with_index
(λ i occ_map ret_arg, do
if i < num_params
then pure occ_map
else do
let ret_arg_consts := ret_arg.list_local_consts',
ret_arg_consts.mfold occ_map $ λ c occ_map, do
ret_arg_type ← infer_type ret_arg,
eq ← index_occurrence_type_match c.local_type ret_arg_type,
pure $ if eq then occ_map.insert c i else occ_map)
mk_rb_map
/--
`match_recursive_constructor_arg I T`, given `I` the name of an inductive type
and `T` the type of an argument of a constructor of `I`, returns `none` if the
argument is non-recursive (i.e. `I` does not appear in `T`). If the argument is
recursive, `T` is of the form `Π (x₁ : T₁) ... (xₙ : Tₙ), I ...`, in which case
`match_recursive_constructor_arg` returns `some n`. Matching is performed up to
WHNF with semireducible transparency.
-/
meta def match_recursive_constructor_arg (I : name) (T : expr) :
tactic (option ℕ) := do
(pis, base) ← open_pis_whnf T,
base ← get_app_fn_whnf base,
pure $
match base with
| (const c _) := if c = I then some pis.length else none
| _ := none
end
/--
Get information about the arguments of a constructor `C` of an inductive type
`I`.
Input:
- `inductive_name`: the name of `I`.
- `num_params`: the number of parameters of `I`.
- `T`: the type of `C`.
Output: a `constructor_argument_info` structure for each argument of `C`.
-/
meta def get_constructor_argument_info (inductive_name : name)
(num_params : ℕ) (T : expr) :
tactic (list constructor_argument_info) := do
⟨args, ret⟩ ← open_pis_whnf_dep T,
index_occs ← get_index_occurrences num_params ret,
args.mmap $ λ ⟨c, dep⟩, do
let occs := rb_set.of_list $ index_occs.find c,
let type := c.local_type,
recursive_leading_pis ← match_recursive_constructor_arg inductive_name type,
pure ⟨c.local_pp_name, type, dep, occs.to_list, recursive_leading_pis⟩
/--
Get information about a constructor `C` of an inductive type `I`.
Input:
- `iname`: the name of `I`.
- `num_params`: the number of parameters of `I`.
- `c` : the name of `C`.
Output:
A `constructor_info` structure for `C`.
-/
meta def get_constructor_info (iname : name) (num_params : ℕ) (c : name) :
tactic constructor_info := do
env ← get_env,
when (¬ env.is_constructor c) $ fail! "Expected {c} to be a constructor.",
decl ← env.get c,
args ← get_constructor_argument_info iname num_params decl.type,
let non_param_args := args.drop num_params,
let rec_args := non_param_args.filter $ λ ainfo, ainfo.is_recursive,
pure
{ cname := decl.to_name,
non_param_args := non_param_args,
num_non_param_args := non_param_args.length,
rec_args := rec_args,
num_rec_args := rec_args.length }
/--
Get information about an inductive type `I`, given `I`'s name.
-/
meta def get_inductive_info (I : name) : tactic inductive_info := do
env ← get_env,
when (¬ env.is_inductive I) $ fail! "Expected {I} to be an inductive type.",
decl ← env.get I,
let type := decl.type,
let num_params := env.inductive_num_params I,
let num_indices := env.inductive_num_indices I,
let constructor_names := env.constructors_of I,
constructors ← constructor_names.mmap
(get_constructor_info I num_params),
pure
{ iname := I,
constructors := constructors,
num_constructors := constructors.length,
type := type,
num_params := num_params,
num_indices := num_indices }
/--
Get information about a major premise. The given `expr` must be a local
hypothesis.
-/
meta def get_major_premise_info (major_premise : expr) :
tactic major_premise_info := do
type ← infer_type major_premise,
⟨f, args⟩ ← get_app_fn_args_whnf type,
pure
{ mpname := major_premise.local_pp_name,
mpexpr := major_premise,
type := type,
args := args.to_rb_map }
/-!
## Constructor Argument Naming
We define the algorithm for naming constructor arguments (which is a remarkably
big part of the tactic).
-/
/--
Information used when naming a constructor argument.
-/
meta structure constructor_argument_naming_info :=
(mpinfo : major_premise_info)
(iinfo : inductive_info)
(cinfo : constructor_info)
(ainfo : constructor_argument_info)
/--
A constructor argument naming rule takes a `constructor_argument_naming_info`
structure and returns a list of suitable names for the argument. If the rule is
not applicable to the given constructor argument, the returned list is empty.
-/
@[reducible] meta def constructor_argument_naming_rule : Type :=
constructor_argument_naming_info → tactic (list name)
/--
Naming rule for recursive constructor arguments.
-/
meta def constructor_argument_naming_rule_rec : constructor_argument_naming_rule :=
λ i, pure $ if i.ainfo.is_recursive then [i.mpinfo.mpname] else []
/--
Naming rule for constructor arguments associated with an index.
-/
meta def constructor_argument_naming_rule_index : constructor_argument_naming_rule :=
λ i,
let index_occs := i.ainfo.index_occurrences in
let major_premise_args := i.mpinfo.args in
let get_major_premise_arg_local_names : ℕ → option (name × name) := λ i, do
{ arg ← major_premise_args.find i,
(uname, ppname, _) ← arg.match_local_const,
pure (uname, ppname) } in
let local_index_instantiations :=
(index_occs.map get_major_premise_arg_local_names).all_some in
/-
Right now, this rule only triggers if the major premise arg is exactly a
local const. We could consider a more permissive rule where the major premise
arg can be an arbitrary term as long as that term *contains* only a single local
const.
-/
pure $
match local_index_instantiations with
| none := []
| some [] := []
| some ((uname, ppname) :: is) :=
if is.all (λ ⟨uname', _⟩, uname' = uname)
then [ppname]
else []
end
/--
Naming rule for constructor arguments which are named in the constructor
declaration.
-/
meta def constructor_argument_naming_rule_named : constructor_argument_naming_rule :=
λ i,
let arg_name := i.ainfo.aname in
let arg_dep := i.ainfo.dependent in
pure $
if ! arg_dep && arg_name.is_likely_generated_binder_name
then []
else [arg_name]
/--
Naming rule for constructor arguments whose type is associated with a list of
typical variable names. See `tactic.typical_variable_names`.
-/
meta def constructor_argument_naming_rule_type : constructor_argument_naming_rule :=
λ i, typical_variable_names i.ainfo.type <|> pure []
/--
Naming rule for constructor arguments whose type is in `Prop`.
-/
meta def constructor_argument_naming_rule_prop : constructor_argument_naming_rule :=
λ i, do
(sort level.zero) ← infer_type i.ainfo.type | pure [],
pure [`h]
/--
Fallback constructor argument naming rule. This rule never fails.
-/
meta def constructor_argument_naming_rule_fallback : constructor_argument_naming_rule :=
λ _, pure [`x]
/--
`apply_constructor_argument_naming_rules info rules` applies the constructor
argument naming rules in `rules` to the constructor argument given by `info`.
Returns the result of the first applicable rule. Fails if no rule is applicable.
-/
meta def apply_constructor_argument_naming_rules
(info : constructor_argument_naming_info)
(rules : list constructor_argument_naming_rule) : tactic (list name) := do
names ← try_core $ rules.mfirst (λ r, do
names ← r info,
match names with
| [] := failed
| _ := pure names
end),
match names with
| none := fail
"apply_constructor_argument_naming_rules: no applicable naming rule"
| (some names) := pure names
end
/--
Get possible names for a constructor argument. This tactic applies all the
previously defined rules in order. It cannot fail and always returns a nonempty
list.
-/
meta def constructor_argument_names (info : constructor_argument_naming_info) :
tactic (list name) :=
apply_constructor_argument_naming_rules info
[ constructor_argument_naming_rule_rec
, constructor_argument_naming_rule_index
, constructor_argument_naming_rule_named
, constructor_argument_naming_rule_type
, constructor_argument_naming_rule_prop
, constructor_argument_naming_rule_fallback ]
/--
`intron_fresh n` introduces `n` hypotheses with names generated by
`tactic.mk_fresh_name`.
-/
meta def intron_fresh (n : ℕ) : tactic (list expr) :=
iterate_exactly n (mk_fresh_name >>= intro)
/--
Introduce the new hypotheses generated by the minor premise for a given
constructor. The new hypotheses are given fresh (unique, non-human-friendly)
names. They are later renamed by `constructor_renames`. We delay the generation
of the human-friendly names because when `constructor_renames` is called, more
names may have become unused.
Input:
- `generate_induction_hyps`: whether we generate induction hypotheses (i.e.
whether `eliminate_hyp` is in `induction` or `cases` mode).
- `cinfo`: information about the constructor.
Output:
- For each constructor argument: (1) the pretty name of the newly introduced
hypothesis corresponding to the argument; (2) the argument's
`constructor_argument_info`.
- For each newly introduced induction hypothesis: (1) its pretty name; (2) the
pretty name of the hypothesis corresponding to the constructor argument from
which this induction hypothesis was derived; (3) that constructor argument's
`constructor_argument_info`.
-/
meta def constructor_intros (generate_induction_hyps : bool)
(cinfo : constructor_info) :
tactic (list (name × constructor_argument_info) ×
list (name × name × constructor_argument_info)) := do
let args := cinfo.non_param_args,
arg_hyps ← intron_fresh cinfo.num_non_param_args,
let args := (arg_hyps.map expr.local_pp_name).zip args,
tt ← pure generate_induction_hyps | pure (args, []),
let rec_args := args.filter $ λ x, x.2.is_recursive,
ih_hyps ← intron_fresh cinfo.num_rec_args,
let ihs := (ih_hyps.map expr.local_pp_name).zip rec_args,
pure (args, ihs)
/--
`ih_name arg_name` is the name `ih_<arg_name>`.
-/
meta def ih_name (arg_name : name) : name :=
mk_simple_name ("ih_" ++ arg_name.to_string)
/--
Representation of a pattern in the `with n ...` syntax supported by
`induction'` and `cases'`. A `with_pattern` can be:
- `with_pattern.auto` (`with _` or no `with` clause): use the name generated by the tactic.
- `with_pattern.clear` (`with -`): clear this hypothesis and any hypotheses depending on it.
- `with_pattern.exact n` (`with n`): use the name `n` for this hypothesis.
-/
@[derive has_reflect]
meta inductive with_pattern
| auto
| clear
| exact (n : name)
namespace with_pattern
open lean (parser)
open lean.parser
/-- Parser for a `with_pattern`. -/
protected meta def parser : lean.parser with_pattern :=
(tk "-" *> pure with_pattern.clear) <|>
(tk "_" *> pure with_pattern.auto) <|>
(with_pattern.exact <$> ident)
/-- Parser for a `with` clause. -/
meta def clause_parser : lean.parser (list with_pattern) :=
(tk "with" *> many with_pattern.parser) <|> pure []
/--
`to_name_spec auto_candidates p` returns a description of how the hypothesis to
which the `with_pattern` `p` applies should be named. If this function returns
`none`, the hypothesis should be cleared. If it returns `some (inl n)`, it
should receive exactly the name `n`, even if this shadows other hypotheses. If
it returns `some (inr ns)`, it should receive the first unused name from `ns`.
If `p = auto`, the `auto_candidates` tactic is run to determine candidate names
for the hypothesis (from which the first fresh one is later chosen).
`auto_candidates` must return a nonempty list.
-/
meta def to_name_spec (auto_candidates : tactic (list name)) :
with_pattern → tactic (option (name ⊕ list name))
| auto := (some ∘ sum.inr) <$> auto_candidates
| clear := pure none
| (exact n) := pure $ some $ sum.inl n
end with_pattern
/--
If `h` refers to a hypothesis, `clear_dependent_if_exists h` clears `h` and any
hypotheses which depend on it. Otherwise, the tactic does nothing.
-/
meta def clear_dependent_if_exists (h : name) : tactic unit := do
(some h) ← try_core $ get_local h | pure (),
clear' tt [h]
/--
Rename the new hypotheses in the goal for a minor premise.
Input:
- `generate_induction_hyps`: whether we generate induction hypotheses (i.e.
whether `eliminate_hyp` is in `induction` or `cases` mode).
- `mpinfo`: information about the major premise.
- `iinfo`: information about the inductive type.
- `cinfo`: information about the constructor whose minor premise we are
processing.
- `with_patterns`: a list of `with` patterns given by the user. These are used
to name constructor arguments and induction hypotheses. If the list does not
contain enough patterns for all introduced hypotheses, the remaining ones are
treated as if the user had given `with_pattern.auto` (`_`).
- `args` and `ihs`: the output of `constructor_intros`.
Output:
- The newly introduced hypotheses corresponding to constructor arguments.
- The newly introduced induction hypotheses.
-/
meta def constructor_renames (generate_induction_hyps : bool)
(mpinfo : major_premise_info) (iinfo : inductive_info)
(cinfo : constructor_info) (with_patterns : list with_pattern)
(args : list (name × constructor_argument_info))
(ihs : list (name × name × constructor_argument_info)) :
tactic (list expr × list expr) := do
-- Rename constructor arguments
let arg_pp_name_set := name_set.of_list $ args.map prod.fst,
let iname := iinfo.iname,
let ⟨args, with_patterns⟩ :=
args.map₂_left' (λ arg p, (arg, p.get_or_else with_pattern.auto))
with_patterns,
arg_renames ← args.mmap_filter $ λ ⟨⟨old_ppname, ainfo⟩, with_pat⟩, do
{ (some new) ← with_pat.to_name_spec
(constructor_argument_names ⟨mpinfo, iinfo, cinfo, ainfo⟩)
| clear_dependent_if_exists old_ppname >> pure none,
-- Some of the arg hyps may have been cleared by earlier simplification
-- steps, so get_local may fail.
(some old) ← try_core $ get_local old_ppname | pure none,
pure $ some (old.local_uniq_name, new) },
let arg_renames := rb_map.of_list arg_renames,
arg_hyp_map ← rename_fresh arg_renames mk_name_set,
let new_arg_hyps := arg_hyp_map.filter_map $ λ ⟨old, new⟩,
if arg_pp_name_set.contains old.local_pp_name then some new else none,
let arg_hyp_map : name_map expr :=
rb_map.of_list $ arg_hyp_map.map $ λ ⟨old, new⟩, (old.local_pp_name, new),
-- Rename induction hypotheses (if we generated them)
tt ← pure generate_induction_hyps | pure (new_arg_hyps, []),
let ih_pp_name_set := name_set.of_list $ ihs.map prod.fst,
let ihs :=
ihs.map₂_left (λ ih p, (ih, p.get_or_else with_pattern.auto)) with_patterns,
let single_ih := ihs.length = 1,
ih_renames ← ihs.mmap_filter $ λ ⟨⟨ih_hyp_ppname, arg_hyp_ppname, _⟩, with_pat⟩, do
{ some arg_hyp ← pure $ arg_hyp_map.find arg_hyp_ppname
| fail! "internal error in constructor_renames: {arg_hyp_ppname} not found in arg_hyp_map",
(some new) ← with_pat.to_name_spec (pure $
if single_ih
then [`ih, ih_name arg_hyp.local_pp_name]
-- If we have only a single IH which hasn't been named explicitly in a
-- `with` clause, the preferred name is "ih". If that is taken, we fall
-- back to the name the IH would ordinarily receive.
else [ih_name arg_hyp.local_pp_name])
| clear_dependent_if_exists ih_hyp_ppname >> pure none,
(some ih_hyp) ← try_core $ get_local ih_hyp_ppname | pure none,
pure $ some (ih_hyp.local_uniq_name, new) },
ih_hyp_map ← rename_fresh (rb_map.of_list ih_renames) mk_name_set,
let new_ih_hyps := ih_hyp_map.filter_map $ λ ⟨old, new⟩,
if ih_pp_name_set.contains old.local_pp_name then some new else none,
pure (new_arg_hyps, new_ih_hyps)
/-!
## Generalisation
`induction'` can generalise the goal before performing an induction, which gives
us a more general induction hypothesis. We call this 'auto-generalisation'.
-/
/--
A value of `generalization_mode` describes the behaviour of the
auto-generalisation functionality:
- `generalize_all_except hs` means that the `hs` remain fixed and all other
hypotheses are generalised. However, there are three exceptions:
* Hypotheses depending on any `h` in `hs` also remain fixed. If we were to
generalise them, we would have to generalise `h` as well.
* Hypotheses which do not occur in the target and which do not mention the
major premise or its dependencies are never generalised. Generalising them
would not lead to a more general induction hypothesis.
* Local definitions (hypotheses of the form `h : T := t`) and their
dependencies are not generalised. This is due to limitations of the
implementation; local definitions could in principle be generalised.
- `generalize_only hs` means that only the `hs` are generalised. Exception:
hypotheses which depend on the major premise are generalised even if they do
not appear in `hs`.
-/
@[derive has_reflect]
inductive generalization_mode
| generalize_all_except (hs : list name) : generalization_mode
| generalize_only (hs : list name) : generalization_mode
instance : inhabited generalization_mode :=
⟨ generalization_mode.generalize_all_except []⟩
namespace generalization_mode
/--
Given the major premise and a generalization_mode, this function returns the
unique names of the hypotheses that should be generalized. See
`generalization_mode` for what these are.
-/
meta def to_generalize (major_premise : expr) :
generalization_mode → tactic name_set
| (generalize_only ns) := do
major_premise_rev_deps ← reverse_dependencies_of_hyps [major_premise],
let major_premise_rev_deps :=
name_set.of_list $ major_premise_rev_deps.map local_uniq_name,
ns ← ns.mmap (functor.map local_uniq_name ∘ get_local),
pure $ major_premise_rev_deps.insert_list ns
| (generalize_all_except fixed) := do
fixed ← fixed.mmap get_local,
tgt ← target,
let tgt_dependencies := tgt.list_local_const_unique_names,
major_premise_type ← infer_type major_premise,
major_premise_dependencies ← dependency_name_set_of_hyp_inclusive major_premise,
defs ← local_defs,
fixed_dependencies ←
(major_premise :: defs ++ fixed).mmap dependency_name_set_of_hyp_inclusive,
let fixed_dependencies := fixed_dependencies.foldl name_set.union mk_name_set,
ctx ← local_context,
to_revert ← ctx.mmap_filter $ λ h, do
{ h_depends_on_major_premise_deps ←
-- TODO `hyp_depends_on_local_name_set` is somewhat expensive
hyp_depends_on_local_name_set h major_premise_dependencies,
let h_name := h.local_uniq_name,
let rev :=
¬ fixed_dependencies.contains h_name ∧
(h_depends_on_major_premise_deps ∨ tgt_dependencies.contains h_name),
/-
I think `h_depends_on_major_premise_deps` is an overapproximation. What we
actually want is any hyp that depends either on the major_premise or on one
of the major_premise's index args. (But the overapproximation seems to work
okay in practice as well.)
-/
pure $ if rev then some h_name else none },
pure $ name_set.of_list to_revert
end generalization_mode
/--
Generalize hypotheses for the given major premise and generalization mode. See
`generalization_mode` and `to_generalize`.
-/
meta def generalize_hyps (major_premise : expr) (gm : generalization_mode) :
tactic ℕ := do
to_revert ← gm.to_generalize major_premise,
⟨n, _⟩ ← unfreezing (revert_name_set to_revert),
pure n
/-!
## Complex Index Generalisation
A *complex* expression is any expression that is not merely a local constant.
When such a complex expression appears as an argument of the major premise, and
when that argument is an index of the inductive type, we must generalise the
complex expression. E.g. when we operate on the major premise `fin (2 + n)`
(assuming that `fin` is encoded as an inductive type), the `2 + n` is a complex
index argument. To generalise it, we replace it with a new hypothesis
`index : ℕ` and add an equation `induction_eq : index = 2 + n`.
-/
/--
Generalise the complex index arguments.
Input:
- `major premise`: the major premise.
- `num_params`: the number of parameters of the inductive type.
- `generate_induction_hyps`: whether we generate induction hypotheses (i.e.
whether `eliminate_hyp` is in `induction` or `cases` mode).
Output:
- The new major premise. This procedure may change the major premise's type
signature, so the old major premise hypothesis is invalidated.
- The number of index placeholder hypotheses we introduced.
- The index placeholder hypotheses we introduced.
- The number of hypotheses which were reverted because they contain complex
indices.
-/
/-
TODO The following function currently replaces complex index arguments
everywhere in the goal, not only in the major premise. Such replacements are
sometimes necessary to make sure that the goal remains type-correct. However,
the replacements can also have the opposite effect, yielding unprovable
subgoals. The test suite contains one such case. There is probably a middle
ground between 'replace everywhere' and 'replace only in the major premise', but
I don't know what exactly this middle ground is. See also the discussion at
https://github.com/leanprover-community/mathlib/pull/5027#discussion_r538902424
-/
meta def generalize_complex_index_args (major_premise : expr) (num_params : ℕ)
(generate_induction_hyps : bool) : tactic (expr × ℕ × list name × ℕ) :=
focus1 $ do
major_premise_type ← infer_type major_premise,
(major_premise_head, major_premise_args) ←
get_app_fn_args_whnf major_premise_type,
let ⟨major_premise_param_args, major_premise_index_args⟩ :=
major_premise_args.split_at num_params,
-- TODO Add equations only for complex index args (not all index args).
-- This shouldn't matter semantically, but we'd get simpler terms.
let js := major_premise_index_args,
ctx ← local_context,
tgt ← target,
major_premise_deps ← dependency_name_set_of_hyp_inclusive major_premise,
-- Revert the hypotheses which depend on the index args or the major_premise.
-- We exclude dependencies of the major premise because we can't replace their
-- index occurrences anyway when we apply the recursor.
relevant_ctx ← ctx.mfilter $ λ h, do
{ let dep_of_major_premise := major_premise_deps.contains h.local_uniq_name,
dep_on_major_premise ← hyp_depends_on_locals h [major_premise],
H ← infer_type h,
dep_of_index ← js.many $ λ j, kdepends_on H j,
-- TODO We need a variant of `kdepends_on` that takes local defs into account.
pure $
(dep_on_major_premise ∧ h ≠ major_premise) ∨
(dep_of_index ∧ ¬ dep_of_major_premise) },
⟨relevant_ctx_size, relevant_ctx⟩ ← unfreezing $ do
{ r ← revert_lst' relevant_ctx,
revert major_premise,
pure r },
-- Create the local constants that will replace the index args. We have to be
-- careful to get the right types.
let go : expr → list expr → tactic (list expr) :=
λ j ks, do
{ J ← infer_type j,
k ← mk_local' `index binder_info.default J,
ks ← ks.mmap $ λ k', kreplace k' j k,
pure $ k :: ks },
ks ← js.mfoldr go [],
let js_ks := js.zip ks,
-- Replace the index args in the relevant context.
new_ctx ← relevant_ctx.mmap $ λ h, js_ks.mfoldr (λ ⟨j, k⟩ h, kreplace h j k) h,
-- Replace the index args in the major premise.
let new_major_premise_type :=
major_premise_head.mk_app (major_premise_param_args ++ ks),
let new_major_premise :=
local_const major_premise.local_uniq_name major_premise.local_pp_name
major_premise.binding_info new_major_premise_type,
-- Replace the index args in the target.
new_tgt ← js_ks.mfoldr (λ ⟨j, k⟩ tgt, kreplace tgt j k) tgt,
let new_tgt := new_tgt.pis (new_major_premise :: new_ctx),
-- Generate the index equations and their proofs.
let eq_name := if generate_induction_hyps then `induction_eq else `cases_eq,
let step2_input := js_ks.map $ λ ⟨j, k⟩, (eq_name, j, k),
eqs_and_proofs ← generalizes.step2 reducible step2_input,
let eqs := eqs_and_proofs.map prod.fst,
let eq_proofs := eqs_and_proofs.map prod.snd,
-- Assert the generalized goal and derive the current goal from it.
generalizes.step3 new_tgt js ks eqs eq_proofs,
-- Introduce the index variables and major premise. The index equations
-- and the relevant context remain reverted.
let num_index_vars := js.length,
index_vars ← intron' num_index_vars,
index_equations ← intron' num_index_vars,
major_premise ← intro1,
revert_lst index_equations,
let index_vars := index_vars.map local_pp_name,
pure (major_premise, index_vars.length, index_vars, relevant_ctx_size)
/-!
## Simplification of Induction Hypotheses
Auto-generalisation and complex index generalisation may produce unnecessarily
complex induction hypotheses. We define a simplification algorithm that recovers
understandable induction hypotheses in many practical cases.
-/
/--
Process one index equation for `simplify_ih`.
Input: a local constant `h : x = y` or `h : x == y`.
Output: A proof of `x = y` or `x == y` and possibly a local constant of type
`x = y` or `x == y` used in the proof. More specifically:
- For `h : x = y` and `x` defeq `y`, we return the proof of `x = y` by
reflexivity and `none`.
- For `h : x = y` and `x` not defeq `y`, we return `h` and `h`.
- For `h : x == y` where `x` and `y` have defeq types:
- If `x` defeq `y`, we return the proof of `x == y` by reflexivity and `none`.
- If `x` not defeq `y`, we return `heq_of_eq h'` and a fresh local constant
`h' : x = y`.
- For `h : x == y` where `x` and `y` do not have defeq types, we return
`h` and `h`.
Checking for definitional equality of the left- and right-hand sides may assign
metavariables.
-/
meta def process_index_equation : expr → tactic (expr × option expr)
| h@(local_const _ ppname binfo
T@(app (app (app (const `eq [u]) type) lhs) rhs)) := do
rhs_eq_lhs ← succeeds $ unify rhs lhs,
-- Note: It is important that we `unify rhs lhs` rather than `unify lhs rhs`.
-- This is because `lhs` and `rhs` may be metavariables which represent
-- Π-bound variables, so if they unify, we want to assign `rhs := lhs`.
-- If we assign `lhs := rhs` instead, it can happen that `lhs` is used before
-- `rhs` is bound, so the generated term becomes ill-typed.
if rhs_eq_lhs
then pure ((const `eq.refl [u]) type lhs, none)
else do
pure (h, some h)
| h@(local_const uname ppname binfo
T@(app (app (app (app (const `heq [u]) lhs_type) lhs) rhs_type) rhs)) := do
lhs_type_eq_rhs_type ← succeeds $ is_def_eq lhs_type rhs_type,
if ¬ lhs_type_eq_rhs_type
then do
pure (h, some h)
else do
lhs_eq_rhs ← succeeds $ unify rhs lhs,
-- See note above about `unify rhs lhs`.
if lhs_eq_rhs
then pure ((const `heq.refl [u]) lhs_type lhs, none)
else do
c ← mk_local' ppname binfo $ (const `eq [u]) lhs_type lhs rhs,
let arg := (const `heq_of_eq [u]) lhs_type lhs rhs c,
pure (arg, some c)
| (local_const _ _ _ T) := fail!
"process_index_equation: expected a homogeneous or heterogeneous equation, but got:\n{T}"
| e := fail!
"process_index_equation: expected a local constant, but got:\n{e}"
/--
`assign_local_to_unassigned_mvar mv pp_name binfo`, where `mv` is a
metavariable, acts as follows:
- If `mv` is assigned, it is not changed and the tactic returns `none`.
- If `mv` is not assigned, it is assigned a fresh local constant with
the type of `mv`, pretty name `pp_name` and binder info `binfo`. This local
constant is returned.
-/
meta def assign_local_to_unassigned_mvar (mv : expr) (pp_name : name)
(binfo : binder_info) : tactic (option expr) := do
ff ← is_assigned mv | pure none,
type ← infer_type mv,
c ← mk_local' pp_name binfo type,
unify mv c,
pure c
/--
Apply `assign_local_to_unassigned_mvar` to a list of metavariables. Returns the
newly created local constants.
-/
meta def assign_locals_to_unassigned_mvars
(mvars : list (expr × name × binder_info)) : tactic (list expr) :=
mvars.mmap_filter $ λ ⟨mv, pp_name, binfo⟩,
assign_local_to_unassigned_mvar mv pp_name binfo
/--
Simplify an induction hypothesis.
Input: a local constant
```
ih : ∀ (a₁ : A₁) ... (aₙ : Aₙ) (b₁ : B₁) ... (bₘ : Bₘ)
(eq₁ : y₁ = z₁) ... (eqₖ : yₒ = zₒ), P
```
where `n = num_leading_pis`, `m = num_generalized` and `o = num_index_vars`.
The `aᵢ` are arguments of the type of the constructor argument to which this
induction hypothesis belongs (usually zero). The `xᵢ` are hypotheses that we
generalised over before performing induction. The `eqᵢ` are index equations.
Output: a new local constant
```
ih' : ∀ (a'₁ : A'₁) ... (b'ₖ : B'ₖ) (eq'₁ : y'₁ = z'₁) ... (eq'ₗ : y'ₗ = z'ₗ), P'
```
This new induction hypothesis is derived from `ih` by removing those `eqᵢ` whose
left- and right-hand sides can be unified. This unification may also determine
some of the `aᵢ` and `bᵢ`. The `a'ᵢ`, `b'ᵢ` and `eq'ᵢ` are those `aᵢ`, `bᵢ` and
`eqᵢ` that were not removed by this process.
Some of the `eqᵢ` may be heterogeneous: `eqᵢ : yᵢ == zᵢ`. In this case, we
proceed as follows:
- If `yᵢ` and `zᵢ` are defeq, then `eqᵢ` is removed.
- If `yᵢ` and `zᵢ` are not defeq but their types are, then `eqᵢ` is replaced by
`eq'ᵢ : x = y`.
- Otherwise `eqᵢ` remains unchanged.
-/
/-
TODO `simplify_ih` currently uses Lean's builtin unification procedure to
process the index equations. This procedure has some limitations. For example,
we would like to clear an IH that assumes `0 = 1` since this IH can never be
applied, but Lean's unification doesn't allow us to conclude this.
It would therefore be preferable to use the algorithm from
`tactic.unify_equations` instead. There is no problem with this in principle,
but it requires a complete refactoring of `unify_equations` so that it works
not only on hypotheses but on arbitrary terms.
-/
meta def simplify_ih (num_leading_pis : ℕ) (num_generalized : ℕ)
(num_index_vars : ℕ) (ih : expr) : tactic expr := do
T ← infer_type ih,
-- Replace the `xᵢ` with fresh metavariables.
(generalized_arg_mvars, body) ← open_n_pis_metas' T (num_leading_pis + num_generalized),
-- Replace the `eqᵢ` with fresh local constants.
(index_eq_lcs, body) ← open_n_pis body num_index_vars,
-- Process the `eqᵢ` local constants, yielding
-- - `new_args`: proofs of `yᵢ = zᵢ`.
-- - `new_index_eq_lcs`: local constants of type `yᵢ = zᵢ` or `yᵢ == zᵢ` used
-- in `new_args`.
new_index_eq_lcs_new_args ← index_eq_lcs.mmap process_index_equation,
let (new_args, new_index_eq_lcs) := new_index_eq_lcs_new_args.unzip,
let new_index_eq_lcs := new_index_eq_lcs.reduce_option,
-- Assign fresh local constants to those `xᵢ` metavariables that were not
-- assigned by the previous step.
new_generalized_arg_lcs ←
assign_locals_to_unassigned_mvars generalized_arg_mvars,
-- Instantiate the metavariables assigned in the previous steps.
new_generalized_arg_lcs ← new_generalized_arg_lcs.mmap instantiate_mvars,
new_index_eq_lcs ← new_index_eq_lcs.mmap instantiate_mvars,
-- Construct a proof of the new induction hypothesis by applying `ih` to the
-- `xᵢ` metavariables and the `new_args`, then abstracting over the
-- `new_index_eq_lcs` and the `new_generalized_arg_lcs`.
b ← instantiate_mvars $
ih.mk_app (generalized_arg_mvars.map prod.fst ++ new_args),
new_ih ← lambdas (new_generalized_arg_lcs ++ new_index_eq_lcs) b,
-- Type-check the new induction hypothesis as a sanity check.
type_check new_ih <|> fail!
"internal error in simplify_ih: constructed term does not type check:\n{new_ih}",
-- Replace the old induction hypothesis with the new one.
ih' ← note ih.local_pp_name none new_ih,
clear ih,
pure ih'
/-!
## Temporary utilities
The utility functions in this section should be removed pending certain changes
to Lean's standard library.
-/
/--
Updates the tags of new subgoals produced by `cases` or `induction`. `in_tag`
is the initial tag, i.e. the tag of the goal on which `cases`/`induction` was
applied. `rs` should contain, for each subgoal, the constructor name
associated with that goal and the hypotheses that were introduced.
-/
-- TODO Copied from init.meta.interactive. Make that function non-private.
meta def set_cases_tags (in_tag : tag) (rs : list (name × list expr)) : tactic unit :=
do gs ← get_goals,
match gs with
-- if only one goal was produced, we should not make the tag longer
| [g] := set_tag g in_tag
| _ :=
let tgs : list (name × list expr × expr) :=
rs.map₂ (λ ⟨n, new_hyps⟩ g, ⟨n, new_hyps, g⟩) gs in
tgs.mmap' $ λ ⟨n, new_hyps, g⟩, with_enable_tags $
set_tag g $
(case_tag.from_tag_hyps (n :: in_tag) (new_hyps.map expr.local_uniq_name)).render
end
end eliminate
/-!
## The Elimination Tactics
Finally, we define the tactics `induction'` and `cases'` tactics as well as the
non-interactive variant `eliminate_hyp.`
-/
open eliminate
/--
`eliminate_hyp generate_ihs h gm with_patterns` performs induction or case
analysis on the hypothesis `h`. If `generate_ihs` is true, the tactic performs
induction, otherwise case analysis.
In case analysis mode, `eliminate_hyp` is very similar to `tactic.cases`. The
only differences (assuming no bugs in `eliminate_hyp`) are that `eliminate_hyp`
can do case analysis on a slightly larger class of hypotheses and that it
generates more human-friendly names.
In induction mode, `eliminate_hyp` is similar to `tactic.induction`, but with
more significant differences:
- If `h` (the hypothesis we are performing induction on) has complex indices,
`eliminate_hyp` 'remembers' them. A complex expression is any expression that
is not merely a local hypothesis. A hypothesis `h : I p₁ ... pₙ j₁ ... jₘ`,
where `I` is an inductive type with `n` parameters and `m` indices, has a
complex index if any of the `jᵢ` are complex. In this situation, standard
`induction` effectively forgets the exact values of the complex indices,
which often leads to unprovable goals. `eliminate_hyp` 'remembers' them by
adding propositional equalities. As a result, you may find equalities named
`induction_eq` in your goal, and the induction hypotheses may also quantify
over additional equalities.
- `eliminate_hyp` generalises induction hypotheses as much as possible by
default. This means that if you eliminate `n` in the goal
```
n m : ℕ
⊢ P n m
```
the induction hypothesis is `∀ m, P n m` instead of `P n m`.
You can modify this behaviour by giving a different generalisation mode `gm`;
see `tactic.eliminate.generalization_mode`.
- `eliminate_hyp` generates much more human-friendly names than `induction`. It
also clears more redundant hypotheses.
- `eliminate_hyp` currently does not support custom induction principles a la
`induction using`.
The `with_patterns` can be used to give names for the hypotheses introduced by
`eliminate_hyp`. See `tactic.eliminate.with_pattern` for details.
To debug this tactic, use
```
set_option trace.eliminate_hyp true
```
-/
meta def eliminate_hyp (generate_ihs : bool) (major_premise : expr)
(gm := generalization_mode.generalize_all_except [])
(with_patterns : list with_pattern := []) : tactic unit :=
focus1 $ do
mpinfo ← get_major_premise_info major_premise,
let major_premise_type := mpinfo.type,
let major_premise_args := mpinfo.args.values.reverse,
env ← get_env,
-- Get info about the inductive type
iname ← get_app_fn_const_whnf major_premise_type <|> fail!
"The type of {major_premise} should be an inductive type, but it is\n{major_premise_type}",
iinfo ← get_inductive_info iname,
-- We would like to disallow mutual/nested inductive types, since these have
-- complicated recursors which we probably don't support. However, there seems
-- to be no way to find out whether an inductive type is mutual/nested.
-- (`environment.is_ginductive` doesn't seem to work.)
trace_state_eliminate_hyp "State before complex index generalisation:",
-- Generalise complex indices
(major_premise, num_index_vars, index_var_names, num_index_generalized) ←
generalize_complex_index_args major_premise iinfo.num_params generate_ihs,
trace_state_eliminate_hyp
"State after complex index generalisation and before auto-generalisation:",
-- Generalise hypotheses according to the given generalization_mode.
num_auto_generalized ← generalize_hyps major_premise gm,
let num_generalized := num_index_generalized + num_auto_generalized,
-- NOTE: The previous step may have changed the unique names of all hyps in
-- the context.
-- Record the current case tag.
in_tag ← get_main_tag,
trace_state_eliminate_hyp
"State after auto-generalisation and before recursor application:",
-- Apply the recursor. We first try the nondependent recursor, then the
-- dependent recursor (if available).
-- Construct a pexpr `@rec _ ... _ major_premise`. Why not
-- ```(%%rec %%major_premise)?` Because for whatever reason, `false.rec_on`
-- takes the motive not as an implicit argument, like any other recursor, but
-- as an explicit one. Why not something based on `mk_app` or `mk_mapp`?
-- Because we need the special elaborator support for `elab_as_eliminator`
-- definitions.
let rec_app : name → pexpr := λ rec_suffix,
(unchecked_cast expr.mk_app : pexpr → list pexpr → pexpr)
(pexpr.mk_explicit (const (iname ++ rec_suffix) []))
(list.replicate (major_premise_args.length + 1) pexpr.mk_placeholder ++
[to_pexpr major_premise]),
let rec_suffix := if generate_ihs then "rec_on" else "cases_on",
let drec_suffix := if generate_ihs then "drec_on" else "dcases_on",
interactive.apply (rec_app rec_suffix)
<|> interactive.apply (rec_app drec_suffix)
<|> fail! "Failed to apply the (dependent) recursor for {iname} on {major_premise}.",
-- Prepare the "with" names for each constructor case.
let with_patterns := prod.fst $
with_patterns.take_list
(iinfo.constructors.map constructor_info.num_nameable_hypotheses),
let constrs := iinfo.constructors.zip with_patterns,
-- For each case (constructor):
cases : list (option (name × list expr)) ←
focus $ constrs.map $ λ ⟨cinfo, with_patterns⟩, do
{ trace_eliminate_hyp "============",
trace_eliminate_hyp $ format! "Case {cinfo.cname}",
trace_state_eliminate_hyp "Initial state:",
-- Get the major premise's arguments. (Some of these may have changed due
-- to the generalising step above.)
major_premise_type ← infer_type major_premise,
major_premise_args ← get_app_args_whnf major_premise_type,
-- Clear the eliminated hypothesis (if possible)
try $ clear major_premise,
-- Clear the index args (unless other stuff in the goal depends on them)
major_premise_args.mmap' (try ∘ clear),
trace_state_eliminate_hyp
"State after clearing the major premise (and its arguments) and before introductions:",
-- Introduce the constructor arguments
(constructor_args, ihs) ←
constructor_intros generate_ihs cinfo,
-- Introduce the auto-generalised hypotheses.
intron num_auto_generalized,
-- Introduce the index equations
index_equations ← intron' num_index_vars,
let index_equations := index_equations.map local_pp_name,
-- Introduce the hypotheses that were generalised during index
-- generalisation.
intron num_index_generalized,
trace_state_eliminate_hyp
"State after introductions and before simplifying index equations:",
-- Simplify the index equations. Stop after this step if the goal has been
-- solved by the simplification.
ff ← unify_equations index_equations
| trace_eliminate_hyp "Case solved while simplifying index equations." >>
pure none,
trace_state_eliminate_hyp
"State after simplifying index equations and before simplifying IHs:",
-- Simplify the induction hypotheses
-- NOTE: The previous step may have changed the unique names of the
-- induction hypotheses, so we have to locate them again. Their pretty
-- names should be unique in the context, so we can use these.
ihs.mmap' $ λ ⟨ih, _, arg_info⟩, do
{ ih ← get_local ih,
(some num_leading_pis) ← pure arg_info.recursive_leading_pis
| fail! "eliminate_hyp: internal error: unexpected non-recursive argument info",
simplify_ih num_leading_pis num_auto_generalized num_index_vars ih },
trace_state_eliminate_hyp
"State after simplifying IHs and before clearing index variables:",
-- Try to clear the index variables. These often become unused during
-- the index equation simplification step.
index_var_names.mmap $ λ h, try (get_local h >>= clear),
trace_state_eliminate_hyp
"State after clearing index variables and before renaming:",
-- Rename the constructor names and IHs. We do this here (rather than
-- earlier, when we introduced them) because there may now be less
-- hypotheses in the context, and therefore more of the desired
-- names may be free.
(constructor_arg_hyps, ih_hyps) ←
constructor_renames generate_ihs mpinfo iinfo cinfo with_patterns
constructor_args ihs,
trace_state_eliminate_hyp "Final state:",
-- Return the constructor name and the renamable new hypotheses. These are
-- the hypotheses that can later be renamed by the `case` tactic. Note
-- that index variables and index equations are not renamable. This may be
-- counterintuitive in some cases, but it's surprisingly difficult to
-- catch exactly the relevant hyps here.
pure $ some (cinfo.cname, constructor_arg_hyps ++ ih_hyps) },
set_cases_tags in_tag cases.reduce_option,
pure ()
/--
A variant of `tactic.eliminate_hyp` which performs induction or case analysis on
an arbitrary expression. `eliminate_hyp` requires that the major premise is a
hypothesis. `eliminate_expr` lifts this restriction by generalising the goal
over the major premise before calling `eliminate_hyp`. The generalisation
replaces the major premise with a new hypothesis `x` everywhere in the goal.
If `eq_name` is `some h`, an equation `h : major_premise = x` is added to
remember the value of the major premise.
-/
meta def eliminate_expr (generate_induction_hyps : bool) (major_premise : expr)
(eq_name : option name := none) (gm := generalization_mode.generalize_all_except [])
(with_patterns : list with_pattern := []) : tactic unit := do
major_premise_revdeps ← reverse_dependencies_of_hyps [major_premise],
num_reverted ← unfreezing (revert_lst major_premise_revdeps),
hyp ← match eq_name with
| some h := do
x ← get_unused_name `x,
interactive.generalize h () (to_pexpr major_premise, x),
get_local x
| none := do
if major_premise.is_local_constant
then pure major_premise
else do
x ← get_unused_name `x,
generalize' major_premise x
end,
intron num_reverted,
eliminate_hyp generate_induction_hyps hyp gm with_patterns
end tactic
namespace tactic.interactive
open tactic tactic.eliminate interactive interactive.types lean.parser
/--
Parse a `fixing` or `generalizing` clause for `induction'` or `cases'`.
-/
meta def generalisation_mode_parser : lean.parser generalization_mode :=
(tk "fixing" *>
((tk "*" *> pure (generalization_mode.generalize_only []))
<|>
generalization_mode.generalize_all_except <$> many ident))
<|>
(tk "generalizing" *> generalization_mode.generalize_only <$> many ident)
<|>
pure (generalization_mode.generalize_all_except [])
/--
A variant of `tactic.interactive.induction`, with the following differences:
- If the major premise (the hypothesis we are performing induction on) has
complex indices, `induction'` 'remembers' them. A complex expression is any
expression that is not merely a local hypothesis. A major premise
`h : I p₁ ... pₙ j₁ ... jₘ`, where `I` is an inductive type with `n`
parameters and `m` indices, has a complex index if any of the `jᵢ` are
complex. In this situation, standard `induction` effectively forgets the exact
values of the complex indices, which often leads to unprovable goals.
`induction'` 'remembers' them by adding propositional equalities. As a
result, you may find equalities named `induction_eq` in your goal, and the
induction hypotheses may also quantify over additional equalities.
- `induction'` generalises induction hypotheses as much as possible by default.
This means that if you eliminate `n` in the goal
```
n m : ℕ
⊢ P n m
```
the induction hypothesis is `∀ m, P n m` instead of `P n m`.
- `induction'` generates much more human-friendly names than `induction`. It
also clears redundant hypotheses more aggressively.
- `induction'` currently does not support custom induction principles a la
`induction using`.
Like `induction`, `induction'` supports some modifiers:
`induction' e with n₁ ... nₘ` uses the names `nᵢ` for the new hypotheses.
Instead of a name, you can also give an underscore (`_`) to have `induction'`
generate a name for you, or a hyphen (`-`) to clear the hypothesis and any
hypotheses that depend on it.
`induction' e fixing h₁ ... hₙ` fixes the hypotheses `hᵢ`, so the induction
hypothesis is not generalised over these hypotheses.
`induction' e fixing *` fixes all hypotheses. This disables the generalisation
functionality, so this mode behaves like standard `induction`.
`induction' e generalizing h₁ ... hₙ` generalises only the hypotheses `hᵢ`. This
mode behaves like `induction e generalizing h₁ ... hₙ`.
`induction' t`, where `t` is an arbitrary term (rather than a hypothesis),
generalises the goal over `t`, then performs induction on the generalised goal.
`induction' h : t = x` is similar, but also adds an equation `h : t = x` to
remember the value of `t`.
To debug this tactic, use
```
set_option trace.eliminate_hyp true
```
-/
meta def induction' (major_premise : parse cases_arg_p)
(gm : parse generalisation_mode_parser)
(with_patterns : parse with_pattern.clause_parser) :
tactic unit := do
let ⟨eq_name, e⟩ := major_premise,
e ← to_expr e,
eliminate_expr tt e eq_name gm with_patterns
/--
A variant of `tactic.interactive.cases`, with minor changes:
- `cases'` can perform case analysis on some (rare) goals that `cases` does not
support.
- `cases'` generates much more human-friendly names for the new hypotheses it
introduces.
This tactic supports the same modifiers as `cases`, e.g.
```
cases' H : e = x with n _ o
```
This is almost exactly the same as `tactic.interactive.induction'`, only that no
induction hypotheses are generated.
To debug this tactic, use
```
set_option trace.eliminate_hyp true
```
-/
meta def cases' (major_premise : parse cases_arg_p)
(with_patterns : parse with_pattern.clause_parser) :
tactic unit := do
let ⟨eq_name, e⟩ := major_premise,
e ← to_expr e,
eliminate_expr ff e eq_name (generalization_mode.generalize_only [])
with_patterns
end tactic.interactive
|
ab2d0550693857f3c5ab76bc4e0d216f96fe32dd | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/data/set/finite.lean | 55c375e5de45068f9ac49d9a46b383d92a985dd3 | [
"Apache-2.0"
] | permissive | hamdysalah1/mathlib | b915f86b2503feeae268de369f1b16932321f097 | 95454452f6b3569bf967d35aab8d852b1ddf8017 | refs/heads/master | 1,677,154,116,545 | 1,611,797,994,000 | 1,611,797,994,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 26,864 | 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.fintype.basic
/-!
# Finite sets
This file defines predicates `finite : set α → Prop` and `infinite : set α → Prop` and proves some
basic facts about finite sets.
-/
open set function
universes u v w x
variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x}
namespace set
/-- A set is finite if the subtype is a fintype, i.e. there is a
list that enumerates its members. -/
def finite (s : set α) : Prop := nonempty (fintype s)
/-- A set is infinite if it is not finite. -/
def infinite (s : set α) : Prop := ¬ finite s
/-- The subtype corresponding to a finite set is a finite type. Note
that because `finite` isn't a typeclass, this will not fire if it
is made into an instance -/
noncomputable def finite.fintype {s : set α} (h : finite s) : fintype s :=
classical.choice h
/-- Get a finset from a finite set -/
noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α :=
@set.to_finset _ _ h.fintype
@[simp] theorem finite.mem_to_finset {s : set α} {h : finite s} {a : α} : a ∈ h.to_finset ↔ a ∈ s :=
@mem_to_finset _ _ h.fintype _
@[simp] theorem finite.to_finset.nonempty {s : set α} (h : finite s) :
h.to_finset.nonempty ↔ s.nonempty :=
show (∃ x, x ∈ h.to_finset) ↔ (∃ x, x ∈ s),
from exists_congr (λ _, finite.mem_to_finset)
@[simp] lemma finite.coe_to_finset {α} {s : set α} (h : finite s) : ↑h.to_finset = s :=
@set.coe_to_finset _ s h.fintype
theorem finite.exists_finset {s : set α} : finite s →
∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s
| ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩
theorem finite.exists_finset_coe {s : set α} (hs : finite s) :
∃ s' : finset α, ↑s' = s :=
⟨hs.to_finset, hs.coe_to_finset⟩
/-- Finite sets can be lifted to finsets. -/
instance : can_lift (set α) (finset α) :=
{ coe := coe,
cond := finite,
prf := λ s hs, hs.exists_finset_coe }
theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} :=
⟨fintype.of_finset s (λ _, iff.rfl)⟩
theorem finite.of_fintype [fintype α] (s : set α) : finite s :=
by classical; exact ⟨set_fintype s⟩
theorem exists_finite_iff_finset {p : set α → Prop} :
(∃ s, finite s ∧ p s) ↔ ∃ s : finset α, p ↑s :=
⟨λ ⟨s, hs, hps⟩, ⟨hs.to_finset, hs.coe_to_finset.symm ▸ hps⟩,
λ ⟨s, hs⟩, ⟨↑s, finite_mem_finset s, hs⟩⟩
/-- Membership of a subset of a finite type is decidable.
Using this as an instance leads to potential loops with `subtype.fintype` under certain decidability
assumptions, so it should only be declared a local instance. -/
def decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) :=
decidable_of_iff _ mem_to_finset
instance fintype_empty : fintype (∅ : set α) :=
fintype.of_finset ∅ $ by simp
theorem empty_card : fintype.card (∅ : set α) = 0 := rfl
@[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} :
@fintype.card (∅ : set α) h = 0 :=
eq.trans (by congr) empty_card
@[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩
instance finite.inhabited : inhabited {s : set α // finite s} := ⟨⟨∅, finite_empty⟩⟩
/-- A `fintype` structure on `insert a s`. -/
def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) :=
fintype.of_finset ⟨a ::ₘ s.to_finset.1,
multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp
theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) :
@fintype.card _ (fintype_insert' s h) = fintype.card s + 1 :=
by rw [fintype_insert', fintype.card_of_finset];
simp [finset.card, to_finset]; refl
@[simp] theorem card_insert {a : α} (s : set α)
[fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} :
@fintype.card _ d = fintype.card s + 1 :=
by rw ← card_fintype_insert' s h; congr
lemma card_image_of_inj_on {s : set α} [fintype s]
{f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) :
fintype.card (f '' s) = fintype.card s :=
by haveI := classical.prop_decidable; exact
calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp)
... = s.to_finset.card : finset.card_image_of_inj_on
(λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy)
... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm
lemma card_image_of_injective (s : set α) [fintype s]
{f : α → β} [fintype (f '' s)] (H : function.injective f) :
fintype.card (f '' s) = fintype.card s :=
card_image_of_inj_on $ λ _ _ _ _ h, H h
section
local attribute [instance] decidable_mem_of_fintype
instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] :
fintype (insert a s : set α) :=
if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)]
else fintype_insert' _ h
end
@[simp] theorem finite.insert (a : α) {s : set α} : finite s → finite (insert a s)
| ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩
lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) :
(hs.insert a).to_finset = insert a hs.to_finset :=
finset.ext $ by simp
@[elab_as_eliminator]
theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s)
(H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s :=
let ⟨t⟩ := h in by exactI
match s.to_finset, @mem_to_finset _ s _ with
| ⟨l, nd⟩, al := begin
change ∀ a, a ∈ l ↔ a ∈ s at al,
clear _let_match _match t h, revert s nd al,
refine multiset.induction_on l _ (λ a l IH, _); intros s nd al,
{ rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al),
exact H0 },
{ rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al),
cases multiset.nodup_cons.1 nd with m nd',
refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)),
exact m }
end
end
@[elab_as_eliminator]
theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s)
(H0 : C ∅ finite_empty)
(H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (h.insert a)) :
C s h :=
have ∀h:finite s, C s h,
from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)),
this h
instance fintype_singleton (a : α) : fintype ({a} : set α) :=
unique.fintype
@[simp] theorem card_singleton (a : α) :
fintype.card ({a} : set α) = 1 :=
fintype.card_of_subsingleton _
@[simp] theorem finite_singleton (a : α) : finite ({a} : set α) :=
⟨set.fintype_singleton _⟩
instance fintype_pure : ∀ a : α, fintype (pure a : set α) :=
set.fintype_singleton
theorem finite_pure (a : α) : finite (pure a : set α) :=
⟨set.fintype_pure a⟩
instance fintype_univ [fintype α] : fintype (@univ α) :=
fintype.of_equiv α $ (equiv.set.univ α).symm
theorem finite_univ [fintype α] : finite (@univ α) := ⟨set.fintype_univ⟩
theorem infinite_univ_iff : (@univ α).infinite ↔ _root_.infinite α :=
⟨λ h₁, ⟨λ h₂, h₁ $ @finite_univ α h₂⟩,
λ ⟨h₁⟩ ⟨h₂⟩, h₁ $ @fintype.of_equiv _ _ h₂ $ equiv.set.univ _⟩
theorem infinite_univ [h : _root_.infinite α] : infinite (@univ α) :=
infinite_univ_iff.2 h
theorem infinite_coe_iff {s : set α} : _root_.infinite s ↔ infinite s :=
⟨λ ⟨h₁⟩ h₂, h₁ h₂.some, λ h₁, ⟨λ h₂, h₁ ⟨h₂⟩⟩⟩
theorem infinite.to_subtype {s : set α} (h : infinite s) : _root_.infinite s :=
infinite_coe_iff.2 h
/-- Embedding of `ℕ` into an infinite set. -/
noncomputable def infinite.nat_embedding (s : set α) (h : infinite s) : ℕ ↪ s :=
by { haveI := h.to_subtype, exact infinite.nat_embedding s }
lemma infinite.exists_subset_card_eq {s : set α} (hs : infinite s) (n : ℕ) :
∃ t : finset α, ↑t ⊆ s ∧ t.card = n :=
⟨((finset.range n).map (hs.nat_embedding _)).map (embedding.subtype _), by simp⟩
instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] :
fintype (s ∪ t : set α) :=
fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp
theorem finite.union {s t : set α} : finite s → finite t → finite (s ∪ t)
| ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩
instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] :
fintype ({a ∈ s | p a} : set α) :=
fintype.of_finset (s.to_finset.filter p) $ by simp
instance fintype_inter (s t : set α) [fintype s] [decidable_pred t] : fintype (s ∩ t : set α) :=
set.fintype_sep s t
/-- A `fintype` structure on a set defines a `fintype` structure on its subset. -/
def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred t] (h : t ⊆ s) : fintype t :=
by rw ← inter_eq_self_of_subset_right h; apply_instance
theorem finite.subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t
| ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩
theorem infinite_mono {s t : set α} (h : s ⊆ t) : infinite s → infinite t :=
mt (λ ht, ht.subset h)
instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) :=
fintype.of_finset (s.to_finset.image f) $ by simp
instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) :=
fintype.of_finset (finset.univ.image f) $ by simp [range]
theorem finite_range (f : α → β) [fintype α] : finite (range f) :=
by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩
theorem finite.image {s : set α} (f : α → β) : finite s → finite (f '' s)
| ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩
theorem infinite_of_infinite_image (f : α → β) {s : set α} (hs : (f '' s).infinite) :
s.infinite :=
mt (finite.image f) hs
lemma finite.dependent_image {s : set α} (hs : finite s) {F : Π i ∈ s, β} {t : set β}
(H : ∀ y ∈ t, ∃ x (hx : x ∈ s), y = F x hx) : set.finite t :=
begin
let G : s → β := λ x, F x.1 x.2,
have A : t ⊆ set.range G,
{ assume y hy,
rcases H y hy with ⟨x, hx, xy⟩,
refine ⟨⟨x, hx⟩, xy.symm⟩ },
letI : fintype s := finite.fintype hs,
exact (finite_range G).subset A
end
instance fintype_map {α β} [decidable_eq β] :
∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image
theorem finite.map {α β} {s : set α} :
∀ (f : α → β), finite s → finite (f <$> s) := finite.image
/-- If a function `f` has a partial inverse and sends a set `s` to a set with `[fintype]` instance,
then `s` has a `fintype` structure as well. -/
def fintype_of_fintype_image (s : set α)
{f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s :=
fintype.of_finset ⟨_, @multiset.nodup_filter_map β α g _
(@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a,
begin
suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s,
by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc],
rw exists_swap,
suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]},
simp [I _, (injective_of_partial_inv I).eq_iff]
end
theorem finite_of_finite_image {s : set α} {f : α → β} (hi : set.inj_on f s) :
finite (f '' s) → finite s | ⟨h⟩ :=
⟨@fintype.of_injective _ _ h (λa:s, ⟨f a.1, mem_image_of_mem f a.2⟩) $
assume a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext_iff_val.1 eq⟩
theorem finite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) :
finite (f '' s) ↔ finite s :=
⟨finite_of_finite_image hi, finite.image _⟩
theorem infinite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) :
infinite (f '' s) ↔ infinite s :=
not_congr $ finite_image_iff hi
theorem infinite_of_inj_on_maps_to {s : set α} {t : set β} {f : α → β}
(hi : inj_on f s) (hm : maps_to f s t) (hs : infinite s) : infinite t :=
infinite_mono (maps_to'.mp hm) $ (infinite_image_iff hi).2 hs
theorem infinite_range_of_injective [_root_.infinite α] {f : α → β} (hi : injective f) :
infinite (range f) :=
by { rw [←image_univ, infinite_image_iff (inj_on_of_injective hi _)], exact infinite_univ }
theorem infinite_of_injective_forall_mem [_root_.infinite α] {s : set β} {f : α → β}
(hi : injective f) (hf : ∀ x : α, f x ∈ s) : infinite s :=
by { rw ←range_subset_iff at hf, exact infinite_mono hf (infinite_range_of_injective hi) }
theorem finite.preimage {s : set β} {f : α → β}
(I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) :=
finite_of_finite_image I (h.subset (image_preimage_subset f s))
theorem finite.preimage_embedding {s : set β} (f : α ↪ β) (h : s.finite) : (f ⁻¹' s).finite :=
finite.preimage (λ _ _ _ _ h', f.injective h') h
instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι]
(f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) :=
fintype.of_finset (finset.univ.bUnion (λ i, (f i).to_finset)) $ by simp
theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) :
finite (⋃ i, f i) :=
⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩
/-- A union of sets with `fintype` structure over a set with `fintype` structure has a `fintype`
structure. -/
def fintype_set_bUnion [decidable_eq α] {ι : Type*} {s : set ι} [fintype s]
(f : ι → set α) (H : ∀ i ∈ s, fintype (f i)) : fintype (⋃ i ∈ s, f i) :=
by rw bUnion_eq_Union; exact
@set.fintype_Union _ _ _ _ _ (by rintro ⟨i, hi⟩; exact H i hi)
instance fintype_set_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s]
(f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) :=
fintype_set_bUnion _ (λ i _, H i)
theorem finite.sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) :=
by rw sUnion_eq_Union; haveI := finite.fintype h;
apply finite_Union; simpa using H
theorem finite.bUnion {α} {ι : Type*} {s : set ι} {f : Π i ∈ s, set α} :
finite s → (∀ i ∈ s, finite (f i ‹_›)) → finite (⋃ i∈s, f i ‹_›)
| ⟨hs⟩ h := by rw [bUnion_eq_Union]; exactI finite_Union (λ i, h _ _)
instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} :=
fintype.of_finset (finset.range n) $ by simp
instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} :=
by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1)
lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩
lemma finite_lt_nat (n : ℕ) : finite {i | i < n} := ⟨set.fintype_lt_nat _⟩
instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) :=
fintype.of_finset (s.to_finset.product t.to_finset) $ by simp
lemma finite.prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t)
| ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩
/-- `image2 f s t` is finitype if `s` and `t` are. -/
instance fintype_image2 [decidable_eq γ] (f : α → β → γ) (s : set α) (t : set β)
[hs : fintype s] [ht : fintype t] : fintype (image2 f s t : set γ) :=
by { rw ← image_prod, apply set.fintype_image }
lemma finite.image2 (f : α → β → γ) {s : set α} {t : set β} (hs : finite s) (ht : finite t) :
finite (image2 f s t) :=
by { rw ← image_prod, exact (hs.prod ht).image _ }
/-- If `s : set α` is a set with `fintype` instance and `f : α → set β` is a function such that
each `f a`, `a ∈ s`, has a `fintype` structure, then `s >>= f` has a `fintype` structure. -/
def fintype_bUnion {α β} [decidable_eq β] (s : set α) [fintype s]
(f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) :=
set.fintype_set_bUnion _ H
instance fintype_bUnion' {α β} [decidable_eq β] (s : set α) [fintype s]
(f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) :=
fintype_bUnion _ _ (λ i _, H i)
theorem finite_bUnion {α β} {s : set α} {f : α → set β} :
finite s → (∀ a ∈ s, finite (f a)) → finite (s >>= f)
| ⟨hs⟩ H := ⟨@fintype_bUnion _ _ (classical.dec_eq β) _ hs _ (λ a ha, (H a ha).fintype)⟩
instance fintype_seq {α β : Type u} [decidable_eq β]
(f : set (α → β)) (s : set α) [fintype f] [fintype s] :
fintype (f <*> s) :=
by rw seq_eq_bind_map; apply set.fintype_bUnion'
theorem finite.seq {α β : Type u} {f : set (α → β)} {s : set α} :
finite f → finite s → finite (f <*> s)
| ⟨hf⟩ ⟨hs⟩ := by { haveI := classical.dec_eq β, exactI ⟨set.fintype_seq _ _⟩ }
/-- There are finitely many subsets of a given finite set -/
lemma finite.finite_subsets {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} :=
begin
-- we just need to translate the result, already known for finsets,
-- to the language of finite sets
let s : set (set α) := coe '' (↑(finset.powerset (finite.to_finset h)) : set (finset α)),
have : finite s := (finite_mem_finset _).image _,
apply this.subset,
refine λ b hb, ⟨(h.subset hb).to_finset, _, finite.coe_to_finset _⟩,
simpa [finset.subset_iff]
end
lemma exists_min_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) :
s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b
| ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset]
using (finite.to_finset h1).exists_min_image f ⟨x, finite.mem_to_finset.2 hx⟩
lemma exists_max_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) :
s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a
| ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset]
using (finite.to_finset h1).exists_max_image f ⟨x, finite.mem_to_finset.2 hx⟩
end set
namespace finset
variables [decidable_eq β]
variables {s : finset α}
lemma finite_to_set (s : finset α) : set.finite (↑s : set α) :=
set.finite_mem_finset s
@[simp] lemma coe_bUnion {f : α → finset β} : ↑(s.bUnion f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) :=
by simp [set.ext_iff]
@[simp] lemma finite_to_set_to_finset {α : Type*} (s : finset α) :
(finite_to_set s).to_finset = s :=
by { ext, rw [set.finite.mem_to_finset, mem_coe] }
end finset
namespace set
lemma finite_subset_Union {s : set α} (hs : finite s)
{ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i :=
begin
casesI hs,
choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h},
refine ⟨range f, finite_range f, _⟩,
rintro x hx,
simp,
exact ⟨x, ⟨hx, hf _⟩⟩,
end
lemma eq_finite_Union_of_finite_subset_Union {ι} {s : ι → set α} {t : set α} (tfin : finite t)
(h : t ⊆ ⋃ i, s i) :
∃ I : set ι, (finite I) ∧ ∃ σ : {i | i ∈ I} → set α,
(∀ i, finite (σ i)) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i :=
let ⟨I, Ifin, hI⟩ := finite_subset_Union tfin h in
⟨I, Ifin, λ x, s x ∩ t,
λ i, tfin.subset (inter_subset_right _ _),
λ i, inter_subset_left _ _,
begin
ext x,
rw mem_Union,
split,
{ intro x_in,
rcases mem_Union.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩,
use [i, hi, H, x_in] },
{ rintros ⟨i, hi, H⟩,
exact H }
end⟩
/-- An increasing union distributes over finite intersection. -/
lemma Union_Inter_of_monotone {ι ι' α : Type*} [fintype ι] [linear_order ι']
[nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) :
(⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j :=
begin
ext x, refine ⟨λ hx, Union_Inter_subset hx, λ hx, _⟩,
simp only [mem_Inter, mem_Union, mem_Inter] at hx ⊢, choose j hj using hx,
obtain ⟨j₀⟩ := show nonempty ι', by apply_instance,
refine ⟨finset.univ.fold max j₀ j, λ i, hs i _ (hj i)⟩,
rw [finset.fold_op_rel_iff_or (@le_max_iff _ _)],
exact or.inr ⟨i, finset.mem_univ i, le_rfl⟩
end
instance nat.fintype_Iio (n : ℕ) : fintype (Iio n) :=
fintype.of_finset (finset.range n) $ by simp
/--
If `P` is some relation between terms of `γ` and sets in `γ`,
such that every finite set `t : set γ` has some `c : γ` related to it,
then there is a recursively defined sequence `u` in `γ`
so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`.
(We use this later to show sequentially compact sets
are totally bounded.)
-/
lemma seq_of_forall_finite_exists {γ : Type*}
{P : γ → set γ → Prop} (h : ∀ t, finite t → ∃ c, P c t) :
∃ u : ℕ → γ, ∀ n, P (u n) (u '' Iio n) :=
⟨λ n, @nat.strong_rec_on' (λ _, γ) n $ λ n ih, classical.some $ h
(range $ λ m : Iio n, ih m.1 m.2)
(finite_range _),
λ n, begin
classical,
refine nat.strong_rec_on' n (λ n ih, _),
rw nat.strong_rec_on_beta', convert classical.some_spec (h _ _),
ext x, split,
{ rintros ⟨m, hmn, rfl⟩, exact ⟨⟨m, hmn⟩, rfl⟩ },
{ rintros ⟨⟨m, hmn⟩, rfl⟩, exact ⟨m, hmn, rfl⟩ }
end⟩
lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : finite (range f))
(hg : finite (range g)) : finite (range (λ x, if p x then f x else g x)) :=
(hf.union hg).subset range_ite_subset
lemma finite_range_const {c : β} : finite (range (λ x : α, c)) :=
(finite_singleton c).subset range_const_subset
lemma range_find_greatest_subset {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ}:
range (λ x, nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) :=
by { rw range_subset_iff, assume x, simp [nat.lt_succ_iff, nat.find_greatest_le] }
lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} :
finite (range (λ x, nat.find_greatest (P x) b)) :=
(finset.range (b + 1)).finite_to_set.subset range_find_greatest_subset
lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) :
fintype.card s < fintype.card t :=
begin
rw [← s.coe_to_finset, ← t.coe_to_finset, finset.coe_ssubset] at h,
rw [fintype.card_of_finset' _ (λ x, mem_to_finset),
fintype.card_of_finset' _ (λ x, mem_to_finset)],
exact finset.card_lt_card h,
end
lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) :
fintype.card s ≤ fintype.card t :=
calc fintype.card s = s.to_finset.card : fintype.card_of_finset' _ (by simp)
... ≤ t.to_finset.card : finset.card_le_of_subset (λ x hx, by simp [set.subset_def, *] at *)
... = fintype.card t : eq.symm (fintype.card_of_finset' _ (by simp))
lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t]
(hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t :=
(eq_or_ssubset_of_subset hsub).elim id
(λ h, absurd hcard $ not_le_of_lt $ card_lt_card h)
lemma subset_iff_to_finset_subset (s t : set α) [fintype s] [fintype t] :
s ⊆ t ↔ s.to_finset ⊆ t.to_finset :=
⟨λ h x hx, set.mem_to_finset.mpr $ h $ set.mem_to_finset.mp hx,
λ h x hx, set.mem_to_finset.mp $ h $ set.mem_to_finset.mpr hx⟩
lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f)
[fintype (range f)] : fintype.card (range f) = fintype.card α :=
eq.symm $ fintype.card_congr $ equiv.set.range f hf
lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) :
s.nonempty → ∃a∈s, ∀a'∈s, f a ≤ f a' → f a = f a' :=
begin
classical,
refine h.induction_on _ _,
{ assume h, exact absurd h empty_not_nonempty },
assume a s his _ ih _,
cases s.eq_empty_or_nonempty with h h,
{ use a, simp [h] },
rcases ih h with ⟨b, hb, ih⟩,
by_cases f b ≤ f a,
{ refine ⟨a, set.mem_insert _ _, assume c hc hac, le_antisymm hac _⟩,
rcases set.mem_insert_iff.1 hc with rfl | hcs,
{ refl },
{ rwa [← ih c hcs (le_trans h hac)] } },
{ refine ⟨b, set.mem_insert_of_mem _ hb, assume c hc hbc, _⟩,
rcases set.mem_insert_iff.1 hc with rfl | hcs,
{ exact (h hbc).elim },
{ exact ih c hcs hbc } }
end
lemma finite.card_to_finset {s : set α} [fintype s] (h : s.finite) :
h.to_finset.card = fintype.card s :=
by { rw [← finset.card_attach, finset.attach_eq_univ, ← fintype.card], congr' 2, funext,
rw set.finite.mem_to_finset }
section
local attribute [instance, priority 1] classical.prop_decidable
lemma to_finset_compl {α : Type*} [fintype α] (s : set α) :
sᶜ.to_finset = (s.to_finset)ᶜ :=
by ext; simp
lemma to_finset_inter {α : Type*} [fintype α] (s t : set α) :
(s ∩ t).to_finset = s.to_finset ∩ t.to_finset :=
by ext; simp
lemma to_finset_union {α : Type*} [fintype α] (s t : set α) :
(s ∪ t).to_finset = s.to_finset ∪ t.to_finset :=
by ext; simp
end
section
variables [semilattice_sup α] [nonempty α] {s : set α}
/--A finite set is bounded above.-/
protected lemma finite.bdd_above (hs : finite s) : bdd_above s :=
finite.induction_on hs bdd_above_empty $ λ a s _ _ h, h.insert a
/--A finite union of sets which are all bounded above is still bounded above.-/
lemma finite.bdd_above_bUnion {I : set β} {S : β → set α} (H : finite I) :
(bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) :=
finite.induction_on H
(by simp only [bUnion_empty, bdd_above_empty, ball_empty_iff])
(λ a s ha _ hs, by simp only [bUnion_insert, ball_insert_iff, bdd_above_union, hs])
end
section
variables [semilattice_inf α] [nonempty α] {s : set α}
/--A finite set is bounded below.-/
protected lemma finite.bdd_below (hs : finite s) : bdd_below s :=
@finite.bdd_above (order_dual α) _ _ _ hs
/--A finite union of sets which are all bounded below is still bounded below.-/
lemma finite.bdd_below_bUnion {I : set β} {S : β → set α} (H : finite I) :
(bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) :=
@finite.bdd_above_bUnion (order_dual α) _ _ _ _ _ H
end
end set
namespace finset
/-- A finset is bounded above. -/
protected lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) :
bdd_above (↑s : set α) :=
s.finite_to_set.bdd_above
/-- A finset is bounded below. -/
protected lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) :
bdd_below (↑s : set α) :=
s.finite_to_set.bdd_below
end finset
lemma fintype.exists_max [fintype α] [nonempty α]
{β : Type*} [linear_order β] (f : α → β) :
∃ x₀ : α, ∀ x, f x ≤ f x₀ :=
begin
rcases set.finite_univ.exists_maximal_wrt f _ univ_nonempty with ⟨x, _, hx⟩,
exact ⟨x, λ y, (le_total (f x) (f y)).elim (λ h, ge_of_eq $ hx _ trivial h) id⟩
end
|
ba6fe02c6447050f2dc18c2be8c530801f811f7f | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/linarith/parsing.lean | 9e946e0f99f95bcec15c9ad01c038851cae27c18 | [] | 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,454 | lean | /-
Copyright (c) 2020 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.linarith.datatypes
import Mathlib.PostPort
namespace Mathlib
/-!
# Parsing input expressions into linear form
`linarith` computes the linear form of its input expressions,
assuming (without justification) that the type of these expressions
is a commutative semiring.
It identifies atoms up to ring-equivalence: that is, `(y*3)*x` will be identified `3*(x*y)`,
where the monomial `x*y` is the linear atom.
* Variables are represented by natural numbers.
* Monomials are represented by `monom := rb_map ℕ ℕ`. The monomial `1` is represented by the empty map.
* Linear combinations of monomials are represented by `sum := rb_map monom ℤ`.
All input expressions are converted to `sum`s, preserving the map from expressions to variables.
We then discard the monomial information, mapping each distinct monomial to a natural number.
The resulting `rb_map ℕ ℤ` represents the ring-normalized linear form of the expression.
This is ultimately converted into a `linexp` in the obvious way.
`linear_forms_and_vars` is the main entry point into this file. Everything else is contained.
-/
namespace linarith
/-! ### Parsing datatypes -/
/-- Variables (represented by natural numbers) map to their power. -/
|
da6c6ab9e6dc81ed2fde319461b07ea6b505a0da | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/limits/constructions/equalizers.lean | 65d273df6b00586c30a371d12d6937495578f034 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,593 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.limits.shapes.equalizers
import Mathlib.category_theory.limits.shapes.binary_products
import Mathlib.category_theory.limits.shapes.pullbacks
import Mathlib.PostPort
universes u u_1 v
namespace Mathlib
/-!
# Constructing equalizers from pullbacks and binary products.
If a category has pullbacks and binary products, then it has equalizers.
TODO: provide the dual result.
-/
namespace category_theory.limits
-- We hide the "implementation details" inside a namespace
namespace has_equalizers_of_pullbacks_and_binary_products
/-- Define the equalizing object -/
def construct_equalizer {C : Type u} [category C] [has_binary_products C] [has_pullbacks C] (F : walking_parallel_pair ⥤ C) : C :=
pullback (prod.lift 𝟙 (functor.map F walking_parallel_pair_hom.left))
(prod.lift 𝟙 (functor.map F walking_parallel_pair_hom.right))
/-- Define the equalizing morphism -/
def pullback_fst {C : Type u} [category C] [has_binary_products C] [has_pullbacks C] (F : walking_parallel_pair ⥤ C) : construct_equalizer F ⟶ functor.obj F walking_parallel_pair.zero :=
pullback.fst
theorem pullback_fst_eq_pullback_snd {C : Type u} [category C] [has_binary_products C] [has_pullbacks C] (F : walking_parallel_pair ⥤ C) : pullback_fst F = pullback.snd := sorry
/-- Define the equalizing cone -/
def equalizer_cone {C : Type u} [category C] [has_binary_products C] [has_pullbacks C] (F : walking_parallel_pair ⥤ C) : cone F :=
cone.of_fork (fork.of_ι (pullback_fst F) sorry)
/-- Show the equalizing cone is a limit -/
def equalizer_cone_is_limit {C : Type u} [category C] [has_binary_products C] [has_pullbacks C] (F : walking_parallel_pair ⥤ C) : is_limit (equalizer_cone F) :=
is_limit.mk
fun (c : cone F) =>
pullback.lift (nat_trans.app (cone.π c) walking_parallel_pair.zero)
(nat_trans.app (cone.π c) walking_parallel_pair.zero) sorry
end has_equalizers_of_pullbacks_and_binary_products
/-- Any category with pullbacks and binary products, has equalizers. -/
-- This is not an instance, as it is not always how one wants to construct equalizers!
theorem has_equalizers_of_pullbacks_and_binary_products {C : Type u} [category C] [has_binary_products C] [has_pullbacks C] : has_equalizers C :=
has_limits_of_shape.mk fun (F : walking_parallel_pair ⥤ C) => has_limit.mk (limit_cone.mk sorry sorry)
|
6f133dda76009bad4bbec325025d598c02ecdc9c | da3a76c514d38801bae19e8a9e496dc31f8e5866 | /tests/lean/run/eval_attr_cache.lean | 1f968ecdc523eaa3b786d98d929d94a42f7ac765 | [
"Apache-2.0"
] | permissive | cipher1024/lean | 270c1ac5781e6aee12f5c8d720d267563a164beb | f5cbdff8932dd30c6dd8eec68f3059393b4f8b3a | refs/heads/master | 1,611,223,459,029 | 1,487,566,573,000 | 1,487,566,573,000 | 83,356,543 | 0 | 0 | null | 1,488,229,336,000 | 1,488,229,336,000 | null | UTF-8 | Lean | false | false | 798 | lean | open tactic
meta def my_attr : caching_user_attribute (name → bool) :=
{ name := "my_attr",
descr := "my attr",
mk_cache := λ ls, do {
els ← list_name.to_expr ls,
c ← to_expr `(λ n : name, (name.cases_on n ff (λ _ _, to_bool (n ∈ %%els)) (λ _ _, ff) : bool)),
eval_expr (name → bool) c
},
dependencies := []
}
run_command attribute.register `my_attr
meta def my_tac : tactic unit :=
do f ← caching_user_attribute.get_cache my_attr,
trace (f `foo),
return ()
@[my_attr] def bla := 10
run_command my_tac
@[my_attr] def foo := 10 -- Cache was invalided
run_command my_tac -- Add closure to the cache containing auxiliary function created by eval_expr
run_command my_tac -- Cache should be flushed since the auxiliary function is gone
|
d2d816b4f33b00b415489c3adbf2e6c9362b8d01 | 91b8df3b248df89472cc0b753fbe2bac750aefea | /experiments/lean/src/ddl/binary/subst.lean | 1585bdb7955dcc939a96402dcf5d7320f77958bf | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | yeslogic/fathom | eabe5c4112d3b4d5ec9096a57bb502254ddbdf15 | 3960a9466150d392c2cb103c5cb5fcffa0200814 | refs/heads/main | 1,685,349,769,736 | 1,675,998,621,000 | 1,675,998,621,000 | 28,993,871 | 214 | 11 | Apache-2.0 | 1,694,044,276,000 | 1,420,764,938,000 | Rust | UTF-8 | Lean | false | false | 3,325 | lean | import ddl.binary.basic
import ddl.binary.monad
namespace ddl.binary
-- open ddl.binary
namespace type
variables {ℓ α : Type} [decidable_eq α]
def open_var : ℕ → α → type ℓ α → type ℓ α
| i x (bvar i') := if i = i' then fvar x else bvar i'
| i x (fvar x') := fvar x'
| i x (bit) := bit
| i x (union_nil) := union_nil
| i x (union_cons l t₁ t₂) := union_cons l (open_var i x t₁) (open_var i x t₂)
| i x (struct_nil) := struct_nil
| i x (struct_cons l t₁ t₂) := struct_cons l (open_var i x t₁) (open_var (i + 1) x t₂)
| i x (array t e) := array (open_var i x t) e
| i x (assert t e) := assert (open_var i x t) e
| i x (interp t e th) := interp (open_var i x t) e th
| i x (lam k t) := lam k (open_var (i + 1) x t)
| i x (app t₁ t₂) := app (open_var i x t₁) (open_var i x t₂)
def close_var : ℕ → α → type ℓ α → type ℓ α
| i x (bvar i') := bvar i'
| i x (fvar x') := if x = x' then bvar i else fvar x'
| i x (bit) := bit
| i x (union_nil) := union_nil
| i x (union_cons l t₁ t₂) := union_cons l (close_var i x t₁) (close_var i x t₂)
| i x (struct_nil) := struct_nil
| i x (struct_cons l t₁ t₂) := struct_cons l (close_var i x t₁) (close_var (i + 1) x t₂)
| i x (array t e) := array (close_var i x t) e
| i x (assert t e) := assert (close_var i x t) e
| i x (interp t e th) := interp (close_var i x t) e th
| i x (lam k t) := lam k (close_var (i + 1) x t)
| i x (app t₁ t₂) := app (close_var i x t₁) (close_var i x t₂)
theorem close_open_var :
Π (x : α) (t : type ℓ α),
close_var 0 x (open_var 0 x t) = t :=
begin
intros x t,
induction t,
case bvar i { admit },
case fvar x { admit },
case bit { admit },
case union_nil { admit },
case union_cons l t₁ t₂ ht₁ ht₂ { admit },
case struct_nil { admit },
case struct_cons l t₁ t₂ ht₁ ht₂ { admit },
case array t e ht { admit },
case assert t e ht { admit },
case interp t e ht hht { admit },
case lam k t ht { admit },
case app t₁ t₂ ht₁ ht₂ { admit },
end
theorem open_close_var :
Π (x : α) (t : type ℓ α),
open_var 0 x (close_var 0 x t) = t :=
begin
intros x t,
induction t,
case bvar i { admit },
case fvar x { admit },
case bit { admit },
case union_nil { admit },
case union_cons l t₁ t₂ ht₁ ht₂ { admit },
case struct_nil { admit },
case struct_cons l t₁ t₂ ht₁ ht₂ { admit },
case array t e ht { admit },
case assert t e ht { admit },
case interp t e ht hht { admit },
case lam k t ht { admit },
case app t₁ t₂ ht₁ ht₂ { admit },
end
def subst (x : α) (src : type ℓ α) (dst : type ℓ α) : type ℓ α :=
dst >>= λ x', if x' = x then src else (fvar x)
notation `[ ` x ` ↦ ` src ` ]` dst := subst x src dst
example {x: α} {t : type ℓ α} :
([x ↦ t] type.lam kind.type (↑0 ∙ ↑x)) = (type.lam kind.type (↑0 ∙ t)) := sorry
end type
end ddl.binary
|
e6542fd6a987518735250eb019a101aaf28d6030 | c777c32c8e484e195053731103c5e52af26a25d1 | /archive/imo/imo1998_q2.lean | c4133b49d376ee48ff436fb78ad56b055ce685b4 | [
"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 | 9,502 | lean | /-
Copyright (c) 2020 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import data.fintype.prod
import data.int.parity
import algebra.big_operators.order
import tactic.ring
import tactic.noncomm_ring
/-!
# IMO 1998 Q2
In a competition, there are `a` contestants and `b` judges, where `b ≥ 3` is an odd integer. Each
judge rates each contestant as either "pass" or "fail". Suppose `k` is a number such that, for any
two judges, their ratings coincide for at most `k` contestants. Prove that `k / a ≥ (b - 1) / (2b)`.
## Solution
The problem asks us to think about triples consisting of a contestant and two judges whose ratings
agree for that contestant. We thus consider the subset `A ⊆ C × JJ` of all such incidences of
agreement, where `C` and `J` are the sets of contestants and judges, and `JJ = J × J - {(j, j)}`. We
have natural maps: `left : A → C` and `right: A → JJ`. We count the elements of `A` in two ways: as
the sum of the cardinalities of the fibres of `left` and as the sum of the cardinalities of the
fibres of `right`. We obtain an upper bound on the cardinality of `A` from the count for `right`,
and a lower bound from the count for `left`. These two bounds combine to the required result.
First consider the map `right : A → JJ`. Since the size of any fibre over a point in JJ is bounded
by `k` and since `|JJ| = b^2 - b`, we obtain the upper bound: `|A| ≤ k(b^2-b)`.
Now consider the map `left : A → C`. The fibre over a given contestant `c ∈ C` is the set of
ordered pairs of (distinct) judges who agree about `c`. We seek to bound the cardinality of this
fibre from below. Minimum agreement for a contestant occurs when the judges' ratings are split as
evenly as possible. Since `b` is odd, this occurs when they are divided into groups of size
`(b-1)/2` and `(b+1)/2`. This corresponds to a fibre of cardinality `(b-1)^2/2` and so we obtain
the lower bound: `a(b-1)^2/2 ≤ |A|`.
Rearranging gives the result.
-/
open_locale classical
noncomputable theory
/-- An ordered pair of judges. -/
abbreviation judge_pair (J : Type*) := J × J
/-- A triple consisting of contestant together with an ordered pair of judges. -/
abbreviation agreed_triple (C J : Type*) := C × (judge_pair J)
variables {C J : Type*} (r : C → J → Prop)
/-- The first judge from an ordered pair of judges. -/
abbreviation judge_pair.judge₁ : judge_pair J → J := prod.fst
/-- The second judge from an ordered pair of judges. -/
abbreviation judge_pair.judge₂ : judge_pair J → J := prod.snd
/-- The proposition that the judges in an ordered pair are distinct. -/
abbreviation judge_pair.distinct (p : judge_pair J) := p.judge₁ ≠ p.judge₂
/-- The proposition that the judges in an ordered pair agree about a contestant's rating. -/
abbreviation judge_pair.agree (p : judge_pair J) (c : C) := r c p.judge₁ ↔ r c p.judge₂
/-- The contestant from the triple consisting of a contestant and an ordered pair of judges. -/
abbreviation agreed_triple.contestant : agreed_triple C J → C := prod.fst
/-- The ordered pair of judges from the triple consisting of a contestant and an ordered pair of
judges. -/
abbreviation agreed_triple.judge_pair : agreed_triple C J → judge_pair J := prod.snd
@[simp] lemma judge_pair.agree_iff_same_rating (p : judge_pair J) (c : C) :
p.agree r c ↔ (r c p.judge₁ ↔ r c p.judge₂) := iff.rfl
/-- The set of contestants on which two judges agree. -/
def agreed_contestants [fintype C] (p : judge_pair J) : finset C :=
finset.univ.filter (λ c, p.agree r c)
section
variables [fintype J] [fintype C]
/-- All incidences of agreement. -/
def A : finset (agreed_triple C J) := finset.univ.filter (λ (a : agreed_triple C J),
a.judge_pair.agree r a.contestant ∧ a.judge_pair.distinct)
lemma A_maps_to_off_diag_judge_pair (a : agreed_triple C J) :
a ∈ A r → a.judge_pair ∈ finset.off_diag (@finset.univ J _) :=
by simp [A, finset.mem_off_diag]
lemma A_fibre_over_contestant (c : C) :
finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct) =
((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).image prod.snd :=
begin
ext p,
simp only [A, finset.mem_univ, finset.mem_filter, finset.mem_image, true_and, exists_prop],
split,
{ rintros ⟨h₁, h₂⟩, refine ⟨(c, p), _⟩, finish, },
{ intros h, finish, },
end
lemma A_fibre_over_contestant_card (c : C) :
(finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card =
((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).card :=
by { rw A_fibre_over_contestant r, apply finset.card_image_of_inj_on, tidy, }
lemma A_fibre_over_judge_pair {p : judge_pair J} (h : p.distinct) :
agreed_contestants r p =
((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).image agreed_triple.contestant :=
begin
dunfold A agreed_contestants, ext c, split; intros h,
{ rw finset.mem_image, refine ⟨⟨c, p⟩, _⟩, finish, },
{ finish, },
end
lemma A_fibre_over_judge_pair_card {p : judge_pair J} (h : p.distinct) :
(agreed_contestants r p).card =
((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).card :=
by { rw A_fibre_over_judge_pair r h, apply finset.card_image_of_inj_on, tidy, }
lemma A_card_upper_bound
{k : ℕ} (hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) :
(A r).card ≤ k * ((fintype.card J) * (fintype.card J) - (fintype.card J)) :=
begin
change _ ≤ k * ((finset.card _ ) * (finset.card _ ) - (finset.card _ )),
rw ← finset.off_diag_card,
apply finset.card_le_mul_card_image_of_maps_to (A_maps_to_off_diag_judge_pair r),
intros p hp,
have hp' : p.distinct, { simp [finset.mem_off_diag] at hp, exact hp, },
rw ← A_fibre_over_judge_pair_card r hp', apply hk, exact hp',
end
end
lemma add_sq_add_sq_sub {α : Type*} [ring α] (x y : α) :
(x + y) * (x + y) + (x - y) * (x - y) = 2*x*x + 2*y*y :=
by noncomm_ring
lemma norm_bound_of_odd_sum {x y z : ℤ} (h : x + y = 2*z + 1) :
2*z*z + 2*z + 1 ≤ x*x + y*y :=
begin
suffices : 4*z*z + 4*z + 1 + 1 ≤ 2*x*x + 2*y*y,
{ rw ← mul_le_mul_left (zero_lt_two' ℤ), convert this; ring, },
have h' : (x + y) * (x + y) = 4*z*z + 4*z + 1, { rw h, ring, },
rw [← add_sq_add_sq_sub, h', add_le_add_iff_left],
suffices : 0 < (x - y) * (x - y), { apply int.add_one_le_of_lt this, },
rw [mul_self_pos, sub_ne_zero], apply int.ne_of_odd_add ⟨z, h⟩,
end
section
variables [fintype J]
lemma judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) :
2*z*z + 2*z + 1 ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card :=
begin
let x := (finset.univ.filter (λ j, r c j)).card,
let y := (finset.univ.filter (λ j, ¬ r c j)).card,
have h : (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card = x*x + y*y,
{ simp [← finset.filter_product_card], },
rw h, apply int.le_of_coe_nat_le_coe_nat, simp only [int.coe_nat_add, int.coe_nat_mul],
apply norm_bound_of_odd_sum,
suffices : x + y = 2*z + 1, { simp [← int.coe_nat_add, this], },
rw [finset.filter_card_add_filter_neg_card_eq_card, ← hJ], refl,
end
lemma distinct_judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) :
2*z*z ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card :=
begin
let s := finset.univ.filter (λ (p : judge_pair J), p.agree r c),
let t := finset.univ.filter (λ (p : judge_pair J), p.distinct),
have hs : 2*z*z + 2*z + 1 ≤ s.card, { exact judge_pairs_card_lower_bound r hJ c, },
have hst : s \ t = finset.univ.diag,
{ ext p, split; intros,
{ finish, },
{ suffices : p.judge₁ = p.judge₂, { simp [this], }, finish, }, },
have hst' : (s \ t).card = 2*z + 1, { rw [hst, finset.diag_card, ← hJ], refl, },
rw [finset.filter_and, ← finset.sdiff_sdiff_self_left s t, finset.card_sdiff],
{ rw hst', rw add_assoc at hs, apply le_tsub_of_add_le_right hs, },
{ apply finset.sdiff_subset, },
end
lemma A_card_lower_bound [fintype C] {z : ℕ} (hJ : fintype.card J = 2*z + 1) :
2*z*z * (fintype.card C) ≤ (A r).card :=
begin
have h : ∀ a, a ∈ A r → prod.fst a ∈ @finset.univ C _, { intros, apply finset.mem_univ, },
apply finset.mul_card_image_le_card_of_maps_to h,
intros c hc,
rw ← A_fibre_over_contestant_card,
apply distinct_judge_pairs_card_lower_bound r hJ,
end
end
lemma clear_denominators {a b k : ℕ} (ha : 0 < a) (hb : 0 < b) :
(b - 1 : ℚ) / (2 * b) ≤ k / a ↔ (b - 1) * a ≤ k * (2 * b) :=
by rw div_le_div_iff; norm_cast; simp [ha, hb]
theorem imo1998_q2 [fintype J] [fintype C]
(a b k : ℕ) (hC : fintype.card C = a) (hJ : fintype.card J = b) (ha : 0 < a) (hb : odd b)
(hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) :
(b - 1 : ℚ) / (2 * b) ≤ k / a :=
begin
rw clear_denominators ha hb.pos,
obtain ⟨z, hz⟩ := hb, rw hz at hJ, rw hz,
have h := le_trans (A_card_lower_bound r hJ) (A_card_upper_bound r hk),
rw [hC, hJ] at h,
-- We are now essentially done; we just need to bash `h` into exactly the right shape.
have hl : k * ((2 * z + 1) * (2 * z + 1) - (2 * z + 1)) = (k * (2 * (2 * z + 1))) * z,
{ simp only [add_mul, two_mul, mul_comm, mul_assoc], finish, },
have hr : 2 * z * z * a = 2 * z * a * z, { ring, },
rw [hl, hr] at h,
cases z,
{ simp, },
{ exact le_of_mul_le_mul_right h z.succ_pos, },
end
|
e92bc4371571e5c85c2e8782983d24d6966f5220 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /tests/lean/run/tacticTests.lean | f760b78bb1ccabaf095525ed77cf34ceed59bd57 | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,412 | lean | inductive Le (m : Nat) : Nat → Prop
| base : Le m m
| succ : (n : Nat) → Le m n → Le m n.succ
theorem ex1 (m : Nat) : Le m 0 → m = 0 := by
intro h
cases h
rfl
theorem ex2 (m n : Nat) : Le m n → Le m.succ n.succ := by
intro h
induction h
| base n => apply Le.base
| succ n m ih =>
apply Le.succ
apply ih
theorem ex3 (m : Nat) : Le 0 m := by
induction m
| zero => apply Le.base
| succ m ih =>
apply Le.succ
apply ih
theorem ex4 (m : Nat) : ¬ Le m.succ 0 := by
intro h
cases h
theorem ex5 {m n : Nat} : Le m n.succ → m = n.succ ∨ Le m n := by
intro h
cases h
| base => apply Or.inl; rfl
| succ => apply Or.inr; assumption
theorem ex6 {m n : Nat} : Le m.succ n.succ → Le m n := by
revert m
induction n
| zero =>
intros m h;
cases h
| base => apply Le.base
| succ n h => exact absurd h (ex4 _)
| succ n ih =>
intros m h
have aux := ih (m := m)
cases ex5 h
| inl h =>
injection h with h
subst h
apply Le.base
| inr h =>
apply Le.succ
exact ih h
theorem ex7 {m n o : Nat} : Le m n → Le n o → Le m o := by
intro h
induction h
| base => intros; assumption
| succ n s ih =>
intro h₂
apply ih
apply ex6
apply Le.succ
assumption
theorem ex8 {m n : Nat} : Le m.succ n → Le m n := by
intro h
apply ex6
apply Le.succ
assumption
theorem ex9 {m n : Nat} : Le m n → m = n ∨ Le m.succ n := by
intro h
cases h
| base => apply Or.inl; rfl
| succ n s =>
apply Or.inr
apply ex2
assumption
/-
theorem ex10 (n : Nat) : ¬ Le n.succ n := by
intro h
cases h -- TODO: improve cases tactic
done
-/
theorem ex10 (n : Nat) : n.succ ≠ n := by
induction n
| zero => intro h; injection h; done
| succ n ih => intro h; injection h with h; apply ih h
theorem ex11 (n : Nat) : ¬ Le n.succ n := by
induction n
| zero => intro h; cases h; done
| succ n ih =>
intro h
have aux := ex6 h
exact absurd aux ih
done
theorem ex12 (m n : Nat) : Le m n → Le n m → m = n := by
revert m
induction n
| zero => intro m h1 h2; apply ex1; assumption; done
| succ n ih =>
intro m h1 h2
have ih := ih m
cases ex5 h1
| inl h => assumption
| inr h =>
have ih := ih h
have h3 := ex8 h2
have ih := ih h3
subst ih
apply absurd h2 (ex11 _)
done
|
b984ddbd88e88ae0ea1ae0ee40ff988aa0e05af8 | 3ed5a65c1ab3ce5d1a094edce8fa3287980f197b | /src/herstein/ex2_3/Q_12.lean | dcfdf4b4555864fb98fa7438d6a0e1985194dd5b | [] | no_license | group-study-group/herstein | 35d32e77158efa2cc303c84e1ee5e3bc80831137 | f5a1a72eb56fa19c19ece0cb3ab6cf7ffd161f66 | refs/heads/master | 1,586,202,191,519 | 1,548,969,759,000 | 1,548,969,759,000 | 157,746,953 | 0 | 0 | null | 1,542,412,901,000 | 1,542,302,366,000 | Lean | UTF-8 | Lean | false | false | 1,601 | lean | import algebra.group
variable {G: Type*}
-- mathlib's constructor for `group` asks only for a (two-sided) identity
-- alongside a left inverse. This exercise shows it is possible to produce
-- both of those things if given a right identity and a right inverse.
theorem Q_12 (G: Type*) (mul: G → G → G) (e: G) (y: G → G):
(∀ a b c: G, (mul (mul a b) c) = (mul a (mul b c))) ∧
(∀ a: G, mul a e = a) ∧
(∀ a: G, mul a (y a) = e)
→ group G :=
λ ⟨h1, ⟨h2, h3⟩⟩, begin
-- the right inverse is also a left inverse
have h4: ∀ a: G, mul (y a) a = e, from λ a, calc
mul (y a) a
= mul (mul (y a) a) e : (h2 _).symm
... = mul (mul (y a) a) (mul (y a) (y (y a))) : by rw ←h3
... = mul (y a) (mul a (mul (y a) (y (y a)))) : h1 _ _ _
... = mul (y a) (mul (mul a (y a)) (y (y a))) : by rw h1
... = mul (y a) (mul e (y (y a))) : by rw h3
... = mul (mul (y a) e) (y (y a)) : by rw ←h1
... = mul (y a) (y (y a)) : by rw h2
... = e : h3 _,
-- the right identity is also the left identity
have h5: ∀ a: G, mul e a = a, from λ a, calc
mul e a
= mul (mul a (y a)) a : by rw h3
... = mul a (mul (y a) a) : h1 _ _ _
... = mul a e : by rw h4
... = a : h2 _,
-- we have now shown everything we need to
-- synthesise an instance of group G:
exact {
mul := mul,
mul_assoc := h1,
one := e,
one_mul := h5,
mul_one := h2,
inv := y,
mul_left_inv := h4
},
end
|
0f729b94b00ad2e6ff434449f18be911786c2620 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/linear_algebra/dimension.lean | 9558e5ab6c861a826df617af28fdbe4ea316fe7e | [] | 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 | 21,407 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro, Johannes Hölzl, Sander Dahmen
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.linear_algebra.basis
import Mathlib.set_theory.cardinal_ordinal
import Mathlib.PostPort
universes u v w w' m v' u_1 u₁ u₁' v''
namespace Mathlib
/-!
# Dimension of modules and vector spaces
## Main definitions
* The dimension of a vector space is defined as `vector_space.dim : cardinal`.
## Main statements
* `mk_eq_mk_of_basis`: the dimension theorem, any two bases of the same vector space have the same
cardinality.
* `dim_quotient_add_dim`: if V₁ is a submodule of V, then dim (V/V₁) + dim V₁ = dim V.
* `dim_range_add_dim_ker`: the rank-nullity theorem.
## Implementation notes
Many theorems in this file are not universe-generic when they relate dimensions
in different universes. They should be as general as they can be without
inserting `lift`s. The types `V`, `V'`, ... all live in different universes,
and `V₁`, `V₂`, ... all live in the same universe.
-/
/-- the dimension of a vector space, defined as a term of type `cardinal` -/
def vector_space.dim (K : Type u) (V : Type v) [field K] [add_comm_group V] [vector_space K V] : cardinal :=
cardinal.min sorry fun (b : Subtype fun (b : set V) => is_basis K fun (i : ↥b) => ↑i) => cardinal.mk ↥(subtype.val b)
theorem is_basis.le_span {K : Type u} {V : Type v} {ι : Type w} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} {J : set V} (hv : is_basis K v) (hJ : submodule.span K J = ⊤) : cardinal.mk ↥(set.range v) ≤ cardinal.mk ↥J := sorry
/-- dimension theorem -/
theorem mk_eq_mk_of_basis {K : Type u} {V : Type v} {ι : Type w} {ι' : Type w'} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} {v' : ι' → V} (hv : is_basis K v) (hv' : is_basis K v') : cardinal.lift (cardinal.mk ι) = cardinal.lift (cardinal.mk ι') := sorry
theorem mk_eq_mk_of_basis' {K : Type u} {V : Type v} {ι : Type w} [field K] [add_comm_group V] [vector_space K V] {ι' : Type w} {v : ι → V} {v' : ι' → V} (hv : is_basis K v) (hv' : is_basis K v') : cardinal.mk ι = cardinal.mk ι' :=
iff.mp cardinal.lift_inj (mk_eq_mk_of_basis hv hv')
theorem is_basis.mk_eq_dim'' {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] {ι : Type v} {v : ι → V} (h : is_basis K v) : cardinal.mk ι = vector_space.dim K V := sorry
theorem is_basis.mk_range_eq_dim {K : Type u} {V : Type v} {ι : Type w} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} (h : is_basis K v) : cardinal.mk ↥(set.range v) = vector_space.dim K V :=
is_basis.mk_eq_dim'' (is_basis.range h)
theorem is_basis.mk_eq_dim {K : Type u} {V : Type v} {ι : Type w} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} (h : is_basis K v) : cardinal.lift (cardinal.mk ι) = cardinal.lift (vector_space.dim K V) := sorry
theorem is_basis.mk_eq_dim' {K : Type u} {V : Type v} {ι : Type w} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} (h : is_basis K v) : cardinal.lift (cardinal.mk ι) = cardinal.lift (vector_space.dim K V) :=
eq.mpr (id (propext cardinal.lift_max))
(eq.mp (Eq.refl (cardinal.lift (cardinal.mk ι) = cardinal.lift (vector_space.dim K V))) (is_basis.mk_eq_dim h))
theorem dim_le {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] {n : ℕ} (H : ∀ (s : finset V), (linear_independent K fun (i : ↥↑s) => ↑i) → finset.card s ≤ n) : vector_space.dim K V ≤ ↑n := sorry
/-- Two linearly equivalent vector spaces have the same dimension, a version with different
universes. -/
theorem linear_equiv.lift_dim_eq {K : Type u} {V : Type v} {V' : Type v'} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V'] [vector_space K V'] (f : linear_equiv K V V') : cardinal.lift (vector_space.dim K V) = cardinal.lift (vector_space.dim K V') := sorry
/-- Two linearly equivalent vector spaces have the same dimension. -/
theorem linear_equiv.dim_eq {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] (f : linear_equiv K V V₁) : vector_space.dim K V = vector_space.dim K V₁ :=
iff.mp cardinal.lift_inj (linear_equiv.lift_dim_eq f)
/-- Two vector spaces are isomorphic if they have the same dimension. -/
theorem nonempty_linear_equiv_of_lift_dim_eq {K : Type u} {V : Type v} {V' : Type v'} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V'] [vector_space K V'] (cond : cardinal.lift (vector_space.dim K V) = cardinal.lift (vector_space.dim K V')) : Nonempty (linear_equiv K V V') := sorry
/-- Two vector spaces are isomorphic if they have the same dimension. -/
theorem nonempty_linear_equiv_of_dim_eq {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] (cond : vector_space.dim K V = vector_space.dim K V₁) : Nonempty (linear_equiv K V V₁) :=
nonempty_linear_equiv_of_lift_dim_eq (congr_arg cardinal.lift cond)
/-- Two vector spaces are isomorphic if they have the same dimension. -/
def linear_equiv.of_lift_dim_eq {K : Type u} (V : Type v) (V' : Type v') [field K] [add_comm_group V] [vector_space K V] [add_comm_group V'] [vector_space K V'] (cond : cardinal.lift (vector_space.dim K V) = cardinal.lift (vector_space.dim K V')) : linear_equiv K V V' :=
Classical.choice (nonempty_linear_equiv_of_lift_dim_eq cond)
/-- Two vector spaces are isomorphic if they have the same dimension. -/
def linear_equiv.of_dim_eq {K : Type u} (V : Type v) (V₁ : Type v) [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] (cond : vector_space.dim K V = vector_space.dim K V₁) : linear_equiv K V V₁ :=
Classical.choice (nonempty_linear_equiv_of_dim_eq cond)
/-- Two vector spaces are isomorphic if and only if they have the same dimension. -/
theorem linear_equiv.nonempty_equiv_iff_lift_dim_eq {K : Type u} {V : Type v} {V' : Type v'} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V'] [vector_space K V'] : Nonempty (linear_equiv K V V') ↔ cardinal.lift (vector_space.dim K V) = cardinal.lift (vector_space.dim K V') := sorry
/-- Two vector spaces are isomorphic if and only if they have the same dimension. -/
theorem linear_equiv.nonempty_equiv_iff_dim_eq {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] : Nonempty (linear_equiv K V V₁) ↔ vector_space.dim K V = vector_space.dim K V₁ := sorry
@[simp] theorem dim_bot {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] : vector_space.dim K ↥⊥ = 0 := sorry
@[simp] theorem dim_top {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] : vector_space.dim K ↥⊤ = vector_space.dim K V :=
linear_equiv.dim_eq (linear_equiv.of_top ⊤ rfl)
theorem dim_of_field (K : Type u_1) [field K] : vector_space.dim K K = 1 := sorry
theorem dim_span {K : Type u} {V : Type v} {ι : Type w} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} (hv : linear_independent K v) : vector_space.dim K ↥(submodule.span K (set.range v)) = cardinal.mk ↥(set.range v) := sorry
theorem dim_span_set {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] {s : set V} (hs : linear_independent K fun (x : ↥s) => ↑x) : vector_space.dim K ↥(submodule.span K s) = cardinal.mk ↥s := sorry
theorem cardinal_lift_le_dim_of_linear_independent {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] {ι : Type w} {v : ι → V} (hv : linear_independent K v) : cardinal.lift (cardinal.mk ι) ≤ cardinal.lift (vector_space.dim K V) := sorry
theorem cardinal_le_dim_of_linear_independent {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] {ι : Type v} {v : ι → V} (hv : linear_independent K v) : cardinal.mk ι ≤ vector_space.dim K V :=
eq.mpr (id (Eq.refl (cardinal.mk ι ≤ vector_space.dim K V)))
(eq.mp (propext cardinal.lift_le) (cardinal_lift_le_dim_of_linear_independent hv))
theorem cardinal_le_dim_of_linear_independent' {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] {s : set V} (hs : linear_independent K fun (x : ↥s) => ↑x) : cardinal.mk ↥s ≤ vector_space.dim K V := sorry
theorem dim_span_le {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (s : set V) : vector_space.dim K ↥(submodule.span K s) ≤ cardinal.mk ↥s := sorry
theorem dim_span_of_finset {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (s : finset V) : vector_space.dim K ↥(submodule.span K ↑s) < cardinal.omega := sorry
theorem dim_prod {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] : vector_space.dim K (V × V₁) = vector_space.dim K V + vector_space.dim K V₁ := sorry
theorem dim_quotient_add_dim {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (p : submodule K V) : vector_space.dim K (submodule.quotient p) + vector_space.dim K ↥p = vector_space.dim K V := sorry
theorem dim_quotient_le {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (p : submodule K V) : vector_space.dim K (submodule.quotient p) ≤ vector_space.dim K V := sorry
/-- rank-nullity theorem -/
theorem dim_range_add_dim_ker {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] (f : linear_map K V V₁) : vector_space.dim K ↥(linear_map.range f) + vector_space.dim K ↥(linear_map.ker f) = vector_space.dim K V := sorry
theorem dim_range_le {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] (f : linear_map K V V₁) : vector_space.dim K ↥(linear_map.range f) ≤ vector_space.dim K V := sorry
theorem dim_map_le {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] (f : linear_map K V V₁) (p : submodule K V) : vector_space.dim K ↥(submodule.map f p) ≤ vector_space.dim K ↥p := sorry
theorem dim_range_of_surjective {K : Type u} {V : Type v} {V' : Type v'} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V'] [vector_space K V'] (f : linear_map K V V') (h : function.surjective ⇑f) : vector_space.dim K ↥(linear_map.range f) = vector_space.dim K V' := sorry
theorem dim_eq_of_surjective {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] (f : linear_map K V V₁) (h : function.surjective ⇑f) : vector_space.dim K V = vector_space.dim K V₁ + vector_space.dim K ↥(linear_map.ker f) := sorry
theorem dim_le_of_surjective {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] (f : linear_map K V V₁) (h : function.surjective ⇑f) : vector_space.dim K V₁ ≤ vector_space.dim K V :=
eq.mpr (id (Eq._oldrec (Eq.refl (vector_space.dim K V₁ ≤ vector_space.dim K V)) (dim_eq_of_surjective f h)))
(self_le_add_right (vector_space.dim K V₁) (vector_space.dim K ↥(linear_map.ker f)))
theorem dim_eq_of_injective {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] (f : linear_map K V V₁) (h : function.injective ⇑f) : vector_space.dim K V = vector_space.dim K ↥(linear_map.range f) := sorry
theorem dim_submodule_le {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (s : submodule K V) : vector_space.dim K ↥s ≤ vector_space.dim K V :=
eq.mpr (id (Eq._oldrec (Eq.refl (vector_space.dim K ↥s ≤ vector_space.dim K V)) (Eq.symm (dim_quotient_add_dim s))))
(self_le_add_left (vector_space.dim K ↥s) (vector_space.dim K (submodule.quotient s)))
theorem dim_le_of_injective {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] (f : linear_map K V V₁) (h : function.injective ⇑f) : vector_space.dim K V ≤ vector_space.dim K V₁ :=
eq.mpr (id (Eq._oldrec (Eq.refl (vector_space.dim K V ≤ vector_space.dim K V₁)) (dim_eq_of_injective f h)))
(dim_submodule_le (linear_map.range f))
theorem dim_le_of_submodule {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (s : submodule K V) (t : submodule K V) (h : s ≤ t) : vector_space.dim K ↥s ≤ vector_space.dim K ↥t := sorry
theorem linear_independent_le_dim {K : Type u} {V : Type v} {ι : Type w} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} (hv : linear_independent K v) : cardinal.lift (cardinal.mk ι) ≤ cardinal.lift (vector_space.dim K V) := sorry
theorem linear_independent_le_dim' {K : Type u} {V : Type v} {ι : Type w} [field K] [add_comm_group V] [vector_space K V] {v : ι → V} (hs : linear_independent K v) : cardinal.lift (cardinal.mk ι) ≤ cardinal.lift (vector_space.dim K V) :=
cardinal.mk_range_eq_lift (linear_independent.injective hs) ▸
dim_span hs ▸ iff.mpr cardinal.lift_le (dim_submodule_le (submodule.span K (set.range v)))
/-- This is mostly an auxiliary lemma for `dim_sup_add_dim_inf_eq`. -/
theorem dim_add_dim_split {K : Type u} {V : Type v} {V₁ : Type v} {V₂ : Type v} {V₃ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] [add_comm_group V₂] [vector_space K V₂] [add_comm_group V₃] [vector_space K V₃] (db : linear_map K V₂ V) (eb : linear_map K V₃ V) (cd : linear_map K V₁ V₂) (ce : linear_map K V₁ V₃) (hde : ⊤ ≤ linear_map.range db ⊔ linear_map.range eb) (hgd : linear_map.ker cd = ⊥) (eq : linear_map.comp db cd = linear_map.comp eb ce) (eq₂ : ∀ (d : V₂) (e : V₃), coe_fn db d = coe_fn eb e → ∃ (c : V₁), coe_fn cd c = d ∧ coe_fn ce c = e) : vector_space.dim K V + vector_space.dim K V₁ = vector_space.dim K V₂ + vector_space.dim K V₃ := sorry
theorem dim_sup_add_dim_inf_eq {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (s : submodule K V) (t : submodule K V) : vector_space.dim K ↥(s ⊔ t) + vector_space.dim K ↥(s ⊓ t) = vector_space.dim K ↥s + vector_space.dim K ↥t := sorry
theorem dim_add_le_dim_add_dim {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (s : submodule K V) (t : submodule K V) : vector_space.dim K ↥(s ⊔ t) ≤ vector_space.dim K ↥s + vector_space.dim K ↥t := sorry
theorem dim_pi {K : Type u} {η : Type u₁'} {φ : η → Type u_1} [field K] [fintype η] [(i : η) → add_comm_group (φ i)] [(i : η) → vector_space K (φ i)] : vector_space.dim K ((i : η) → φ i) = cardinal.sum fun (i : η) => vector_space.dim K (φ i) := sorry
theorem dim_fun {K : Type u} [field K] {V : Type u} {η : Type u} [fintype η] [add_comm_group V] [vector_space K V] : vector_space.dim K (η → V) = ↑(fintype.card η) * vector_space.dim K V := sorry
theorem dim_fun_eq_lift_mul {K : Type u} {V : Type v} {η : Type u₁'} [field K] [add_comm_group V] [vector_space K V] [fintype η] : vector_space.dim K (η → V) = ↑(fintype.card η) * cardinal.lift (vector_space.dim K V) := sorry
theorem dim_fun' {K : Type u} {η : Type u₁'} [field K] [fintype η] : vector_space.dim K (η → K) = ↑(fintype.card η) := sorry
theorem dim_fin_fun {K : Type u} [field K] (n : ℕ) : vector_space.dim K (fin n → K) = ↑n := sorry
theorem exists_mem_ne_zero_of_ne_bot {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] {s : submodule K V} (h : s ≠ ⊥) : ∃ (b : V), b ∈ s ∧ b ≠ 0 := sorry
theorem exists_mem_ne_zero_of_dim_pos {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] {s : submodule K V} (h : 0 < vector_space.dim K ↥s) : ∃ (b : V), b ∈ s ∧ b ≠ 0 := sorry
theorem exists_is_basis_fintype {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (h : vector_space.dim K V < cardinal.omega) : ∃ (s : set V), is_basis K subtype.val ∧ Nonempty (fintype ↥s) := sorry
/-- `rank f` is the rank of a `linear_map f`, defined as the dimension of `f.range`. -/
def rank {K : Type u} {V : Type v} {V' : Type v'} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V'] [vector_space K V'] (f : linear_map K V V') : cardinal :=
vector_space.dim K ↥(linear_map.range f)
theorem rank_le_domain {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] (f : linear_map K V V₁) : rank f ≤ vector_space.dim K V :=
eq.mpr (id (Eq._oldrec (Eq.refl (rank f ≤ vector_space.dim K V)) (Eq.symm (dim_range_add_dim_ker f))))
(self_le_add_right (rank f) (vector_space.dim K ↥(linear_map.ker f)))
theorem rank_le_range {K : Type u} {V : Type v} {V₁ : Type v} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V₁] [vector_space K V₁] (f : linear_map K V V₁) : rank f ≤ vector_space.dim K V₁ :=
dim_submodule_le (linear_map.range f)
theorem rank_add_le {K : Type u} {V : Type v} {V' : Type v'} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V'] [vector_space K V'] (f : linear_map K V V') (g : linear_map K V V') : rank (f + g) ≤ rank f + rank g := sorry
@[simp] theorem rank_zero {K : Type u} {V : Type v} {V' : Type v'} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V'] [vector_space K V'] : rank 0 = 0 :=
eq.mpr (id (Eq._oldrec (Eq.refl (rank 0 = 0)) (rank.equations._eqn_1 0)))
(eq.mpr (id (Eq._oldrec (Eq.refl (vector_space.dim K ↥(linear_map.range 0) = 0)) linear_map.range_zero))
(eq.mpr (id (Eq._oldrec (Eq.refl (vector_space.dim K ↥⊥ = 0)) dim_bot)) (Eq.refl 0)))
theorem rank_finset_sum_le {K : Type u} {V : Type v} {V' : Type v'} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V'] [vector_space K V'] {η : Type u_1} (s : finset η) (f : η → linear_map K V V') : rank (finset.sum s fun (d : η) => f d) ≤ finset.sum s fun (d : η) => rank (f d) :=
finset.sum_hom_rel (le_of_eq rank_zero)
fun (i : η) (g : linear_map K V V') (c : cardinal) (h : rank g ≤ c) =>
le_trans (rank_add_le (f i) g) (add_le_add_left h (rank (f i)))
theorem rank_comp_le1 {K : Type u} {V : Type v} {V' : Type v'} {V'' : Type v''} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V'] [vector_space K V'] [add_comm_group V''] [vector_space K V''] (g : linear_map K V V') (f : linear_map K V' V'') : rank (linear_map.comp f g) ≤ rank f := sorry
theorem rank_comp_le2 {K : Type u} {V : Type v} {V' : Type v'} {V'₁ : Type v'} [field K] [add_comm_group V] [vector_space K V] [add_comm_group V'] [vector_space K V'] [add_comm_group V'₁] [vector_space K V'₁] (g : linear_map K V V') (f : linear_map K V' V'₁) : rank (linear_map.comp f g) ≤ rank g := sorry
theorem dim_zero_iff_forall_zero {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] : vector_space.dim K V = 0 ↔ ∀ (x : V), x = 0 := sorry
theorem dim_pos_iff_exists_ne_zero {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] : 0 < vector_space.dim K V ↔ ∃ (x : V), x ≠ 0 := sorry
theorem dim_pos_iff_nontrivial {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] : 0 < vector_space.dim K V ↔ nontrivial V := sorry
theorem dim_pos {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] [h : nontrivial V] : 0 < vector_space.dim K V :=
iff.mpr dim_pos_iff_nontrivial h
/-- A vector space has dimension at most `1` if and only if there is a
single vector of which all vectors are multiples. -/
theorem dim_le_one_iff {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] : vector_space.dim K V ≤ 1 ↔ ∃ (v₀ : V), ∀ (v : V), ∃ (r : K), r • v₀ = v := sorry
/-- A submodule has dimension at most `1` if and only if there is a
single vector in the submodule such that the submodule is contained in
its span. -/
theorem dim_submodule_le_one_iff {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (s : submodule K V) : vector_space.dim K ↥s ≤ 1 ↔ ∃ (v₀ : V), ∃ (H : v₀ ∈ s), s ≤ submodule.span K (singleton v₀) := sorry
/-- A submodule has dimension at most `1` if and only if there is a
single vector, not necessarily in the submodule, such that the
submodule is contained in its span. -/
theorem dim_submodule_le_one_iff' {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] (s : submodule K V) : vector_space.dim K ↥s ≤ 1 ↔ ∃ (v₀ : V), s ≤ submodule.span K (singleton v₀) := sorry
/-- Version of linear_equiv.dim_eq without universe constraints. -/
theorem linear_equiv.dim_eq_lift {K : Type u} {V : Type v} {E : Type v'} [field K] [add_comm_group V] [vector_space K V] [add_comm_group E] [vector_space K E] (f : linear_equiv K V E) : cardinal.lift (vector_space.dim K V) = cardinal.lift (vector_space.dim K E) := sorry
|
20dca16905ec2c347e15540b33a96ba17ed1af75 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /library/init/data/nat/bitwise.lean | dd25ea4b2e7e5af6de0ea27961d70a16ae1d9938 | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 7,827 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
prelude
import .lemmas init.meta.well_founded_tactics
universe u
namespace nat
def shiftl : ℕ → ℕ → ℕ
| m 0 := m
| m (n+1) := 2 * shiftl m n
def shiftr : ℕ → ℕ → ℕ
| m 0 := m
| m (n+1) := shiftr m n / 2
def bodd (n : ℕ) : bool := n % 2 = 1
def test_bit (m n : ℕ) : bool := bodd (shiftr m n)
def bit (b : bool) : ℕ → ℕ := cond b bit1 bit0
lemma bit0_val (n : nat) : bit0 n = 2 * n := (two_mul _).symm
lemma bit1_val (n : nat) : bit1 n = 2 * n + 1 := congr_arg succ (bit0_val _)
lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 :=
by { cases b, apply bit0_val, apply bit1_val }
lemma mod_two_of_bodd (n : nat) : n % 2 = cond (bodd n) 1 0 :=
match by apply_instance : ∀ d, n % 2 = cond (@to_bool (n % 2 = 1) d) 1 0 with
| is_true h := h
| is_false h := (mod_two_eq_zero_or_one _).resolve_right h
end
lemma bit_decomp (n : nat) : bit (bodd n) (shiftr n 1) = n :=
(bit_val _ _).trans $ (add_comm _ _).trans $
eq.trans (by rw mod_two_of_bodd; refl) (mod_add_div n 2)
lemma bit_cases_on {C : nat → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n :=
by rw -bit_decomp n; apply h
lemma bodd_bit (b n) : bodd (bit b n) = b :=
begin
rw bit_val, dsimp [bodd],
rw [add_comm, add_mul_mod_self_left, mod_eq_of_lt];
cases b; exact dec_trivial
end
lemma shiftr1_bit (b n) : shiftr (bit b n) 1 = n :=
begin
rw bit_val, dsimp [shiftr],
rw [add_comm, add_mul_div_left, div_eq_of_lt, zero_add];
cases b; exact dec_trivial
end
def shiftl_add (m n) : ∀ k, shiftl m (n + k) = shiftl (shiftl m n) k
| 0 := rfl
| (k+1) := congr_arg ((*) 2) (shiftl_add k)
def shiftr_add (m n) : ∀ k, shiftr m (n + k) = shiftr (shiftr m n) k
| 0 := rfl
| (k+1) := congr_arg (/ 2) (shiftr_add k)
def shiftl_eq_mul_pow (m) : ∀ n, shiftl m n = m * 2 ^ n
| 0 := (mul_one _).symm
| (k+1) := (congr_arg ((*) 2) (shiftl_eq_mul_pow k)).trans $ by simp [pow_succ]
def one_shiftl (n) : shiftl 1 n = 2 ^ n :=
(shiftl_eq_mul_pow _ _).trans (one_mul _)
def zero_shiftl (n) : shiftl 0 n = 0 :=
(shiftl_eq_mul_pow _ _).trans (zero_mul _)
def shiftr_eq_div_pow (m) : ∀ n, shiftr m n = m / 2 ^ n
| 0 := (nat.div_one _).symm
| (k+1) := (congr_arg (/ 2) (shiftr_eq_div_pow k)).trans $
by dsimp; rw [nat.div_div_eq_div_mul]; refl
def zero_shiftr (n) : shiftr 0 n = 0 :=
(shiftr_eq_div_pow _ _).trans (nat.zero_div _)
def test_bit_zero (b n) : test_bit (bit b n) 0 = b := bodd_bit _ _
def test_bit_succ (m b n) : test_bit (bit b n) (succ m) = test_bit n m :=
have bodd (shiftr (shiftr (bit b n) 1) m) = bodd (shiftr n m), by rw shiftr1_bit,
by rw [-shiftr_add, add_comm] at this; exact this
def binary_rec {C : nat → Sort u} (f : ∀ b n, C n → C (bit b n)) (z : C 0) : Π n, C n
| n := if n0 : n = 0 then by rw n0; exact z else let n' := shiftr n 1 in
have n' < n, from (div_lt_iff_lt_mul _ _ dec_trivial).2 $
by note := nat.mul_lt_mul_of_pos_left (dec_trivial : 1 < 2)
(lt_of_le_of_ne (zero_le _) (ne.symm n0));
rwa mul_one at this,
by rw [-show bit (bodd n) n' = n, from bit_decomp n]; exact
f (bodd n) n' (binary_rec n')
def size : ℕ → ℕ := binary_rec (λ_ _, succ) 0
def bits : ℕ → list bool := binary_rec (λb _ IH, b :: IH) []
def bitwise (f : bool → bool → bool) : ℕ → ℕ → ℕ :=
binary_rec
(λa m Ia, binary_rec
(λb n _, bit (f a b) (Ia n))
(cond (f tt ff) (bit a m) 0))
(λn, cond (f ff tt) n 0)
def lor : ℕ → ℕ → ℕ := bitwise bor
def land : ℕ → ℕ → ℕ := bitwise band
def ldiff : ℕ → ℕ → ℕ := bitwise (λ a b, a && bnot b)
def lxor : ℕ → ℕ → ℕ := bitwise bxor
set_option type_context.unfold_lemmas true
lemma binary_rec_eq {C : nat → Sort u} {f : ∀ b n, C n → C (bit b n)} {z}
(h : f ff 0 z = z) (b n) :
binary_rec f z (bit b n) = f b n (binary_rec f z n) :=
begin
rw [binary_rec.equations._eqn_1],
cases (by apply_instance : decidable (bit b n = 0)) with b0 b0; dsimp [dite],
{ generalize (binary_rec._main._pack._proof_2 (bit b n)) e,
rw [bodd_bit, shiftr1_bit], intro e, refl },
{ generalize (binary_rec._main._pack._proof_1 (bit b n) b0) e,
note bf := bodd_bit b n, note n0 := shiftr1_bit b n,
rw b0 at bf n0, rw [-show ff = b, from bf, -show 0 = n, from n0], intro e,
exact h.symm },
end
lemma binary_rec_zero {C : nat → Sort u} (f : ∀ b n, C n → C (bit b n)) (z) :
binary_rec f z 0 = z := by {rw [binary_rec.equations._eqn_1], refl}
lemma bitwise_bit_aux {f : bool → bool → bool} (h : f ff ff = ff) :
@binary_rec (λ_, ℕ)
(λ b n _, bit (f ff b) (cond (f ff tt) n 0))
(cond (f tt ff) (bit ff 0) 0) =
λ (n : ℕ), cond (f ff tt) n 0 :=
begin
apply funext, intro n,
apply bit_cases_on n, intros b n, rw [binary_rec_eq],
{ cases b; try {rw h}; ginduction f ff tt with fft; dsimp [cond]; refl },
{ rw [h, show cond (f ff tt) 0 0 = 0, by cases f ff tt; refl,
show cond (f tt ff) (bit ff 0) 0 = 0, by cases f tt ff; refl]; refl }
end
lemma bitwise_zero_left (f : bool → bool → bool) (n) :
bitwise f 0 n = cond (f ff tt) n 0 :=
by unfold bitwise; rw [binary_rec_zero]
lemma bitwise_zero_right (f : bool → bool → bool) (h : f ff ff = ff) (m) :
bitwise f m 0 = cond (f tt ff) m 0 :=
by unfold bitwise; apply bit_cases_on m; intros;
rw [binary_rec_eq, binary_rec_zero]; exact bitwise_bit_aux h
lemma bitwise_zero (f : bool → bool → bool) :
bitwise f 0 0 = 0 :=
by rw bitwise_zero_left; cases f ff tt; refl
lemma bitwise_bit {f : bool → bool → bool} (h : f ff ff = ff) (a m b n) :
bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) :=
begin
unfold bitwise,
rw [binary_rec_eq, binary_rec_eq],
{ ginduction f tt ff with ftf; dsimp [cond],
rw [show f a ff = ff, by cases a; assumption],
apply @congr_arg _ _ _ 0 (bit ff), tactic.swap,
rw [show f a ff = a, by cases a; assumption],
apply congr_arg (bit a),
all_goals {
apply bit_cases_on m, intros a m,
rw [binary_rec_eq, binary_rec_zero],
rw [-bitwise_bit_aux h, ftf], refl } },
{ exact bitwise_bit_aux h }
end
lemma lor_bit : ∀ (a m b n),
lor (bit a m) (bit b n) = bit (a || b) (lor m n) := bitwise_bit rfl
lemma land_bit : ∀ (a m b n),
land (bit a m) (bit b n) = bit (a && b) (land m n) := bitwise_bit rfl
lemma ldiff_bit : ∀ (a m b n),
ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := bitwise_bit rfl
lemma lxor_bit : ∀ (a m b n),
lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := bitwise_bit rfl
def test_bit_bitwise {f : bool → bool → bool} (h : f ff ff = ff) (m n k) :
test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) :=
begin
revert m n; induction k with k IH; intros m n;
apply bit_cases_on m; intros a m';
apply bit_cases_on n; intros b n';
rw bitwise_bit h,
{ simp [test_bit_zero] },
{ simp [test_bit_succ, IH] }
end
lemma test_bit_lor : ∀ (m n k),
test_bit (lor m n) k = test_bit m k || test_bit n k := test_bit_bitwise rfl
lemma test_bit_land : ∀ (m n k),
test_bit (land m n) k = test_bit m k && test_bit n k := test_bit_bitwise rfl
lemma test_bit_ldiff : ∀ (m n k),
test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := test_bit_bitwise rfl
lemma test_bit_lxor : ∀ (m n k),
test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := test_bit_bitwise rfl
end nat
|
1994981c1bf897c6630bb9e07a40542f6931cea3 | 19cc34575500ee2e3d4586c15544632aa07a8e66 | /src/field_theory/tower.lean | b3a05e689ead3177e6767f5431a5b575b8c94e0c | [
"Apache-2.0"
] | permissive | LibertasSpZ/mathlib | b9fcd46625eb940611adb5e719a4b554138dade6 | 33f7870a49d7cc06d2f3036e22543e6ec5046e68 | refs/heads/master | 1,672,066,539,347 | 1,602,429,158,000 | 1,602,429,158,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,072 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import ring_theory.algebra_tower
import linear_algebra.matrix
/-!
# Tower of field extensions
In this file we prove the tower law for arbitrary extensions and finite extensions.
Suppose `L` is a field extension of `K` and `K` is a field extension of `F`.
Then `[L:F] = [L:K] [K:F]` where `[E₁:E₂]` means the `E₂`-dimension of `E₁`.
In fact we generalize it to vector spaces, where `L` is not necessarily a field,
but just a vector space over `K`.
## Implementation notes
We prove two versions, since there are two notions of dimensions: `vector_space.dim` which gives
the dimension of an arbitrary vector space as a cardinal, and `finite_dimensional.findim` which
gives the dimension of a finitely-dimensional vector space as a natural number.
## Tags
tower law
-/
universes u v w u₁ v₁ w₁
open_locale classical big_operators
section field
open cardinal
variables (F : Type u) (K : Type v) (A : Type w)
variables [field F] [field K] [add_comm_group A]
variables [algebra F K] [vector_space K A] [vector_space F A] [is_scalar_tower F K A]
/-- Tower law: if `A` is a `K`-vector space and `K` is a field extension of `F` then
`dim_F(A) = dim_F(K) * dim_K(A)`. -/
theorem dim_mul_dim' :
(cardinal.lift.{v w} (vector_space.dim F K) *
cardinal.lift.{w v} (vector_space.dim K A) : cardinal.{max w v}) =
cardinal.lift.{w v} (vector_space.dim F A) :=
let ⟨b, hb⟩ := exists_is_basis F K, ⟨c, hc⟩ := exists_is_basis K A in
by rw [← (vector_space.dim F K).lift_id, ← hb.mk_eq_dim,
← (vector_space.dim K A).lift_id, ← hc.mk_eq_dim,
← lift_umax.{w v}, ← (hb.smul hc).mk_eq_dim, mk_prod, lift_mul,
lift_lift, lift_lift, lift_lift, lift_lift, lift_umax]
/-- Tower law: if `A` is a `K`-vector space and `K` is a field extension of `F` then
`dim_F(A) = dim_F(K) * dim_K(A)`. -/
theorem dim_mul_dim (F : Type u) (K A : Type v) [field F] [field K] [add_comm_group A]
[algebra F K] [vector_space K A] [vector_space F A] [is_scalar_tower F K A] :
vector_space.dim F K * vector_space.dim K A = vector_space.dim F A :=
by convert dim_mul_dim' F K A; rw lift_id
namespace finite_dimensional
theorem trans [finite_dimensional F K] [finite_dimensional K A] : finite_dimensional F A :=
let ⟨b, hb⟩ := exists_is_basis_finset F K in
let ⟨c, hc⟩ := exists_is_basis_finset K A in
of_finite_basis $ hb.smul hc
lemma right [hf : finite_dimensional F A] : finite_dimensional K A :=
let ⟨b, hb⟩ := iff_fg.1 hf in
iff_fg.2 ⟨b, @submodule.restrict_scalars'_injective F _ _ _ _ _ _ _ _ _ _ _ $
by { rw [submodule.restrict_scalars'_top, eq_top_iff, ← hb, submodule.span_le],
exact submodule.subset_span }⟩
/-- Tower law: if `A` is a `K`-algebra and `K` is a field extension of `F` then
`dim_F(A) = dim_F(K) * dim_K(A)`. -/
theorem findim_mul_findim [finite_dimensional F K] [finite_dimensional K A] :
findim F K * findim K A = findim F A :=
let ⟨b, hb⟩ := exists_is_basis_finset F K in
let ⟨c, hc⟩ := exists_is_basis_finset K A in
by rw [findim_eq_card_basis hb, findim_eq_card_basis hc,
findim_eq_card_basis (hb.smul hc), fintype.card_prod]
instance linear_map (F : Type u) (V : Type v) (W : Type w)
[field F] [add_comm_group V] [vector_space F V] [add_comm_group W] [vector_space F W]
[finite_dimensional F V] [finite_dimensional F W] :
finite_dimensional F (V →ₗ[F] W) :=
let ⟨b, hb⟩ := exists_is_basis_finset F V in
let ⟨c, hc⟩ := exists_is_basis_finset F W in
(matrix.to_lin hb hc).finite_dimensional
lemma findim_linear_map (F : Type u) (V : Type v) (W : Type w)
[field F] [add_comm_group V] [vector_space F V] [add_comm_group W] [vector_space F W]
[finite_dimensional F V] [finite_dimensional F W] :
findim F (V →ₗ[F] W) = findim F V * findim F W :=
let ⟨b, hb⟩ := exists_is_basis_finset F V in
let ⟨c, hc⟩ := exists_is_basis_finset F W in
by rw [linear_equiv.findim_eq (linear_map.to_matrix hb hc), matrix.findim_matrix,
findim_eq_card_basis hb, findim_eq_card_basis hc, mul_comm]
-- TODO: generalize by removing [finite_dimensional F K]
-- V = ⊕F,
-- (V →ₗ[F] K) = ((⊕F) →ₗ[F] K) = (⊕ (F →ₗ[F] K)) = ⊕K
instance linear_map' (F : Type u) (K : Type v) (V : Type w)
[field F] [field K] [algebra F K] [finite_dimensional F K]
[add_comm_group V] [vector_space F V] [finite_dimensional F V] :
finite_dimensional K (V →ₗ[F] K) :=
right F _ _
lemma findim_linear_map' (F : Type u) (K : Type v) (V : Type w)
[field F] [field K] [algebra F K] [finite_dimensional F K]
[add_comm_group V] [vector_space F V] [finite_dimensional F V] :
findim K (V →ₗ[F] K) = findim F V :=
(nat.mul_right_inj $ show 0 < findim F K, from findim_pos).1 $
calc findim F K * findim K (V →ₗ[F] K)
= findim F (V →ₗ[F] K) : findim_mul_findim _ _ _
... = findim F V * findim F K : findim_linear_map F V K
... = findim F K * findim F V : mul_comm _ _
end finite_dimensional
end field
|
67be6d50e2003b3c5f9a02305a2f5255f9b6eb7b | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/topology/metric_space/lipschitz.lean | 786f99a94abb58eabc74dee05dc7b459633011a9 | [
"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 | 16,463 | lean | /-
Copyright (c) 2018 Rohan Mitta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rohan Mitta, Kevin Buzzard, Alistair Tucker, Johannes Hölzl, Yury Kudryashov
-/
import logic.function.iterate
import data.set.intervals.proj_Icc
import topology.metric_space.basic
import category_theory.endomorphism
import category_theory.types
/-!
# Lipschitz continuous functions
A map `f : α → β` between two (extended) metric spaces is called *Lipschitz continuous*
with constant `K ≥ 0` if for all `x, y` we have `edist (f x) (f y) ≤ K * edist x y`.
For a metric space, the latter inequality is equivalent to `dist (f x) (f y) ≤ K * dist x y`.
There is also a version asserting this inequality only for `x` and `y` in some set `s`.
In this file we provide various ways to prove that various combinations of Lipschitz continuous
functions are Lipschitz continuous. We also prove that Lipschitz continuous functions are
uniformly continuous.
## Main definitions and lemmas
* `lipschitz_with K f`: states that `f` is Lipschitz with constant `K : ℝ≥0`
* `lipschitz_on_with K f`: states that `f` is Lipschitz with constant `K : ℝ≥0` on a set `s`
* `lipschitz_with.uniform_continuous`: a Lipschitz function is uniformly continuous
* `lipschitz_on_with.uniform_continuous_on`: a function which is Lipschitz on a set is uniformly
continuous on that set.
## Implementation notes
The parameter `K` has type `ℝ≥0`. This way we avoid conjuction in the definition and have
coercions both to `ℝ` and `ℝ≥0∞`. Constructors whose names end with `'` take `K : ℝ` as an
argument, and return `lipschitz_with (real.to_nnreal K) f`.
-/
universes u v w x
open filter function set
open_locale topological_space nnreal ennreal
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Type x}
/-- A function `f` is Lipschitz continuous with constant `K ≥ 0` if for all `x, y`
we have `dist (f x) (f y) ≤ K * dist x y` -/
def lipschitz_with [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (f : α → β) :=
∀x y, edist (f x) (f y) ≤ K * edist x y
lemma lipschitz_with_iff_dist_le_mul [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0}
{f : α → β} : lipschitz_with K f ↔ ∀ x y, dist (f x) (f y) ≤ K * dist x y :=
by { simp only [lipschitz_with, edist_nndist, dist_nndist], norm_cast }
alias lipschitz_with_iff_dist_le_mul ↔ lipschitz_with.dist_le_mul lipschitz_with.of_dist_le_mul
/-- A function `f` is Lipschitz continuous with constant `K ≥ 0` on `s` if for all `x, y` in `s`
we have `dist (f x) (f y) ≤ K * dist x y` -/
def lipschitz_on_with [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (f : α → β)
(s : set α) :=
∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), edist (f x) (f y) ≤ K * edist x y
@[simp] lemma lipschitz_on_with_empty [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0)
(f : α → β) : lipschitz_on_with K f ∅ :=
λ x x_in y y_in, false.elim x_in
lemma lipschitz_on_with.mono [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0}
{s t : set α} {f : α → β} (hf : lipschitz_on_with K f t) (h : s ⊆ t) : lipschitz_on_with K f s :=
λ x x_in y y_in, hf (h x_in) (h y_in)
lemma lipschitz_on_with_iff_dist_le_mul [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0}
{s : set α} {f : α → β} :
lipschitz_on_with K f s ↔ ∀ (x ∈ s) (y ∈ s), dist (f x) (f y) ≤ K * dist x y :=
by { simp only [lipschitz_on_with, edist_nndist, dist_nndist], norm_cast }
alias lipschitz_on_with_iff_dist_le_mul ↔
lipschitz_on_with.dist_le_mul lipschitz_on_with.of_dist_le_mul
@[simp] lemma lipschitz_on_univ [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0}
{f : α → β} : lipschitz_on_with K f univ ↔ lipschitz_with K f :=
by simp [lipschitz_on_with, lipschitz_with]
lemma lipschitz_on_with_iff_restrict [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0}
{f : α → β} {s : set α} : lipschitz_on_with K f s ↔ lipschitz_with K (s.restrict f) :=
by simp only [lipschitz_on_with, lipschitz_with, set_coe.forall', restrict, subtype.edist_eq]
namespace lipschitz_with
section emetric
variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ]
variables {K : ℝ≥0} {f : α → β}
protected lemma lipschitz_on_with (h : lipschitz_with K f) (s : set α) : lipschitz_on_with K f s :=
λ x _ y _, h x y
lemma edist_le_mul (h : lipschitz_with K f) (x y : α) : edist (f x) (f y) ≤ K * edist x y := h x y
lemma edist_lt_top (hf : lipschitz_with K f) {x y : α} (h : edist x y ≠ ⊤) :
edist (f x) (f y) < ⊤ :=
lt_of_le_of_lt (hf x y) $ ennreal.mul_lt_top ennreal.coe_ne_top h
lemma mul_edist_le (h : lipschitz_with K f) (x y : α) :
(K⁻¹ : ℝ≥0∞) * edist (f x) (f y) ≤ edist x y :=
begin
rw [mul_comm, ← div_eq_mul_inv],
exact ennreal.div_le_of_le_mul' (h x y)
end
protected lemma of_edist_le (h : ∀ x y, edist (f x) (f y) ≤ edist x y) :
lipschitz_with 1 f :=
λ x y, by simp only [ennreal.coe_one, one_mul, h]
protected lemma weaken (hf : lipschitz_with K f) {K' : ℝ≥0} (h : K ≤ K') :
lipschitz_with K' f :=
assume x y, le_trans (hf x y) $ ennreal.mul_right_mono (ennreal.coe_le_coe.2 h)
lemma ediam_image_le (hf : lipschitz_with K f) (s : set α) :
emetric.diam (f '' s) ≤ K * emetric.diam s :=
begin
apply emetric.diam_le,
rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩,
calc edist (f x) (f y) ≤ ↑K * edist x y : hf.edist_le_mul x y
... ≤ ↑K * emetric.diam s :
ennreal.mul_left_mono (emetric.edist_le_diam_of_mem hx hy)
end
/-- A Lipschitz function is uniformly continuous -/
protected lemma uniform_continuous (hf : lipschitz_with K f) :
uniform_continuous f :=
begin
refine emetric.uniform_continuous_iff.2 (λε εpos, _),
use [ε / K, ennreal.div_pos_iff.2 ⟨ne_of_gt εpos, ennreal.coe_ne_top⟩],
assume x y Dxy,
apply lt_of_le_of_lt (hf.edist_le_mul x y),
rw [mul_comm],
exact ennreal.mul_lt_of_lt_div Dxy
end
/-- A Lipschitz function is continuous -/
protected lemma continuous (hf : lipschitz_with K f) :
continuous f :=
hf.uniform_continuous.continuous
protected lemma const (b : β) : lipschitz_with 0 (λa:α, b) :=
assume x y, by simp only [edist_self, zero_le]
protected lemma id : lipschitz_with 1 (@id α) :=
lipschitz_with.of_edist_le $ assume x y, le_refl _
protected lemma subtype_val (s : set α) : lipschitz_with 1 (subtype.val : s → α) :=
lipschitz_with.of_edist_le $ assume x y, le_refl _
protected lemma subtype_coe (s : set α) : lipschitz_with 1 (coe : s → α) :=
lipschitz_with.subtype_val s
lemma subtype_mk (hf : lipschitz_with K f) {p : β → Prop} (hp : ∀ x, p (f x)) :
lipschitz_with K (λ x, ⟨f x, hp x⟩ : α → {y // p y}) :=
hf
protected lemma eval {α : ι → Type u} [Π i, pseudo_emetric_space (α i)] [fintype ι] (i : ι) :
lipschitz_with 1 (function.eval i : (Π i, α i) → α i) :=
lipschitz_with.of_edist_le $ λ f g, by convert edist_le_pi_edist f g i
protected lemma restrict (hf : lipschitz_with K f) (s : set α) :
lipschitz_with K (s.restrict f) :=
λ x y, hf x y
protected lemma comp {Kf Kg : ℝ≥0} {f : β → γ} {g : α → β}
(hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf * Kg) (f ∘ g) :=
assume x y,
calc edist (f (g x)) (f (g y)) ≤ Kf * edist (g x) (g y) : hf _ _
... ≤ Kf * (Kg * edist x y) : ennreal.mul_left_mono (hg _ _)
... = (Kf * Kg : ℝ≥0) * edist x y : by rw [← mul_assoc, ennreal.coe_mul]
protected lemma prod_fst : lipschitz_with 1 (@prod.fst α β) :=
lipschitz_with.of_edist_le $ assume x y, le_max_left _ _
protected lemma prod_snd : lipschitz_with 1 (@prod.snd α β) :=
lipschitz_with.of_edist_le $ assume x y, le_max_right _ _
protected lemma prod {f : α → β} {Kf : ℝ≥0} (hf : lipschitz_with Kf f)
{g : α → γ} {Kg : ℝ≥0} (hg : lipschitz_with Kg g) :
lipschitz_with (max Kf Kg) (λ x, (f x, g x)) :=
begin
assume x y,
rw [ennreal.coe_mono.map_max, prod.edist_eq, ennreal.max_mul],
exact max_le_max (hf x y) (hg x y)
end
protected lemma uncurry {f : α → β → γ} {Kα Kβ : ℝ≥0} (hα : ∀ b, lipschitz_with Kα (λ a, f a b))
(hβ : ∀ a, lipschitz_with Kβ (f a)) :
lipschitz_with (Kα + Kβ) (function.uncurry f) :=
begin
rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩,
simp only [function.uncurry, ennreal.coe_add, add_mul],
apply le_trans (edist_triangle _ (f a₂ b₁) _),
exact add_le_add (le_trans (hα _ _ _) $ ennreal.mul_left_mono $ le_max_left _ _)
(le_trans (hβ _ _ _) $ ennreal.mul_left_mono $ le_max_right _ _)
end
protected lemma iterate {f : α → α} (hf : lipschitz_with K f) :
∀n, lipschitz_with (K ^ n) (f^[n])
| 0 := lipschitz_with.id
| (n + 1) := by rw [pow_succ']; exact (iterate n).comp hf
lemma edist_iterate_succ_le_geometric {f : α → α} (hf : lipschitz_with K f) (x n) :
edist (f^[n] x) (f^[n + 1] x) ≤ edist x (f x) * K ^ n :=
begin
rw [iterate_succ, mul_comm],
simpa only [ennreal.coe_pow] using (hf.iterate n) x (f x)
end
open category_theory
protected lemma mul {f g : End α} {Kf Kg} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) :
lipschitz_with (Kf * Kg) (f * g : End α) :=
hf.comp hg
/-- The product of a list of Lipschitz continuous endomorphisms is a Lipschitz continuous
endomorphism. -/
protected lemma list_prod (f : ι → End α) (K : ι → ℝ≥0) (h : ∀ i, lipschitz_with (K i) (f i)) :
∀ l : list ι, lipschitz_with (l.map K).prod (l.map f).prod
| [] := by simp [types_id, lipschitz_with.id]
| (i :: l) := by { simp only [list.map_cons, list.prod_cons], exact (h i).mul (list_prod l) }
protected lemma pow {f : End α} {K} (h : lipschitz_with K f) :
∀ n : ℕ, lipschitz_with (K^n) (f^n : End α)
| 0 := lipschitz_with.id
| (n + 1) := by { rw [pow_succ, pow_succ], exact h.mul (pow n) }
end emetric
section metric
variables [pseudo_metric_space α] [pseudo_metric_space β] [pseudo_metric_space γ] {K : ℝ≥0}
protected lemma of_dist_le' {f : α → β} {K : ℝ} (h : ∀ x y, dist (f x) (f y) ≤ K * dist x y) :
lipschitz_with (real.to_nnreal K) f :=
of_dist_le_mul $ λ x y, le_trans (h x y) $
mul_le_mul_of_nonneg_right (real.le_coe_to_nnreal K) dist_nonneg
protected lemma mk_one {f : α → β} (h : ∀ x y, dist (f x) (f y) ≤ dist x y) :
lipschitz_with 1 f :=
of_dist_le_mul $ by simpa only [nnreal.coe_one, one_mul] using h
/-- For functions to `ℝ`, it suffices to prove `f x ≤ f y + K * dist x y`; this version
doesn't assume `0≤K`. -/
protected lemma of_le_add_mul' {f : α → ℝ} (K : ℝ) (h : ∀x y, f x ≤ f y + K * dist x y) :
lipschitz_with (real.to_nnreal K) f :=
have I : ∀ x y, f x - f y ≤ K * dist x y,
from assume x y, sub_le_iff_le_add'.2 (h x y),
lipschitz_with.of_dist_le' $
assume x y,
abs_sub_le_iff.2 ⟨I x y, dist_comm y x ▸ I y x⟩
/-- For functions to `ℝ`, it suffices to prove `f x ≤ f y + K * dist x y`; this version
assumes `0≤K`. -/
protected lemma of_le_add_mul {f : α → ℝ} (K : ℝ≥0) (h : ∀x y, f x ≤ f y + K * dist x y) :
lipschitz_with K f :=
by simpa only [real.to_nnreal_coe] using lipschitz_with.of_le_add_mul' K h
protected lemma of_le_add {f : α → ℝ} (h : ∀ x y, f x ≤ f y + dist x y) :
lipschitz_with 1 f :=
lipschitz_with.of_le_add_mul 1 $ by simpa only [nnreal.coe_one, one_mul]
protected lemma le_add_mul {f : α → ℝ} {K : ℝ≥0} (h : lipschitz_with K f) (x y) :
f x ≤ f y + K * dist x y :=
sub_le_iff_le_add'.1 $ le_trans (le_abs_self _) $ h.dist_le_mul x y
protected lemma iff_le_add_mul {f : α → ℝ} {K : ℝ≥0} :
lipschitz_with K f ↔ ∀ x y, f x ≤ f y + K * dist x y :=
⟨lipschitz_with.le_add_mul, lipschitz_with.of_le_add_mul K⟩
lemma nndist_le {f : α → β} (hf : lipschitz_with K f) (x y : α) :
nndist (f x) (f y) ≤ K * nndist x y :=
hf.dist_le_mul x y
lemma diam_image_le {f : α → β} (hf : lipschitz_with K f) (s : set α) (hs : metric.bounded s) :
metric.diam (f '' s) ≤ K * metric.diam s :=
begin
apply metric.diam_le_of_forall_dist_le (mul_nonneg K.coe_nonneg metric.diam_nonneg),
rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩,
calc dist (f x) (f y) ≤ ↑K * dist x y : hf.dist_le_mul x y
... ≤ ↑K * metric.diam s :
mul_le_mul_of_nonneg_left (metric.dist_le_diam_of_mem hs hx hy) K.2
end
protected lemma dist_left (y : α) : lipschitz_with 1 (λ x, dist x y) :=
lipschitz_with.of_le_add $ assume x z, by { rw [add_comm], apply dist_triangle }
protected lemma dist_right (x : α) : lipschitz_with 1 (dist x) :=
lipschitz_with.of_le_add $ assume y z, dist_triangle_right _ _ _
protected lemma dist : lipschitz_with 2 (function.uncurry $ @dist α _) :=
lipschitz_with.uncurry lipschitz_with.dist_left lipschitz_with.dist_right
lemma dist_iterate_succ_le_geometric {f : α → α} (hf : lipschitz_with K f) (x n) :
dist (f^[n] x) (f^[n + 1] x) ≤ dist x (f x) * K ^ n :=
begin
rw [iterate_succ, mul_comm],
simpa only [nnreal.coe_pow] using (hf.iterate n).dist_le_mul x (f x)
end
lemma _root_.lipschitz_with_max : lipschitz_with 1 (λ p : ℝ × ℝ, max p.1 p.2) :=
lipschitz_with.of_le_add $ λ p₁ p₂, sub_le_iff_le_add'.1 $
(le_abs_self _).trans (abs_max_sub_max_le_max _ _ _ _)
lemma _root_.lipschitz_with_min : lipschitz_with 1 (λ p : ℝ × ℝ, min p.1 p.2) :=
lipschitz_with.of_le_add $ λ p₁ p₂, sub_le_iff_le_add'.1 $
(le_abs_self _).trans (abs_min_sub_min_le_max _ _ _ _)
end metric
section emetric
variables {α} [pseudo_emetric_space α] {f g : α → ℝ} {Kf Kg : ℝ≥0}
protected lemma max (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) :
lipschitz_with (max Kf Kg) (λ x, max (f x) (g x)) :=
by simpa only [(∘), one_mul] using lipschitz_with_max.comp (hf.prod hg)
protected lemma min (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) :
lipschitz_with (max Kf Kg) (λ x, min (f x) (g x)) :=
by simpa only [(∘), one_mul] using lipschitz_with_min.comp (hf.prod hg)
lemma max_const (hf : lipschitz_with Kf f) (a : ℝ) : lipschitz_with Kf (λ x, max (f x) a) :=
by simpa only [max_eq_left (zero_le Kf)] using hf.max (lipschitz_with.const a)
lemma const_max (hf : lipschitz_with Kf f) (a : ℝ) : lipschitz_with Kf (λ x, max a (f x)) :=
by simpa only [max_comm] using hf.max_const a
lemma min_const (hf : lipschitz_with Kf f) (a : ℝ) : lipschitz_with Kf (λ x, min (f x) a) :=
by simpa only [max_eq_left (zero_le Kf)] using hf.min (lipschitz_with.const a)
lemma const_min (hf : lipschitz_with Kf f) (a : ℝ) : lipschitz_with Kf (λ x, min a (f x)) :=
by simpa only [min_comm] using hf.min_const a
end emetric
protected lemma proj_Icc {a b : ℝ} (h : a ≤ b) :
lipschitz_with 1 (proj_Icc a b h) :=
((lipschitz_with.id.const_min _).const_max _).subtype_mk _
end lipschitz_with
namespace lipschitz_on_with
variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ]
variables {K : ℝ≥0} {s : set α} {f : α → β}
protected lemma uniform_continuous_on (hf : lipschitz_on_with K f s) : uniform_continuous_on f s :=
uniform_continuous_on_iff_restrict.mpr (lipschitz_on_with_iff_restrict.mp hf).uniform_continuous
protected lemma continuous_on (hf : lipschitz_on_with K f s) : continuous_on f s :=
hf.uniform_continuous_on.continuous_on
end lipschitz_on_with
open metric
/-- If a function is locally Lipschitz around a point, then it is continuous at this point. -/
lemma continuous_at_of_locally_lipschitz [metric_space α] [metric_space β] {f : α → β} {x : α}
{r : ℝ} (hr : 0 < r) (K : ℝ) (h : ∀y, dist y x < r → dist (f y) (f x) ≤ K * dist y x) :
continuous_at f x :=
begin
refine (nhds_basis_ball.tendsto_iff nhds_basis_closed_ball).2
(λε εpos, ⟨min r (ε / max K 1), _, λ y hy, _⟩),
{ simp [hr, div_pos εpos, zero_lt_one] },
have A : max K 1 ≠ 0 := ne_of_gt (lt_max_iff.2 (or.inr zero_lt_one)),
calc dist (f y) (f x)
≤ K * dist y x : h y (lt_of_lt_of_le hy (min_le_left _ _))
... ≤ max K 1 * dist y x : mul_le_mul_of_nonneg_right (le_max_left K 1) dist_nonneg
... ≤ max K 1 * (ε / max K 1) :
mul_le_mul_of_nonneg_left (le_of_lt (lt_of_lt_of_le hy (min_le_right _ _)))
(le_trans zero_le_one (le_max_right K 1))
... = ε : mul_div_cancel' _ A
end
|
ea6a04850017fb4de1f751ea70515e0538b1dfe7 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/data/zmod/basic.lean | d90e2afc57777ba79643b4d16286fef290941c87 | [
"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 | 21,613 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Chris Hughes
-/
import data.int.modeq data.int.gcd data.fintype data.pnat.basic tactic.ring
/-!
# Integers mod `n`
Definition of the integers mod n, and the field structure on the integers mod p.
There are two types defined, `zmod n`, which is for integers modulo a positive nat `n : ℕ+`.
`zmodp` is the type of integers modulo a prime number, for which a field structure is defined.
## Definitions
* `val` is inherited from `fin` and returns the least natural number in the equivalence class
* `val_min_abs` returns the integer closest to zero in the equivalence class.
* A coercion `cast` is defined from `zmod n` into any semiring. This is a semiring hom if the ring has
characteristic dividing `n`
## Implentation notes
`zmod` and `zmodp` are implemented as different types so that the field instance for `zmodp` can be
synthesized. This leads to a lot of code duplication and most of the functions and theorems for
`zmod` are restated for `zmodp`
-/
open nat nat.modeq int
def zmod (n : ℕ+) := fin n
namespace zmod
instance (n : ℕ+) : has_neg (zmod n) :=
⟨λ a, ⟨nat_mod (-(a.1 : ℤ)) n,
have h : (n : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.2 n.pos,
have h₁ : ((n : ℕ) : ℤ) = abs n := (abs_of_nonneg (int.coe_nat_nonneg n)).symm,
by rw [← int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h), h₁];
exact int.mod_lt _ h⟩⟩
instance (n : ℕ+) : add_comm_semigroup (zmod n) :=
{ add_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(show ((a + b) % n + c) ≡ (a + (b + c) % n) [MOD n],
from calc ((a + b) % n + c) ≡ a + b + c [MOD n] : modeq_add (nat.mod_mod _ _) rfl
... ≡ a + (b + c) [MOD n] : by rw add_assoc
... ≡ (a + (b + c) % n) [MOD n] : modeq_add rfl (nat.mod_mod _ _).symm),
add_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a + b) % n = (b + a) % n, by rw add_comm),
..fin.has_add }
instance (n : ℕ+) : comm_semigroup (zmod n) :=
{ mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc ((a * b) % n * c) ≡ a * b * c [MOD n] : modeq_mul (nat.mod_mod _ _) rfl
... ≡ a * (b * c) [MOD n] : by rw mul_assoc
... ≡ a * (b * c % n) [MOD n] : modeq_mul rfl (nat.mod_mod _ _).symm),
mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % n = (b * a) % n, by rw mul_comm),
..fin.has_mul }
instance (n : ℕ+) : has_one (zmod n) := ⟨⟨(1 % n), nat.mod_lt _ n.pos⟩⟩
instance (n : ℕ+) : has_zero (zmod n) := ⟨⟨0, n.pos⟩⟩
instance (n : ℕ+) : inhabited (zmod n) := ⟨0⟩
instance zmod_one.subsingleton : subsingleton (zmod 1) :=
⟨λ a b, fin.eq_of_veq (by rw [eq_zero_of_le_zero (le_of_lt_succ a.2),
eq_zero_of_le_zero (le_of_lt_succ b.2)])⟩
lemma add_val {n : ℕ+} : ∀ a b : zmod n, (a + b).val = (a.val + b.val) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma mul_val {n : ℕ+} : ∀ a b : zmod n, (a * b).val = (a.val * b.val) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma one_val {n : ℕ+} : (1 : zmod n).val = 1 % n := rfl
@[simp] lemma zero_val (n : ℕ+) : (0 : zmod n).val = 0 := rfl
private lemma one_mul_aux (n : ℕ+) (a : zmod n) : (1 : zmod n) * a = a :=
begin
cases n with n hn,
cases n with n,
{ exact (lt_irrefl _ hn).elim },
{ cases n with n,
{ exact @subsingleton.elim (zmod 1) _ _ _ },
{ have h₁ : a.1 % n.succ.succ = a.1 := nat.mod_eq_of_lt a.2,
have h₂ : 1 % n.succ.succ = 1 := nat.mod_eq_of_lt dec_trivial,
refine fin.eq_of_veq _,
simp [mul_val, one_val, h₁, h₂] } }
end
private lemma left_distrib_aux (n : ℕ+) : ∀ a b c : zmod n, a * (b + c) = a * b + a * c :=
λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc a * ((b + c) % n) ≡ a * (b + c) [MOD n] : modeq_mul rfl (nat.mod_mod _ _)
... ≡ a * b + a * c [MOD n] : by rw mul_add
... ≡ (a * b) % n + (a * c) % n [MOD n] : modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm)
instance (n : ℕ+) : comm_ring (zmod n) :=
{ zero_add := λ ⟨a, ha⟩, fin.eq_of_veq (show (0 + a) % n = a, by rw zero_add; exact nat.mod_eq_of_lt ha),
add_zero := λ ⟨a, ha⟩, fin.eq_of_veq (nat.mod_eq_of_lt ha),
add_left_neg :=
λ ⟨a, ha⟩, fin.eq_of_veq (show (((-a : ℤ) % n).to_nat + a) % n = 0,
from int.coe_nat_inj
begin
have hn : (n : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 n.pos)).symm,
rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm],
simp,
end),
one_mul := one_mul_aux n,
mul_one := λ a, by rw mul_comm; exact one_mul_aux n a,
left_distrib := left_distrib_aux n,
right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl,
..zmod.has_zero n,
..zmod.has_one n,
..zmod.has_neg n,
..zmod.add_comm_semigroup n,
..zmod.comm_semigroup n }
lemma val_cast_nat {n : ℕ+} (a : ℕ) : (a : zmod n).val = a % n :=
begin
induction a with a ih,
{ rw [nat.zero_mod]; refl },
{ rw [succ_eq_add_one, nat.cast_add, add_val, ih],
show (a % n + ((0 + (1 % n)) % n)) % n = (a + 1) % n,
rw [zero_add, nat.mod_mod],
exact nat.modeq.modeq_add (nat.mod_mod a n) (nat.mod_mod 1 n) }
end
lemma neg_val' {m : pnat} (n : zmod m) : (-n).val = (m - n.val) % m :=
have ((-n).val + n.val) % m = (m - n.val + n.val) % m,
by { rw [←add_val, add_left_neg, nat.sub_add_cancel (le_of_lt n.is_lt), nat.mod_self], refl },
(nat.mod_eq_of_lt (fin.is_lt _)).symm.trans (nat.modeq.modeq_add_cancel_right rfl this)
lemma neg_val {m : pnat} (n : zmod m) : (-n).val = if n = 0 then 0 else m - n.val :=
begin
rw neg_val',
by_cases h : n = 0; simp [h],
cases n with n nlt; cases n; dsimp, { contradiction },
rw nat.mod_eq_of_lt,
apply nat.sub_lt m.2 (nat.succ_pos _),
end
lemma mk_eq_cast {n : ℕ+} {a : ℕ} (h : a < n) : (⟨a, h⟩ : zmod n) = (a : zmod n) :=
fin.eq_of_veq (by rw [val_cast_nat, nat.mod_eq_of_lt h])
@[simp] lemma cast_self_eq_zero {n : ℕ+} : ((n : ℕ) : zmod n) = 0 :=
fin.eq_of_veq (show (n : zmod n).val = 0, by simp [val_cast_nat])
lemma val_cast_of_lt {n : ℕ+} {a : ℕ} (h : a < n) : (a : zmod n).val = a :=
by rw [val_cast_nat, nat.mod_eq_of_lt h]
@[simp] lemma cast_mod_nat (n : ℕ+) (a : ℕ) : ((a % n : ℕ) : zmod n) = a :=
by conv {to_rhs, rw ← nat.mod_add_div a n}; simp
@[simp, priority 980]
lemma cast_mod_nat' {n : ℕ} (hn : 0 < n) (a : ℕ) : ((a % n : ℕ) : zmod ⟨n, hn⟩) = a :=
cast_mod_nat _ _
@[simp] lemma cast_val {n : ℕ+} (a : zmod n) : (a.val : zmod n) = a :=
by cases a; simp [mk_eq_cast]
@[simp] lemma cast_mod_int (n : ℕ+) (a : ℤ) : ((a % (n : ℕ) : ℤ) : zmod n) = a :=
by conv {to_rhs, rw ← int.mod_add_div a n}; simp
@[simp, priority 980]
lemma cast_mod_int' {n : ℕ} (hn : 0 < n) (a : ℤ) :
((a % (n : ℕ) : ℤ) : zmod ⟨n, hn⟩) = a := cast_mod_int _ _
lemma val_cast_int {n : ℕ+} (a : ℤ) : (a : zmod n).val = (a % (n : ℕ)).nat_abs :=
have h : nat_abs (a % (n : ℕ)) < n := int.coe_nat_lt.1 begin
rw [nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))],
conv {to_rhs, rw ← abs_of_nonneg (int.coe_nat_nonneg n)},
exact int.mod_lt _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)
end,
int.coe_nat_inj $
by conv {to_lhs, rw [← cast_mod_int n a,
← nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)),
int.cast_coe_nat, val_cast_of_lt h] }
lemma coe_val_cast_int {n : ℕ+} (a : ℤ) : ((a : zmod n).val : ℤ) = a % (n : ℕ) :=
by rw [val_cast_int, int.nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))]
lemma eq_iff_modeq_nat {n : ℕ+} {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] :=
⟨λ h, by have := fin.veq_of_eq h;
rwa [val_cast_nat, val_cast_nat] at this,
λ h, fin.eq_of_veq $ by rwa [val_cast_nat, val_cast_nat]⟩
lemma eq_iff_modeq_nat' {n : ℕ} (hn : 0 < n) {a b : ℕ} : (a : zmod ⟨n, hn⟩) = b ↔ a ≡ b [MOD n] :=
eq_iff_modeq_nat
lemma eq_iff_modeq_int {n : ℕ+} {a b : ℤ} : (a : zmod n) = b ↔ a ≡ b [ZMOD (n : ℕ)] :=
⟨λ h, by have := fin.veq_of_eq h;
rwa [val_cast_int, val_cast_int, ← int.coe_nat_eq_coe_nat_iff,
nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos)),
nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 n.pos))] at this,
λ h : a % (n : ℕ) = b % (n : ℕ),
by rw [← cast_mod_int n a, ← cast_mod_int n b, h]⟩
lemma eq_iff_modeq_int' {n : ℕ} (hn : 0 < n) {a b : ℤ} :
(a : zmod ⟨n, hn⟩) = b ↔ a ≡ b [ZMOD (n : ℕ)] := eq_iff_modeq_int
lemma eq_zero_iff_dvd_nat {n : ℕ+} {a : ℕ} : (a : zmod n) = 0 ↔ (n : ℕ) ∣ a :=
by rw [← @nat.cast_zero (zmod n), eq_iff_modeq_nat, nat.modeq.modeq_zero_iff]
lemma eq_zero_iff_dvd_int {n : ℕ+} {a : ℤ} : (a : zmod n) = 0 ↔ ((n : ℕ) : ℤ) ∣ a :=
by rw [← @int.cast_zero (zmod n), eq_iff_modeq_int, int.modeq.modeq_zero_iff]
instance (n : ℕ+) : fintype (zmod n) := fin.fintype _
instance decidable_eq (n : ℕ+) : decidable_eq (zmod n) := fin.decidable_eq _
instance (n : ℕ+) : has_repr (zmod n) := fin.has_repr _
lemma card_zmod (n : ℕ+) : fintype.card (zmod n) = n := fintype.card_fin n
instance : subsingleton (units (zmod 2)) :=
⟨λ x y, begin
cases x with x xi,
cases y with y yi,
revert x y xi yi,
exact dec_trivial
end⟩
lemma le_div_two_iff_lt_neg {n : ℕ+} (hn : (n : ℕ) % 2 = 1)
{x : zmod n} (hx0 : x ≠ 0) : x.1 ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).1 :=
have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left n.pos).2 dec_trivial),
have hn2' : (n : ℕ) - n / 2 = n / 2 + 1,
by conv {to_lhs, congr, rw [← succ_sub_one n, succ_sub n.pos]};
rw [← two_mul_odd_div_two hn, two_mul, ← succ_add, nat.add_sub_cancel],
have hxn : (n : ℕ) - x.val < n,
begin
rw [nat.sub_lt_iff (le_of_lt x.2) (le_refl _), nat.sub_self],
rw ← zmod.cast_val x at hx0,
exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0)
end,
by conv {to_rhs, rw [← nat.succ_le_iff, succ_eq_add_one, ← hn2', ← zero_add (- x), ← zmod.cast_self_eq_zero,
← sub_eq_add_neg, ← zmod.cast_val x, ← nat.cast_sub (le_of_lt x.2),
zmod.val_cast_nat, mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.2)] }
lemma ne_neg_self {n : ℕ+} (hn1 : (n : ℕ) % 2 = 1) {a : zmod n} (ha : a ≠ 0) : a ≠ -a :=
λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg hn1 ha,
by rwa [← h, ← not_lt, not_iff_self] at this
@[simp] lemma cast_mul_right_val_cast {n m : ℕ+} (a : ℕ) :
((a : zmod (m * n)).val : zmod m) = (a : zmod m) :=
zmod.eq_iff_modeq_nat.2 (by rw zmod.val_cast_nat;
exact nat.modeq.modeq_of_modeq_mul_right _ (nat.mod_mod _ _))
@[simp] lemma cast_mul_left_val_cast {n m : ℕ+} (a : ℕ) :
((a : zmod (n * m)).val : zmod m) = (a : zmod m) :=
zmod.eq_iff_modeq_nat.2 (by rw zmod.val_cast_nat;
exact nat.modeq.modeq_of_modeq_mul_left _ (nat.mod_mod _ _))
lemma cast_val_cast_of_dvd {n m : ℕ+} (h : (m : ℕ) ∣ n) (a : ℕ) :
((a : zmod n).val : zmod m) = (a : zmod m) :=
let ⟨k , hk⟩ := h in
zmod.eq_iff_modeq_nat.2 (nat.modeq.modeq_of_modeq_mul_right k
(by rw [← hk, zmod.val_cast_nat]; exact nat.mod_mod _ _))
/-- `unit_of_coprime` makes an element of `units (zmod n)` given
a natural number `x` and a proof that `x` is coprime to `n` -/
def unit_of_coprime {n : ℕ+} (x : ℕ) (h : nat.coprime x n) : units (zmod n) :=
have (x * gcd_a x ↑n : zmod n) = 1,
by rw [← int.cast_coe_nat, ← int.cast_one, ← int.cast_mul,
zmod.eq_iff_modeq_int, ← int.coe_nat_one, ← (show nat.gcd _ _ = _, from h)];
simpa using int.modeq.gcd_a_modeq x n,
⟨x, gcd_a x n, this, by simpa [mul_comm] using this⟩
@[simp] lemma cast_unit_of_coprime {n : ℕ+} (x : ℕ) (h : nat.coprime x n) :
(unit_of_coprime x h : zmod n) = x := rfl
def units_equiv_coprime {n : ℕ+} : units (zmod n) ≃ {x : zmod n // nat.coprime x.1 n} :=
{ to_fun := λ x, ⟨x, nat.modeq.coprime_of_mul_modeq_one (x⁻¹).1.1 begin
have := units.ext_iff.1 (mul_right_inv x),
rwa [← zmod.cast_val ((1 : units (zmod n)) : zmod n), units.coe_one, zmod.one_val,
← zmod.cast_val ((x * x⁻¹ : units (zmod n)) : zmod n),
units.coe_mul, zmod.mul_val, zmod.cast_mod_nat, zmod.cast_mod_nat,
zmod.eq_iff_modeq_nat] at this
end⟩,
inv_fun := λ x, unit_of_coprime x.1.1 x.2,
left_inv := λ ⟨_, _, _, _⟩, units.ext (by simp),
right_inv := λ ⟨_, _⟩, by simp }
/-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`,
The result will be in the interval `(-n/2, n/2]` -/
def val_min_abs {n : ℕ+} (x : zmod n) : ℤ :=
if x.val ≤ n / 2 then x.val else x.val - n
@[simp] lemma coe_val_min_abs {n : ℕ+} (x : zmod n) :
(x.val_min_abs : zmod n) = x :=
by simp [zmod.val_min_abs]; split_ifs; simp [sub_eq_add_neg]
lemma nat_abs_val_min_abs_le {n : ℕ+} (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 :=
have (x.val - n : ℤ) ≤ 0, from sub_nonpos.2 $ int.coe_nat_le.2 $ le_of_lt x.2,
begin
rw zmod.val_min_abs,
split_ifs with h,
{ exact h },
{ rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub],
conv_lhs { congr, rw [coe_coe, ← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul,
int.coe_nat_bit0, int.coe_nat_one] },
rw ← sub_nonneg,
suffices : (0 : ℤ) ≤ x.val - ((n % 2 : ℕ) + (n / 2 : ℕ)),
{ exact le_trans this (le_of_eq $ by ring) },
exact sub_nonneg.2 (by rw [← int.coe_nat_add, int.coe_nat_le];
exact calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 :
add_le_add (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) (le_refl _)
... ≤ x.val : by rw add_comm; exact nat.succ_le_of_lt (lt_of_not_ge h)) }
end
@[simp] lemma val_min_abs_zero {n : ℕ+} : (0 : zmod n).val_min_abs = 0 :=
by simp [zmod.val_min_abs]
@[simp] lemma val_min_abs_eq_zero {n : ℕ+} (x : zmod n) :
x.val_min_abs = 0 ↔ x = 0 :=
⟨λ h, begin
dsimp [zmod.val_min_abs] at h,
split_ifs at h,
{ exact fin.eq_of_veq (by simp * at *) },
{ exact absurd h (mt sub_eq_zero.1 (ne_of_lt $ int.coe_nat_lt.2 x.2)) }
end, λ hx0, hx0.symm ▸ zmod.val_min_abs_zero⟩
lemma cast_nat_abs_val_min_abs {n : ℕ+} (a : zmod n) :
(a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a :=
have (a.val : ℤ) + -n ≤ 0, by erw [sub_nonpos, int.coe_nat_le]; exact le_of_lt a.2,
begin
dsimp [zmod.val_min_abs],
split_ifs,
{ simp },
{ erw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this],
simp }
end
@[simp] lemma nat_abs_val_min_abs_neg {n : ℕ+} (a : zmod n) :
(-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs :=
if haa : -a = a then by rw [haa]
else
have hpa : (n : ℕ) - a.val ≤ n / 2 ↔ (n : ℕ) / 2 < a.val,
from suffices (((n : ℕ) % 2) + 2 * (n / 2)) - a.val ≤ (n : ℕ) / 2 ↔ (n : ℕ) / 2 < a.val,
by rwa [nat.mod_add_div] at this,
begin
rw [nat.sub_le_iff, two_mul, ← add_assoc, nat.add_sub_cancel],
cases (n : ℕ).mod_two_eq_zero_or_one with hn0 hn1,
{ split,
{ exact λ h, lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h)
begin
assume hna,
rw [← zmod.cast_val a, ← hna, neg_eq_iff_add_eq_zero, ← nat.cast_add,
zmod.eq_zero_iff_dvd_nat, ← two_mul, ← zero_add (2 * _), ← hn0,
nat.mod_add_div] at haa,
exact haa (dvd_refl _)
end },
{ rw [hn0, zero_add], exact le_of_lt } },
{ rw [hn1, add_comm, nat.succ_le_iff] }
end,
have ha0 : ¬ a = 0, from λ ha0, by simp * at *,
begin
dsimp [zmod.val_min_abs],
rw [← not_le] at hpa,
simp only [if_neg ha0, zmod.neg_val, hpa, int.coe_nat_sub (le_of_lt a.2)],
split_ifs,
{ simp [sub_eq_add_neg] },
{ rw [← int.nat_abs_neg], simp }
end
lemma val_eq_ite_val_min_abs {n : ℕ+} (a : zmod n) :
(a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n :=
by simp [zmod.val_min_abs]; split_ifs; simp
lemma neg_eq_self_mod_two : ∀ (a : zmod 2), -a = a := dec_trivial
@[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a :=
by cases a; simp [zmod.neg_eq_self_mod_two]
section
variables {α : Type*} [has_zero α] [has_one α] [has_add α] {n : ℕ+}
def cast : zmod n → α := nat.cast ∘ fin.val
end
end zmod
def zmodp (p : ℕ) (hp : prime p) : Type := zmod ⟨p, hp.pos⟩
namespace zmodp
variables {p : ℕ} (hp : prime p)
instance : comm_ring (zmodp p hp) := zmod.comm_ring ⟨p, hp.pos⟩
instance : inhabited (zmodp p hp) := ⟨0⟩
instance {p : ℕ} (hp : prime p) : has_inv (zmodp p hp) :=
⟨λ a, gcd_a a.1 p⟩
lemma add_val : ∀ a b : zmodp p hp, (a + b).val = (a.val + b.val) % p
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma mul_val : ∀ a b : zmodp p hp, (a * b).val = (a.val * b.val) % p
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp] lemma one_val : (1 : zmodp p hp).val = 1 :=
nat.mod_eq_of_lt hp.one_lt
@[simp] lemma zero_val : (0 : zmodp p hp).val = 0 := rfl
lemma val_cast_nat (a : ℕ) : (a : zmodp p hp).val = a % p :=
@zmod.val_cast_nat ⟨p, hp.pos⟩ _
lemma mk_eq_cast {a : ℕ} (h : a < p) : (⟨a, h⟩ : zmodp p hp) = (a : zmodp p hp) :=
@zmod.mk_eq_cast ⟨p, hp.pos⟩ _ _
@[simp] lemma cast_self_eq_zero: (p : zmodp p hp) = 0 :=
fin.eq_of_veq $ by simp [val_cast_nat]
lemma val_cast_of_lt {a : ℕ} (h : a < p) : (a : zmodp p hp).val = a :=
@zmod.val_cast_of_lt ⟨p, hp.pos⟩ _ h
@[simp] lemma cast_mod_nat (a : ℕ) : ((a % p : ℕ) : zmodp p hp) = a :=
@zmod.cast_mod_nat ⟨p, hp.pos⟩ _
@[simp] lemma cast_val (a : zmodp p hp) : (a.val : zmodp p hp) = a :=
@zmod.cast_val ⟨p, hp.pos⟩ _
@[simp] lemma cast_mod_int (a : ℤ) : ((a % p : ℤ) : zmodp p hp) = a :=
@zmod.cast_mod_int ⟨p, hp.pos⟩ _
lemma val_cast_int (a : ℤ) : (a : zmodp p hp).val = (a % p).nat_abs :=
@zmod.val_cast_int ⟨p, hp.pos⟩ _
lemma coe_val_cast_int (a : ℤ) : ((a : zmodp p hp).val : ℤ) = a % (p : ℕ) :=
@zmod.coe_val_cast_int ⟨p, hp.pos⟩ _
lemma eq_iff_modeq_nat {a b : ℕ} : (a : zmodp p hp) = b ↔ a ≡ b [MOD p] :=
@zmod.eq_iff_modeq_nat ⟨p, hp.pos⟩ _ _
lemma eq_iff_modeq_int {a b : ℤ} : (a : zmodp p hp) = b ↔ a ≡ b [ZMOD p] :=
@zmod.eq_iff_modeq_int ⟨p, hp.pos⟩ _ _
lemma eq_zero_iff_dvd_nat (a : ℕ) : (a : zmodp p hp) = 0 ↔ p ∣ a :=
@zmod.eq_zero_iff_dvd_nat ⟨p, hp.pos⟩ _
lemma eq_zero_iff_dvd_int (a : ℤ) : (a : zmodp p hp) = 0 ↔ (p : ℤ) ∣ a :=
@zmod.eq_zero_iff_dvd_int ⟨p, hp.pos⟩ _
instance : fintype (zmodp p hp) := @zmod.fintype ⟨p, hp.pos⟩
instance decidable_eq : decidable_eq (zmodp p hp) := fin.decidable_eq _
instance X (h : prime 2) : subsingleton (units (zmodp 2 h)) :=
zmod.subsingleton
instance : has_repr (zmodp p hp) := fin.has_repr _
@[simp] lemma card_zmodp : fintype.card (zmodp p hp) = p :=
@zmod.card_zmod ⟨p, hp.pos⟩
lemma le_div_two_iff_lt_neg {p : ℕ} (hp : prime p) (hp1 : p % 2 = 1)
{x : zmodp p hp} (hx0 : x ≠ 0) : x.1 ≤ (p / 2 : ℕ) ↔ (p / 2 : ℕ) < (-x).1 :=
@zmod.le_div_two_iff_lt_neg ⟨p, hp.pos⟩ hp1 _ hx0
lemma ne_neg_self (hp1 : p % 2 = 1) {a : zmodp p hp} (ha : a ≠ 0) : a ≠ -a :=
@zmod.ne_neg_self ⟨p, hp.pos⟩ hp1 _ ha
variable {hp}
/-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`,
The result will be in the interval `(-n/2, n/2]` -/
def val_min_abs (x : zmodp p hp) : ℤ := zmod.val_min_abs x
@[simp] lemma coe_val_min_abs (x : zmodp p hp) :
(x.val_min_abs : zmodp p hp) = x :=
zmod.coe_val_min_abs x
lemma nat_abs_val_min_abs_le (x : zmodp p hp) : x.val_min_abs.nat_abs ≤ p / 2 :=
zmod.nat_abs_val_min_abs_le x
@[simp] lemma val_min_abs_zero : (0 : zmodp p hp).val_min_abs = 0 :=
zmod.val_min_abs_zero
@[simp] lemma val_min_abs_eq_zero (x : zmodp p hp) : x.val_min_abs = 0 ↔ x = 0 :=
zmod.val_min_abs_eq_zero x
lemma cast_nat_abs_val_min_abs (a : zmodp p hp) :
(a.val_min_abs.nat_abs : zmodp p hp) = if a.val ≤ p / 2 then a else -a :=
zmod.cast_nat_abs_val_min_abs a
@[simp] lemma nat_abs_val_min_abs_neg (a : zmodp p hp) :
(-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs :=
zmod.nat_abs_val_min_abs_neg _
lemma val_eq_ite_val_min_abs (a : zmodp p hp) :
(a.val : ℤ) = a.val_min_abs + if a.val ≤ p / 2 then 0 else p :=
zmod.val_eq_ite_val_min_abs _
variable (hp)
lemma prime_ne_zero {q : ℕ} (hq : prime q) (hpq : p ≠ q) : (q : zmodp p hp) ≠ 0 :=
by rwa [← nat.cast_zero, ne.def, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_zero_iff,
← hp.coprime_iff_not_dvd, coprime_primes hp hq]
lemma mul_inv_eq_gcd (a : ℕ) : (a : zmodp p hp) * a⁻¹ = nat.gcd a p :=
by rw [← int.cast_coe_nat (nat.gcd _ _), nat.gcd_comm, nat.gcd_rec, ← (eq_iff_modeq_int _).2 (int.modeq.gcd_a_modeq _ _)];
simp [has_inv.inv, val_cast_nat]
private lemma mul_inv_cancel_aux : ∀ a : zmodp p hp, a ≠ 0 → a * a⁻¹ = 1 :=
λ ⟨a, hap⟩ ha0, begin
rw [mk_eq_cast, ne.def, ← @nat.cast_zero (zmodp p hp), eq_iff_modeq_nat, modeq_zero_iff] at ha0,
have : nat.gcd p a = 1 := (prime.coprime_iff_not_dvd hp).2 ha0,
rw [mk_eq_cast _ hap, mul_inv_eq_gcd, nat.gcd_comm],
simpa [nat.gcd_comm, this]
end
instance : field (zmodp p hp) :=
{ zero_ne_one := fin.ne_of_vne $ show 0 ≠ 1 % p,
by rw nat.mod_eq_of_lt hp.one_lt;
exact zero_ne_one,
mul_inv_cancel := mul_inv_cancel_aux hp,
inv_zero := show (gcd_a 0 p : zmodp p hp) = 0,
by unfold gcd_a xgcd xgcd_aux; refl,
..zmodp.comm_ring hp,
..zmodp.has_inv hp }
end zmodp
|
0af461139b51aa9e5177847e54be6e77f77f1209 | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /library/init/meta/interaction_monad.lean | 2afc5e45d2514e00d7c92a3d92e91b1cf5ca305b | [
"Apache-2.0"
] | permissive | kbuzzard/lean | ae3c3db4bb462d750dbf7419b28bafb3ec983ef7 | ed1788fd674bb8991acffc8fca585ec746711928 | refs/heads/master | 1,620,983,366,617 | 1,618,937,600,000 | 1,618,937,600,000 | 359,886,396 | 1 | 0 | Apache-2.0 | 1,618,936,987,000 | 1,618,936,987,000 | null | UTF-8 | Lean | false | false | 4,438 | 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, Sebastian Ullrich
-/
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.data.to_string
universes u v
meta inductive interaction_monad.result (state : Type) (α : Type u)
| success : α → state → interaction_monad.result
| exception : option (unit → format) → option pos → state → interaction_monad.result
open interaction_monad.result
section
variables {state : Type} {α : Type u}
variables [has_to_string α]
meta def interaction_monad.result_to_string : result state α → string
| (success a s) := to_string a
| (exception (some t) ref s) := "Exception: " ++ to_string (t ())
| (exception none ref s) := "[silent exception]"
meta instance interaction_monad.result_has_string : has_to_string (result state α) :=
⟨interaction_monad.result_to_string⟩
end
meta def interaction_monad.result.clamp_pos {state : Type} {α : Type u} (line0 line col : ℕ) : result state α → result state α
| (success a s) := success a s
| (exception msg (some p) s) := exception msg (some $ if p.line < line0 then ⟨line, col⟩ else p) s
| (exception msg none s) := exception msg (some ⟨line, col⟩) s
@[reducible] meta def interaction_monad (state : Type) (α : Type u) :=
state → result state α
section
parameter {state : Type}
variables {α : Type u} {β : Type v}
local notation `m` := interaction_monad state
@[inline] meta def interaction_monad_fmap (f : α → β) (t : m α) : m β :=
λ s, interaction_monad.result.cases_on (t s)
(λ a s', success (f a) s')
(λ e s', exception e s')
@[inline] meta def interaction_monad_bind (t₁ : m α) (t₂ : α → m β) : m β :=
λ s, interaction_monad.result.cases_on (t₁ s)
(λ a s', t₂ a s')
(λ e s', exception e s')
@[inline] meta def interaction_monad_return (a : α) : m α :=
λ s, success a s
meta def interaction_monad_orelse {α : Type u} (t₁ t₂ : m α) : m α :=
λ s, interaction_monad.result.cases_on (t₁ s)
success
(λ e₁ ref₁ s', interaction_monad.result.cases_on (t₂ s)
success
exception)
@[inline] meta def interaction_monad_seq (t₁ : m α) (t₂ : m β) : m β :=
interaction_monad_bind t₁ (λ a, t₂)
meta instance interaction_monad.monad : monad m :=
{map := @interaction_monad_fmap, pure := @interaction_monad_return, bind := @interaction_monad_bind}
meta def interaction_monad.mk_exception {α : Type u} {β : Type v} [has_to_format β] (msg : β) (ref : option expr) (s : state) : result state α :=
exception (some (λ _, to_fmt msg)) none s
meta def interaction_monad.fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : m α :=
λ s, interaction_monad.mk_exception msg none s
meta def interaction_monad.silent_fail {α : Type u} : m α :=
λ s, exception none none s
meta def interaction_monad.failed {α : Type u} : m α :=
interaction_monad.fail "failed"
/- Alternative orelse operator that allows to select which exception should be used.
The default is to use the first exception since the standard `orelse` uses the second. -/
meta def interaction_monad.orelse' {α : Type u} (t₁ t₂ : m α) (use_first_ex := tt) : m α :=
λ s, interaction_monad.result.cases_on (t₁ s)
success
(λ e₁ ref₁ s₁', interaction_monad.result.cases_on (t₂ s)
success
(λ e₂ ref₂ s₂', if use_first_ex then (exception e₁ ref₁ s₁') else (exception e₂ ref₂ s₂')))
meta instance interaction_monad.monad_fail : monad_fail m :=
{ fail := λ α s, interaction_monad.fail (to_fmt s), ..interaction_monad.monad }
@[inline]
meta def interaction_monad.bracket {α β γ} (x : m α) (inside : m β) (y : m γ) : m β :=
x >> λ s,
match inside s with
| success r s' := (y >> success r) s'
| exception msg p s' := (y >> exception msg p) s'
end
-- TODO: unify `parser` and `tactic` behavior?
-- meta instance interaction_monad.alternative : alternative m :=
-- ⟨@interaction_monad_fmap, (λ α a s, success a s), (@fapp _ _), @interaction_monad.failed, @interaction_monad_orelse⟩
end
|
e62d281b3db34009b77d73966a6651345b86f86a | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/topology/subset_properties.lean | 4e9dda350b681618d260ecb1237a423bf1b7012b | [
"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 | 59,318 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov
-/
import topology.continuous_on
import data.finset.order
/-!
# Properties of subsets of topological spaces
## Main definitions
`compact`, `is_clopen`, `is_irreducible`, `is_connected`, `is_totally_disconnected`,
`is_totally_separated`
TODO: write better docs
## On the definition of irreducible and connected sets/spaces
In informal mathematics, irreducible and connected spaces are assumed to be nonempty.
We formalise the predicate without that assumption
as `is_preirreducible` and `is_preconnected` respectively.
In other words, the only difference is whether the empty space
counts as irreducible and/or connected.
There are good reasons to consider the empty space to be “too simple to be simple”
See also https://ncatlab.org/nlab/show/too+simple+to+be+simple,
and in particular
https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions.
-/
open set filter classical
open_locale classical topological_space filter
universes u v
variables {α : Type u} {β : Type v} [topological_space α] {s t : set α}
/- compact sets -/
section compact
/-- A set `s` is compact if for every filter `f` that contains `s`,
every set of `f` also meets every neighborhood of some `a ∈ s`. -/
def is_compact (s : set α) := ∀ ⦃f⦄ [ne_bot f], f ≤ 𝓟 s → ∃a∈s, cluster_pt a f
/-- The complement to a compact set belongs to a filter `f` if it belongs to each filter
`𝓝 a ⊓ f`, `a ∈ s`. -/
lemma is_compact.compl_mem_sets (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, sᶜ ∈ 𝓝 a ⊓ f) :
sᶜ ∈ f :=
begin
contrapose! hf,
simp only [mem_iff_inf_principal_compl, compl_compl, inf_assoc, ← exists_prop] at hf ⊢,
exact @hs _ hf inf_le_right
end
/-- The complement to a compact set belongs to a filter `f` if each `a ∈ s` has a neighborhood `t`
within `s` such that `tᶜ` belongs to `f`. -/
lemma is_compact.compl_mem_sets_of_nhds_within (hs : is_compact s) {f : filter α}
(hf : ∀ a ∈ s, ∃ t ∈ 𝓝[s] a, tᶜ ∈ f) :
sᶜ ∈ f :=
begin
refine hs.compl_mem_sets (λ a ha, _),
rcases hf a ha with ⟨t, ht, hst⟩,
replace ht := mem_inf_principal.1 ht,
refine mem_inf_sets.2 ⟨_, ht, _, hst, _⟩,
rintros x ⟨h₁, h₂⟩ hs,
exact h₂ (h₁ hs)
end
/-- If `p : set α → Prop` is stable under restriction and union, and each point `x of a compact set `s`
has a neighborhood `t` within `s` such that `p t`, then `p s` holds. -/
@[elab_as_eliminator]
lemma is_compact.induction_on {s : set α} (hs : is_compact s) {p : set α → Prop} (he : p ∅)
(hmono : ∀ ⦃s t⦄, s ⊆ t → p t → p s) (hunion : ∀ ⦃s t⦄, p s → p t → p (s ∪ t))
(hnhds : ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, p t) :
p s :=
let f : filter α :=
{ sets := {t | p tᶜ},
univ_sets := by simpa,
sets_of_superset := λ t₁ t₂ ht₁ ht, hmono (compl_subset_compl.2 ht) ht₁,
inter_sets := λ t₁ t₂ ht₁ ht₂, by simp [compl_inter, hunion ht₁ ht₂] } in
have sᶜ ∈ f, from hs.compl_mem_sets_of_nhds_within (by simpa using hnhds),
by simpa
/-- The intersection of a compact set and a closed set is a compact set. -/
lemma is_compact.inter_right (hs : is_compact s) (ht : is_closed t) :
is_compact (s ∩ t) :=
begin
introsI f hnf hstf,
obtain ⟨a, hsa, ha⟩ : ∃ a ∈ s, cluster_pt a f :=
hs (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))),
have : a ∈ t :=
(ht.mem_of_nhds_within_ne_bot $ ha.mono $
le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))),
exact ⟨a, ⟨hsa, this⟩, ha⟩
end
/-- The intersection of a closed set and a compact set is a compact set. -/
lemma is_compact.inter_left (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) :=
inter_comm t s ▸ ht.inter_right hs
/-- The set difference of a compact set and an open set is a compact set. -/
lemma compact_diff (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) :=
hs.inter_right (is_closed_compl_iff.mpr ht)
/-- A closed subset of a compact set is a compact set. -/
lemma compact_of_is_closed_subset (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) :
is_compact t :=
inter_eq_self_of_subset_right h ▸ hs.inter_right ht
lemma is_compact.adherence_nhdset {f : filter α}
(hs : is_compact s) (hf₂ : f ≤ 𝓟 s) (ht₁ : is_open t) (ht₂ : ∀a∈s, cluster_pt a f → a ∈ t) :
t ∈ f :=
classical.by_cases mem_sets_of_eq_bot $
assume : f ⊓ 𝓟 tᶜ ≠ ⊥,
let ⟨a, ha, (hfa : cluster_pt a $ f ⊓ 𝓟 tᶜ)⟩ := @@hs this $ inf_le_left_of_le hf₂ in
have a ∈ t,
from ht₂ a ha (hfa.of_inf_left),
have tᶜ ∩ t ∈ 𝓝[tᶜ] a,
from inter_mem_nhds_within _ (mem_nhds_sets ht₁ this),
have A : 𝓝[tᶜ] a = ⊥,
from empty_in_sets_eq_bot.1 $ compl_inter_self t ▸ this,
have 𝓝[tᶜ] a ≠ ⊥,
from hfa.of_inf_right,
absurd A this
lemma compact_iff_ultrafilter_le_nhds :
is_compact s ↔ (∀f, is_ultrafilter f → f ≤ 𝓟 s → ∃a∈s, f ≤ 𝓝 a) :=
⟨assume hs : is_compact s, assume f hf hfs,
let ⟨a, ha, h⟩ := @hs _ hf.left hfs in
⟨a, ha, le_of_ultrafilter hf h⟩,
assume hs : (∀f, is_ultrafilter f → f ≤ 𝓟 s → ∃a∈s, f ≤ 𝓝 a),
assume f hf hfs,
let ⟨a, ha, (h : ultrafilter_of f ≤ 𝓝 a)⟩ :=
hs (ultrafilter_of f) (ultrafilter_ultrafilter_of' hf) (le_trans ultrafilter_of_le hfs) in
have cluster_pt a (ultrafilter_of f),
from cluster_pt.of_le_nhds' h (ultrafilter_ultrafilter_of' hf).left,
⟨a, ha, this.mono ultrafilter_of_le⟩⟩
/-- For every open cover of a compact set, there exists a finite subcover. -/
lemma is_compact.elim_finite_subcover {ι : Type v} (hs : is_compact s)
(U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) :
∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i :=
is_compact.induction_on hs ⟨∅, empty_subset _⟩ (λ s₁ s₂ hs ⟨t, hs₂⟩, ⟨t, subset.trans hs hs₂⟩)
(λ s₁ s₂ ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩,
⟨t₁ ∪ t₂, by { rw [finset.bUnion_union], exact union_subset_union ht₁ ht₂ }⟩)
(λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hsU hx) in
⟨U i, mem_nhds_within.2 ⟨U i, hUo i, hi, inter_subset_left _ _⟩, {i}, by simp⟩)
/-- For every family of closed sets whose intersection avoids a compact set,
there exists a finite subfamily whose intersection avoids this compact set. -/
lemma is_compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : is_compact s)
(Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) :
∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ :=
let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, (Z i)ᶜ) hZc
(by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union,
exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ)
in
⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union,
exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩
/-- To show that a compact set intersects the intersection of a family of closed sets,
it is sufficient to show that it intersects every finite subfamily. -/
lemma is_compact.inter_Inter_nonempty {s : set α} {ι : Type v} (hs : is_compact s)
(Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : ∀ t : finset ι, (s ∩ ⋂ i ∈ t, Z i).nonempty) :
(s ∩ ⋂ i, Z i).nonempty :=
begin
simp only [← ne_empty_iff_nonempty] at hsZ ⊢,
apply mt (hs.elim_finite_subfamily_closed Z hZc), push_neg, exact hsZ
end
/-- Cantor's intersection theorem:
the intersection of a directed family of nonempty compact closed sets is nonempty. -/
lemma is_compact.nonempty_Inter_of_directed_nonempty_compact_closed
{ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z)
(hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, is_compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) :
(⋂ i, Z i).nonempty :=
begin
apply hι.elim,
intro i₀,
let Z' := λ i, Z i ∩ Z i₀,
suffices : (⋂ i, Z' i).nonempty,
{ exact nonempty.mono (Inter_subset_Inter $ assume i, inter_subset_left (Z i) (Z i₀)) this },
rw ← ne_empty_iff_nonempty,
intro H,
obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅,
from (hZc i₀).elim_finite_subfamily_closed Z'
(assume i, is_closed_inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]),
obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i,
{ rcases directed.finset_le hZd t with ⟨i, hi⟩,
rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩,
use [i₁, hi₁₀],
intros j hj,
exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ },
suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty,
{ rw ← ne_empty_iff_nonempty at this, contradiction },
refine nonempty.mono _ (hZn i₁),
exact subset_inter hi₁.left (subset_bInter hi₁.right)
end
/-- Cantor's intersection theorem for sequences indexed by `ℕ`:
the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/
lemma is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed
(Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i)
(hZn : ∀ i, (Z i).nonempty) (hZ0 : is_compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) :
(⋂ i, Z i).nonempty :=
have Zmono : _, from @monotone_of_monotone_nat (order_dual _) _ Z hZd,
have hZd : directed (⊇) Z, from directed_of_sup Zmono,
have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i,
have hZc : ∀ i, is_compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i),
is_compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl
/-- For every open cover of a compact set, there exists a finite subcover. -/
lemma is_compact.elim_finite_subcover_image {b : set β} {c : β → set α}
(hs : is_compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) :
∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i :=
begin
rcases hs.elim_finite_subcover (λ i, c i.1 : b → set α) _ _ with ⟨d, hd⟩,
refine ⟨↑(d.image subtype.val), _, finset.finite_to_set _, _⟩,
{ intros i hi,
erw finset.mem_image at hi,
rcases hi with ⟨s, hsd, rfl⟩,
exact s.property },
{ refine subset.trans hd _,
rintros x ⟨_, ⟨s, rfl⟩, ⟨_, ⟨hsd, rfl⟩, H⟩⟩,
refine ⟨c s.val, ⟨s.val, _⟩, H⟩,
simp [finset.mem_image_of_mem subtype.val hsd] },
{ rintro ⟨i, hi⟩, exact hc₁ i hi },
{ refine subset.trans hc₂ _,
rintros x ⟨_, ⟨i, rfl⟩, ⟨_, ⟨hib, rfl⟩, H⟩⟩,
exact ⟨_, ⟨⟨i, hib⟩, rfl⟩, H⟩ },
end
/-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`,
there exists a finite subfamily whose intersection avoids `s`. -/
theorem compact_of_finite_subfamily_closed
(h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) :
is_compact s :=
assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, cluster_pt x f),
have hf : ∀x∈s, 𝓝 x ⊓ f = ⊥,
by simpa only [cluster_pt, not_exists, not_not, ne_bot],
have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t,
from assume ⟨x, hxs, hx⟩,
have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_in_sets_eq_bot, hf x hxs],
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in
have ∅ ∈ 𝓝[t₂] x,
from (𝓝[t₂] x).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht,
have 𝓝[t₂] x = ⊥,
by rwa [empty_in_sets_eq_bot] at this,
by simp only [closure_eq_cluster_pts] at hx; exact hx t₂ ht₂ this,
let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure)
(by simpa [eq_empty_iff_forall_not_mem, not_exists]) in
have (⋂i∈t, subtype.val i) ∈ f,
from Inter_mem_sets t.finite_to_set $ assume i hi, i.2,
have s ∩ (⋂i∈t, subtype.val i) ∈ f,
from inter_mem_sets (le_principal_iff.1 hfs) this,
have ∅ ∈ f,
from mem_sets_of_superset this $ assume x ⟨hxs, hx⟩,
let ⟨i, hit, hxi⟩ := (show ∃i ∈ t, x ∉ closure (subtype.val i),
by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in
have x ∈ closure i.val, from subset_closure (mem_bInter_iff.mp hx i hit),
show false, from hxi this,
hfn $ by rwa [empty_in_sets_eq_bot] at this
/-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/
lemma compact_of_finite_subcover
(h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) →
s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) :
is_compact s :=
compact_of_finite_subfamily_closed $
assume ι Z hZc hsZ,
let ⟨t, ht⟩ := h (λ i, (Z i)ᶜ) (assume i, is_open_compl_iff.mpr $ hZc i)
(by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union,
exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ)
in
⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union,
exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩
/-- A set `s` is compact if and only if
for every open cover of `s`, there exists a finite subcover. -/
lemma compact_iff_finite_subcover :
is_compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) →
s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) :=
⟨assume hs ι, hs.elim_finite_subcover, compact_of_finite_subcover⟩
/-- A set `s` is compact if and only if
for every family of closed sets whose intersection avoids `s`,
there exists a finite subfamily whose intersection avoids `s`. -/
theorem compact_iff_finite_subfamily_closed :
is_compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) :=
⟨assume hs ι, hs.elim_finite_subfamily_closed, compact_of_finite_subfamily_closed⟩
@[simp]
lemma compact_empty : is_compact (∅ : set α) :=
assume f hnf hsf, not.elim hnf $
empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf
@[simp]
lemma compact_singleton {a : α} : is_compact ({a} : set α) :=
λ f hf hfa, ⟨a, rfl, cluster_pt.of_le_nhds'
(hfa.trans $ by simpa only [principal_singleton] using pure_le_nhds a) hf⟩
lemma set.finite.compact_bUnion {s : set β} {f : β → set α} (hs : finite s)
(hf : ∀i ∈ s, is_compact (f i)) :
is_compact (⋃i ∈ s, f i) :=
compact_of_finite_subcover $ assume ι U hUo hsU,
have ∀i : subtype s, ∃t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from
assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo
(calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi
... ⊆ ⋃j, U j : hsU),
let ⟨finite_subcovers, h⟩ := axiom_of_choice this in
by haveI : fintype (subtype s) := hs.fintype; exact
let t := finset.bind finset.univ finite_subcovers in
have (⋃i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from bUnion_subset $
assume i hi, calc
f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩)
... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $
assume j hj, finset.mem_bind.mpr ⟨_, finset.mem_univ _, hj⟩,
⟨t, this⟩
lemma compact_Union {f : β → set α} [fintype β]
(h : ∀i, is_compact (f i)) : is_compact (⋃i, f i) :=
by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i)
lemma set.finite.is_compact (hs : finite s) : is_compact s :=
bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, compact_singleton)
lemma is_compact.union (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) :=
by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption)
lemma is_compact.insert (hs : is_compact s) (a) : is_compact (insert a s) :=
compact_singleton.union hs
/-- `filter.cocompact` is the filter generated by complements to compact sets. -/
def filter.cocompact (α : Type*) [topological_space α] : filter α :=
⨅ (s : set α) (hs : is_compact s), 𝓟 (sᶜ)
lemma filter.has_basis_cocompact : (filter.cocompact α).has_basis is_compact compl :=
has_basis_binfi_principal'
(λ s hs t ht, ⟨s ∪ t, hs.union ht, compl_subset_compl.2 (subset_union_left s t),
compl_subset_compl.2 (subset_union_right s t)⟩)
⟨∅, compact_empty⟩
lemma filter.mem_cocompact : s ∈ filter.cocompact α ↔ ∃ t, is_compact t ∧ tᶜ ⊆ s :=
filter.has_basis_cocompact.mem_iff.trans $ exists_congr $ λ t, exists_prop
lemma filter.mem_cocompact' : s ∈ filter.cocompact α ↔ ∃ t, is_compact t ∧ sᶜ ⊆ t :=
filter.mem_cocompact.trans $ exists_congr $ λ t, and_congr_right $ λ ht, compl_subset_comm
lemma is_compact.compl_mem_cocompact (hs : is_compact s) : sᶜ ∈ filter.cocompact α :=
filter.has_basis_cocompact.mem_of_mem hs
section tube_lemma
variables [topological_space β]
/-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes
a product of an open neighborhood of `s` by an open neighborhood of `t`. -/
def nhds_contain_boxes (s : set α) (t : set β) : Prop :=
∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n),
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n
lemma nhds_contain_boxes.symm {s : set α} {t : set β} :
nhds_contain_boxes s t → nhds_contain_boxes t s :=
assume H n hn hp,
let ⟨u, v, uo, vo, su, tv, p⟩ :=
H (prod.swap ⁻¹' n)
(continuous_swap n hn)
(by rwa [←image_subset_iff, image_swap_prod]) in
⟨v, u, vo, uo, tv, su,
by rwa [←image_subset_iff, image_swap_prod] at p⟩
lemma nhds_contain_boxes.comm {s : set α} {t : set β} :
nhds_contain_boxes s t ↔ nhds_contain_boxes t s :=
iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm
lemma nhds_contain_boxes_of_singleton {x : α} {y : β} :
nhds_contain_boxes ({x} : set α) ({y} : set β) :=
assume n hn hp,
let ⟨u, v, uo, vo, xu, yv, hp'⟩ :=
is_open_prod_iff.mp hn x y (hp $ by simp) in
⟨u, v, uo, vo, by simpa, by simpa, hp'⟩
lemma nhds_contain_boxes_of_compact {s : set α} (hs : is_compact s) (t : set β)
(H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t :=
assume n hn hp,
have ∀x : subtype s, ∃uv : set α × set β,
is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n,
from assume ⟨x, hx⟩,
have set.prod {x} t ⊆ n, from
subset.trans (prod_mono (by simpa) (subset.refl _)) hp,
let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩,
let ⟨uvs, h⟩ := classical.axiom_of_choice this in
have us_cover : s ⊆ ⋃i, (uvs i).1, from
assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1),
let ⟨s0, s0_cover⟩ :=
hs.elim_finite_subcover _ (λi, (h i).1) us_cover in
let u := ⋃(i ∈ s0), (uvs i).1 in
let v := ⋂(i ∈ s0), (uvs i).2 in
have is_open u, from is_open_bUnion (λi _, (h i).1),
have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1),
have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1),
have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩,
have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx',
let ⟨i,is0,hi⟩ := this in
(h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩,
⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩
/-- If `s` and `t` are compact sets and `n` is an open neighborhood of `s × t`, then there exist
open neighborhoods `u ⊇ s` and `v ⊇ t` such that `u × v ⊆ n`. -/
lemma generalized_tube_lemma {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t)
{n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) :
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n :=
have _, from
nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $
nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton,
this n hn hp
end tube_lemma
/-- Type class for compact spaces. Separation is sometimes included in the definition, especially
in the French literature, but we do not include it here. -/
class compact_space (α : Type*) [topological_space α] : Prop :=
(compact_univ : is_compact (univ : set α))
lemma compact_univ [h : compact_space α] : is_compact (univ : set α) := h.compact_univ
lemma cluster_point_of_compact [compact_space α] (f : filter α) [ne_bot f] :
∃ x, cluster_pt x f :=
by simpa using compact_univ (show f ≤ 𝓟 univ, by simp)
theorem compact_space_of_finite_subfamily_closed {α : Type u} [topological_space α]
(h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
(⋂ i, Z i) = ∅ → (∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅)) :
compact_space α :=
{ compact_univ :=
begin
apply compact_of_finite_subfamily_closed,
intros ι Z, specialize h Z,
simpa using h
end }
lemma is_closed.compact [compact_space α] {s : set α} (h : is_closed s) :
is_compact s :=
compact_of_is_closed_subset compact_univ h (subset_univ _)
variables [topological_space β]
lemma is_compact.image_of_continuous_on {f : α → β} (hs : is_compact s) (hf : continuous_on f s) :
is_compact (f '' s) :=
begin
intros l lne ls,
have : ne_bot (l.comap f ⊓ 𝓟 s) :=
comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls),
obtain ⟨a, has, ha⟩ : ∃ a ∈ s, cluster_pt a (l.comap f ⊓ 𝓟 s) := @@hs this inf_le_right,
use [f a, mem_image_of_mem f has],
have : tendsto f (𝓝 a ⊓ (comap f l ⊓ 𝓟 s)) (𝓝 (f a) ⊓ l),
{ convert (hf a has).inf (@tendsto_comap _ _ f l) using 1,
rw nhds_within,
ac_refl },
exact @@tendsto.ne_bot _ this ha,
end
lemma is_compact.image {f : α → β} (hs : is_compact s) (hf : continuous f) :
is_compact (f '' s) :=
hs.image_of_continuous_on hf.continuous_on
lemma compact_range [compact_space α] {f : α → β} (hf : continuous f) :
is_compact (range f) :=
by rw ← image_univ; exact compact_univ.image hf
/-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/
theorem is_closed_proj_of_compact
{X : Type*} [topological_space X] [compact_space X]
{Y : Type*} [topological_space Y] :
is_closed_map (prod.snd : X × Y → Y) :=
begin
set πX := (prod.fst : X × Y → X),
set πY := (prod.snd : X × Y → Y),
assume C (hC : is_closed C),
rw is_closed_iff_cluster_pt at hC ⊢,
assume y (y_closure : cluster_pt y $ 𝓟 (πY '' C)),
have : ne_bot (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)),
{ suffices : ne_bot (map πY (comap πY (𝓝 y) ⊓ 𝓟 C)),
by simpa only [map_ne_bot_iff],
calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) =
𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _
... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal
... ≠ ⊥ : y_closure },
resetI,
obtain ⟨x, hx⟩ : ∃ x, cluster_pt x (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)),
from cluster_point_of_compact _,
refine ⟨⟨x, y⟩, _, by simp [πY]⟩,
apply hC,
rw [cluster_pt, ← filter.map_ne_bot_iff πX],
calc map πX (𝓝 (x, y) ⊓ 𝓟 C)
= map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod]
... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl
... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull
... = 𝓝 x ⊓ map πX (comap πY (𝓝 y) ⊓ 𝓟 C) : by rw inf_comm
... ≠ ⊥ : hx,
end
lemma embedding.compact_iff_compact_image {f : α → β} (hf : embedding f) :
is_compact s ↔ is_compact (f '' s) :=
iff.intro (assume h, h.image hf.continuous) $ assume h, begin
rw compact_iff_ultrafilter_le_nhds at ⊢ h,
intros u hu us',
let u' : filter β := map f u,
have : u' ≤ 𝓟 (f '' s), begin
rw [map_le_iff_le_comap, comap_principal], convert us',
exact preimage_image_eq _ hf.inj
end,
rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩,
refine ⟨a, ha, _⟩,
rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap]
end
lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} :
is_compact s ↔ is_compact ((coe : _ → α) '' s) :=
embedding_subtype_coe.compact_iff_compact_image
lemma compact_iff_compact_univ {s : set α} : is_compact s ↔ is_compact (univ : set s) :=
by rw [compact_iff_compact_in_subtype, image_univ, subtype.range_coe]; refl
lemma compact_iff_compact_space {s : set α} : is_compact s ↔ compact_space s :=
compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩
lemma is_compact.prod {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) :
is_compact (set.prod s t) :=
begin
rw compact_iff_ultrafilter_le_nhds at hs ht ⊢,
intros f hf hfs,
rw le_principal_iff at hfs,
rcases hs (map prod.fst f) (ultrafilter_map hf)
(le_principal_iff.2 (mem_map_sets_iff.2
⟨_, hfs, image_subset_iff.2 (λ s h, h.1)⟩)) with ⟨a, sa, ha⟩,
rcases ht (map prod.snd f) (ultrafilter_map hf)
(le_principal_iff.2 (mem_map_sets_iff.2
⟨_, hfs, image_subset_iff.2 (λ s h, h.2)⟩)) with ⟨b, tb, hb⟩,
rw map_le_iff_le_comap at ha hb,
refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩,
rw nhds_prod_eq, exact le_inf ha hb
end
/-- Finite topological spaces are compact. -/
@[priority 100] instance fintype.compact_space [fintype α] : compact_space α :=
{ compact_univ := set.finite_univ.is_compact }
/-- The product of two compact spaces is compact. -/
instance [compact_space α] [compact_space β] : compact_space (α × β) :=
⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩
/-- The disjoint union of two compact spaces is compact. -/
instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) :=
⟨begin
rw ← range_inl_union_range_inr,
exact (compact_range continuous_inl).union (compact_range continuous_inr)
end⟩
section tychonoff
variables {ι : Type*} {π : ι → Type*} [∀i, topological_space (π i)]
/-- Tychonoff's theorem -/
lemma compact_pi_infinite {s : Πi:ι, set (π i)} :
(∀i, is_compact (s i)) → is_compact {x : Πi:ι, π i | ∀i, x i ∈ s i} :=
begin
simp only [compact_iff_ultrafilter_le_nhds, nhds_pi, exists_prop, mem_set_of_eq, le_infi_iff, le_principal_iff],
intros h f hf hfs,
have : ∀i:ι, ∃a, a∈s i ∧ tendsto (λx:Πi:ι, π i, x i) f (𝓝 a),
{ refine λ i, h i _ (ultrafilter_map hf) (mem_map.2 _),
exact mem_sets_of_superset hfs (λ x hx, hx i) },
choose a ha,
exact ⟨a, assume i, (ha i).left, assume i, (ha i).right.le_comap⟩
end
/-- A version of Tychonoff's theorem that uses `set.pi`. -/
lemma compact_univ_pi {s : Πi:ι, set (π i)} (h : ∀i, is_compact (s i)) :
is_compact (set.pi set.univ s) :=
by { convert compact_pi_infinite h, simp only [pi, forall_prop_of_true, mem_univ] }
instance pi.compact [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) :=
⟨begin
have A : is_compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} :=
compact_pi_infinite (λi, compact_univ),
have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp,
rwa this at A,
end⟩
end tychonoff
instance quot.compact_space {r : α → α → Prop} [compact_space α] :
compact_space (quot r) :=
⟨by { rw ← range_quot_mk, exact compact_range continuous_quot_mk }⟩
instance quotient.compact_space {s : setoid α} [compact_space α] :
compact_space (quotient s) :=
quot.compact_space
/-- There are various definitions of "locally compact space" in the literature, which agree for
Hausdorff spaces but not in general. This one is the precise condition on X needed for the
evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the
compact-open topology. -/
class locally_compact_space (α : Type*) [topological_space α] : Prop :=
(local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s)
/-- A reformulation of the definition of locally compact space: In a locally compact space,
every open set containing `x` has a compact subset containing `x` in its interior. -/
lemma exists_compact_subset [locally_compact_space α] {x : α} {U : set α}
(hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U :=
begin
rcases locally_compact_space.local_compact_nhds x U _ with ⟨K, h1K, h2K, h3K⟩,
{ refine ⟨K, h3K, _, h2K⟩, rwa [ mem_interior_iff_mem_nhds] },
rwa [← mem_interior_iff_mem_nhds, hU.interior_eq]
end
lemma is_ultrafilter.le_nhds_Lim [compact_space α] (F : ultrafilter α) :
F.1 ≤ nhds (@Lim _ _ F.1.nonempty_of_ne_bot F.1) :=
begin
rcases compact_iff_ultrafilter_le_nhds.mp compact_univ F.1 F.2 (by simp) with ⟨x, -, h⟩,
exact le_nhds_Lim ⟨x,h⟩,
end
end compact
section clopen
/-- A set is clopen if it is both open and closed. -/
def is_clopen (s : set α) : Prop :=
is_open s ∧ is_closed s
theorem is_clopen_union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) :=
⟨is_open_union hs.1 ht.1, is_closed_union hs.2 ht.2⟩
theorem is_clopen_inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) :=
⟨is_open_inter hs.1 ht.1, is_closed_inter hs.2 ht.2⟩
@[simp] theorem is_clopen_empty : is_clopen (∅ : set α) :=
⟨is_open_empty, is_closed_empty⟩
@[simp] theorem is_clopen_univ : is_clopen (univ : set α) :=
⟨is_open_univ, is_closed_univ⟩
theorem is_clopen_compl {s : set α} (hs : is_clopen s) : is_clopen sᶜ :=
⟨hs.2, is_closed_compl_iff.2 hs.1⟩
@[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen sᶜ ↔ is_clopen s :=
⟨λ h, compl_compl s ▸ is_clopen_compl h, is_clopen_compl⟩
theorem is_clopen_diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) :=
is_clopen_inter hs (is_clopen_compl ht)
end clopen
section preirreducible
/-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/
def is_preirreducible (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v →
(s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty
/-- An irreducible set `s` is one that is nonempty and
where there is no non-trivial pair of disjoint opens on `s`. -/
def is_irreducible (s : set α) : Prop :=
s.nonempty ∧ is_preirreducible s
lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) :
s.nonempty := h.1
lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) :
is_preirreducible s := h.2
theorem is_preirreducible_empty : is_preirreducible (∅ : set α) :=
λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim
theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) :=
⟨singleton_nonempty x,
λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3;
substs y z; exact ⟨x, rfl, h2, h4⟩⟩
theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) :
is_preirreducible (closure s) :=
λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩,
let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in
let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in
let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in
⟨r, subset_closure hrs, hruv⟩
lemma is_irreducible.closure {s : set α} (h : is_irreducible s) :
is_irreducible (closure s) :=
⟨h.nonempty.closure, h.is_preirreducible.closure⟩
theorem exists_preirreducible (s : set α) (H : is_preirreducible s) :
∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t :=
let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset₀ {t : set α | is_preirreducible t}
(λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in
⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩,
let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy,
⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in
or.cases_on (zorn.chain.total hcc hpc hqc)
(assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv
⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩)
(assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv
⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩),
λ x hxc, set.subset_sUnion_of_mem hxc⟩) s H in
⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩
/-- A maximal irreducible set that contains a given point. -/
def irreducible_component (x : α) : set α :=
classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible)
lemma irreducible_component_property (x : α) :
is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧
∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) :=
classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible)
theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x :=
singleton_subset_iff.1 (irreducible_component_property x).2.1
theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) :=
⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩
theorem eq_irreducible_component {x : α} :
∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x :=
(irreducible_component_property x).2.2
theorem is_closed_irreducible_component {x : α} :
is_closed (irreducible_component x) :=
closure_eq_iff_is_closed.1 $ eq_irreducible_component
is_irreducible_irreducible_component.is_preirreducible.closure
subset_closure
/-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/
class preirreducible_space (α : Type u) [topological_space α] : Prop :=
(is_preirreducible_univ [] : is_preirreducible (univ : set α))
/-- An irreducible space is one that is nonempty
and where there is no non-trivial pair of disjoint opens. -/
class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop :=
(to_nonempty [] : nonempty α)
attribute [instance, priority 50] irreducible_space.to_nonempty -- see Note [lower instance priority]
theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} :
is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty :=
by simpa only [univ_inter, univ_subset_iff] using
@preirreducible_space.is_preirreducible_univ α _ _ s t
theorem is_preirreducible.image [topological_space β] {s : set α} (H : is_preirreducible s)
(f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) :=
begin
rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩,
rw ← set.mem_preimage at hxu hyv,
rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩,
rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩,
have := H u' v' hu' hv',
rw [set.inter_comm s u', ← u'_eq] at this,
rw [set.inter_comm s v', ← v'_eq] at this,
rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩,
refine ⟨f z, mem_image_of_mem f hzs, _, _⟩,
all_goals
{ rw ← set.mem_preimage,
apply set.mem_of_mem_inter_left,
show z ∈ _ ∩ s,
simp [*] }
end
theorem is_irreducible.image [topological_space β] {s : set α} (H : is_irreducible s)
(f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) :=
⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩
lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) :
preirreducible_space s :=
{ is_preirreducible_univ :=
begin
intros u v hu hv hsu hsv,
rw is_open_induced_iff at hu hv,
rcases hu with ⟨u, hu, rfl⟩,
rcases hv with ⟨v, hv, rfl⟩,
rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩,
rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩,
rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩,
exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩
end }
lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) :
irreducible_space s :=
{ is_preirreducible_univ :=
(subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ,
to_nonempty := h.nonempty.to_subtype }
/-- A set `s` is irreducible if and only if
for every finite collection of open sets all of whose members intersect `s`,
`s` also intersects the intersection of the entire collection
(i.e., there is an element of `s` contained in every member of the collection). -/
lemma is_irreducible_iff_sInter {s : set α} :
is_irreducible s ↔
∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty),
(s ∩ ⋂₀ ↑U).nonempty :=
begin
split; intro h,
{ intro U, apply finset.induction_on U,
{ intros, simpa using h.nonempty },
{ intros u U hu IH hU H,
rw [finset.coe_insert, sInter_insert],
apply h.2,
{ solve_by_elim [finset.mem_insert_self] },
{ apply is_open_sInter (finset.finite_to_set U),
intros, solve_by_elim [finset.mem_insert_of_mem] },
{ solve_by_elim [finset.mem_insert_self] },
{ apply IH,
all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } },
{ split,
{ simpa using h ∅ _ _; intro u; simp },
intros u v hu hv hu' hv',
simpa using h {u,v} _ _,
all_goals
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption } }
end
/-- A set is preirreducible if and only if
for every cover by two closed sets, it is contained in one of the two covering sets. -/
lemma is_preirreducible_iff_closed_union_closed {s : set α} :
is_preirreducible s ↔
∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ :=
begin
split,
all_goals
{ intros h t₁ t₂ ht₁ ht₂,
specialize h t₁ᶜ t₂ᶜ,
simp only [is_open_compl_iff, is_closed_compl_iff] at h,
specialize h ht₁ ht₂ },
{ contrapose!, simp only [not_subset],
rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩,
rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩,
rw ← compl_union at hz',
exact ⟨z, hz, hz'⟩ },
{ rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩,
rw ← compl_inter at h,
delta set.nonempty,
rw imp_iff_not_or at h,
contrapose! h,
split,
{ intros z hz hz', exact h z ⟨hz, hz'⟩ },
{ split; intro H; refine H _ ‹_›; assumption } }
end
/-- A set is irreducible if and only if
for every cover by a finite collection of closed sets,
it is contained in one of the members of the collection. -/
lemma is_irreducible_iff_sUnion_closed {s : set α} :
is_irreducible s ↔
∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z),
∃ z ∈ Z, s ⊆ z :=
begin
rw [is_irreducible, is_preirreducible_iff_closed_union_closed],
split; intro h,
{ intro Z, apply finset.induction_on Z,
{ intros, rw [finset.coe_empty, sUnion_empty] at H,
rcases h.1 with ⟨x, hx⟩,
exfalso, tauto },
{ intros z Z hz IH hZ H,
cases h.2 z (⋃₀ ↑Z) _ _ _
with h' h',
{ exact ⟨z, finset.mem_insert_self _ _, h'⟩ },
{ rcases IH _ h' with ⟨z', hz', hsz'⟩,
{ exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ },
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ solve_by_elim [finset.mem_insert_self] },
{ rw sUnion_eq_bUnion,
apply is_closed_bUnion (finset.finite_to_set Z),
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ simpa using H } } },
{ split,
{ by_contradiction hs,
simpa using h ∅ _ _,
{ intro z, simp },
{ simpa [set.nonempty] using hs } },
intros z₁ z₂ hz₁ hz₂ H,
have := h {z₁, z₂} _ _,
simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this,
{ rcases this with ⟨z, rfl|rfl, hz⟩; tauto },
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption },
{ simpa using H } }
end
end preirreducible
section preconnected
/-- A preconnected set is one where there is no non-trivial open partition. -/
def is_preconnected (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v →
(s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty
/-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/
def is_connected (s : set α) : Prop :=
s.nonempty ∧ is_preconnected s
lemma is_connected.nonempty {s : set α} (h : is_connected s) :
s.nonempty := h.1
lemma is_connected.is_preconnected {s : set α} (h : is_connected s) :
is_preconnected s := h.2
theorem is_preirreducible.is_preconnected {s : set α} (H : is_preirreducible s) :
is_preconnected s :=
λ _ _ hu hv _, H _ _ hu hv
theorem is_irreducible.is_connected {s : set α} (H : is_irreducible s) : is_connected s :=
⟨H.nonempty, H.is_preirreducible.is_preconnected⟩
theorem is_preconnected_empty : is_preconnected (∅ : set α) :=
is_preirreducible_empty.is_preconnected
theorem is_connected_singleton {x} : is_connected ({x} : set α) :=
is_irreducible_singleton.is_connected
/-- If any point of a set is joined to a fixed point by a preconnected subset,
then the original set is preconnected as well. -/
theorem is_preconnected_of_forall {s : set α} (x : α)
(H : ∀ y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) :
is_preconnected s :=
begin
rintros u v hu hv hs ⟨z, zs, zu⟩ ⟨y, ys, yv⟩,
have xs : x ∈ s, by { rcases H y ys with ⟨t, ts, xt, yt, ht⟩, exact ts xt },
wlog xu : x ∈ u := hs xs using [u v y z, v u z y],
rcases H y ys with ⟨t, ts, xt, yt, ht⟩,
have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩,
exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩)
end
/-- If any two points of a set are contained in a preconnected subset,
then the original set is preconnected as well. -/
theorem is_preconnected_of_forall_pair {s : set α}
(H : ∀ x y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) :
is_preconnected s :=
begin
rintros u v hu hv hs ⟨x, xs, xu⟩ ⟨y, ys, yv⟩,
rcases H x y xs ys with ⟨t, ts, xt, yt, ht⟩,
have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩,
exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩)
end
/-- A union of a family of preconnected sets with a common point is preconnected as well. -/
theorem is_preconnected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s)
(H2 : ∀ s ∈ c, is_preconnected s) : is_preconnected (⋃₀ c) :=
begin
apply is_preconnected_of_forall x,
rintros y ⟨s, sc, ys⟩,
exact ⟨s, subset_sUnion_of_mem sc, H1 s sc, ys, H2 s sc⟩
end
theorem is_preconnected.union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t)
(H3 : is_preconnected s) (H4 : is_preconnected t) : is_preconnected (s ∪ t) :=
sUnion_pair s t ▸ is_preconnected_sUnion x {s, t}
(by rintro r (rfl | rfl | h); assumption)
(by rintro r (rfl | rfl | h); assumption)
theorem is_connected.union {s t : set α} (H : (s ∩ t).nonempty)
(Hs : is_connected s) (Ht : is_connected t) : is_connected (s ∪ t) :=
begin
rcases H with ⟨x, hx⟩,
refine ⟨⟨x, mem_union_left t (mem_of_mem_inter_left hx)⟩, _⟩,
exact is_preconnected.union x (mem_of_mem_inter_left hx) (mem_of_mem_inter_right hx)
Hs.is_preconnected Ht.is_preconnected
end
theorem is_preconnected.closure {s : set α} (H : is_preconnected s) :
is_preconnected (closure s) :=
λ u v hu hv hcsuv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩,
let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in
let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in
let ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans subset_closure hcsuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in
⟨r, subset_closure hrs, hruv⟩
theorem is_connected.closure {s : set α} (H : is_connected s) :
is_connected (closure s) :=
⟨H.nonempty.closure, H.is_preconnected.closure⟩
theorem is_preconnected.image [topological_space β] {s : set α} (H : is_preconnected s)
(f : α → β) (hf : continuous_on f s) : is_preconnected (f '' s) :=
begin
-- Unfold/destruct definitions in hypotheses
rintros u v hu hv huv ⟨_, ⟨x, xs, rfl⟩, xu⟩ ⟨_, ⟨y, ys, rfl⟩, yv⟩,
rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩,
rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩,
-- Reformulate `huv : f '' s ⊆ u ∪ v` in terms of `u'` and `v'`
replace huv : s ⊆ u' ∪ v',
{ rw [image_subset_iff, preimage_union] at huv,
replace huv := subset_inter huv (subset.refl _),
rw [inter_distrib_right, u'_eq, v'_eq, ← inter_distrib_right] at huv,
exact (subset_inter_iff.1 huv).1 },
-- Now `s ⊆ u' ∪ v'`, so we can apply `‹is_preconnected s›`
obtain ⟨z, hz⟩ : (s ∩ (u' ∩ v')).nonempty,
{ refine H u' v' hu' hv' huv ⟨x, _⟩ ⟨y, _⟩; rw inter_comm,
exacts [u'_eq ▸ ⟨xu, xs⟩, v'_eq ▸ ⟨yv, ys⟩] },
rw [← inter_self s, inter_assoc, inter_left_comm s u', ← inter_assoc,
inter_comm s, inter_comm s, ← u'_eq, ← v'_eq] at hz,
exact ⟨f z, ⟨z, hz.1.2, rfl⟩, hz.1.1, hz.2.1⟩
end
theorem is_connected.image [topological_space β] {s : set α} (H : is_connected s)
(f : α → β) (hf : continuous_on f s) : is_connected (f '' s) :=
⟨nonempty_image_iff.mpr H.nonempty, H.is_preconnected.image f hf⟩
theorem is_preconnected_closed_iff {s : set α} :
is_preconnected s ↔ ∀ t t', is_closed t → is_closed t' → s ⊆ t ∪ t' →
(s ∩ t).nonempty → (s ∩ t').nonempty → (s ∩ (t ∩ t')).nonempty :=
⟨begin
rintros h t t' ht ht' htt' ⟨x, xs, xt⟩ ⟨y, ys, yt'⟩,
by_contradiction h',
rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h',
have xt' : x ∉ t', from (h' xs).elim (absurd xt) id,
have yt : y ∉ t, from (h' ys).elim id (absurd yt'),
have := ne_empty_iff_nonempty.2 (h tᶜ t'ᶜ (is_open_compl_iff.2 ht)
(is_open_compl_iff.2 ht') h' ⟨y, ys, yt⟩ ⟨x, xs, xt'⟩),
rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this,
contradiction
end,
begin
rintros h u v hu hv huv ⟨x, xs, xu⟩ ⟨y, ys, yv⟩,
by_contradiction h',
rw [← ne_empty_iff_nonempty, ne.def, not_not,
← subset_compl_iff_disjoint, compl_inter] at h',
have xv : x ∉ v, from (h' xs).elim (absurd xu) id,
have yu : y ∉ u, from (h' ys).elim id (absurd yv),
have := ne_empty_iff_nonempty.2 (h uᶜ vᶜ (is_closed_compl_iff.2 hu)
(is_closed_compl_iff.2 hv) h' ⟨y, ys, yu⟩ ⟨x, xs, xv⟩),
rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this,
contradiction
end⟩
/-- The connected component of a point is the maximal connected set
that contains this point. -/
def connected_component (x : α) : set α :=
⋃₀ { s : set α | is_preconnected s ∧ x ∈ s }
/-- The connected component of a point inside a set. -/
def connected_component_in (F : set α) (x : F) : set α := coe '' (connected_component x)
theorem mem_connected_component {x : α} : x ∈ connected_component x :=
mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton.is_preconnected, mem_singleton x⟩
theorem is_connected_connected_component {x : α} : is_connected (connected_component x) :=
⟨⟨x, mem_connected_component⟩, is_preconnected_sUnion x _ (λ _, and.right) (λ _, and.left)⟩
theorem subset_connected_component {x : α} {s : set α} (H1 : is_preconnected s) (H2 : x ∈ s) :
s ⊆ connected_component x :=
λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩
theorem is_closed_connected_component {x : α} :
is_closed (connected_component x) :=
closure_eq_iff_is_closed.1 $ subset.antisymm
(subset_connected_component
is_connected_connected_component.closure.is_preconnected
(subset_closure mem_connected_component))
subset_closure
theorem irreducible_component_subset_connected_component {x : α} :
irreducible_component x ⊆ connected_component x :=
subset_connected_component
is_irreducible_irreducible_component.is_connected.is_preconnected
mem_irreducible_component
/-- A preconnected space is one where there is no non-trivial open partition. -/
class preconnected_space (α : Type u) [topological_space α] : Prop :=
(is_preconnected_univ : is_preconnected (univ : set α))
export preconnected_space (is_preconnected_univ)
/-- A connected space is a nonempty one where there is no non-trivial open partition. -/
class connected_space (α : Type u) [topological_space α] extends preconnected_space α : Prop :=
(to_nonempty : nonempty α)
attribute [instance, priority 50] connected_space.to_nonempty -- see Note [lower instance priority]
lemma is_connected_range [topological_space β] [connected_space α] {f : α → β} (h : continuous f) :
is_connected (range f) :=
begin
inhabit α,
rw ← image_univ,
exact ⟨⟨f (default α), mem_image_of_mem _ (mem_univ _)⟩,
is_preconnected.image is_preconnected_univ _ h.continuous_on⟩
end
lemma connected_space_iff_connected_component :
connected_space α ↔ ∃ x : α, connected_component x = univ :=
begin
split,
{ rintros ⟨h, ⟨x⟩⟩,
exactI ⟨x, eq_univ_of_univ_subset $ subset_connected_component is_preconnected_univ (mem_univ x)⟩ },
{ rintros ⟨x, h⟩,
haveI : preconnected_space α := ⟨by {rw ← h, exact is_connected_connected_component.2 }⟩,
exact ⟨⟨x⟩⟩ }
end
@[priority 100] -- see Note [lower instance priority]
instance preirreducible_space.preconnected_space (α : Type u) [topological_space α]
[preirreducible_space α] : preconnected_space α :=
⟨(preirreducible_space.is_preirreducible_univ α).is_preconnected⟩
@[priority 100] -- see Note [lower instance priority]
instance irreducible_space.connected_space (α : Type u) [topological_space α]
[irreducible_space α] : connected_space α :=
{ to_nonempty := irreducible_space.to_nonempty α }
theorem nonempty_inter [preconnected_space α] {s t : set α} :
is_open s → is_open t → s ∪ t = univ → s.nonempty → t.nonempty → (s ∩ t).nonempty :=
by simpa only [univ_inter, univ_subset_iff] using
@preconnected_space.is_preconnected_univ α _ _ s t
theorem is_clopen_iff [preconnected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ :=
⟨λ hs, classical.by_contradiction $ λ h,
have h1 : s ≠ ∅ ∧ sᶜ ≠ ∅, from ⟨mt or.inl h,
mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩,
let ⟨_, h2, h3⟩ := nonempty_inter hs.1 hs.2 (union_compl_self s)
(ne_empty_iff_nonempty.1 h1.1) (ne_empty_iff_nonempty.1 h1.2) in
h3 h2,
by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩
lemma eq_univ_of_nonempty_clopen [preconnected_space α] {s : set α}
(h : s.nonempty) (h' : is_clopen s) : s = univ :=
by { rw is_clopen_iff at h', finish [h.ne_empty] }
lemma subtype.preconnected_space {s : set α} (h : is_preconnected s) :
preconnected_space s :=
{ is_preconnected_univ :=
begin
intros u v hu hv hs hsu hsv,
rw is_open_induced_iff at hu hv,
rcases hu with ⟨u, hu, rfl⟩,
rcases hv with ⟨v, hv, rfl⟩,
rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩,
rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩,
rcases h u v hu hv _ ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩,
exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩,
intros z hz,
rcases hs (set.mem_univ ⟨z, hz⟩) with hzu|hzv,
{ left, assumption },
{ right, assumption }
end }
lemma subtype.connected_space {s : set α} (h : is_connected s) :
connected_space s :=
{ is_preconnected_univ :=
(subtype.preconnected_space h.is_preconnected).is_preconnected_univ,
to_nonempty := h.nonempty.to_subtype }
lemma is_preconnected_iff_preconnected_space {s : set α} :
is_preconnected s ↔ preconnected_space s :=
⟨subtype.preconnected_space,
begin
introI,
simpa using is_preconnected_univ.image (coe : s → α) continuous_subtype_coe.continuous_on
end⟩
lemma is_connected_iff_connected_space {s : set α} : is_connected s ↔ connected_space s :=
⟨subtype.connected_space,
λ h, ⟨nonempty_subtype.mp h.2, is_preconnected_iff_preconnected_space.mpr h.1⟩⟩
/-- A set `s` is preconnected if and only if
for every cover by two open sets that are disjoint on `s`,
it is contained in one of the two covering sets. -/
lemma is_preconnected_iff_subset_of_disjoint {s : set α} :
is_preconnected s ↔
∀ (u v : set α) (hu : is_open u) (hv : is_open v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅),
s ⊆ u ∨ s ⊆ v :=
begin
split; intro h,
{ intros u v hu hv hs huv,
specialize h u v hu hv hs,
contrapose! huv,
rw ne_empty_iff_nonempty,
simp [not_subset] at huv,
rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩,
have hxv : x ∈ v := or_iff_not_imp_left.mp (hs hxs) hxu,
have hyu : y ∈ u := or_iff_not_imp_right.mp (hs hys) hyv,
exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ },
{ intros u v hu hv hs hsu hsv,
rw ← ne_empty_iff_nonempty,
intro H,
specialize h u v hu hv hs H,
contrapose H,
apply ne_empty_iff_nonempty.mpr,
cases h,
{ rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ },
{ rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } }
end
/-- A set `s` is connected if and only if
for every cover by a finite collection of open sets that are pairwise disjoint on `s`,
it is contained in one of the members of the collection. -/
lemma is_connected_iff_sUnion_disjoint_open {s : set α} :
is_connected s ↔
∀ (U : finset (set α)) (H : ∀ (u v : set α), u ∈ U → v ∈ U → (s ∩ (u ∩ v)).nonempty → u = v)
(hU : ∀ u ∈ U, is_open u) (hs : s ⊆ ⋃₀ ↑U),
∃ u ∈ U, s ⊆ u :=
begin
rw [is_connected, is_preconnected_iff_subset_of_disjoint],
split; intro h,
{ intro U, apply finset.induction_on U,
{ rcases h.left,
suffices : s ⊆ ∅ → false, { simpa },
intro, solve_by_elim },
{ intros u U hu IH hs hU H,
rw [finset.coe_insert, sUnion_insert] at H,
cases h.2 u (⋃₀ ↑U) _ _ H _ with hsu hsU,
{ exact ⟨u, finset.mem_insert_self _ _, hsu⟩ },
{ rcases IH _ _ hsU with ⟨v, hvU, hsv⟩,
{ exact ⟨v, finset.mem_insert_of_mem hvU, hsv⟩ },
{ intros, apply hs; solve_by_elim [finset.mem_insert_of_mem] },
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ solve_by_elim [finset.mem_insert_self] },
{ apply is_open_sUnion,
intros, solve_by_elim [finset.mem_insert_of_mem] },
{ apply eq_empty_of_subset_empty,
rintro x ⟨hxs, hxu, hxU⟩,
rw mem_sUnion at hxU,
rcases hxU with ⟨v, hvU, hxv⟩,
rcases hs u v (finset.mem_insert_self _ _) (finset.mem_insert_of_mem hvU) _ with rfl,
{ contradiction },
{ exact ⟨x, hxs, hxu, hxv⟩ } } } },
{ split,
{ rw ← ne_empty_iff_nonempty,
by_contradiction hs, push_neg at hs, subst hs,
simpa using h ∅ _ _ _; simp },
intros u v hu hv hs hsuv,
rcases h {u, v} _ _ _ with ⟨t, ht, ht'⟩,
{ rw [finset.mem_insert, finset.mem_singleton] at ht,
rcases ht with rfl|rfl; tauto },
{ intros t₁ t₂ ht₁ ht₂ hst,
rw ← ne_empty_iff_nonempty at hst,
rw [finset.mem_insert, finset.mem_singleton] at ht₁ ht₂,
rcases ht₁ with rfl|rfl; rcases ht₂ with rfl|rfl,
all_goals { refl <|> contradiction <|> skip },
rw inter_comm t₁ at hst, contradiction },
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption },
{ simpa using hs } }
end
end preconnected
section totally_disconnected
/-- A set is called totally disconnected if all of its connected components are singletons. -/
def is_totally_disconnected (s : set α) : Prop :=
∀ t, t ⊆ s → is_preconnected t → subsingleton t
theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) :=
λ t ht _, ⟨λ ⟨_, h⟩, (ht h).elim⟩
theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) :=
λ t ht _, ⟨λ ⟨p, hp⟩ ⟨q, hq⟩, subtype.eq $ show p = q,
from (eq_of_mem_singleton (ht hp)).symm ▸ (eq_of_mem_singleton (ht hq)).symm⟩
/-- A space is totally disconnected if all of its connected components are singletons. -/
class totally_disconnected_space (α : Type u) [topological_space α] : Prop :=
(is_totally_disconnected_univ : is_totally_disconnected (univ : set α))
end totally_disconnected
section totally_separated
/-- A set `s` is called totally separated if any two points of this set can be separated
by two disjoint open sets covering `s`. -/
def is_totally_separated (s : set α) : Prop :=
∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧
x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅
theorem is_totally_separated_empty : is_totally_separated (∅ : set α) :=
λ x, false.elim
theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) :=
λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim
theorem is_totally_disconnected_of_is_totally_separated {s : set α}
(H : is_totally_separated s) : is_totally_disconnected s :=
λ t hts ht, ⟨λ ⟨x, hxt⟩ ⟨y, hyt⟩, subtype.eq $ classical.by_contradiction $
assume hxy : x ≠ y, let ⟨u, v, hu, hv, hxu, hyv, hsuv, huv⟩ := H x (hts hxt) y (hts hyt) hxy in
let ⟨r, hrt, hruv⟩ := ht u v hu hv (subset.trans hts hsuv) ⟨x, hxt, hxu⟩ ⟨y, hyt, hyv⟩ in
(ext_iff.1 huv r).1 hruv⟩
/-- A space is totally separated if any two points can be separated by two disjoint open sets
covering the whole space. -/
class totally_separated_space (α : Type u) [topological_space α] : Prop :=
(is_totally_separated_univ [] : is_totally_separated (univ : set α))
@[priority 100] -- see Note [lower instance priority]
instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α]
[totally_separated_space α] : totally_disconnected_space α :=
⟨is_totally_disconnected_of_is_totally_separated $ totally_separated_space.is_totally_separated_univ α⟩
end totally_separated
|
4b4136c9d5c61e32c0313f72473a0a3cab2290cf | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Compiler/IR/Boxing.lean | 31e9c9e15adb3e237a11b3f2e2a7ffd04e013102 | [
"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 | 13,275 | 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.Runtime
import Lean.Compiler.ClosedTermCache
import Lean.Compiler.ExternAttr
import Lean.Compiler.IR.Basic
import Lean.Compiler.IR.CompilerM
import Lean.Compiler.IR.FreeVars
import Lean.Compiler.IR.ElimDeadVars
namespace Lean.IR.ExplicitBoxing
/-
Add explicit boxing and unboxing instructions.
Recall that the Lean to λ_pure compiler produces code without these instructions.
Assumptions:
- This transformation is applied before explicit RC instructions (`inc`, `dec`) are inserted.
- This transformation is applied before `FnBody.case` has been simplified and `Alt.default` is used.
Reason: if there is no `Alt.default` branch, then we can decide whether `x` at `FnBody.case x alts` is an
enumeration type by simply inspecting the `CtorInfo` values at `alts`.
- This transformation is applied before lower level optimizations are applied which use
`Expr.isShared`, `Expr.isTaggedPtr`, and `FnBody.set`.
- This transformation is applied after `reset` and `reuse` instructions have been added.
Reason: `resetreuse.lean` ignores `box` and `unbox` instructions.
-/
open Std (AssocList)
def mkBoxedName (n : Name) : Name :=
Name.mkStr n "_boxed"
def isBoxedName : Name → Bool
| Name.str _ "_boxed" _ => true
| _ => false
abbrev N := StateM Nat
private def N.mkFresh : N VarId :=
modifyGet fun n => ({ idx := n }, n + 1)
def requiresBoxedVersion (env : Environment) (decl : Decl) : Bool :=
let ps := decl.params
(ps.size > 0 && (decl.resultType.isScalar || ps.any (fun p => p.ty.isScalar || p.borrow) || isExtern env decl.name))
|| ps.size > closureMaxArgs
def mkBoxedVersionAux (decl : Decl) : N Decl := do
let ps := decl.params
let qs ← ps.mapM fun _ => do let x ← N.mkFresh; pure { x := x, ty := IRType.object, borrow := false : Param }
let (newVDecls, xs) ← qs.size.foldM (init := (#[], #[])) fun i (newVDecls, xs) => do
let p := ps[i]
let q := qs[i]
if !p.ty.isScalar then
pure (newVDecls, xs.push (Arg.var q.x))
else
let x ← N.mkFresh
pure (newVDecls.push (FnBody.vdecl x p.ty (Expr.unbox q.x) arbitrary), xs.push (Arg.var x))
let r ← N.mkFresh
let newVDecls := newVDecls.push (FnBody.vdecl r decl.resultType (Expr.fap decl.name xs) arbitrary)
let body ←
if !decl.resultType.isScalar then
pure <| reshape newVDecls (FnBody.ret (Arg.var r))
else
let newR ← N.mkFresh
let newVDecls := newVDecls.push (FnBody.vdecl newR IRType.object (Expr.box decl.resultType r) arbitrary)
pure <| reshape newVDecls (FnBody.ret (Arg.var newR))
return Decl.fdecl (mkBoxedName decl.name) qs IRType.object body decl.getInfo
def mkBoxedVersion (decl : Decl) : Decl :=
(mkBoxedVersionAux decl).run' 1
def addBoxedVersions (env : Environment) (decls : Array Decl) : Array Decl :=
let boxedDecls := decls.foldl (init := #[]) fun newDecls decl =>
if requiresBoxedVersion env decl then newDecls.push (mkBoxedVersion decl) else newDecls
decls ++ boxedDecls
/- Infer scrutinee type using `case` alternatives.
This can be done whenever `alts` does not contain an `Alt.default _` value. -/
def getScrutineeType (alts : Array Alt) : IRType :=
let isScalar :=
alts.size > 1 && -- Recall that we encode Unit and PUnit using `object`.
alts.all fun
| Alt.ctor c _ => c.isScalar
| Alt.default _ => false
match isScalar with
| false => IRType.object
| true =>
let n := alts.size
if n < 256 then IRType.uint8
else if n < 65536 then IRType.uint16
else if n < 4294967296 then IRType.uint32
else IRType.object -- in practice this should be unreachable
def eqvTypes (t₁ t₂ : IRType) : Bool :=
(t₁.isScalar == t₂.isScalar) && (!t₁.isScalar || t₁ == t₂)
structure BoxingContext where
f : FunId := arbitrary
localCtx : LocalContext := {}
resultType : IRType := IRType.irrelevant
decls : Array Decl
env : Environment
structure BoxingState where
nextIdx : Index
/- We create auxiliary declarations when boxing constant and literals.
The idea is to avoid code such as
```
let x1 := Uint64.inhabited;
let x2 := box x1;
...
```
We currently do not cache these declarations in an environment extension, but
we use auxDeclCache to avoid creating equivalent auxiliary declarations more than once when
processing the same IR declaration.
-/
auxDecls : Array Decl := #[]
auxDeclCache : AssocList FnBody Expr := Std.AssocList.empty
nextAuxId : Nat := 1
abbrev M := ReaderT BoxingContext (StateT BoxingState Id)
private def M.mkFresh : M VarId := do
let oldS ← getModify fun s => { s with nextIdx := s.nextIdx + 1 }
pure { idx := oldS.nextIdx }
def getEnv : M Environment := BoxingContext.env <$> read
def getLocalContext : M LocalContext := BoxingContext.localCtx <$> read
def getResultType : M IRType := BoxingContext.resultType <$> read
def getVarType (x : VarId) : M IRType := do
let localCtx ← getLocalContext
match localCtx.getType x with
| some t => pure t
| none => pure IRType.object -- unreachable, we assume the code is well formed
def getJPParams (j : JoinPointId) : M (Array Param) := do
let localCtx ← getLocalContext
match localCtx.getJPParams j with
| some ys => pure ys
| none => pure #[] -- unreachable, we assume the code is well formed
def getDecl (fid : FunId) : M Decl := do
let ctx ← read
match findEnvDecl' ctx.env fid ctx.decls with
| some decl => pure decl
| none => pure arbitrary -- unreachable if well-formed
@[inline] def withParams {α : Type} (xs : Array Param) (k : M α) : M α :=
withReader (fun ctx => { ctx with localCtx := ctx.localCtx.addParams xs }) k
@[inline] def withVDecl {α : Type} (x : VarId) (ty : IRType) (v : Expr) (k : M α) : M α :=
withReader (fun ctx => { ctx with localCtx := ctx.localCtx.addLocal x ty v }) k
@[inline] def withJDecl {α : Type} (j : JoinPointId) (xs : Array Param) (v : FnBody) (k : M α) : M α :=
withReader (fun ctx => { ctx with localCtx := ctx.localCtx.addJP j xs v }) k
/- If `x` declaration is of the form `x := Expr.lit _` or `x := Expr.fap c #[]`,
and `x`'s type is not cheap to box (e.g., it is `UInt64), then return its value. -/
private def isExpensiveConstantValueBoxing (x : VarId) (xType : IRType) : M (Option Expr) :=
if !xType.isScalar then
pure none -- We assume unboxing is always cheap
else match xType with
| IRType.uint8 => pure none
| IRType.uint16 => pure none
| _ => do
let localCtx ← getLocalContext
match localCtx.getValue x with
| some val =>
match val with
| Expr.lit _ => pure $ some val
| Expr.fap _ args => pure $ if args.size == 0 then some val else none
| _ => pure none
| _ => pure none
/- Auxiliary function used by castVarIfNeeded.
It is used when the expected type does not match `xType`.
If `xType` is scalar, then we need to "box" it. Otherwise, we need to "unbox" it. -/
def mkCast (x : VarId) (xType : IRType) (expectedType : IRType) : M Expr := do
match (← isExpensiveConstantValueBoxing x xType) with
| some v => do
let ctx ← read
let s ← get
/- Create auxiliary FnBody
```
let x_1 : xType := v;
let x_2 : expectedType := Expr.box xType x_1;
ret x_2
```
-/
let body : FnBody :=
FnBody.vdecl { idx := 1 } xType v $
FnBody.vdecl { idx := 2 } expectedType (Expr.box xType { idx := 1 }) $
FnBody.ret (mkVarArg { idx := 2 })
match s.auxDeclCache.find? body with
| some v => pure v
| none => do
let auxName := ctx.f ++ ((`_boxed_const).appendIndexAfter s.nextAuxId)
let auxConst := Expr.fap auxName #[]
let auxDecl := Decl.fdecl auxName #[] expectedType body {}
modify fun s => { s with
auxDecls := s.auxDecls.push auxDecl
auxDeclCache := s.auxDeclCache.cons body auxConst
nextAuxId := s.nextAuxId + 1
}
pure auxConst
| none => pure $ if xType.isScalar then Expr.box xType x else Expr.unbox x
@[inline] def castVarIfNeeded (x : VarId) (expected : IRType) (k : VarId → M FnBody) : M FnBody := do
let xType ← getVarType x
if eqvTypes xType expected then
k x
else
let y ← M.mkFresh
let v ← mkCast x xType expected
FnBody.vdecl y expected v <$> k y
@[inline] def castArgIfNeeded (x : Arg) (expected : IRType) (k : Arg → M FnBody) : M FnBody :=
match x with
| Arg.var x => castVarIfNeeded x expected (fun x => k (Arg.var x))
| _ => k x
@[specialize] def castArgsIfNeededAux (xs : Array Arg) (typeFromIdx : Nat → IRType) : M (Array Arg × Array FnBody) := do
let mut xs' := #[]
let mut bs := #[]
let mut i := 0
for x in xs do
let expected := typeFromIdx i
match x with
| Arg.irrelevant =>
xs' := xs'.push x
| Arg.var x =>
let xType ← getVarType x
if eqvTypes xType expected then
xs' := xs'.push (Arg.var x)
else
let y ← M.mkFresh
let v ← mkCast x xType expected
let b := FnBody.vdecl y expected v FnBody.nil
xs' := xs'.push (Arg.var y)
bs := bs.push b
i := i + 1
return (xs', bs)
@[inline] def castArgsIfNeeded (xs : Array Arg) (ps : Array Param) (k : Array Arg → M FnBody) : M FnBody := do
let (ys, bs) ← castArgsIfNeededAux xs fun i => ps[i].ty
let b ← k ys
pure (reshape bs b)
@[inline] def boxArgsIfNeeded (xs : Array Arg) (k : Array Arg → M FnBody) : M FnBody := do
let (ys, bs) ← castArgsIfNeededAux xs (fun _ => IRType.object)
let b ← k ys
pure (reshape bs b)
def unboxResultIfNeeded (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : M FnBody := do
if ty.isScalar then
let y ← M.mkFresh
pure $ FnBody.vdecl y IRType.object e (FnBody.vdecl x ty (Expr.unbox y) b)
else
pure $ FnBody.vdecl x ty e b
def castResultIfNeeded (x : VarId) (ty : IRType) (e : Expr) (eType : IRType) (b : FnBody) : M FnBody := do
if eqvTypes ty eType then
pure $ FnBody.vdecl x ty e b
else
let y ← M.mkFresh
let v ← mkCast y eType ty
pure $ FnBody.vdecl y eType e (FnBody.vdecl x ty v b)
def visitVDeclExpr (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : M FnBody :=
match e with
| Expr.ctor c ys =>
if c.isScalar && ty.isScalar then
pure $ FnBody.vdecl x ty (Expr.lit (LitVal.num c.cidx)) b
else
boxArgsIfNeeded ys fun ys => pure $ FnBody.vdecl x ty (Expr.ctor c ys) b
| Expr.reuse w c u ys =>
boxArgsIfNeeded ys fun ys => pure $ FnBody.vdecl x ty (Expr.reuse w c u ys) b
| Expr.fap f ys => do
let decl ← getDecl f
castArgsIfNeeded ys decl.params fun ys =>
castResultIfNeeded x ty (Expr.fap f ys) decl.resultType b
| Expr.pap f ys => do
let env ← getEnv
let decl ← getDecl f
let f := if requiresBoxedVersion env decl then mkBoxedName f else f
boxArgsIfNeeded ys fun ys => pure $ FnBody.vdecl x ty (Expr.pap f ys) b
| Expr.ap f ys =>
boxArgsIfNeeded ys fun ys =>
unboxResultIfNeeded x ty (Expr.ap f ys) b
| other =>
pure $ FnBody.vdecl x ty e b
partial def visitFnBody : FnBody → M FnBody
| FnBody.vdecl x t v b => do
let b ← withVDecl x t v (visitFnBody b)
visitVDeclExpr x t v b
| FnBody.jdecl j xs v b => do
let v ← withParams xs (visitFnBody v)
let b ← withJDecl j xs v (visitFnBody b)
pure $ FnBody.jdecl j xs v b
| FnBody.uset x i y b => do
let b ← visitFnBody b
castVarIfNeeded y IRType.usize fun y =>
pure $ FnBody.uset x i y b
| FnBody.sset x i o y ty b => do
let b ← visitFnBody b
castVarIfNeeded y ty fun y =>
pure $ FnBody.sset x i o y ty b
| FnBody.mdata d b =>
FnBody.mdata d <$> visitFnBody b
| FnBody.case tid x _ alts => do
let expected := getScrutineeType alts
let alts ← alts.mapM fun alt => alt.mmodifyBody visitFnBody
castVarIfNeeded x expected fun x => do
pure $ FnBody.case tid x expected alts
| FnBody.ret x => do
let expected ← getResultType
castArgIfNeeded x expected (fun x => pure $ FnBody.ret x)
| FnBody.jmp j ys => do
let ps ← getJPParams j
castArgsIfNeeded ys ps fun ys => pure $ FnBody.jmp j ys
| other =>
pure other
def run (env : Environment) (decls : Array Decl) : Array Decl :=
let ctx : BoxingContext := { decls := decls, env := env }
let decls := decls.foldl (init := #[]) fun newDecls decl =>
match decl with
| Decl.fdecl (f := f) (xs := xs) (type := t) (body := b) .. =>
let nextIdx := decl.maxIndex + 1
let (b, s) := (withParams xs (visitFnBody b) { ctx with f := f, resultType := t }).run { nextIdx := nextIdx }
let newDecls := newDecls ++ s.auxDecls
let newDecl := decl.updateBody! b
let newDecl := newDecl.elimDead
newDecls.push newDecl
| d => newDecls.push d
addBoxedVersions env decls
end ExplicitBoxing
def explicitBoxing (decls : Array Decl) : CompilerM (Array Decl) := do
let env ← getEnv
pure $ ExplicitBoxing.run env decls
end Lean.IR
|
8aaac4f1fd873494ef380ca9659d4f3cb5338b37 | 5e3548e65f2c037cb94cd5524c90c623fbd6d46a | /src_icannos_totilas/topologie-espaces-normés/cpge_ten_02c.lean | c6eb447e4cac0999ba55526f8b27ff21af198e54 | [] | no_license | ahayat16/lean_exos | d4f08c30adb601a06511a71b5ffb4d22d12ef77f | 682f2552d5b04a8c8eb9e4ab15f875a91b03845c | refs/heads/main | 1,693,101,073,585 | 1,636,479,336,000 | 1,636,479,336,000 | 415,000,441 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 676 | lean | import data.set.basic
import topology.basic
import algebra.module.basic
import algebra.module.submodule
import analysis.normed_space.basic
-- On désigne par p1 et p2 les applications coordonnées de R 2 définies par pi (x1 , x2 ) = xi.
-- (a) Soit O un ouvert de R 2 , montrer que p 1 (O) et p 2 (O) sont des ouverts de R.
-- (b) Soit H = (x, y) ∈ R 2 xy = 1. Montrer que H est un fermé de R 2 et que p 1 (H) et p 2 (H) ne sont pas des fermés de R .
-- (c) Montrer que si F est fermé et que p2 (F) est borné, alors p1 (F) est fermé.
theorem c:
forall f: set (real × real), is_closed f -> metric.bounded (prod.snd '' f) -> is_closed (prod.fst '' f)
:= sorry |
a51c98a47098c132b8f2e7d9f3164e8d0d630bad | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/computability/turing_machine.lean | ca400cd8c50da04e55496c2b8cd9fe1c0b6e8ebc | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 68,009 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Define a sequence of simple machine languages, starting with Turing
machines and working up to more complex lanaguages based on
Wang B-machines.
-/
import data.fintype.basic data.pfun logic.relation
open relation
namespace turing
/-- A direction for the turing machine `move` command, either
left or right. -/
@[derive decidable_eq, derive inhabited]
inductive dir | left | right
def tape (Γ) := Γ × list Γ × list Γ
instance {Γ} [inhabited Γ] : inhabited (tape Γ) :=
⟨by constructor; apply default⟩
def tape.mk {Γ} [inhabited Γ] (l : list Γ) : tape Γ :=
(l.head, [], l.tail)
def tape.mk' {Γ} [inhabited Γ] (L R : list Γ) : tape Γ :=
(R.head, L, R.tail)
def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ
| dir.left (a, L, R) := (L.head, L.tail, a :: R)
| dir.right (a, L, R) := (R.head, a :: L, R.tail)
def tape.nth {Γ} [inhabited Γ] : tape Γ → ℤ → Γ
| (a, L, R) 0 := a
| (a, L, R) (n+1:ℕ) := R.inth n
| (a, L, R) -[1+ n] := L.inth n
@[simp] theorem tape.nth_zero {Γ} [inhabited Γ] :
∀ (T : tape Γ), T.nth 0 = T.1
| (a, L, R) := rfl
@[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] :
∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1)
| (a, L, R) -[1+ n] := by cases L; refl
| (a, L, R) 0 := by cases L; refl
| (a, L, R) 1 := rfl
| (a, L, R) ((n+1:ℕ)+1) := by rw add_sub_cancel; refl
@[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] :
∀ (T : tape Γ) (i : ℤ), (T.move dir.right).nth i = T.nth (i+1)
| (a, L, R) (n+1:ℕ) := by cases R; refl
| (a, L, R) 0 := by cases R; refl
| (a, L, R) -1 := rfl
| (a, L, R) -[1+ n+1] := show _ = tape.nth _ (-[1+ n] - 1 + 1),
by rw sub_add_cancel; refl
def tape.write {Γ} (b : Γ) : tape Γ → tape Γ
| (a, LR) := (b, LR)
@[simp] theorem tape.write_self {Γ} : ∀ (T : tape Γ), T.write T.1 = T
| (a, LR) := rfl
@[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) :
∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i
| (a, L, R) 0 := rfl
| (a, L, R) (n+1:ℕ) := rfl
| (a, L, R) -[1+ n] := rfl
def tape.map {Γ Γ'} (f : Γ → Γ') : tape Γ → tape Γ'
| (a, L, R) := (f a, L.map f, R.map f)
@[simp] theorem tape.map_fst {Γ Γ'} (f : Γ → Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1
| (a, L, R) := rfl
@[simp] theorem tape.map_write {Γ Γ'} (f : Γ → Γ') (b : Γ) :
∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b)
| (a, L, R) := rfl
@[class] def pointed_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') :=
f (default _) = default _
theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : Γ → Γ') [pointed_map f] :
∀ (T : tape Γ) d, (T.move d).map f = (T.map f).move d
| (a, [], R) dir.left := prod.ext ‹pointed_map f› rfl
| (a, b::L, R) dir.left := rfl
| (a, L, []) dir.right := prod.ext ‹pointed_map f› rfl
| (a, L, b::R) dir.right := rfl
theorem tape.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : Γ → Γ') [f0 : pointed_map f] :
∀ (l : list Γ), (tape.mk l).map f = tape.mk (l.map f)
| [] := prod.ext ‹pointed_map f› rfl
| (a::l) := rfl
def eval {σ} (f : σ → option σ) : σ → roption σ :=
pfun.fix (λ s, roption.some $
match f s with none := sum.inl s | some s' := sum.inr s' end)
def reaches {σ} (f : σ → option σ) : σ → σ → Prop :=
refl_trans_gen (λ a b, b ∈ f a)
def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop :=
trans_gen (λ a b, b ∈ f a)
theorem reaches₁_eq {σ} {f : σ → option σ} {a b c}
(h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c :=
trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm
theorem reaches_total {σ} {f : σ → option σ}
{a b c} : reaches f a b → reaches f a c →
reaches f b c ∨ reaches f c b :=
refl_trans_gen.total_of_right_unique $ λ _ _ _, option.mem_unique
theorem reaches₁_fwd {σ} {f : σ → option σ}
{a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c :=
begin
rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩,
cases option.mem_unique hab h₂, exact hbc
end
def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop :=
∀ c, reaches₁ f b c → reaches₁ f a c
theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ}
(h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c
| d h₃ := h₁ _ (h₂ _ h₃)
@[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a
| b h := h
theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ}
(h : b ∈ f a) : reaches₀ f a b
| c h₂ := h₂.head h
theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ}
(h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c :=
(reaches₀.single h).trans h₂
theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ}
(h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c :=
h₁.trans (reaches₀.single h)
theorem reaches₀_eq {σ} {f : σ → option σ} {a b}
(e : f a = f b) : reaches₀ f a b
| d h := (reaches₁_eq e).2 h
theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ}
(h : reaches₁ f a b) : reaches₀ f a b
| c h₂ := h.trans h₂
theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ}
(h : reaches f a b) : reaches₀ f a b
| c h₂ := h₂.trans_right h
theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ}
(h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c :=
h _ (trans_gen.single h₂)
theorem mem_eval {σ} {f : σ → option σ} {a b} :
b ∈ eval f a ↔ reaches f a b ∧ f b = none :=
⟨λ h, begin
refine pfun.fix_induction h (λ a h IH, _),
cases e : f a with a',
{ rw roption.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $
roption.mem_some_iff.2 $ by rw e; refl),
exact ⟨refl_trans_gen.refl, e⟩ },
{ rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, h'⟩;
rw e at h; cases roption.mem_some_iff.1 h,
cases IH a' h' (by rwa e) with h₁ h₂,
exact ⟨refl_trans_gen.head e h₁, h₂⟩ }
end, λ ⟨h₁, h₂⟩, begin
refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _),
{ refine pfun.mem_fix_iff.2 (or.inl _),
rw h₂, apply roption.mem_some },
{ refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩),
rw show f a = _, from h,
apply roption.mem_some }
end⟩
theorem eval_maximal₁ {σ} {f : σ → option σ} {a b}
(h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc :=
let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in
by cases b0.symm.trans h'
theorem eval_maximal {σ} {f : σ → option σ} {a b}
(h : b ∈ eval f a) {c} : reaches f b c ↔ c = b :=
let ⟨ab, b0⟩ := mem_eval.1 h in
refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h'
theorem reaches_eval {σ} {f : σ → option σ} {a b}
(ab : reaches f a b) : eval f a = eval f b :=
roption.ext $ λ c,
⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in
mem_eval.2 ⟨(or_iff_left_of_imp $ by exact
λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1
(reaches_total ab ac), c0⟩,
λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩
def respects {σ₁ σ₂}
(f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) :=
∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with
| some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂
| none := f₂ a₂ = none
end : Prop)
theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) :
∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ :=
begin
induction ab with c₁ ac c₁ d₁ ac cd IH,
{ have := H aa,
rwa (show f₁ a₁ = _, from ac) at this },
{ rcases IH with ⟨c₂, cc, ac₂⟩,
have := H cc,
rw (show f₁ c₁ = _, from cd) at this,
rcases this with ⟨d₂, dd, cd₂⟩,
exact ⟨_, dd, ac₂.trans cd₂⟩ }
end
theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) :
∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ :=
begin
rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab,
{ exact ⟨_, aa, refl_trans_gen.refl⟩ },
{ exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in
⟨b₂, bb, h.to_refl⟩ }
end
theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) :
∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ :=
begin
induction ab with c₂ d₂ ac cd IH,
{ exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ },
{ rcases IH with ⟨e₁, e₂, ce, ee, ae⟩,
rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩,
{ have := H ee, revert this,
cases eg : f₁ e₁ with g₁; simp [respects],
{ intro c0, cases cd.symm.trans c0 },
{ intros g₂ gg cg,
rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩,
cases option.mem_unique cd cd',
exact ⟨_, _, dg, gg, ae.tail eg⟩ } },
{ cases option.mem_unique cd cd',
exact ⟨_, _, de, ee, ae⟩ } }
end
theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂)
(ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ :=
begin
cases mem_eval.1 ab with ab b0,
rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩,
refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩,
have := H bb, rwa b0 at this
end
theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂)
(ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ :=
begin
cases mem_eval.1 ab with ab b0,
rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩,
cases (refl_trans_gen_iff_eq
(by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc,
refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩,
have := H cc, cases f₁ c₁ with d₁, {refl},
rcases this with ⟨d₂, dd, bd⟩,
rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩,
cases b0.symm.trans h
end
theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) :
(eval f₂ a₂).dom ↔ (eval f₁ a₁).dom :=
⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h,
λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩
def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop
| (some b₁) := reaches₁ f₂ a₂ (tr b₁)
| none := f₂ a₂ = none
theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂}
(h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁
| (some b₁) := reaches₁_eq h
| none := by unfold frespects; rw h
theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} :
respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) :=
forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq']
theorem tr_eval' {σ₁ σ₂}
(f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂)
(H : respects f₁ f₂ (λ a b, tr a = b))
(a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ :=
roption.ext $ λ b₂,
⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in
(roption.mem_map_iff _).2 ⟨b₁, hb, bb⟩,
λ h, begin
rcases (roption.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩,
rcases tr_eval H rfl ab with ⟨_, rfl, h⟩,
rwa bb at h
end⟩
def dwrite {K} [decidable_eq K] {C : K → Type*}
(S : ∀ k, C k) (k') (l : C k') (k) : C k :=
if h : k = k' then eq.rec_on h.symm l else S k
@[simp] theorem dwrite_eq {K} [decidable_eq K] {C : K → Type*}
(S : ∀ k, C k) (k) (l : C k) : dwrite S k l k = l :=
dif_pos rfl
@[simp] theorem dwrite_ne {K} [decidable_eq K] {C : K → Type*}
(S : ∀ k, C k) (k') (l : C k') (k) (h : ¬ k = k') : dwrite S k' l k = S k :=
dif_neg h
@[simp] theorem dwrite_self
{K} [decidable_eq K] {C : K → Type*}
(S : ∀ k, C k) (k) : dwrite S k (S k) = S :=
funext $ λ k', by unfold dwrite; split_ifs; [subst h, refl]
namespace TM0
section
parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols
parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states
/-- A Turing machine "statement" is just a command to either move
left or right, or write a symbol on the tape. -/
@[derive inhabited]
inductive stmt
| move : dir → stmt
| write : Γ → stmt
/-- A Post-Turing machine with symbol type `Γ` and label type `Λ`
is a function which, given the current state `q : Λ` and
the tape head `a : Γ`, either halts (returns `none`) or returns
a new state `q' : Λ` and a `stmt` describing what to do,
either a move left or right, or a write command.
Both `Λ` and `Γ` are required to be inhabited; the default value
for `Γ` is the "blank" tape value, and the default value of `Λ` is
the initial state. -/
def machine := Λ → Γ → option (Λ × stmt)
instance machine.inhabited : inhabited machine := by unfold machine; apply_instance
/-- The configuration state of a Turing machine during operation
consists of a label (machine state), and a tape, represented in
the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R`
with the machine currently reading the `a`. The lists are
automatically extended with blanks as the machine moves around. -/
@[derive inhabited]
structure cfg :=
(q : Λ)
(tape : tape Γ)
parameters {Γ Λ}
/-- Execution semantics of the Turing machine. -/
def step (M : machine) : cfg → option cfg
| ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q',
match a with
| stmt.move d := T.move d
| stmt.write a := T.write a
end⟩)
/-- The statement `reaches M s₁ s₂` means that `s₂` is obtained
starting from `s₁` after a finite number of steps from `s₂`. -/
def reaches (M : machine) : cfg → cfg → Prop :=
refl_trans_gen (λ a b, b ∈ step M a)
/-- The initial configuration. -/
def init (l : list Γ) : cfg :=
⟨default Λ, tape.mk l⟩
/-- Evaluate a Turing machine on initial input to a final state,
if it terminates. -/
def eval (M : machine) (l : list Γ) : roption (list Γ) :=
(eval (step M) (init l)).map (λ c, c.tape.2.2)
/-- The raw definition of a Turing machine does not require that
`Γ` and `Λ` are finite, and in practice we will be interested
in the infinite `Λ` case. We recover instead a notion of
"effectively finite" Turing machines, which only make use of a
finite subset of their states. We say that a set `S ⊆ Λ`
supports a Turing machine `M` if `S` is closed under the
transition function and contains the initial state. -/
def supports (M : machine) (S : set Λ) :=
default Λ ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S
theorem step_supports (M : machine) {S}
(ss : supports M S) : ∀ {c c' : cfg},
c' ∈ step M c → c.q ∈ S → c'.q ∈ S
| ⟨q, T⟩ c' h₁ h₂ := begin
rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩,
exact ss.2 h h₂,
end
theorem univ_supports (M : machine) : supports M set.univ :=
⟨trivial, λ q a q' s h₁ h₂, trivial⟩
end
section
variables {Γ : Type*} [inhabited Γ]
variables {Γ' : Type*} [inhabited Γ']
variables {Λ : Type*} [inhabited Λ]
variables {Λ' : Type*} [inhabited Λ']
def stmt.map (f : Γ → Γ') : stmt Γ → stmt Γ'
| (stmt.move d) := stmt.move d
| (stmt.write a) := stmt.write (f a)
def cfg.map (f : Γ → Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ'
| ⟨q, T⟩ := ⟨g q, T.map f⟩
variables (M : machine Γ Λ)
(f₁ : Γ → Γ') (f₂ : Γ' → Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ)
def machine.map : machine Γ' Λ'
| q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁))
theorem machine.map_step {S} (ss : supports M S)
[pointed_map f₁] (f₂₁ : function.right_inverse f₁ f₂)
(g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) :
∀ c : cfg Γ Λ, c.q ∈ S →
(step M c).map (cfg.map f₁ g₁) =
step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c)
| ⟨q, T⟩ h := begin
unfold step machine.map cfg.map,
simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _],
rcases M q T.1 with _|⟨q', d|a⟩, {refl},
{ simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl },
{ simp only [step, cfg.map, option.map_some', tape.map_write], refl }
end
theorem map_init [pointed_map f₁] [g0 : pointed_map g₁] (l : list Γ) :
(init l).map f₁ g₁ = init (l.map f₁) :=
congr (congr_arg cfg.mk g0) (tape.map_mk _ _)
theorem machine.map_respects {S} (ss : supports M S)
[pointed_map f₁] [pointed_map g₁]
(f₂₁ : function.right_inverse f₁ f₂)
(g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) :
respects (step M) (step (M.map f₁ f₂ g₁ g₂))
(λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b)
| c _ ⟨cs, rfl⟩ := begin
cases e : step M c with c'; unfold respects,
{ rw [← M.map_step f₁ f₂ g₁ g₂ ss f₂₁ g₂₁ _ cs, e], refl },
{ refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩,
rw [← M.map_step f₁ f₂ g₁ g₂ ss f₂₁ g₂₁ _ cs, e], exact rfl }
end
end
end TM0
namespace TM1
section
parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols
parameters (Λ : Type*) -- Type of function labels
parameters (σ : Type*) -- Type of variable settings
/-- The TM1 model is a simplification and extension of TM0
(Post-Turing model) in the direction of Wang B-machines. The machine's
internal state is extended with a (finite) store `σ` of variables
that may be accessed and updated at any time.
A machine is given by a `Λ` indexed set of procedures or functions.
Each function has a body which is a `stmt`, which can either be a
`move` or `write` command, a `branch` (if statement based on the
current tape value), a `load` (set the variable value),
a `goto` (call another function), or `halt`. Note that here
most statements do not have labels; `goto` commands can only
go to a new function. All commands have access to the variable value
and current tape value. -/
inductive stmt
| move : dir → stmt → stmt
| write : (Γ → σ → Γ) → stmt → stmt
| load : (Γ → σ → σ) → stmt → stmt
| branch : (Γ → σ → bool) → stmt → stmt → stmt
| goto : (Γ → σ → Λ) → stmt
| halt : stmt
open stmt
instance stmt.inhabited : inhabited stmt := ⟨halt⟩
/-- The configuration of a TM1 machine is given by the currently
evaluating statement, the variable store value, and the tape. -/
@[derive inhabited]
structure cfg :=
(l : option Λ)
(var : σ)
(tape : tape Γ)
parameters {Γ Λ σ}
/-- The semantics of TM1 evaluation. -/
def step_aux : stmt → σ → tape Γ → cfg
| (move d q) v T := step_aux q v (T.move d)
| (write a q) v T := step_aux q v (T.write (a T.1 v))
| (load s q) v T := step_aux q (s T.1 v) T
| (branch p q₁ q₂) v T :=
cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T)
| (goto l) v T := ⟨some (l T.1 v), v, T⟩
| halt v T := ⟨none, v, T⟩
def step (M : Λ → stmt) : cfg → option cfg
| ⟨none, v, T⟩ := none
| ⟨some l, v, T⟩ := some (step_aux (M l) v T)
variables [inhabited Λ] [inhabited σ]
def init (l : list Γ) : cfg :=
⟨some (default _), default _, tape.mk l⟩
def eval (M : Λ → stmt) (l : list Γ) : roption (list Γ) :=
(eval (step M) (init l)).map (λ c, c.tape.2.2)
variables [fintype Γ]
def supports_stmt (S : finset Λ) : stmt → Prop
| (move d q) := supports_stmt q
| (write a q) := supports_stmt q
| (load s q) := supports_stmt q
| (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂
| (goto l) := ∀ a v, l a v ∈ S
| halt := true
/-- A set `S` of labels supports machine `M` if all the `goto`
statements in the functions in `S` refer only to other functions
in `S`. -/
def supports (M : Λ → stmt) (S : finset Λ) :=
default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q)
open_locale classical
noncomputable def stmts₁ : stmt → finset stmt
| Q@(move d q) := insert Q (stmts₁ q)
| Q@(write a q) := insert Q (stmts₁ q)
| Q@(load s q) := insert Q (stmts₁ q)
| Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂)
| Q := {Q}
theorem stmts₁_self {q} : q ∈ stmts₁ q :=
by cases q; apply finset.mem_insert_self
theorem stmts₁_trans {q₁ q₂} :
q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ :=
begin
intros h₁₂ q₀ h₀₁,
induction q₂ with _ q IH _ q IH _ q IH;
simp only [stmts₁] at h₁₂ ⊢;
simp only [finset.mem_insert, finset.mem_union,
finset.insert_empty_eq_singleton, finset.mem_singleton] at h₁₂,
iterate 3 {
rcases h₁₂ with rfl | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (IH h₁₂) } },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
rcases h₁₂ with rfl | h₁₂ | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) },
{ exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } },
case TM1.stmt.goto : l {
subst h₁₂, exact h₀₁ },
case TM1.stmt.halt {
subst h₁₂, exact h₀₁ }
end
theorem stmts₁_supports_stmt_mono {S q₁ q₂}
(h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ :=
begin
induction q₂ with _ q IH _ q IH _ q IH;
simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union,
finset.insert_empty_eq_singleton, finset.mem_singleton] at h hs,
iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] },
case TM1.stmt.goto : l { subst h, exact hs },
case TM1.stmt.halt { subst h, trivial }
end
noncomputable def stmts
(M : Λ → stmt) (S : finset Λ) : finset (option stmt) :=
(S.bind (λ q, stmts₁ (M q))).insert_none
theorem stmts_trans {M : Λ → stmt} {S q₁ q₂}
(h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bind,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩
theorem stmts_supports_stmt {M : Λ → stmt} {S q}
(ss : supports M S) : some q ∈ stmts M S → supports_stmt S q :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bind,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls)
theorem step_supports (M : Λ → stmt) {S}
(ss : supports M S) : ∀ {c c' : cfg},
c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none
| ⟨some l₁, v, T⟩ c' h₁ h₂ := begin
replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂),
simp only [step, option.mem_def] at h₁, subst c',
revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T;
intro hs,
iterate 3 { exact IH _ _ hs },
case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ {
unfold step_aux, cases p T.1 v,
{ exact IH₂ _ _ hs.2 },
{ exact IH₁ _ _ hs.1 } },
case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) },
case TM1.stmt.halt { apply multiset.mem_cons_self }
end
end
end TM1
namespace TM1to0
section
parameters {Γ : Type*} [inhabited Γ]
parameters {Λ : Type*} [inhabited Λ]
parameters {σ : Type*} [inhabited σ]
local notation `stmt₁` := TM1.stmt Γ Λ σ
local notation `cfg₁` := TM1.cfg Γ Λ σ
local notation `stmt₀` := TM0.stmt Γ
parameters (M : Λ → stmt₁)
include M
def Λ' := option stmt₁ × σ
instance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩
open TM0.stmt
def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀
| (TM1.stmt.move d q) v := ((some q, v), move d)
| (TM1.stmt.write a q) v := ((some q, v), write (a s v))
| (TM1.stmt.load a q) v := tr_aux q (a s v)
| (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v)
| (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s)
| TM1.stmt.halt v := ((none, v), write s)
local notation `cfg₀` := TM0.cfg Γ Λ'
def tr : TM0.machine Γ Λ'
| (none, v) s := none
| (some q, v) s := some (tr_aux s q v)
def tr_cfg : cfg₁ → cfg₀
| ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩
theorem tr_respects : respects (TM1.step M) (TM0.step tr)
(λ c₁ c₂, tr_cfg c₁ = c₂) :=
fun_respects.2 $ λ ⟨l₁, v, T⟩, begin
cases l₁ with l₁, {exact rfl},
unfold tr_cfg TM1.step frespects option.map function.comp option.bind,
induction M l₁ with _ q IH _ q IH _ q IH generalizing v T,
case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) },
case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) },
case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
unfold TM1.step_aux, cases e : p T.1 v,
{ exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) },
{ exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } },
iterate 2 {
exact trans_gen.single (congr_arg some
(congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) }
end
variables [fintype Γ] [fintype σ]
noncomputable def tr_stmts (S : finset Λ) : finset Λ' :=
(TM1.stmts M S).product finset.univ
open_locale classical
local attribute [simp] TM1.stmts₁_self
theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) :
TM0.supports tr (↑(tr_stmts S)) :=
⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2
(finset.mem_bind.2 ⟨_, ss.1, TM1.stmts₁_self⟩),
finset.mem_univ _⟩,
λ q a q' s h₁ h₂, begin
rcases q with ⟨_|q, v⟩, {cases h₁},
cases q' with q' v', simp only [tr_stmts, finset.mem_coe,
finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢,
cases q', {exact multiset.mem_cons_self _ _},
simp only [tr, option.mem_def] at h₁,
have := TM1.stmts_supports_stmt ss h₂,
revert this, induction q generalizing v; intro hs,
case TM1.stmt.move : d q {
cases h₁, refine TM1.stmts_trans _ h₂,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem TM1.stmts₁_self },
case TM1.stmt.write : b q {
cases h₁, refine TM1.stmts_trans _ h₂,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem TM1.stmts₁_self },
case TM1.stmt.load : b q IH {
refine IH (TM1.stmts_trans _ h₂) _ h₁ hs,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem TM1.stmts₁_self },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
change cond (p a v) _ _ = ((some q', v'), s) at h₁,
cases p a v,
{ refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) },
{ refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } },
case TM1.stmt.goto : l {
cases h₁, exact finset.some_mem_insert_none.2
(finset.mem_bind.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) },
case TM1.stmt.halt { cases h₁ }
end⟩
theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l :=
(congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin
rw [roption.map_eq_map, roption.map_map, TM1.eval],
congr', exact funext (λ ⟨_, _, _⟩, rfl)
end
end
end TM1to0
/- Reduce an n-symbol Turing machine to a 2-symbol Turing machine -/
namespace TM1to1
open TM1
section
parameters {Γ : Type*} [inhabited Γ]
theorem exists_enc_dec [fintype Γ] :
∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ),
enc (default _) = vector.repeat ff n ∧ ∀ a, dec (enc a) = a :=
begin
rcases fintype.exists_equiv_fin Γ with ⟨n, ⟨F⟩⟩,
let G : fin n ↪ fin n → bool := ⟨λ a b, a = b,
λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩,
let H := (F.to_embedding.trans G).trans
(equiv.vector_equiv_fin _ _).symm.to_embedding,
let enc := H.set_value (default _) (vector.repeat ff n),
exact ⟨_, enc, function.inv_fun enc,
H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩
end
parameters {Λ : Type*} [inhabited Λ]
parameters {σ : Type*} [inhabited σ]
local notation `stmt₁` := stmt Γ Λ σ
local notation `cfg₁` := cfg Γ Λ σ
inductive Λ' : Type (max u_1 u_2 u_3)
| normal : Λ → Λ'
| write : Γ → stmt₁ → Λ'
instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩
local notation `stmt'` := stmt bool Λ' σ
local notation `cfg'` := cfg bool Λ' σ
def read_aux : ∀ n, (vector bool n → stmt') → stmt'
| 0 f := f vector.nil
| (i+1) f := stmt.branch (λ a s, a)
(stmt.move dir.right $ read_aux i (λ v, f (tt :: v)))
(stmt.move dir.right $ read_aux i (λ v, f (ff :: v)))
parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ)
def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q
def read (f : Γ → stmt') : stmt' :=
read_aux n (λ v, move dir.left $ f (dec v))
def write : list bool → stmt' → stmt'
| [] q := q
| (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q
def tr_normal : stmt₁ → stmt'
| (stmt.move dir.left q) := move dir.right $ (move dir.left)^[2] $ tr_normal q
| (stmt.move dir.right q) := move dir.right $ tr_normal q
| (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q
| (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q
| (stmt.branch p q₁ q₂) := read $ λ a,
stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂)
| (stmt.goto l) := read $ λ a,
stmt.goto (λ _ s, Λ'.normal (l a s))
| stmt.halt := move dir.right $ move dir.left $ stmt.halt
def tr_tape' (L R : list Γ) : tape bool :=
tape.mk'
(L.bind (λ x, (enc x).to_list.reverse))
(R.bind (λ x, (enc x).to_list) ++ [default _])
def tr_tape : tape Γ → tape bool
| (a, L, R) := tr_tape' L (a :: R)
theorem tr_tape_drop_right : ∀ R : list Γ,
list.drop n (R.bind (λ x, (enc x).to_list)) =
R.tail.bind (λ x, (enc x).to_list)
| [] := list.drop_nil _
| (a::R) := list.drop_left' (enc a).2
parameters (enc0 : enc (default _) = vector.repeat ff n)
section
include enc0
theorem tr_tape_take_right : ∀ R : list Γ,
list.take' n (R.bind (λ x, (enc x).to_list)) =
(enc R.head).to_list
| [] := show list.take' n list.nil = _,
by rw [list.take'_nil]; exact (congr_arg vector.to_list enc0).symm
| (a::R) := list.take'_left' (enc a).2
end
parameters (M : Λ → stmt₁)
def tr : Λ' → stmt'
| (Λ'.normal l) := tr_normal (M l)
| (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q
def tr_cfg : cfg₁ → cfg'
| ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩
include enc0
theorem tr_tape'_move_left (L R) :
(tape.move dir.left)^[n] (tr_tape' L R) =
(tr_tape' L.tail (L.head :: R)) :=
begin
cases L with a L,
{ simp only [enc0, vector.repeat, tr_tape',
list.cons_bind, list.head, list.append_assoc],
suffices : ∀ i R', default _ ∈ R' →
(tape.move dir.left^[i]) (tape.mk' [] R') =
tape.mk' [] (list.repeat ff i ++ R'),
from this n _ (list.mem_append_right _
(list.mem_singleton_self _)),
intros i R' hR, induction i with i IH, {refl},
rw [nat.iterate_succ', IH],
refine prod.ext rfl (prod.ext rfl (list.cons_head_tail
(list.ne_nil_of_mem $ list.mem_append_right _ hR))) },
{ simp only [tr_tape', list.cons_bind, list.append_assoc],
suffices : ∀ L' R' l₁ l₂
(hR : default _ ∈ R')
(e : vector.to_list (enc a) = list.reverse_core l₁ l₂),
(tape.move dir.left^[l₁.length]) (tape.mk' (l₁ ++ L') (l₂ ++ R')) =
tape.mk' L' (vector.to_list (enc a) ++ R'),
{ simpa only [list.length_reverse, vector.to_list_length]
using this _ _ _ _ _ (list.reverse_reverse _).symm,
exact list.mem_append_right _ (list.mem_singleton_self _) },
intros, induction l₁ with b l₁ IH generalizing l₂,
{ cases e, refl },
simp only [list.length, list.cons_append, nat.iterate_succ],
convert IH _ e,
exact prod.ext rfl (prod.ext rfl (list.cons_head_tail
(list.ne_nil_of_mem $ list.mem_append_right _ hR))) }
end
theorem tr_tape'_move_right (L R) :
(tape.move dir.right)^[n] (tr_tape' L R) =
(tr_tape' (R.head :: L) R.tail) :=
begin
cases R with a R,
{ simp only [enc0, vector.repeat, tr_tape', list.head,
list.cons_bind, vector.to_list_mk, list.reverse_repeat],
suffices : ∀ i L',
(tape.move dir.right^[i]) (ff, L', []) =
(ff, list.repeat ff i ++ L', []),
from this n _,
intros, induction i with i IH, {refl},
rw [nat.iterate_succ', IH],
refine prod.ext rfl (prod.ext rfl rfl) },
{ simp only [tr_tape', list.cons_bind, list.append_assoc],
suffices : ∀ L' R' l₁ l₂ : list bool,
(tape.move dir.right^[l₂.length]) (tape.mk' (l₁ ++ L') (l₂ ++ R')) =
tape.mk' (list.reverse_core l₂ l₁ ++ L') R',
{ simpa only [vector.to_list_length] using this _ _ [] (enc a).to_list },
intros, induction l₂ with b l₂ IH generalizing l₁, {refl},
exact IH (b::l₁) }
end
theorem step_aux_move (d q v T) :
step_aux (move d q) v T =
step_aux q v ((tape.move d)^[n] T) :=
begin
suffices : ∀ i,
step_aux (stmt.move d^[i] q) v T =
step_aux q v (tape.move d^[i] T), from this n,
intro, induction i with i IH generalizing T, {refl},
rw [nat.iterate_succ', step_aux, IH, ← nat.iterate_succ]
end
parameters (encdec : ∀ a, dec (enc a) = a)
include encdec
theorem step_aux_read (f v L R) :
step_aux (read f) v (tr_tape' L R) =
step_aux (f R.head) v (tr_tape' L (R.head :: R.tail)) :=
begin
suffices : ∀ f,
step_aux (read_aux n f) v (tr_tape' enc L R) =
step_aux (f (enc R.head)) v
(tr_tape' enc (R.head :: L) R.tail),
{ rw [read, this, step_aux_move enc enc0, encdec,
tr_tape'_move_left enc enc0], refl },
cases R with a R,
{ suffices : ∀ i f L',
step_aux (read_aux i f) v (ff, L', []) =
step_aux (f (vector.repeat ff i)) v
(ff, list.repeat ff i ++ L', []),
{ intro f, convert this n f _,
refine prod.ext rfl (prod.ext ((list.cons_bind _ _ _).trans _) rfl),
simp only [list.head, enc0, vector.repeat, vector.to_list, list.reverse_repeat] },
clear f L, intros, induction i with i IH generalizing L', {refl},
change step_aux (read_aux i (λ v, f (ff :: v))) v (ff, ff :: L', [])
= step_aux (f (vector.repeat ff (nat.succ i))) v (ff, ff :: (list.repeat ff i ++ L'), []),
rw [IH], congr',
simpa only [list.append_assoc] using congr_arg (++ L') (list.repeat_add ff i 1).symm },
{ simp only [tr_tape', list.cons_bind, list.append_assoc],
suffices : ∀ i f L' R' l₁ l₂ h,
step_aux (read_aux i f) v
(tape.mk' (l₁ ++ L') (l₂ ++ R')) =
step_aux (f ⟨l₂, h⟩) v
(tape.mk' (l₂.reverse_core l₁ ++ L') R'),
{ intro f, convert this n f _ _ _ _ (enc a).2; simp },
clear f L a R, intros, subst i,
induction l₂ with a l₂ IH generalizing l₁, {refl},
change (tape.mk' (l₁ ++ L') (a :: (l₂ ++ R'))).1 with a,
transitivity step_aux
(read_aux l₂.length (λ v, f (a :: v))) v
(tape.mk' (a :: l₁ ++ L') (l₂ ++ R')),
{ cases a; refl },
rw IH, refl }
end
theorem step_aux_write (q v a b L R) :
step_aux (write (enc a).to_list q) v (tr_tape' L (b :: R)) =
step_aux q v (tr_tape' (a :: L) R) :=
begin
simp only [tr_tape', list.cons_bind, list.append_assoc],
suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool)
(e : l₂'.length = l₂.length),
step_aux (write l₂ q) v (tape.mk' (l₁ ++ L') (l₂' ++ R')) =
step_aux q v (tape.mk' (list.reverse_core l₂ l₁ ++ L') R'),
from this [] _ _ ((enc b).2.trans (enc a).2.symm),
clear a b L R, intros,
induction l₂ with a l₂ IH generalizing l₁ l₂',
{ cases list.length_eq_zero.1 e, refl },
cases l₂' with b l₂'; injection e with e,
unfold write step_aux,
convert IH _ _ e, refl
end
theorem tr_respects : respects (step M) (step tr)
(λ c₁ c₂, tr_cfg c₁ = c₂) :=
fun_respects.2 $ λ ⟨l₁, v, (a, L, R)⟩, begin
cases l₁ with l₁, {exact rfl},
suffices : ∀ q R, reaches (step (tr enc dec M))
(step_aux (tr_normal dec q) v (tr_tape' enc L R))
(tr_cfg enc (step_aux q v (tape.mk' L R))),
{ refine trans_gen.head' rfl (this _ (a::R)) },
clear R l₁, intros,
induction q with _ q IH _ q IH _ q IH generalizing v L R,
case TM1.stmt.move : d q IH {
cases d; simp only [tr_normal, nat.iterate, step_aux_move enc enc0, step_aux,
tr_tape'_move_left enc enc0, tr_tape'_move_right enc enc0];
apply IH },
case TM1.stmt.write : a q IH {
simp only [tr_normal, step_aux_read enc dec enc0 encdec, step_aux],
refine refl_trans_gen.head rfl _,
simp only [tr, tr_normal, step_aux,
step_aux_write enc dec enc0 encdec,
step_aux_move enc enc0, tr_tape'_move_left enc enc0],
apply IH },
case TM1.stmt.load : a q IH {
simp only [tr_normal, step_aux_read enc dec enc0 encdec],
apply IH },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
simp only [tr_normal, step_aux_read enc dec enc0 encdec, step_aux],
change (tape.mk' L R).1 with R.head,
cases p R.head v; [apply IH₂, apply IH₁] },
case TM1.stmt.goto : l {
simp only [tr_normal, step_aux_read enc dec enc0 encdec, step_aux],
apply refl_trans_gen.refl },
case TM1.stmt.halt {
simp only [tr_normal, step_aux, tr_cfg, step_aux_move enc enc0,
tr_tape'_move_left enc enc0, tr_tape'_move_right enc enc0],
apply refl_trans_gen.refl }
end
omit enc0 encdec
open_locale classical
parameters [fintype Γ]
noncomputable def writes : stmt₁ → finset Λ'
| (stmt.move d q) := writes q
| (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q
| (stmt.load f q) := writes q
| (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂
| (stmt.goto l) := ∅
| stmt.halt := ∅
noncomputable def tr_supp (S : finset Λ) : finset Λ' :=
S.bind (λ l, insert (Λ'.normal l) (writes (M l)))
theorem supports_stmt_move {S d q} :
supports_stmt S (move d q) = supports_stmt S q :=
suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this,
by intro; induction i generalizing q; simp only [*, nat.iterate]; refl
theorem supports_stmt_write {S l q} :
supports_stmt S (write l q) = supports_stmt S q :=
by induction l with a l IH; simp only [write, supports_stmt, *]
local attribute [simp] supports_stmt_move supports_stmt_write
theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'},
(∀ a, supports_stmt S (f a)) → supports_stmt S (read f) :=
suffices ∀ i (f : vector bool i → stmt'),
(∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f),
from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]),
λ i f hf, begin
induction i with i IH, {exact hf _},
split; apply IH; intro; apply hf,
end
theorem tr_supports {S} (ss : supports M S) :
supports tr (tr_supp S) :=
⟨finset.mem_bind.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩,
λ q h, begin
suffices : ∀ q, supports_stmt S q →
(∀ q' ∈ writes q, q' ∈ tr_supp M S) →
supports_stmt (tr_supp M S) (tr_normal dec q) ∧
∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'),
{ rcases finset.mem_bind.1 h with ⟨l, hl, h⟩,
have := this _ (ss.2 _ hl) (λ q' hq,
finset.mem_bind.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩),
rcases finset.mem_insert.1 h with rfl | h,
exacts [this.1, this.2 _ h] },
intros q hs hw, induction q,
case TM1.stmt.move : d q IH {
unfold writes at hw ⊢,
replace IH := IH hs hw, refine ⟨_, IH.2⟩,
cases d; simp only [tr_normal, nat.iterate, supports_stmt_move, IH] },
case TM1.stmt.write : f q IH {
unfold writes at hw ⊢,
simp only [finset.mem_image, finset.mem_union, finset.mem_univ,
exists_prop, true_and] at hw ⊢,
replace IH := IH hs (λ q hq, hw q (or.inr hq)),
refine ⟨supports_stmt_read _ $ λ a _ s,
hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩,
rcases hq with ⟨a, q₂, rfl⟩ | hq,
{ simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] },
{ exact IH.2 _ hq } },
case TM1.stmt.load : a q IH {
unfold writes at hw ⊢,
replace IH := IH hs hw,
refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
unfold writes at hw ⊢,
simp only [finset.mem_union] at hw ⊢,
replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)),
replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)),
exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩),
λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ },
case TM1.stmt.goto : l {
refine ⟨_, λ _, false.elim⟩,
refine supports_stmt_read _ (λ a _ s, _),
exact finset.mem_bind.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ },
case TM1.stmt.halt {
refine ⟨_, λ _, false.elim⟩,
simp only [supports_stmt, supports_stmt_move, tr_normal] }
end⟩
end
end TM1to1
namespace TM0to1
section
parameters {Γ : Type*} [inhabited Γ]
parameters {Λ : Type*} [inhabited Λ]
inductive Λ'
| normal : Λ → Λ'
| act : TM0.stmt Γ → Λ → Λ'
instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩
local notation `cfg₀` := TM0.cfg Γ Λ
local notation `stmt₁` := TM1.stmt Γ Λ' unit
local notation `cfg₁` := TM1.cfg Γ Λ' unit
parameters (M : TM0.machine Γ Λ)
open TM1.stmt
def tr : Λ' → stmt₁
| (Λ'.normal q) :=
branch (λ a _, (M q a).is_none) halt $
goto (λ a _, match M q a with
| none := default _
| some (q', s) := Λ'.act s q'
end)
| (Λ'.act (TM0.stmt.move d) q) :=
move d $ goto (λ _ _, Λ'.normal q)
| (Λ'.act (TM0.stmt.write a) q) :=
write (λ _ _, a) $ goto (λ _ _, Λ'.normal q)
def tr_cfg : cfg₀ → cfg₁
| ⟨q, T⟩ := ⟨cond (M q T.1).is_some
(some (Λ'.normal q)) none, (), T⟩
theorem tr_respects : respects (TM0.step M) (TM1.step tr)
(λ a b, tr_cfg a = b) :=
fun_respects.2 $ λ ⟨q, T⟩, begin
cases e : M q T.1,
{ simp only [TM0.step, tr_cfg, e]; exact eq.refl none },
cases val with q' s,
simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'],
have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ =
some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩,
{ cases s with d a; refl },
refine trans_gen.head _ (trans_gen.head' this _),
{ unfold TM1.step TM1.step_aux tr has_mem.mem,
rw e, refl },
cases e' : M q' _,
{ apply refl_trans_gen.single,
unfold TM1.step TM1.step_aux tr has_mem.mem,
rw e', refl },
{ refl }
end
end
end TM0to1
namespace TM2
section
parameters {K : Type*} [decidable_eq K] -- Index type of stacks
parameters (Γ : K → Type*) -- Type of stack elements
parameters (Λ : Type*) -- Type of function labels
parameters (σ : Type*) -- Type of variable settings
/-- The TM2 model removes the tape entirely from the TM1 model,
replacing it with an arbitrary (finite) collection of stacks.
The operation `push` puts an element on one of the stacks,
and `pop` removes an element from a stack (and modifying the
internal state based on the result). `peek` modifies the
internal state but does not remove an element. -/
inductive stmt
| push : ∀ k, (σ → Γ k) → stmt → stmt
| peek : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt
| pop : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt
| load : (σ → σ) → stmt → stmt
| branch : (σ → bool) → stmt → stmt → stmt
| goto : (σ → Λ) → stmt
| halt : stmt
open stmt
instance stmt.inhabited : inhabited stmt := ⟨halt⟩
structure cfg :=
(l : option Λ)
(var : σ)
(stk : ∀ k, list (Γ k))
instance cfg.inhabited [inhabited σ] [∀ k, inhabited (Γ k)] : inhabited cfg :=
⟨by constructor; intros; apply default⟩
parameters {Γ Λ σ K}
def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg
| (push k f q) v S := step_aux q v (dwrite S k (f v :: S k))
| (peek k f q) v S := step_aux q (f v (S k).head') S
| (pop k f q) v S := step_aux q (f v (S k).head') (dwrite S k (S k).tail)
| (load a q) v S := step_aux q (a v) S
| (branch f q₁ q₂) v S :=
cond (f v) (step_aux q₁ v S) (step_aux q₂ v S)
| (goto f) v S := ⟨some (f v), v, S⟩
| halt v S := ⟨none, v, S⟩
def step (M : Λ → stmt) : cfg → option cfg
| ⟨none, v, S⟩ := none
| ⟨some l, v, S⟩ := some (step_aux (M l) v S)
def reaches (M : Λ → stmt) : cfg → cfg → Prop :=
refl_trans_gen (λ a b, b ∈ step M a)
variables [inhabited Λ] [inhabited σ]
def init (k) (L : list (Γ k)) : cfg :=
⟨some (default _), default _, dwrite (λ _, []) k L⟩
def eval (M : Λ → stmt) (k) (L : list (Γ k)) : roption (list (Γ k)) :=
(eval (step M) (init k L)).map $ λ c, c.stk k
variables [fintype K] [∀ k, fintype (Γ k)] [fintype σ]
def supports_stmt (S : finset Λ) : stmt → Prop
| (push k f q) := supports_stmt q
| (peek k f q) := supports_stmt q
| (pop k f q) := supports_stmt q
| (load a q) := supports_stmt q
| (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂
| (goto l) := ∀ v, l v ∈ S
| halt := true
def supports (M : Λ → stmt) (S : finset Λ) :=
default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q)
open_locale classical
noncomputable def stmts₁ : stmt → finset stmt
| Q@(push k f q) := insert Q (stmts₁ q)
| Q@(peek k f q) := insert Q (stmts₁ q)
| Q@(pop k f q) := insert Q (stmts₁ q)
| Q@(load a q) := insert Q (stmts₁ q)
| Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂)
| Q@(goto l) := {Q}
| Q@halt := {Q}
theorem stmts₁_self {q} : q ∈ stmts₁ q :=
by cases q; apply finset.mem_insert_self
theorem stmts₁_trans {q₁ q₂} :
q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ :=
begin
intros h₁₂ q₀ h₀₁,
induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH;
simp only [stmts₁] at h₁₂ ⊢;
simp only [finset.mem_insert, finset.insert_empty_eq_singleton,
finset.mem_singleton, finset.mem_union] at h₁₂,
iterate 4 {
rcases h₁₂ with rfl | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (IH h₁₂) } },
case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ {
rcases h₁₂ with rfl | h₁₂ | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) },
{ exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } },
case TM2.stmt.goto : l {
subst h₁₂, exact h₀₁ },
case TM2.stmt.halt {
subst h₁₂, exact h₀₁ }
end
theorem stmts₁_supports_stmt_mono {S q₁ q₂}
(h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ :=
begin
induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH;
simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union,
finset.insert_empty_eq_singleton, finset.mem_singleton] at h hs,
iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] },
case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ {
rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] },
case TM2.stmt.goto : l { subst h, exact hs },
case TM2.stmt.halt { subst h, trivial }
end
noncomputable def stmts
(M : Λ → stmt) (S : finset Λ) : finset (option stmt) :=
(S.bind (λ q, stmts₁ (M q))).insert_none
theorem stmts_trans {M : Λ → stmt} {S q₁ q₂}
(h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bind,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩
theorem stmts_supports_stmt {M : Λ → stmt} {S q}
(ss : supports M S) : some q ∈ stmts M S → supports_stmt S q :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bind,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls)
theorem step_supports (M : Λ → stmt) {S}
(ss : supports M S) : ∀ {c c' : cfg},
c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none
| ⟨some l₁, v, T⟩ c' h₁ h₂ := begin
replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂),
simp only [step, option.mem_def] at h₁, subst c',
revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T;
intro hs,
iterate 4 { exact IH _ _ hs },
case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ {
unfold step_aux, cases p v,
{ exact IH₂ _ _ hs.2 },
{ exact IH₁ _ _ hs.1 } },
case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) },
case TM2.stmt.halt { apply multiset.mem_cons_self }
end
end
end TM2
namespace TM2to1
section
parameters {K : Type*} [decidable_eq K]
parameters {Γ : K → Type*}
parameters {Λ : Type*} [inhabited Λ]
parameters {σ : Type*} [inhabited σ]
local notation `stmt₂` := TM2.stmt Γ Λ σ
local notation `cfg₂` := TM2.cfg Γ Λ σ
inductive stackel (k : K)
| val : Γ k → stackel
| bottom [] : stackel
| top [] : stackel
instance stackel.inhabited (k) : inhabited (stackel k) :=
⟨stackel.top _⟩
def stackel.is_bottom {k} : stackel k → bool
| (stackel.bottom _) := tt
| _ := ff
def stackel.is_top {k} : stackel k → bool
| (stackel.top _) := tt
| _ := ff
def stackel.get {k} : stackel k → option (Γ k)
| (stackel.val a) := some a
| _ := none
section
open stackel
def stackel_equiv {k} : stackel k ≃ option (option (Γ k)) :=
begin
refine ⟨λ s, _, λ s, _, _, _⟩,
{ cases s, exacts [some (some s), none, some none] },
{ rcases s with _|_|s, exacts [bottom _, top _, val s] },
{ intro s, cases s; refl },
{ intro s, rcases s with _|_|s; refl },
end
end
def Γ' := ∀ k, stackel k
instance Γ'.inhabited : inhabited Γ' := ⟨λ _, default _⟩
instance stackel.fintype {k} [fintype (Γ k)] : fintype (stackel k) :=
fintype.of_equiv _ stackel_equiv.symm
instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' :=
pi.fintype
inductive st_act (k : K)
| push : (σ → Γ k) → st_act
| pop : bool → (σ → option (Γ k) → σ) → st_act
section
open st_act
instance st_act.inhabited {k} : inhabited (st_act k) :=
⟨pop (default _) (λ s _, s)⟩
def st_run {k : K} : st_act k → stmt₂ → stmt₂
| (push f) := TM2.stmt.push k f
| (pop ff f) := TM2.stmt.peek k f
| (pop tt f) := TM2.stmt.pop k f
def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ
| (push f) := v
| (pop b f) := f v l.head'
def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k)
| (push f) := f v :: l
| (pop ff f) := l
| (pop tt f) := l.tail
@[elab_as_eliminator] def {l} stmt_st_rec
{C : stmt₂ → Sort l}
(H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q))
(H₂ : Π a q (IH : C q), C (TM2.stmt.load a q))
(H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂))
(H₄ : Π l, C (TM2.stmt.goto l))
(H₅ : C TM2.stmt.halt) : ∀ n, C n
| (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q)
| (TM2.stmt.peek k f q) := H₁ _ (pop ff f) _ (stmt_st_rec q)
| (TM2.stmt.pop k f q) := H₁ _ (pop tt f) _ (stmt_st_rec q)
| (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q)
| (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂)
| (TM2.stmt.goto l) := H₄ _
| TM2.stmt.halt := H₅
theorem supports_run [fintype K] [∀ k, fintype (Γ k)] [fintype σ]
(S : finset Λ) {k} (s : st_act k) (q) :
TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q :=
by rcases s with _|_|_; refl
end
inductive Λ' : Type (max u_1 u_2 u_3 u_4)
| normal : Λ → Λ'
| go (k) : st_act k → stmt₂ → Λ'
| ret : K → stmt₂ → Λ'
open Λ'
instance : inhabited Λ' := ⟨normal (default _)⟩
local notation `stmt₁` := TM1.stmt Γ' Λ' σ
local notation `cfg₁` := TM1.cfg Γ' Λ' σ
open TM1.stmt
def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁
| (st_act.push f) :=
write (λ a s, dwrite a k $ stackel.val $ f s) $
move dir.right $
write (λ a s, dwrite a k $ stackel.top k) q
| (st_act.pop b f) :=
move dir.left $
load (λ a s, f s (a k).get) $
cond b
( branch (λ a s, (a k).is_bottom)
( move dir.right q )
( move dir.right $
write (λ a s, dwrite a k $ default _) $
move dir.left $
write (λ a s, dwrite a k $ stackel.top k) q ) )
( move dir.right q )
def tr_init (k) (L : list (Γ k)) : list Γ' :=
stackel.bottom :: match L.reverse with
| [] := [stackel.top]
| (a::L') := dwrite stackel.top k (stackel.val a) ::
(L'.map stackel.val ++ [stackel.top k]).map (dwrite (default _) k)
end
theorem step_run {k : K} (q v S) : ∀ s : st_act k,
TM2.step_aux (st_run s q) v S =
TM2.step_aux q (st_var v (S k) s) (dwrite S k (st_write v (S k) s))
| (st_act.push f) := rfl
| (st_act.pop ff f) := by unfold st_write; rw dwrite_self; refl
| (st_act.pop tt f) := rfl
def tr_normal : stmt₂ → stmt₁
| (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q)
| (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.pop ff f) q)
| (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop tt f) q)
| (TM2.stmt.load a q) := load (λ _, a) (tr_normal q)
| (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂)
| (TM2.stmt.goto l) := goto (λ a s, normal (l s))
| TM2.stmt.halt := halt
theorem tr_normal_run {k} (s q) :
tr_normal (st_run s q) = goto (λ _ _, go k s q) :=
by rcases s with _|_|_; refl
parameters (M : Λ → stmt₂)
include M
def tr : Λ' → stmt₁
| (normal q) := tr_normal (M q)
| (go k s q) :=
branch (λ a s, (a k).is_top) (tr_st_act (goto (λ _ _, ret k q)) s)
(move dir.right $ goto (λ _ _, go k s q))
| (ret k q) :=
branch (λ a s, (a k).is_bottom) (tr_normal q)
(move dir.left $ goto (λ _ _, ret k q))
def tr_stk {k} (S : list (Γ k)) (L : list (stackel k)) : Prop :=
∃ n, L = (S.map stackel.val).reverse_core (stackel.top k :: list.repeat (default _) n)
local attribute [pp_using_anonymous_constructor] turing.TM1.cfg
inductive tr_cfg : cfg₂ → cfg₁ → Prop
| mk {q v} {S : ∀ k, list (Γ k)} {L : list Γ'} :
(∀ k, tr_stk (S k) (L.map (λ a, a k))) →
tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, (stackel.bottom, [], L)⟩
theorem tr_respects_aux₁ {k} (o q v) : ∀ S₁ {s S₂} {T : list Γ'},
T.map (λ (a : Γ'), a k) = (list.map stackel.val S₁).reverse_core (s :: S₂) →
∃ a T₁ T₂,
T = list.reverse_core T₁ (a :: T₂) ∧
a k = s ∧
T₁.map (λ (a : Γ'), a k) = S₁.map stackel.val ∧
T₂.map (λ (a : Γ'), a k) = S₂ ∧
reaches₀ (TM1.step tr)
⟨some (go k o q), v, (stackel.bottom, [], T)⟩
⟨some (go k o q), v, (a, T₁ ++ [stackel.bottom], T₂)⟩
| [] s S₂ (a :: T) hT := by injection hT with es e₂; exact
⟨a, [], _, rfl, es, rfl, e₂, reaches₀.single rfl⟩
| (s' :: S₁) s S₂ T hT :=
let ⟨a, T₁, b'::T₂, e, es', e₁, e₂, H⟩ := tr_respects_aux₁ S₁ hT in
by injection e₂ with es e₂; exact
⟨b', a::T₁, T₂, e, es, congr (congr_arg list.cons es') e₁,
e₂, H.tail (by unfold TM1.step;
change some (cond (TM2to1.stackel.is_top (a k)) _ _) = _;
rw es'; refl)⟩
local attribute [simp] TM1.step TM1.step_aux tr tr_st_act st_var st_write
tape.move tape.write list.reverse_core stackel.get stackel.is_bottom
theorem tr_respects_aux₂
{k q v} {S : Π k, list (Γ k)} {T₁ T₂ : list Γ'} {a : Γ'}
(hT : ∀ k, tr_stk (S k) ((T₁.reverse_core (a :: T₂)).map (λ (a : Γ'), a k)))
(e₁ : T₁.map (λ (a : Γ'), a k) = list.map stackel.val (S k))
(ea : a k = stackel.top k) (o) :
let v' := st_var v (S k) o,
Sk' := st_write v (S k) o,
S' : ∀ k, list (Γ k) := dwrite S k Sk' in
∃ b (T₁' T₂' : list Γ'),
(∀ (k' : K), tr_stk (S' k') ((T₁'.reverse_core (b :: T₂')).map (λ (a : Γ'), a k'))) ∧
T₁'.map (λ a, a k) = Sk'.map stackel.val ∧
b k = stackel.top k ∧
TM1.step_aux (tr_st_act q o) v (a, T₁ ++ [stackel.bottom], T₂) =
TM1.step_aux q v' (b, T₁' ++ [stackel.bottom], T₂') :=
begin
dsimp only,
cases o with f b f,
case TM2to1.st_act.push : {
refine ⟨_, dwrite a k (stackel.val (f v)) :: T₁,
_, _, by simp only [list.map, dwrite_eq, e₁]; refl,
by simp only [tape.write, tape.move, dwrite_eq], rfl⟩,
intro k', cases hT k' with n e,
by_cases h : k' = k,
{ subst k', existsi n.pred,
simp only [list.reverse_core_eq, list.map_append, list.map_reverse, e₁,
list.map_cons, list.append_left_inj] at e,
simp only [list.reverse_core_eq, e.1, e.2, list.map_append, prod.fst,
list.map_reverse, list.reverse_cons, list.map, dwrite_eq, e₁, list.map_tail,
list.tail_repeat, TM2to1.st_write] },
{ cases T₂ with t T₂,
{ existsi n+1,
simpa only [dwrite_ne _ _ _ _ h, list.reverse_core_eq, e₁, list.repeat_add,
tape.write, tape.move, list.reverse_cons, list.map_reverse, list.map_append,
list.map, list.head, list.tail, list.append_assoc] using
congr_arg (++ [default Γ' k']) e },
{ existsi n,
simpa only [dwrite_ne _ _ _ _ h, list.reverse_core_eq, e₁, list.repeat_add,
tape.write, tape.move, list.reverse_cons, list.map_reverse, list.map_append,
list.map, list.head, list.tail, list.append_assoc] using e } } },
have dw := dwrite_self S k,
cases T₁ with t T₁; cases eS : S k with s Sk;
rw eS at e₁ dw; injection e₁ with tk e₁'; cases b,
{ -- peek nil
simp only [dw, st_write],
exact ⟨_, [], _, hT, rfl, ea, rfl⟩ },
{ -- pop nil
simp only [dw, st_write, list.tail],
exact ⟨_, [], _, hT, rfl, ea, rfl⟩ },
{ -- peek cons
change t k = stackel.val s at tk,
simp only [eS, tk, dw, st_write, TM1.step_aux, tr_st_act, cond, tape.move,
list.head, list.tail, list.cons_append],
exact ⟨_, t::T₁, _, hT, e₁, ea, rfl⟩ },
{ -- pop cons
change t k = stackel.val s at tk,
simp only [tk, st_write, list.tail, TM1.step_aux, tr_st_act, cond,
tape.move, list.cons_append, list.head],
refine ⟨_, _, _, _, e₁', dwrite_eq _ _ _, rfl⟩,
intro k', cases hT k' with n e,
by_cases h : k' = k,
{ subst k', existsi n+1,
simp only [list.reverse_core_eq, eS, e₁', list.append_left_inj,
list.map_append, list.map_reverse, list.map, list.reverse_cons,
list.append_assoc, list.cons_append] at e ⊢,
simp only [tape.move, tape.write, list.head, list.tail, dwrite_eq],
rw [e.2.2]; refl },
{ existsi n, simpa only [dwrite_ne _ _ _ _ h, list.map, list.head, list.tail,
list.reverse_core, list.map_reverse_core, tape.move, tape.write] using e } },
end
theorem tr_respects_aux₃ {k q v}
{S : Π k, list (Γ k)} {T : list Γ'}
(hT : ∀ k, tr_stk (S k) (T.map (λ (a : Γ'), a k))) :
∀ (T₁ : list Γ') {T₂ : list Γ'} {a : Γ'} {S₁}
(e : T = T₁.reverse_core (a :: T₂))
(ha : (a k).is_bottom = ff)
(e₁ : T₁.map (λ (a : Γ'), a k) = list.map stackel.val S₁),
reaches₀ (TM1.step tr)
⟨some (ret k q), v, (a, T₁ ++ [stackel.bottom], T₂)⟩
⟨some (ret k q), v, (stackel.bottom, [], T)⟩
| [] T₂ a S₁ e ha e₁ := reaches₀.single (by simp only [ha, e, TM1.step,
option.mem_def, tr, TM1.step_aux] {constructor_eq:=ff}; refl)
| (b :: T₁) T₂ a (s :: S₁) e ha e₁ := begin
unfold list.map at e₁, injection e₁ with es e₁,
refine reaches₀.head _ (tr_respects_aux₃ T₁ e (by rw es; refl) e₁),
simp only [ha, option.mem_def, TM1.step, tr, TM1.step_aux], refl
end
theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)}
(hT : ∀ (k : K), tr_stk (S k) (list.map (λ (a : Γ'), a k) T))
(o : st_act k)
(IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list Γ'},
(∀ (k : K), tr_stk (S k) (list.map (λ (a : Γ'), a k) T)) →
(∃ b, tr_cfg (TM2.step_aux q v S) b ∧
reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (stackel.bottom, [], T)) b)) :
∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧
reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q))
v (stackel.bottom, [], T)) b :=
begin
rcases hT k with ⟨n, hTk⟩,
simp only [tr_normal_run],
rcases tr_respects_aux₁ M o q v _ hTk with ⟨a, T₁, T₂, rfl, ea, e₁, e₂, hgo⟩,
rcases tr_respects_aux₂ M hT e₁ ea _ with ⟨b, T₁', T₂', hT', e₁', eb, hrun⟩,
have hret := tr_respects_aux₃ M hT' _ rfl (by rw eb; refl) e₁',
have := hgo.tail' rfl,
simp only [ea, tr, TM1.step_aux] at this,
rw [hrun, TM1.step_aux] at this,
rcases IH hT' with ⟨c, gc, rc⟩,
simp only [step_run],
refine ⟨c, gc, (this.to₀.trans hret _ (trans_gen.head' rfl rc)).to_refl⟩
end
local attribute [simp] respects TM2.step TM2.step_aux tr_normal
theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg :=
λ c₁ c₂ h, begin
cases h with l v S L hT, clear h,
cases l, {constructor},
simp only [TM2.step, respects, option.map_some'],
suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _,
from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩,
rw [tr],
revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros,
{ exact tr_respects_aux M hT s @IH },
{ exact IH hT },
{ unfold TM2.step_aux tr_normal TM1.step_aux,
cases p v; [exact IH₂ hT, exact IH₁ hT] },
{ exact ⟨_, ⟨hT⟩, refl_trans_gen.refl⟩ },
{ exact ⟨_, ⟨hT⟩, refl_trans_gen.refl⟩ }
end
theorem tr_cfg_init (k) (L : list (Γ k)) :
tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) :=
⟨λ k', begin
unfold tr_init,
cases e : L.reverse with a L',
{ cases list.reverse_eq_nil.1 e, rw dwrite_self, exact ⟨0, rfl⟩ },
by_cases k' = k,
{ subst k', existsi 0,
simp only [list.tail, dwrite_eq, list.reverse_core_eq,
list.repeat, tr_init, list.map, list.map_map, (∘), list.map_id' (λ _, rfl)],
rw [← list.map_reverse, e], refl },
{ existsi L'.length + 1,
simp only [dwrite_ne _ _ _ _ h, list.tail, tr_init, list.map_map,
list.map, list.map_append, list.repeat_add, (∘),
list.map_const] {constructor_eq:=ff},
refl }
end⟩
theorem tr_eval_dom (k) (L : list (Γ k)) :
(TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom :=
tr_eval_dom tr_respects (tr_cfg_init _ _)
theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂}
(H₁ : L₁ ∈ TM1.eval tr (tr_init k L))
(H₂ : L₂ ∈ TM2.eval M k L) :
∃ S : ∀ k, list (Γ k),
(∀ k', tr_stk (S k') (L₁.map (λ a, a k'))) ∧ S k = L₂ :=
begin
rcases (roption.mem_map_iff _).1 H₁ with ⟨c₁, h₁, rfl⟩,
rcases (roption.mem_map_iff _).1 H₂ with ⟨c₂, h₂, rfl⟩,
rcases tr_eval (tr_respects M) (tr_cfg_init M k L) h₂
with ⟨_, ⟨q, v, S, L₁', hT⟩, h₃⟩,
cases roption.mem_unique h₁ h₃,
exact ⟨S, hT, rfl⟩
end
variables [fintype K] [∀ k, fintype (Γ k)] [fintype σ]
open_locale classical
local attribute [simp] TM2.stmts₁_self
noncomputable def tr_stmts₁ : stmt₂ → finset Λ'
| Q@(TM2.stmt.push k f q) := {go k (st_act.push f) q, ret k q} ∪ tr_stmts₁ q
| Q@(TM2.stmt.peek k f q) := {go k (st_act.pop ff f) q, ret k q} ∪ tr_stmts₁ q
| Q@(TM2.stmt.pop k f q) := {go k (st_act.pop tt f) q, ret k q} ∪ tr_stmts₁ q
| Q@(TM2.stmt.load a q) := tr_stmts₁ q
| Q@(TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂
| _ := ∅
theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret k q} ∪ tr_stmts₁ q :=
by rcases s with _|_|_; unfold tr_stmts₁ st_run
noncomputable def tr_supp (S : finset Λ) : finset Λ' :=
S.bind (λ l, insert (normal l) (tr_stmts₁ (M l)))
local attribute [simp] tr_stmts₁ tr_stmts₁_run supports_run
tr_normal_run TM1.supports_stmt TM2.supports_stmt
theorem tr_supports {S} (ss : TM2.supports M S) :
TM1.supports tr (tr_supp S) :=
⟨finset.mem_bind.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩,
λ l' h, begin
suffices : ∀ q (ss' : TM2.supports_stmt S q)
(sub : ∀ x ∈ tr_stmts₁ M q, x ∈ tr_supp M S),
TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧
(∀ l' ∈ tr_stmts₁ M q, TM1.supports_stmt (tr_supp M S) (tr M l')),
{ rcases finset.mem_bind.1 h with ⟨l, lS, h⟩,
have := this _ (ss.2 l lS) (λ x hx,
finset.mem_bind.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩),
rcases finset.mem_insert.1 h with rfl | h;
[exact this.1, exact this.2 _ h] },
clear h l', refine stmt_st_rec _ _ _ _ _; intros,
{ -- stack op
rw TM2to1.supports_run at ss',
simp only [TM2to1.tr_stmts₁_run, finset.mem_union,
finset.insert_empty_eq_singleton,
finset.mem_insert, finset.mem_singleton] at sub,
have hgo := sub _ (or.inl $ or.inr rfl),
have hret := sub _ (or.inl $ or.inl rfl),
cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂,
refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩,
rw [tr_stmts₁_run] at h,
simp only [TM2to1.tr_stmts₁_run, finset.mem_union,
finset.insert_empty_eq_singleton,
finset.mem_insert, finset.mem_singleton] at h,
rcases h with ⟨rfl | rfl⟩ | h,
{ unfold TM1.supports_stmt TM2to1.tr,
exact ⟨IH₁, λ _ _, hret⟩ },
{ unfold TM1.supports_stmt TM2to1.tr,
rcases s with _|_|_,
{ exact ⟨λ _ _, hret, λ _ _, hgo⟩ },
{ exact ⟨λ _ _, hret, λ _ _, hgo⟩ },
{ exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } },
{ exact IH₂ _ h } },
{ -- load
unfold TM2to1.tr_stmts₁ at ss' sub ⊢,
exact IH ss' sub },
{ -- branch
unfold TM2to1.tr_stmts₁ at sub,
cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂,
cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂,
refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩,
rw [tr_stmts₁] at h,
rcases finset.mem_union.1 h with h | h;
[exact IH₁₂ _ h, exact IH₂₂ _ h] },
{ -- goto
rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt,
unfold TM2.supports_stmt at ss',
exact ⟨λ _ v, finset.mem_bind.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ },
{ exact ⟨trivial, λ _, false.elim⟩ } -- halt
end⟩
end
end TM2to1
end turing
|
23da7fb2f8ff2b7a0f6b774e2694a78f897d14c5 | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/algebra/direct_limit.lean | 178db43c74c18e5d0ef99576a7ee0a03d76a0268 | [
"Apache-2.0"
] | permissive | hamdysalah1/mathlib | b915f86b2503feeae268de369f1b16932321f097 | 95454452f6b3569bf967d35aab8d852b1ddf8017 | refs/heads/master | 1,677,154,116,545 | 1,611,797,994,000 | 1,611,797,994,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,940 | lean | /-
Copyright (c) 2019 Kenny Lau, Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Chris Hughes
-/
import data.finset.order
import linear_algebra.direct_sum_module
import ring_theory.free_comm_ring
import ring_theory.ideal.operations
/-!
# Direct limit of modules, abelian groups, rings, and fields.
See Atiyah-Macdonald PP.32-33, Matsumura PP.269-270
Generalizes the notion of "union", or "gluing", of incomparable modules over the same ring,
or incomparable abelian groups, or rings, or fields.
It is constructed as a quotient of the free module (for the module case) or quotient of
the free commutative ring (for the ring case) instead of a quotient of the disjoint union
so as to make the operations (addition etc.) "computable".
-/
universes u v w u₁
open submodule
variables {R : Type u} [ring R]
variables {ι : Type v}
variables [dec_ι : decidable_eq ι] [directed_order ι]
variables (G : ι → Type w)
/-- A directed system is a functor from the category (directed poset) to another category.
This is used for abelian groups and rings and fields because their maps are not bundled.
See module.directed_system -/
class directed_system (f : Π i j, i ≤ j → G i → G j) : Prop :=
(map_self [] : ∀ i x h, f i i h x = x)
(map_map [] : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x)
namespace module
variables [Π i, add_comm_group (G i)] [Π i, module R (G i)]
/-- A directed system is a functor from the category (directed poset) to the category of
`R`-modules. -/
class directed_system (f : Π i j, i ≤ j → G i →ₗ[R] G j) : Prop :=
(map_self [] : ∀ i x h, f i i h x = x)
(map_map [] : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x)
variables (f : Π i j, i ≤ j → G i →ₗ[R] G j)
include dec_ι
/-- The direct limit of a directed system is the modules glued together along the maps. -/
def direct_limit : Type (max v w) :=
(span R $ { a | ∃ (i j) (H : i ≤ j) x,
direct_sum.lof R ι G i x - direct_sum.lof R ι G j (f i j H x) = a }).quotient
namespace direct_limit
instance : add_comm_group (direct_limit G f) := quotient.add_comm_group _
instance : semimodule R (direct_limit G f) := quotient.semimodule _
instance : inhabited (direct_limit G f) := ⟨0⟩
variables (R ι)
/-- The canonical map from a component to the direct limit. -/
def of (i) : G i →ₗ[R] direct_limit G f :=
(mkq _).comp $ direct_sum.lof R ι G i
variables {R ι G f}
@[simp] lemma of_f {i j hij x} : (of R ι G f j (f i j hij x)) = of R ι G f i x :=
eq.symm $ (submodule.quotient.eq _).2 $ subset_span ⟨i, j, hij, x, rfl⟩
/-- Every element of the direct limit corresponds to some element in
some component of the directed system. -/
theorem exists_of [nonempty ι] (z : direct_limit G f) : ∃ i x, of R ι G f i x = z :=
nonempty.elim (by apply_instance) $ assume ind : ι,
quotient.induction_on' z $ λ z, direct_sum.induction_on z
⟨ind, 0, linear_map.map_zero _⟩
(λ i x, ⟨i, x, rfl⟩)
(λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in
⟨k, f i k hik x + f j k hjk y, by rw [linear_map.map_add, of_f, of_f, ihx, ihy]; refl⟩)
@[elab_as_eliminator]
protected theorem induction_on [nonempty ι] {C : direct_limit G f → Prop} (z : direct_limit G f)
(ih : ∀ i x, C (of R ι G f i x)) : C z :=
let ⟨i, x, h⟩ := exists_of z in h ▸ ih i x
variables {P : Type u₁} [add_comm_group P] [module R P] (g : Π i, G i →ₗ[R] P)
variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x)
include Hg
variables (R ι G f)
/-- The universal property of the direct limit: maps from the components to another module
that respect the directed system structure (i.e. make some diagram commute) give rise
to a unique map out of the direct limit. -/
def lift : direct_limit G f →ₗ[R] P :=
liftq _ (direct_sum.to_module R ι P g)
(span_le.2 $ λ a ⟨i, j, hij, x, hx⟩, by rw [← hx, mem_coe, linear_map.sub_mem_ker_iff,
direct_sum.to_module_lof, direct_sum.to_module_lof, Hg])
variables {R ι G f}
omit Hg
lemma lift_of {i} (x) : lift R ι G f g Hg (of R ι G f i x) = g i x :=
direct_sum.to_module_lof R _ _
theorem lift_unique [nonempty ι] (F : direct_limit G f →ₗ[R] P) (x) :
F x = lift R ι G f (λ i, F.comp $ of R ι G f i)
(λ i j hij x, by rw [linear_map.comp_apply, of_f]; refl) x :=
direct_limit.induction_on x $ λ i x, by rw lift_of; refl
section totalize
open_locale classical
variables (G f)
omit dec_ι
/-- `totalize G f i j` is a linear map from `G i` to `G j`, for *every* `i` and `j`.
If `i ≤ j`, then it is the map `f i j` that comes with the directed system `G`,
and otherwise it is the zero map. -/
noncomputable def totalize : Π i j, G i →ₗ[R] G j :=
λ i j, if h : i ≤ j then f i j h else 0
variables {G f}
lemma totalize_apply (i j x) :
totalize G f i j x = if h : i ≤ j then f i j h x else 0 :=
if h : i ≤ j
then by dsimp only [totalize]; rw [dif_pos h, dif_pos h]
else by dsimp only [totalize]; rw [dif_neg h, dif_neg h, linear_map.zero_apply]
end totalize
variables [directed_system G f]
open_locale classical
lemma to_module_totalize_of_le {x : direct_sum ι G} {i j : ι}
(hij : i ≤ j) (hx : ∀ k ∈ x.support, k ≤ i) :
direct_sum.to_module R ι (G j) (λ k, totalize G f k j) x =
f i j hij (direct_sum.to_module R ι (G i) (λ k, totalize G f k i) x) :=
begin
rw [← @dfinsupp.sum_single ι G _ _ _ x],
unfold dfinsupp.sum,
simp only [linear_map.map_sum],
refine finset.sum_congr rfl (λ k hk, _),
rw direct_sum.single_eq_lof R k (x k),
simp [totalize_apply, hx k hk, le_trans (hx k hk) hij, directed_system.map_map f]
end
lemma of.zero_exact_aux [nonempty ι] {x : direct_sum ι G}
(H : submodule.quotient.mk x = (0 : direct_limit G f)) :
∃ j, (∀ k ∈ x.support, k ≤ j) ∧
direct_sum.to_module R ι (G j) (λ i, totalize G f i j) x = (0 : G j) :=
nonempty.elim (by apply_instance) $ assume ind : ι,
span_induction ((quotient.mk_eq_zero _).1 H)
(λ x ⟨i, j, hij, y, hxy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in
⟨k, begin
clear_,
subst hxy,
split,
{ intros i0 hi0,
rw [dfinsupp.mem_support_iff, direct_sum.sub_apply, ← direct_sum.single_eq_lof,
← direct_sum.single_eq_lof, dfinsupp.single_apply, dfinsupp.single_apply] at hi0,
split_ifs at hi0 with hi hj hj, { rwa hi at hik }, { rwa hi at hik }, { rwa hj at hjk },
exfalso, apply hi0, rw sub_zero },
simp [linear_map.map_sub, totalize_apply, hik, hjk,
directed_system.map_map f, direct_sum.apply_eq_component,
direct_sum.component.of],
end⟩)
⟨ind, λ _ h, (finset.not_mem_empty _ h).elim, linear_map.map_zero _⟩
(λ x y ⟨i, hi, hxi⟩ ⟨j, hj, hyj⟩,
let ⟨k, hik, hjk⟩ := directed_order.directed i j in
⟨k, λ l hl,
(finset.mem_union.1 (dfinsupp.support_add hl)).elim
(λ hl, le_trans (hi _ hl) hik)
(λ hl, le_trans (hj _ hl) hjk),
by simp [linear_map.map_add, hxi, hyj,
to_module_totalize_of_le hik hi,
to_module_totalize_of_le hjk hj]⟩)
(λ a x ⟨i, hi, hxi⟩,
⟨i, λ k hk, hi k (direct_sum.support_smul _ _ hk),
by simp [linear_map.map_smul, hxi]⟩)
/-- A component that corresponds to zero in the direct limit is already zero in some
bigger module in the directed system. -/
theorem of.zero_exact {i x} (H : of R ι G f i x = 0) :
∃ j hij, f i j hij x = (0 : G j) :=
by haveI : nonempty ι := ⟨i⟩; exact
let ⟨j, hj, hxj⟩ := of.zero_exact_aux H in
if hx0 : x = 0 then ⟨i, le_refl _, by simp [hx0]⟩
else
have hij : i ≤ j, from hj _ $
by simp [direct_sum.apply_eq_component, hx0],
⟨j, hij, by simpa [totalize_apply, hij] using hxj⟩
end direct_limit
end module
namespace add_comm_group
variables [Π i, add_comm_group (G i)]
include dec_ι
/-- The direct limit of a directed system is the abelian groups glued together along the maps. -/
def direct_limit (f : Π i j, i ≤ j → G i →+ G j) : Type* :=
@module.direct_limit ℤ _ ι _ _ G _ _
(λ i j hij, (f i j hij).to_int_linear_map)
namespace direct_limit
variables (f : Π i j, i ≤ j → G i →+ G j)
omit dec_ι
protected lemma directed_system [directed_system G (λ i j h, f i j h)] :
module.directed_system G (λ i j hij, (f i j hij).to_int_linear_map) :=
⟨directed_system.map_self (λ i j h, f i j h), directed_system.map_map (λ i j h, f i j h)⟩
include dec_ι
local attribute [instance] direct_limit.directed_system
instance : add_comm_group (direct_limit G f) :=
module.direct_limit.add_comm_group G (λ i j hij, (f i j hij).to_int_linear_map)
instance : inhabited (direct_limit G f) := ⟨0⟩
/-- The canonical map from a component to the direct limit. -/
def of (i) : G i →ₗ[ℤ] direct_limit G f :=
module.direct_limit.of ℤ ι G (λ i j hij, (f i j hij).to_int_linear_map) i
variables {G f}
@[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x :=
module.direct_limit.of_f
@[elab_as_eliminator]
protected theorem induction_on [nonempty ι] {C : direct_limit G f → Prop} (z : direct_limit G f)
(ih : ∀ i x, C (of G f i x)) : C z :=
module.direct_limit.induction_on z ih
/-- A component that corresponds to zero in the direct limit is already zero in some
bigger module in the directed system. -/
theorem of.zero_exact [directed_system G (λ i j h, f i j h)] (i x) (h : of G f i x = 0) :
∃ j hij, f i j hij x = 0 :=
module.direct_limit.of.zero_exact h
variables (P : Type u₁) [add_comm_group P]
variables (g : Π i, G i →+ P)
variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x)
variables (G f)
/-- The universal property of the direct limit: maps from the components to another abelian group
that respect the directed system structure (i.e. make some diagram commute) give rise
to a unique map out of the direct limit. -/
def lift : direct_limit G f →ₗ[ℤ] P :=
module.direct_limit.lift ℤ ι G (λ i j hij, (f i j hij).to_int_linear_map)
(λ i, (g i).to_int_linear_map) Hg
variables {G f}
@[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x :=
module.direct_limit.lift_of _ _ _
lemma lift_unique [nonempty ι] (F : direct_limit G f →+ P) (x) :
F x = lift G f P (λ i, F.comp (of G f i).to_add_monoid_hom)
(λ i j hij x, by simp) x :=
direct_limit.induction_on x $ λ i x, by simp
end direct_limit
end add_comm_group
namespace ring
variables [Π i, comm_ring (G i)]
section
variables (f : Π i j, i ≤ j → G i → G j)
open free_comm_ring
/-- The direct limit of a directed system is the rings glued together along the maps. -/
def direct_limit : Type (max v w) :=
(ideal.span { a |
(∃ i j H x, of (⟨j, f i j H x⟩ : Σ i, G i) - of ⟨i, x⟩ = a) ∨
(∃ i, of (⟨i, 1⟩ : Σ i, G i) - 1 = a) ∨
(∃ i x y, of (⟨i, x + y⟩ : Σ i, G i) - (of ⟨i, x⟩ + of ⟨i, y⟩) = a) ∨
(∃ i x y, of (⟨i, x * y⟩ : Σ i, G i) - (of ⟨i, x⟩ * of ⟨i, y⟩) = a) }).quotient
namespace direct_limit
instance : comm_ring (direct_limit G f) :=
ideal.quotient.comm_ring _
instance : ring (direct_limit G f) :=
comm_ring.to_ring _
instance : inhabited (direct_limit G f) := ⟨0⟩
/-- The canonical map from a component to the direct limit. -/
def of (i) : G i →+* direct_limit G f :=
ring_hom.mk'
{ to_fun := λ x, ideal.quotient.mk _ (of (⟨i, x⟩ : Σ i, G i)),
map_one' := ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inl ⟨i, rfl⟩,
map_mul' := λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inr ⟨i, x, y, rfl⟩, }
(λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inl ⟨i, x, y, rfl⟩)
variables {G f}
@[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x :=
ideal.quotient.eq.2 $ subset_span $ or.inl ⟨i, j, hij, x, rfl⟩
/-- Every element of the direct limit corresponds to some element in
some component of the directed system. -/
theorem exists_of [nonempty ι] (z : direct_limit G f) : ∃ i x, of G f i x = z :=
nonempty.elim (by apply_instance) $ assume ind : ι,
quotient.induction_on' z $ λ x, free_abelian_group.induction_on x
⟨ind, 0, (of _ _ ind).map_zero⟩
(λ s, multiset.induction_on s
⟨ind, 1, (of _ _ ind).map_one⟩
(λ a s ih, let ⟨i, x⟩ := a, ⟨j, y, hs⟩ := ih, ⟨k, hik, hjk⟩ := directed_order.directed i j in
⟨k, f i k hik x * f j k hjk y, by rw [(of _ _ _).map_mul, of_f, of_f, hs]; refl⟩))
(λ s ⟨i, x, ih⟩, ⟨i, -x, by rw [(of _ _ _).map_neg, ih]; refl⟩)
(λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in
⟨k, f i k hik x + f j k hjk y, by rw [(of _ _ _).map_add, of_f, of_f, ihx, ihy]; refl⟩)
section
open_locale classical
open polynomial
variables {f' : Π i j, i ≤ j → G i →+* G j}
theorem polynomial.exists_of [nonempty ι] (q : polynomial (direct_limit G (λ i j h, f' i j h))) :
∃ i p, polynomial.map (of G (λ i j h, f' i j h) i) p = q :=
polynomial.induction_on q
(λ z, let ⟨i, x, h⟩ := exists_of z in ⟨i, C x, by rw [map_C, h]⟩)
(λ q₁ q₂ ⟨i₁, p₁, ih₁⟩ ⟨i₂, p₂, ih₂⟩, let ⟨i, h1, h2⟩ := directed_order.directed i₁ i₂ in
⟨i, p₁.map (f' i₁ i h1) + p₂.map (f' i₂ i h2),
by { rw [polynomial.map_add, map_map, map_map, ← ih₁, ← ih₂],
congr' 2; ext x; simp_rw [ring_hom.comp_apply, of_f] }⟩)
(λ n z ih, let ⟨i, x, h⟩ := exists_of z in ⟨i, C x * X ^ (n + 1),
by rw [polynomial.map_mul, map_C, h, polynomial.map_pow, map_X]⟩)
end
@[elab_as_eliminator] theorem induction_on [nonempty ι] {C : direct_limit G f → Prop}
(z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z :=
let ⟨i, x, hx⟩ := exists_of z in hx ▸ ih i x
section of_zero_exact
open_locale classical
variables (f' : Π i j, i ≤ j → G i →+* G j)
variables [directed_system G (λ i j h, f' i j h)]
variables (G f)
lemma of.zero_exact_aux2 {x : free_comm_ring Σ i, G i} {s t} (hxs : is_supported x s) {j k}
(hj : ∀ z : Σ i, G i, z ∈ s → z.1 ≤ j) (hk : ∀ z : Σ i, G i, z ∈ t → z.1 ≤ k)
(hjk : j ≤ k) (hst : s ⊆ t) :
f' j k hjk (lift (λ ix : s, f' ix.1.1 j (hj ix ix.2) ix.1.2) (restriction s x)) =
lift (λ ix : t, f' ix.1.1 k (hk ix ix.2) ix.1.2) (restriction t x) :=
begin
refine ring.in_closure.rec_on hxs _ _ _ _,
{ rw [(restriction _).map_one, (free_comm_ring.lift _).map_one, (f' j k hjk).map_one,
(restriction _).map_one, (free_comm_ring.lift _).map_one] },
{ rw [(restriction _).map_neg, (restriction _).map_one,
(free_comm_ring.lift _).map_neg, (free_comm_ring.lift _).map_one,
(f' j k hjk).map_neg, (f' j k hjk).map_one,
(restriction _).map_neg, (restriction _).map_one,
(free_comm_ring.lift _).map_neg, (free_comm_ring.lift _).map_one] },
{ rintros _ ⟨p, hps, rfl⟩ n ih,
rw [(restriction _).map_mul, (free_comm_ring.lift _).map_mul,
(f' j k hjk).map_mul, ih,
(restriction _).map_mul, (free_comm_ring.lift _).map_mul,
restriction_of, dif_pos hps, lift_of, restriction_of, dif_pos (hst hps), lift_of],
dsimp only,
have := directed_system.map_map (λ i j h, f' i j h),
dsimp only at this,
rw this, refl },
{ rintros x y ihx ihy,
rw [(restriction _).map_add, (free_comm_ring.lift _).map_add,
(f' j k hjk).map_add, ihx, ihy,
(restriction _).map_add, (free_comm_ring.lift _).map_add] }
end
variables {G f f'}
lemma of.zero_exact_aux [nonempty ι] {x : free_comm_ring Σ i, G i}
(H : ideal.quotient.mk _ x = (0 : direct_limit G (λ i j h, f' i j h))) :
∃ j s, ∃ H : (∀ k : Σ i, G i, k ∈ s → k.1 ≤ j), is_supported x s ∧
lift (λ ix : s, f' ix.1.1 j (H ix ix.2) ix.1.2) (restriction s x) = (0 : G j) :=
begin
refine span_induction (ideal.quotient.eq_zero_iff_mem.1 H) _ _ _ _,
{ rintros x (⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩),
{ refine ⟨j, {⟨i, x⟩, ⟨j, f' i j hij x⟩}, _,
is_supported_sub (is_supported_of.2 $ or.inr rfl) (is_supported_of.2 $ or.inl rfl), _⟩,
{ rintros k (rfl | ⟨rfl | _⟩), exact hij, refl },
{ rw [(restriction _).map_sub, (free_comm_ring.lift _).map_sub,
restriction_of, dif_pos, restriction_of, dif_pos, lift_of, lift_of],
dsimp only,
have := directed_system.map_map (λ i j h, f' i j h),
dsimp only at this,
rw this, exact sub_self _,
exacts [or.inr rfl, or.inl rfl] } },
{ refine ⟨i, {⟨i, 1⟩}, _, is_supported_sub (is_supported_of.2 rfl) is_supported_one, _⟩,
{ rintros k (rfl|h), refl },
{ rw [(restriction _).map_sub, (free_comm_ring.lift _).map_sub, restriction_of, dif_pos,
(restriction _).map_one, lift_of, (free_comm_ring.lift _).map_one],
dsimp only, rw [(f' i i _).map_one, sub_self],
{ exact set.mem_singleton _ } } },
{ refine ⟨i, {⟨i, x+y⟩, ⟨i, x⟩, ⟨i, y⟩}, _,
is_supported_sub (is_supported_of.2 $ or.inl rfl)
(is_supported_add (is_supported_of.2 $ or.inr $ or.inl rfl)
(is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩,
{ rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl },
{ rw [(restriction _).map_sub, (restriction _).map_add,
restriction_of, restriction_of, restriction_of,
dif_pos, dif_pos, dif_pos,
(free_comm_ring.lift _).map_sub, (free_comm_ring.lift _).map_add,
lift_of, lift_of, lift_of],
dsimp only, rw (f' i i _).map_add, exact sub_self _,
exacts [or.inl rfl, or.inr (or.inr rfl), or.inr (or.inl rfl)] } },
{ refine ⟨i, {⟨i, x*y⟩, ⟨i, x⟩, ⟨i, y⟩}, _,
is_supported_sub (is_supported_of.2 $ or.inl rfl)
(is_supported_mul (is_supported_of.2 $ or.inr $ or.inl rfl)
(is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩,
{ rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl },
{ rw [(restriction _).map_sub, (restriction _).map_mul,
restriction_of, restriction_of, restriction_of,
dif_pos, dif_pos, dif_pos,
(free_comm_ring.lift _).map_sub, (free_comm_ring.lift _).map_mul,
lift_of, lift_of, lift_of],
dsimp only, rw (f' i i _).map_mul,
exacts [sub_self _, or.inl rfl, or.inr (or.inr rfl),
or.inr (or.inl rfl)] } } },
{ refine nonempty.elim (by apply_instance) (assume ind : ι, _),
refine ⟨ind, ∅, λ _, false.elim, is_supported_zero, _⟩,
rw [(restriction _).map_zero, (free_comm_ring.lift _).map_zero] },
{ rintros x y ⟨i, s, hi, hxs, ihs⟩ ⟨j, t, hj, hyt, iht⟩,
rcases directed_order.directed i j with ⟨k, hik, hjk⟩,
have : ∀ z : Σ i, G i, z ∈ s ∪ t → z.1 ≤ k,
{ rintros z (hz | hz), exact le_trans (hi z hz) hik, exact le_trans (hj z hz) hjk },
refine ⟨k, s ∪ t, this, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t)
(is_supported_upwards hyt $ set.subset_union_right s t), _⟩,
{ rw [(restriction _).map_add, (free_comm_ring.lift _).map_add,
← of.zero_exact_aux2 G f' hxs hi this hik (set.subset_union_left s t),
← of.zero_exact_aux2 G f' hyt hj this hjk (set.subset_union_right s t),
ihs, (f' i k hik).map_zero, iht, (f' j k hjk).map_zero, zero_add] } },
{ rintros x y ⟨j, t, hj, hyt, iht⟩, rw smul_eq_mul,
rcases exists_finset_support x with ⟨s, hxs⟩,
rcases (s.image sigma.fst).exists_le with ⟨i, hi⟩,
rcases directed_order.directed i j with ⟨k, hik, hjk⟩,
have : ∀ z : Σ i, G i, z ∈ ↑s ∪ t → z.1 ≤ k,
{ rintros z (hz | hz),
exacts [(hi z.1 $ finset.mem_image.2 ⟨z, hz, rfl⟩).trans hik, (hj z hz).trans hjk] },
refine ⟨k, ↑s ∪ t, this, is_supported_mul
(is_supported_upwards hxs $ set.subset_union_left ↑s t)
(is_supported_upwards hyt $ set.subset_union_right ↑s t), _⟩,
rw [(restriction _).map_mul, (free_comm_ring.lift _).map_mul,
← of.zero_exact_aux2 G f' hyt hj this hjk (set.subset_union_right ↑s t),
iht, (f' j k hjk).map_zero, mul_zero] }
end
/-- A component that corresponds to zero in the direct limit is already zero in some
bigger module in the directed system. -/
lemma of.zero_exact {i x} (hix : of G (λ i j h, f' i j h) i x = 0) :
∃ j (hij : i ≤ j), f' i j hij x = 0 :=
by haveI : nonempty ι := ⟨i⟩; exact
let ⟨j, s, H, hxs, hx⟩ := of.zero_exact_aux hix in
have hixs : (⟨i, x⟩ : Σ i, G i) ∈ s, from is_supported_of.1 hxs,
⟨j, H ⟨i, x⟩ hixs, by rw [restriction_of, dif_pos hixs, lift_of] at hx; exact hx⟩
end of_zero_exact
variables (f' : Π i j, i ≤ j → G i →+* G j)
/-- If the maps in the directed system are injective, then the canonical maps
from the components to the direct limits are injective. -/
theorem of_injective [directed_system G (λ i j h, f' i j h)]
(hf : ∀ i j hij, function.injective (f' i j hij)) (i) :
function.injective (of G (λ i j h, f' i j h) i) :=
begin
suffices : ∀ x, of G (λ i j h, f' i j h) i x = 0 → x = 0,
{ intros x y hxy, rw ← sub_eq_zero_iff_eq, apply this,
rw [(of G _ i).map_sub, hxy, sub_self] },
intros x hx, rcases of.zero_exact hx with ⟨j, hij, hfx⟩,
apply hf i j hij, rw [hfx, (f' i j hij).map_zero]
end
variables (P : Type u₁) [comm_ring P]
variables (g : Π i, G i →+* P)
variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x)
include Hg
open free_comm_ring
variables (G f)
/-- The universal property of the direct limit: maps from the components to another ring
that respect the directed system structure (i.e. make some diagram commute) give rise
to a unique map out of the direct limit.
-/
def lift : direct_limit G f →+* P :=
ideal.quotient.lift _ (free_comm_ring.lift $ λ x, g x.1 x.2) begin
suffices : ideal.span _ ≤
ideal.comap (free_comm_ring.lift (λ (x : Σ (i : ι), G i), g (x.fst) (x.snd))) ⊥,
{ intros x hx, exact (mem_bot P).1 (this hx) },
rw ideal.span_le, intros x hx,
rw [mem_coe, ideal.mem_comap, mem_bot],
rcases hx with ⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩;
simp only [ring_hom.map_sub, lift_of, Hg, ring_hom.map_one, ring_hom.map_add, ring_hom.map_mul,
(g i).map_one, (g i).map_add, (g i).map_mul, sub_self]
end
variables {G f}
omit Hg
@[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := free_comm_ring.lift_of _ _
theorem lift_unique [nonempty ι] (F : direct_limit G f →+* P) (x) :
F x = lift G f P (λ i, F.comp $ of G f i) (λ i j hij x, by simp) x :=
direct_limit.induction_on x $ λ i x, by simp
end direct_limit
end
end ring
namespace field
variables [nonempty ι] [Π i, field (G i)]
variables (f : Π i j, i ≤ j → G i → G j)
variables (f' : Π i j, i ≤ j → G i →+* G j)
namespace direct_limit
instance nontrivial [directed_system G (λ i j h, f' i j h)] :
nontrivial (ring.direct_limit G (λ i j h, f' i j h)) :=
⟨⟨0, 1, nonempty.elim (by apply_instance) $ assume i : ι, begin
change (0 : ring.direct_limit G (λ i j h, f' i j h)) ≠ 1,
rw ← (ring.direct_limit.of _ _ _).map_one,
intros H, rcases ring.direct_limit.of.zero_exact H.symm with ⟨j, hij, hf⟩,
rw (f' i j hij).map_one at hf,
exact one_ne_zero hf
end ⟩⟩
theorem exists_inv {p : ring.direct_limit G f} : p ≠ 0 → ∃ y, p * y = 1 :=
ring.direct_limit.induction_on p $ λ i x H,
⟨ring.direct_limit.of G f i (x⁻¹), by erw [← (ring.direct_limit.of _ _ _).map_mul,
mul_inv_cancel (assume h : x = 0, H $ by rw [h, (ring.direct_limit.of _ _ _).map_zero]),
(ring.direct_limit.of _ _ _).map_one]⟩
section
open_locale classical
/-- Noncomputable multiplicative inverse in a direct limit of fields. -/
noncomputable def inv (p : ring.direct_limit G f) : ring.direct_limit G f :=
if H : p = 0 then 0 else classical.some (direct_limit.exists_inv G f H)
protected theorem mul_inv_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : p * inv G f p = 1 :=
by rw [inv, dif_neg hp, classical.some_spec (direct_limit.exists_inv G f hp)]
protected theorem inv_mul_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : inv G f p * p = 1 :=
by rw [_root_.mul_comm, direct_limit.mul_inv_cancel G f hp]
/-- Noncomputable field structure on the direct limit of fields. -/
protected noncomputable def field [directed_system G (λ i j h, f' i j h)] :
field (ring.direct_limit G (λ i j h, f' i j h)) :=
{ inv := inv G (λ i j h, f' i j h),
mul_inv_cancel := λ p, direct_limit.mul_inv_cancel G (λ i j h, f' i j h),
inv_zero := dif_pos rfl,
.. ring.direct_limit.comm_ring G (λ i j h, f' i j h),
.. direct_limit.nontrivial G (λ i j h, f' i j h) }
end
end direct_limit
end field
|
0306b1ca201432df4d056d4bb2eac1c187bcc53a | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/set/function.lean | 99872f8d59cf832d610f3c955c9442296fbd30ae | [
"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,902 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu, Yury Kudryashov
-/
import data.set.basic
import logic.function.conjugate
/-!
# Functions over sets
## Main definitions
### Predicate
* `eq_on f₁ f₂ s` : functions `f₁` and `f₂` are equal at every point of `s`;
* `maps_to f s t` : `f` sends every point of `s` to a point of `t`;
* `inj_on f s` : restriction of `f` to `s` is injective;
* `surj_on f s t` : every point in `s` has a preimage in `s`;
* `bij_on f s t` : `f` is a bijection between `s` and `t`;
* `left_inv_on f' f s` : for every `x ∈ s` we have `f' (f x) = x`;
* `right_inv_on f' f t` : for every `y ∈ t` we have `f (f' y) = y`;
* `inv_on f' f s t` : `f'` is a two-side inverse of `f` on `s` and `t`, i.e.
we have `left_inv_on f' f s` and `right_inv_on f' f t`.
### Functions
* `restrict f s` : restrict the domain of `f` to the set `s`;
* `cod_restrict f s h` : given `h : ∀ x, f x ∈ s`, restrict the codomain of `f` to the set `s`;
* `maps_to.restrict f s t h`: given `h : maps_to f s t`, restrict the domain of `f` to `s`
and the codomain to `t`.
-/
universes u v w x y
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
open function
namespace set
/-! ### Restrict -/
/-- Restrict domain of a function `f` to a set `s`. Same as `subtype.restrict` but this version
takes an argument `↥s` instead of `subtype s`. -/
def restrict (f : α → β) (s : set α) : s → β := λ x, f x
lemma restrict_eq (f : α → β) (s : set α) : s.restrict f = f ∘ coe := rfl
@[simp] lemma restrict_apply (f : α → β) (s : set α) (x : s) : restrict f s x = f x := rfl
@[simp] lemma range_restrict (f : α → β) (s : set α) : set.range (restrict f s) = f '' s :=
range_comp.trans $ congr_arg (('') f) subtype.range_coe
/-- Restrict codomain of a function `f` to a set `s`. Same as `subtype.coind` but this version
has codomain `↥s` instead of `subtype s`. -/
def cod_restrict (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) : α → s :=
λ x, ⟨f x, h x⟩
@[simp] lemma coe_cod_restrict_apply (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) (x : α) :
(cod_restrict f s h x : β) = f x :=
rfl
variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} {p : set γ} {f f₁ f₂ f₃ : α → β} {g : β → γ}
{f' f₁' f₂' : β → α} {g' : γ → β}
/-! ### Equality on a set -/
/-- Two functions `f₁ f₂ : α → β` are equal on `s`
if `f₁ x = f₂ x` for all `x ∈ a`. -/
@[reducible] def eq_on (f₁ f₂ : α → β) (s : set α) : Prop :=
∀ ⦃x⦄, x ∈ s → f₁ x = f₂ x
@[symm] lemma eq_on.symm (h : eq_on f₁ f₂ s) : eq_on f₂ f₁ s :=
λ x hx, (h hx).symm
lemma eq_on_comm : eq_on f₁ f₂ s ↔ eq_on f₂ f₁ s :=
⟨eq_on.symm, eq_on.symm⟩
@[refl] lemma eq_on_refl (f : α → β) (s : set α) : eq_on f f s :=
λ _ _, rfl
@[trans] lemma eq_on.trans (h₁ : eq_on f₁ f₂ s) (h₂ : eq_on f₂ f₃ s) : eq_on f₁ f₃ s :=
λ x hx, (h₁ hx).trans (h₂ hx)
theorem eq_on.image_eq (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s :=
image_congr heq
lemma eq_on.mono (hs : s₁ ⊆ s₂) (hf : eq_on f₁ f₂ s₂) : eq_on f₁ f₂ s₁ :=
λ x hx, hf (hs hx)
lemma comp_eq_of_eq_on_range {ι : Sort*} {f : ι → α} {g₁ g₂ : α → β} (h : eq_on g₁ g₂ (range f)) :
g₁ ∘ f = g₂ ∘ f :=
funext $ λ x, h $ mem_range_self _
/-! ### maps to -/
/-- `maps_to f a b` means that the image of `a` is contained in `b`. -/
@[reducible] def maps_to (f : α → β) (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ s → f x ∈ t
/-- Given a map `f` sending `s : set α` into `t : set β`, restrict domain of `f` to `s`
and the codomain to `t`. Same as `subtype.map`. -/
def maps_to.restrict (f : α → β) (s : set α) (t : set β) (h : maps_to f s t) :
s → t :=
subtype.map f h
@[simp] lemma maps_to.coe_restrict_apply (h : maps_to f s t) (x : s) :
(h.restrict f s t x : β) = f x := rfl
theorem maps_to' : maps_to f s t ↔ f '' s ⊆ t :=
image_subset_iff.symm
theorem maps_to_empty (f : α → β) (t : set β) : maps_to f ∅ t := empty_subset _
theorem maps_to.image_subset (h : maps_to f s t) : f '' s ⊆ t :=
maps_to'.1 h
theorem maps_to.congr (h₁ : maps_to f₁ s t) (h : eq_on f₁ f₂ s) :
maps_to f₂ s t :=
λ x hx, h hx ▸ h₁ hx
theorem eq_on.maps_to_iff (H : eq_on f₁ f₂ s) : maps_to f₁ s t ↔ maps_to f₂ s t :=
⟨λ h, h.congr H, λ h, h.congr H.symm⟩
theorem maps_to.comp (h₁ : maps_to g t p) (h₂ : maps_to f s t) : maps_to (g ∘ f) s p :=
λ x h, h₁ (h₂ h)
theorem maps_to.iterate {f : α → α} {s : set α} (h : maps_to f s s) :
∀ n, maps_to (f^[n]) s s
| 0 := λ _, id
| (n+1) := (maps_to.iterate n).comp h
theorem maps_to.iterate_restrict {f : α → α} {s : set α} (h : maps_to f s s) (n : ℕ) :
(h.restrict f s s^[n]) = (h.iterate n).restrict _ _ _ :=
begin
funext x,
rw [subtype.ext_iff, maps_to.coe_restrict_apply],
induction n with n ihn generalizing x,
{ refl },
{ simp [nat.iterate, ihn] }
end
theorem maps_to.mono (hs : s₂ ⊆ s₁) (ht : t₁ ⊆ t₂) (hf : maps_to f s₁ t₁) :
maps_to f s₂ t₂ :=
λ x hx, ht (hf $ hs hx)
theorem maps_to.union_union (h₁ : maps_to f s₁ t₁) (h₂ : maps_to f s₂ t₂) :
maps_to f (s₁ ∪ s₂) (t₁ ∪ t₂) :=
λ x hx, hx.elim (λ hx, or.inl $ h₁ hx) (λ hx, or.inr $ h₂ hx)
theorem maps_to.union (h₁ : maps_to f s₁ t) (h₂ : maps_to f s₂ t) :
maps_to f (s₁ ∪ s₂) t :=
union_self t ▸ h₁.union_union h₂
theorem maps_to.inter (h₁ : maps_to f s t₁) (h₂ : maps_to f s t₂) :
maps_to f s (t₁ ∩ t₂) :=
λ x hx, ⟨h₁ hx, h₂ hx⟩
theorem maps_to.inter_inter (h₁ : maps_to f s₁ t₁) (h₂ : maps_to f s₂ t₂) :
maps_to f (s₁ ∩ s₂) (t₁ ∩ t₂) :=
λ x hx, ⟨h₁ hx.1, h₂ hx.2⟩
theorem maps_to_univ (f : α → β) (s : set α) : maps_to f s univ := λ x h, trivial
theorem maps_to_image (f : α → β) (s : set α) : maps_to f s (f '' s) := by rw maps_to'
theorem maps_to_preimage (f : α → β) (t : set β) : maps_to f (f ⁻¹' t) t := subset.refl _
theorem maps_to_range (f : set α) (s : set α) : maps_to f s (range f) :=
(maps_to_image f s).mono (subset.refl s) (image_subset_range _ _)
/-! ### Injectivity on a set -/
/-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/
@[reducible] def inj_on (f : α → β) (s : set α) : Prop :=
∀ ⦃x₁ : α⦄, x₁ ∈ s → ∀ ⦃x₂ : α⦄, x₂ ∈ s → f x₁ = f x₂ → x₁ = x₂
theorem inj_on_empty (f : α → β) : inj_on f ∅ :=
λ _ h₁, false.elim h₁
theorem inj_on.congr (h₁ : inj_on f₁ s) (h : eq_on f₁ f₂ s) :
inj_on f₂ s :=
λ x hx y hy, h hx ▸ h hy ▸ h₁ hx hy
theorem eq_on.inj_on_iff (H : eq_on f₁ f₂ s) : inj_on f₁ s ↔ inj_on f₂ s :=
⟨λ h, h.congr H, λ h, h.congr H.symm⟩
theorem inj_on.mono (h : s₁ ⊆ s₂) (ht : inj_on f s₂) : inj_on f s₁ :=
λ x hx y hy H, ht (h hx) (h hy) H
theorem inj_on_insert {f : α → β} {s : set α} {a : α} (has : a ∉ s) :
set.inj_on f (insert a s) ↔ set.inj_on f s ∧ f a ∉ f '' s :=
⟨λ hf, ⟨hf.mono $ subset_insert a s,
λ ⟨x, hxs, hx⟩, has $ mem_of_eq_of_mem (hf (or.inl rfl) (or.inr hxs) hx.symm) hxs⟩,
λ ⟨h1, h2⟩ x hx y hy hfxy, or.cases_on hx
(λ hxa : x = a, or.cases_on hy
(λ hya : y = a, hxa.trans hya.symm)
(λ hys : y ∈ s, h2.elim ⟨y, hys, hxa ▸ hfxy.symm⟩))
(λ hxs : x ∈ s, or.cases_on hy
(λ hya : y = a, h2.elim ⟨x, hxs, hya ▸ hfxy⟩)
(λ hys : y ∈ s, h1 hxs hys hfxy))⟩
lemma injective_iff_inj_on_univ : injective f ↔ inj_on f univ :=
⟨λ h x hx y hy hxy, h hxy, λ h _ _ heq, h trivial trivial heq⟩
theorem inj_on.comp (hg : inj_on g t) (hf: inj_on f s) (h : maps_to f s t) :
inj_on (g ∘ f) s :=
λ x hx y hy heq, hf hx hy $ hg (h hx) (h hy) heq
lemma inj_on_iff_injective : inj_on f s ↔ injective (restrict f s) :=
⟨λ H a b h, subtype.eq $ H a.2 b.2 h,
λ H a as b bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩
lemma inj_on.inv_fun_on_image [nonempty α] (h : inj_on f s₂) (ht : s₁ ⊆ s₂) :
(inv_fun_on f s₂) '' (f '' s₁) = s₁ :=
begin
have : eq_on ((inv_fun_on f s₂) ∘ f) id s₁, from λz hz, inv_fun_on_eq' h (ht hz),
rw [← image_comp, this.image_eq, image_id]
end
lemma inj_on_preimage {B : set (set β)} (hB : B ⊆ powerset (range f)) :
inj_on (preimage f) B :=
λ s hs t ht hst, (preimage_eq_preimage' (hB hs) (hB ht)).1 hst
/-! ### Surjectivity on a set -/
/-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/
@[reducible] def surj_on (f : α → β) (s : set α) (t : set β) : Prop := t ⊆ f '' s
theorem surj_on.subset_range (h : surj_on f s t) : t ⊆ range f :=
subset.trans h $ image_subset_range f s
theorem surj_on_empty (f : α → β) (s : set α) : surj_on f s ∅ := empty_subset _
theorem surj_on.comap_nonempty (h : surj_on f s t) (ht : t.nonempty) : s.nonempty :=
(ht.mono h).of_image
theorem surj_on.congr (h : surj_on f₁ s t) (H : eq_on f₁ f₂ s) : surj_on f₂ s t :=
by rwa [surj_on, ← H.image_eq]
theorem eq_on.surj_on_iff (h : eq_on f₁ f₂ s) : surj_on f₁ s t ↔ surj_on f₂ s t :=
⟨λ H, H.congr h, λ H, H.congr h.symm⟩
theorem surj_on.mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (hf : surj_on f s₁ t₂) : surj_on f s₂ t₁ :=
subset.trans ht $ subset.trans hf $ image_subset _ hs
theorem surj_on.union (h₁ : surj_on f s t₁) (h₂ : surj_on f s t₂) : surj_on f s (t₁ ∪ t₂) :=
λ x hx, hx.elim (λ hx, h₁ hx) (λ hx, h₂ hx)
theorem surj_on.union_union (h₁ : surj_on f s₁ t₁) (h₂ : surj_on f s₂ t₂) :
surj_on f (s₁ ∪ s₂) (t₁ ∪ t₂) :=
(h₁.mono (subset_union_left _ _) (subset.refl _)).union
(h₂.mono (subset_union_right _ _) (subset.refl _))
theorem surj_on.inter_inter (h₁ : surj_on f s₁ t₁) (h₂ : surj_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) :
surj_on f (s₁ ∩ s₂) (t₁ ∩ t₂) :=
begin
intros y hy,
rcases h₁ hy.1 with ⟨x₁, hx₁, rfl⟩,
rcases h₂ hy.2 with ⟨x₂, hx₂, heq⟩,
have : x₁ = x₂, from h (or.inl hx₁) (or.inr hx₂) heq.symm,
subst x₂,
exact mem_image_of_mem f ⟨hx₁, hx₂⟩
end
theorem surj_on.inter (h₁ : surj_on f s₁ t) (h₂ : surj_on f s₂ t) (h : inj_on f (s₁ ∪ s₂)) :
surj_on f (s₁ ∩ s₂) t :=
inter_self t ▸ h₁.inter_inter h₂ h
theorem surj_on.comp (hg : surj_on g t p) (hf : surj_on f s t) : surj_on (g ∘ f) s p :=
subset.trans hg $ subset.trans (image_subset g hf) $ (image_comp g f s) ▸ subset.refl _
lemma surjective_iff_surj_on_univ : surjective f ↔ surj_on f univ univ :=
by simp [surjective, surj_on, subset_def]
lemma surj_on_iff_surjective : surj_on f s univ ↔ surjective (restrict f s) :=
⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩,
λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩
lemma surj_on.image_eq_of_maps_to (h₁ : surj_on f s t) (h₂ : maps_to f s t) :
f '' s = t :=
eq_of_subset_of_subset h₂.image_subset h₁
/-! ### Bijectivity -/
/-- `f` is bijective from `s` to `t` if `f` is injective on `s` and `f '' s = t`. -/
@[reducible] def bij_on (f : α → β) (s : set α) (t : set β) : Prop :=
maps_to f s t ∧ inj_on f s ∧ surj_on f s t
lemma bij_on.maps_to (h : bij_on f s t) : maps_to f s t := h.left
lemma bij_on.inj_on (h : bij_on f s t) : inj_on f s := h.right.left
lemma bij_on.surj_on (h : bij_on f s t) : surj_on f s t := h.right.right
lemma bij_on.mk (h₁ : maps_to f s t) (h₂ : inj_on f s) (h₃ : surj_on f s t) :
bij_on f s t :=
⟨h₁, h₂, h₃⟩
lemma bij_on_empty (f : α → β) : bij_on f ∅ ∅ :=
⟨maps_to_empty f ∅, inj_on_empty f, surj_on_empty f ∅⟩
lemma bij_on.inter (h₁ : bij_on f s₁ t₁) (h₂ : bij_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) :
bij_on f (s₁ ∩ s₂) (t₁ ∩ t₂) :=
⟨h₁.maps_to.inter_inter h₂.maps_to, h₁.inj_on.mono $ inter_subset_left _ _,
h₁.surj_on.inter_inter h₂.surj_on h⟩
lemma bij_on.union (h₁ : bij_on f s₁ t₁) (h₂ : bij_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) :
bij_on f (s₁ ∪ s₂) (t₁ ∪ t₂) :=
⟨h₁.maps_to.union_union h₂.maps_to, h, h₁.surj_on.union_union h₂.surj_on⟩
theorem bij_on.subset_range (h : bij_on f s t) : t ⊆ range f :=
h.surj_on.subset_range
lemma inj_on.bij_on_image (h : inj_on f s) : bij_on f s (f '' s) :=
bij_on.mk (maps_to_image f s) h (subset.refl _)
theorem bij_on.congr (h₁ : bij_on f₁ s t) (h : eq_on f₁ f₂ s) :
bij_on f₂ s t :=
bij_on.mk (h₁.maps_to.congr h) (h₁.inj_on.congr h) (h₁.surj_on.congr h)
theorem eq_on.bij_on_iff (H : eq_on f₁ f₂ s) : bij_on f₁ s t ↔ bij_on f₂ s t :=
⟨λ h, h.congr H, λ h, h.congr H.symm⟩
lemma bij_on.image_eq (h : bij_on f s t) :
f '' s = t :=
h.surj_on.image_eq_of_maps_to h.maps_to
theorem bij_on.comp (hg : bij_on g t p) (hf : bij_on f s t) : bij_on (g ∘ f) s p :=
bij_on.mk (hg.maps_to.comp hf.maps_to) (hg.inj_on.comp hf.inj_on hf.maps_to)
(hg.surj_on.comp hf.surj_on)
lemma bijective_iff_bij_on_univ : bijective f ↔ bij_on f univ univ :=
iff.intro
(λ h, let ⟨inj, surj⟩ := h in
⟨maps_to_univ f _, iff.mp injective_iff_inj_on_univ inj, iff.mp surjective_iff_surj_on_univ surj⟩)
(λ h, let ⟨map, inj, surj⟩ := h in
⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩)
/-! ### left inverse -/
/-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/
@[reducible] def left_inv_on (f' : β → α) (f : α → β) (s : set α) : Prop :=
∀ ⦃x⦄, x ∈ s → f' (f x) = x
lemma left_inv_on.eq_on (h : left_inv_on f' f s) : eq_on (f' ∘ f) id s := h
lemma left_inv_on.eq (h : left_inv_on f' f s) {x} (hx : x ∈ s) : f' (f x) = x := h hx
lemma left_inv_on.congr_left (h₁ : left_inv_on f₁' f s)
{t : set β} (h₁' : maps_to f s t) (heq : eq_on f₁' f₂' t) : left_inv_on f₂' f s :=
λ x hx, heq (h₁' hx) ▸ h₁ hx
theorem left_inv_on.congr_right (h₁ : left_inv_on f₁' f₁ s) (heq : eq_on f₁ f₂ s) :
left_inv_on f₁' f₂ s :=
λ x hx, heq hx ▸ h₁ hx
theorem left_inv_on.inj_on (h : left_inv_on f₁' f s) : inj_on f s :=
λ x₁ h₁ x₂ h₂ heq,
calc
x₁ = f₁' (f x₁) : eq.symm $ h h₁
... = f₁' (f x₂) : congr_arg f₁' heq
... = x₂ : h h₂
theorem left_inv_on.surj_on (h : left_inv_on f₁' f s) (hf : maps_to f s t) : surj_on f₁' t s :=
λ x hx, ⟨f x, hf hx, h hx⟩
theorem left_inv_on.comp (hf' : left_inv_on f' f s) (hg' : left_inv_on g' g t) (hf : maps_to f s t) :
left_inv_on (f' ∘ g') (g ∘ f) s :=
λ x h,
calc
(f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (hg' (hf h))
... = x : hf' h
/-! ### Right inverse -/
/-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/
@[reducible] def right_inv_on (f' : β → α) (f : α → β) (t : set β) : Prop :=
left_inv_on f f' t
lemma right_inv_on.eq_on (h : right_inv_on f' f t) : eq_on (f ∘ f') id t := h
lemma right_inv_on.eq (h : right_inv_on f' f t) {y} (hy : y ∈ t) : f (f' y) = y := h hy
theorem right_inv_on.congr_left (h₁ : right_inv_on f₁' f t) (heq : eq_on f₁' f₂' t) :
right_inv_on f₂' f t :=
h₁.congr_right heq
theorem right_inv_on.congr_right (h₁ : right_inv_on f' f₁ t) (hg : maps_to f' t s)
(heq : eq_on f₁ f₂ s) : right_inv_on f' f₂ t :=
left_inv_on.congr_left h₁ hg heq
theorem right_inv_on.surj_on (hf : right_inv_on f' f t) (hf' : maps_to f' t s) :
surj_on f s t :=
hf.surj_on hf'
theorem right_inv_on.comp (hf : right_inv_on f' f t) (hg : right_inv_on g' g p)
(g'pt : maps_to g' p t) : right_inv_on (f' ∘ g') (g ∘ f) p :=
hg.comp hf g'pt
theorem inj_on.right_inv_on_of_left_inv_on (hf : inj_on f s) (hf' : left_inv_on f f' t)
(h₁ : maps_to f s t) (h₂ : maps_to f' t s) :
right_inv_on f f' s :=
λ x h, hf (h₂ $ h₁ h) h (hf' (h₁ h))
theorem eq_on_of_left_inv_on_of_right_inv_on (h₁ : left_inv_on f₁' f s) (h₂ : right_inv_on f₂' f t)
(h : maps_to f₂' t s) : eq_on f₁' f₂' t :=
λ y hy,
calc f₁' y = (f₁' ∘ f ∘ f₂') y : congr_arg f₁' (h₂ hy).symm
... = f₂' y : h₁ (h hy)
theorem surj_on.left_inv_on_of_right_inv_on (hf : surj_on f s t) (hf' : right_inv_on f f' s) :
left_inv_on f f' t :=
λ y hy, let ⟨x, hx, heq⟩ := hf hy in by rw [← heq, hf' hx]
/-! ### Two-side inverses -/
/-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/
@[reducible] def inv_on (g : β → α) (f : α → β) (s : set α) (t : set β) : Prop :=
left_inv_on g f s ∧ right_inv_on g f t
lemma inv_on.symm (h : inv_on f' f s t) : inv_on f f' t s := ⟨h.right, h.left⟩
theorem inv_on.bij_on (h : inv_on f' f s t) (hf : maps_to f s t) (hf' : maps_to f' t s) :
bij_on f s t :=
⟨hf, h.left.inj_on, h.right.surj_on hf'⟩
/-! ### `inv_fun_on` is a left/right inverse -/
theorem inj_on.left_inv_on_inv_fun_on [nonempty α] (h : inj_on f s) :
left_inv_on (inv_fun_on f s) f s :=
λ x hx, inv_fun_on_eq' h hx
theorem surj_on.right_inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) :
right_inv_on (inv_fun_on f s) f t :=
λ y hy, inv_fun_on_eq $ mem_image_iff_bex.1 $ h hy
theorem bij_on.inv_on_inv_fun_on [nonempty α] (h : bij_on f s t) :
inv_on (inv_fun_on f s) f s t :=
⟨h.inj_on.left_inv_on_inv_fun_on, h.surj_on.right_inv_on_inv_fun_on⟩
theorem surj_on.inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) :
inv_on (inv_fun_on f s) f (inv_fun_on f s '' t) t :=
begin
refine ⟨_, h.right_inv_on_inv_fun_on⟩,
rintros _ ⟨y, hy, rfl⟩,
rw [h.right_inv_on_inv_fun_on hy]
end
theorem surj_on.maps_to_inv_fun_on [nonempty α] (h : surj_on f s t) :
maps_to (inv_fun_on f s) t s :=
λ y hy, mem_preimage.2 $ inv_fun_on_mem $ mem_image_iff_bex.1 $ h hy
theorem surj_on.bij_on_subset [nonempty α] (h : surj_on f s t) :
bij_on f (inv_fun_on f s '' t) t :=
begin
refine h.inv_on_inv_fun_on.bij_on _ (maps_to_image _ _),
rintros _ ⟨y, hy, rfl⟩,
rwa [h.right_inv_on_inv_fun_on hy]
end
theorem surj_on_iff_exists_bij_on_subset :
surj_on f s t ↔ ∃ s' ⊆ s, bij_on f s' t :=
begin
split,
{ rcases eq_empty_or_nonempty t with rfl|ht,
{ exact λ _, ⟨∅, empty_subset _, bij_on_empty f⟩ },
{ assume h,
haveI : nonempty α := ⟨classical.some (h.comap_nonempty ht)⟩,
exact ⟨_, h.maps_to_inv_fun_on.image_subset, h.bij_on_subset⟩ }},
{ rintros ⟨s', hs', hfs'⟩,
exact hfs'.surj_on.mono hs' (subset.refl _) }
end
end set
/-! ### Piecewise defined function -/
namespace set
variables {δ : α → Sort y} (s : set α) (f g : Πi, δ i)
@[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : set α))] : piecewise ∅ f g = g :=
by { ext i, simp [piecewise] }
@[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (set.univ : set α))] :
piecewise set.univ f g = f :=
by { ext i, simp [piecewise] }
@[simp] lemma piecewise_insert_self {j : α} [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g j = f j :=
by simp [piecewise]
variable [∀j, decidable (j ∈ s)]
instance compl.decidable_mem (j : α) : decidable (j ∈ sᶜ) := not.decidable
lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) :=
begin
simp [piecewise],
ext i,
by_cases h : i = j,
{ rw h, simp },
{ by_cases h' : i ∈ s; simp [h, h'] }
end
@[simp, priority 990]
lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i :=
by simp [piecewise, hi]
@[simp, priority 990]
lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i :=
by simp [piecewise, hi]
lemma piecewise_eq_on (f g : α → β) : eq_on (s.piecewise f g) f s :=
λ _, piecewise_eq_of_mem _ _ _
lemma piecewise_eq_on_compl (f g : α → β) : eq_on (s.piecewise f g) g sᶜ :=
λ _, piecewise_eq_of_not_mem _ _ _
@[simp, priority 990]
lemma piecewise_insert_of_ne {i j : α} (h : i ≠ j) [∀i, decidable (i ∈ insert j s)] :
(insert j s).piecewise f g i = s.piecewise f g i :=
by simp [piecewise, h]
@[simp] lemma piecewise_compl [∀ i, decidable (i ∈ sᶜ)] : sᶜ.piecewise f g = s.piecewise g f :=
funext $ λ x, if hx : x ∈ s then by simp [hx] else by simp [hx]
@[simp] lemma piecewise_range_comp {ι : Sort*} (f : ι → α) [Π j, decidable (j ∈ range f)]
(g₁ g₂ : α → β) :
(range f).piecewise g₁ g₂ ∘ f = g₁ ∘ f :=
comp_eq_of_eq_on_range $ piecewise_eq_on _ _ _
lemma piecewise_preimage (f g : α → β) (t) :
s.piecewise f g ⁻¹' t = s ∩ f ⁻¹' t ∪ sᶜ ∩ g ⁻¹' t :=
ext $ λ x, by by_cases x ∈ s; simp *
lemma comp_piecewise (h : β → γ) {f g : α → β} {x : α} :
h (s.piecewise f g x) = s.piecewise (h ∘ f) (h ∘ g) x :=
by by_cases hx : x ∈ s; simp [hx]
@[simp] lemma piecewise_same : s.piecewise f f = f :=
by { ext x, by_cases hx : x ∈ s; simp [hx] }
lemma range_piecewise (f g : α → β) : range (s.piecewise f g) = f '' s ∪ g '' sᶜ :=
begin
ext y, split,
{ rintro ⟨x, rfl⟩, by_cases h : x ∈ s;[left, right]; use x; simp [h] },
{ rintro (⟨x, hx, rfl⟩|⟨x, hx, rfl⟩); use x; simp * at * }
end
end set
namespace function
open set
variables {fa : α → α} {fb : β → β} {f : α → β} {g : β → γ} {s t : set α}
lemma injective.inj_on (h : injective f) (s : set α) : s.inj_on f :=
λ _ _ _ _ heq, h heq
lemma injective.comp_inj_on (hg : injective g) (hf : s.inj_on f) : s.inj_on (g ∘ f) :=
(hg.inj_on univ).comp hf (maps_to_univ _ _)
lemma surjective.surj_on (hf : surjective f) (s : set β) :
surj_on f univ s :=
(surjective_iff_surj_on_univ.1 hf).mono (subset.refl _) (subset_univ _)
namespace semiconj
lemma maps_to_image (h : semiconj f fa fb) (ha : maps_to fa s t) :
maps_to fb (f '' s) (f '' t) :=
λ y ⟨x, hx, hy⟩, hy ▸ ⟨fa x, ha hx, h x⟩
lemma maps_to_range (h : semiconj f fa fb) : maps_to fb (range f) (range f) :=
λ y ⟨x, hy⟩, hy ▸ ⟨fa x, h x⟩
lemma surj_on_image (h : semiconj f fa fb) (ha : surj_on fa s t) :
surj_on fb (f '' s) (f '' t) :=
begin
rintros y ⟨x, hxt, rfl⟩,
rcases ha hxt with ⟨x, hxs, rfl⟩,
rw [h x],
exact mem_image_of_mem _ (mem_image_of_mem _ hxs)
end
lemma surj_on_range (h : semiconj f fa fb) (ha : surjective fa) :
surj_on fb (range f) (range f) :=
by { rw ← image_univ, exact h.surj_on_image (ha.surj_on univ) }
lemma inj_on_image (h : semiconj f fa fb) (ha : inj_on fa s) (hf : inj_on f (fa '' s)) :
inj_on fb (f '' s) :=
begin
rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ H,
simp only [← h.eq] at H,
exact congr_arg f (ha hx hy $ hf (mem_image_of_mem fa hx) (mem_image_of_mem fa hy) H)
end
lemma inj_on_range (h : semiconj f fa fb) (ha : injective fa) (hf : inj_on f (range fa)) :
inj_on fb (range f) :=
by { rw ← image_univ at *, exact h.inj_on_image (ha.inj_on univ) hf }
lemma bij_on_image (h : semiconj f fa fb) (ha : bij_on fa s t) (hf : inj_on f t) :
bij_on fb (f '' s) (f '' t) :=
⟨h.maps_to_image ha.maps_to, h.inj_on_image ha.inj_on (ha.image_eq.symm ▸ hf),
h.surj_on_image ha.surj_on⟩
lemma bij_on_range (h : semiconj f fa fb) (ha : bijective fa) (hf : injective f) :
bij_on fb (range f) (range f) :=
begin
rw [← image_univ],
exact h.bij_on_image (bijective_iff_bij_on_univ.1 ha) (hf.inj_on univ)
end
lemma maps_to_preimage (h : semiconj f fa fb) {s t : set β} (hb : maps_to fb s t) :
maps_to fa (f ⁻¹' s) (f ⁻¹' t) :=
λ x hx, by simp only [mem_preimage, h x, hb hx]
lemma inj_on_preimage (h : semiconj f fa fb) {s : set β} (hb : inj_on fb s)
(hf : inj_on f (f ⁻¹' s)) :
inj_on fa (f ⁻¹' s) :=
begin
intros x hx y hy H,
have := congr_arg f H,
rw [h.eq, h.eq] at this,
exact hf hx hy (hb hx hy this)
end
end semiconj
lemma update_comp_eq_of_not_mem_range [decidable_eq β]
(g : β → γ) {f : α → β} {i : β} (a : γ) (h : i ∉ set.range f) :
(function.update g i a) ∘ f = g ∘ f :=
begin
ext p,
have : f p ≠ i,
{ by_contradiction H,
push_neg at H,
rw ← H at h,
exact h (set.mem_range_self _) },
simp [this],
end
lemma update_comp_eq_of_injective [decidable_eq α] [decidable_eq β]
(g : β → γ) {f : α → β} (hf : function.injective f) (i : α) (a : γ) :
(function.update g (f i) a) ∘ f = function.update (g ∘ f) i a :=
begin
ext j,
by_cases h : j = i,
{ rw h, simp },
{ have : f j ≠ f i := hf.ne h,
simp [h, this] }
end
end function
|
63a568f9c381be8ae495b50ec0690851e0dfff14 | fe84e287c662151bb313504482b218a503b972f3 | /src/commutative_algebra/galois_field_4.lean | 584f26295ebe406fb7b2f1eb6333e2db6fa5f49a | [] | no_license | NeilStrickland/lean_lib | 91e163f514b829c42fe75636407138b5c75cba83 | 6a9563de93748ace509d9db4302db6cd77d8f92c | refs/heads/master | 1,653,408,198,261 | 1,652,996,419,000 | 1,652,996,419,000 | 181,006,067 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 1,473 | lean | import algebra.ring algebra.field.basic
@[derive decidable_eq]
inductive F4 : Type
| zero : F4
| one : F4
| alpha : F4
| beta : F4
namespace F4
def add : F4 → F4 → F4
| zero y := y
| x zero := x
| one one := zero
| one alpha := beta
| one beta := alpha
| alpha one := beta
| alpha alpha := zero
| alpha beta := one
| beta one := alpha
| beta alpha := one
| beta beta := zero
def mul : F4 → F4 → F4
| zero y := zero
| one y := y
| x zero := zero
| x one := x
| alpha alpha := beta
| alpha beta := one
| beta alpha := one
| beta beta := alpha
def inv : F4 → F4
| zero := zero
| one := one
| alpha := beta
| beta := alpha
instance : field F4 :=
begin
letI : has_zero F4 := ⟨F4.zero⟩,
letI : has_add F4 := ⟨F4.add⟩,
letI : has_neg F4 := ⟨id⟩,
letI : has_one F4 := ⟨F4.one⟩,
letI : has_mul F4 := ⟨F4.mul⟩,
letI : has_inv F4 := ⟨F4.inv⟩,
refine_struct {
zero := F4.zero, add := (+), neg := id, sub := (+),
one := F4.one, mul := (*), inv := F4.inv, div := λ a b, a * b⁻¹,
nsmul := nsmul_rec, npow := npow_rec,
zsmul := zsmul_rec, zpow := zpow_rec,
nsmul_succ' := λ n x, rfl,
npow_succ' := λ n x, rfl,
zsmul_succ' := λ n x, rfl, zsmul_neg' := λ n x, rfl,
zpow_succ' := λ n x, rfl, zpow_neg' := λ n x, rfl,
exists_pair_ne := by { use F4.zero, use F4.one }
};
try { repeat { intro a, cases a }; exact dec_trivial, },
end
end F4
|
e42686354d40863a68b5f54df1866880cd4484ce | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /src/analysis/normed_space/bounded_linear_maps.lean | 03ea61296c4a0899fcb393d093d2cd7b91441c18 | [
"Apache-2.0"
] | permissive | johoelzl/mathlib | 253f46daa30b644d011e8e119025b01ad69735c4 | 592e3c7a2dfbd5826919b4605559d35d4d75938f | refs/heads/master | 1,625,657,216,488 | 1,551,374,946,000 | 1,551,374,946,000 | 98,915,829 | 0 | 0 | Apache-2.0 | 1,522,917,267,000 | 1,501,524,499,000 | Lean | UTF-8 | Lean | false | false | 5,906 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
Continuous linear functions -- functions between normed vector spaces which are bounded and linear.
-/
import algebra.field
import tactic.norm_num
import analysis.normed_space.basic
@[simp] lemma mul_inv_eq' {α} [discrete_field α] (a b : α) : (a * b)⁻¹ = b⁻¹ * a⁻¹ :=
classical.by_cases (assume : a = 0, by simp [this]) $ assume ha,
classical.by_cases (assume : b = 0, by simp [this]) $ assume hb,
mul_inv_eq hb ha
noncomputable theory
local attribute [instance] classical.prop_decidable
local notation f ` →_{`:50 a `} `:0 b := filter.tendsto f (nhds a) (nhds b)
open filter (tendsto)
open metric
variables {k : Type*} [normed_field k]
variables {E : Type*} [normed_space k E]
variables {F : Type*} [normed_space k F]
variables {G : Type*} [normed_space k G]
structure is_bounded_linear_map {k : Type*}
[normed_field k] {E : Type*} [normed_space k E] {F : Type*} [normed_space k F] (L : E → F)
extends is_linear_map k L : Prop :=
(bound : ∃ M, M > 0 ∧ ∀ x : E, ∥ L x ∥ ≤ M * ∥ x ∥)
include k
lemma is_linear_map.with_bound
{L : E → F} (hf : is_linear_map k L) (M : ℝ) (h : ∀ x : E, ∥ L x ∥ ≤ M * ∥ x ∥) :
is_bounded_linear_map L :=
⟨ hf, classical.by_cases
(assume : M ≤ 0, ⟨1, zero_lt_one, assume x,
le_trans (h x) $ mul_le_mul_of_nonneg_right (le_trans this zero_le_one) (norm_nonneg x)⟩)
(assume : ¬ M ≤ 0, ⟨M, lt_of_not_ge this, h⟩)⟩
namespace is_bounded_linear_map
lemma zero : is_bounded_linear_map (λ (x:E), (0:F)) :=
(0 : E →ₗ F).is_linear.with_bound 0 $ by simp [le_refl]
lemma id : is_bounded_linear_map (λ (x:E), x) :=
linear_map.id.is_linear.with_bound 1 $ by simp [le_refl]
lemma smul {f : E → F} (c : k) : is_bounded_linear_map f → is_bounded_linear_map (λ e, c • f e)
| ⟨hf, ⟨M, hM, h⟩⟩ := (c • hf.mk' f).is_linear.with_bound (∥c∥ * M) $ assume x,
calc ∥c • f x∥ = ∥c∥ * ∥f x∥ : norm_smul c (f x)
... ≤ ∥c∥ * (M * ∥x∥) : mul_le_mul_of_nonneg_left (h x) (norm_nonneg c)
... = (∥c∥ * M) * ∥x∥ : (mul_assoc _ _ _).symm
lemma neg {f : E → F} (hf : is_bounded_linear_map f) : is_bounded_linear_map (λ e, -f e) :=
begin
rw show (λ e, -f e) = (λ e, (-1 : k) • f e), { funext, simp },
exact smul (-1) hf
end
lemma add {f : E → F} {g : E → F} :
is_bounded_linear_map f → is_bounded_linear_map g → is_bounded_linear_map (λ e, f e + g e)
| ⟨hlf, Mf, hMf, hf⟩ ⟨hlg, Mg, hMg, hg⟩ := (hlf.mk' _ + hlg.mk' _).is_linear.with_bound (Mf + Mg) $ assume x,
calc ∥f x + g x∥ ≤ ∥f x∥ + ∥g x∥ : norm_triangle _ _
... ≤ Mf * ∥x∥ + Mg * ∥x∥ : add_le_add (hf x) (hg x)
... ≤ (Mf + Mg) * ∥x∥ : by rw add_mul
lemma sub {f : E → F} {g : E → F} (hf : is_bounded_linear_map f) (hg : is_bounded_linear_map g) :
is_bounded_linear_map (λ e, f e - g e) := add hf (neg hg)
lemma comp {f : E → F} {g : F → G} :
is_bounded_linear_map g → is_bounded_linear_map f → is_bounded_linear_map (g ∘ f)
| ⟨hlg, Mg, hMg, hg⟩ ⟨hlf, Mf, hMf, hf⟩ := ((hlg.mk' _).comp (hlf.mk' _)).is_linear.with_bound (Mg * Mf) $ assume x,
calc ∥g (f x)∥ ≤ Mg * ∥f x∥ : hg _
... ≤ Mg * (Mf * ∥x∥) : mul_le_mul_of_nonneg_left (hf _) (le_of_lt hMg)
... = Mg * Mf * ∥x∥ : (mul_assoc _ _ _).symm
lemma tendsto {L : E → F} (x : E) : is_bounded_linear_map L → L →_{x} (L x)
| ⟨hL, M, hM, h_ineq⟩ := tendsto_iff_norm_tendsto_zero.2 $
squeeze_zero (assume e, norm_nonneg _)
(assume e, calc ∥L e - L x∥ = ∥hL.mk' L (e - x)∥ : by rw (hL.mk' _).map_sub e x; refl
... ≤ M*∥e-x∥ : h_ineq (e-x))
(suffices (λ (e : E), M * ∥e - x∥) →_{x} (M * 0), by simpa,
tendsto_mul tendsto_const_nhds (lim_norm _))
lemma continuous {L : E → F} (hL : is_bounded_linear_map L) : continuous L :=
continuous_iff_continuous_at.2 $ assume x, hL.tendsto x
lemma lim_zero_bounded_linear_map {L : E → F} (H : is_bounded_linear_map L) : (L →_{0} 0) :=
(H.1.mk' _).map_zero ▸ continuous_iff_continuous_at.1 H.continuous 0
end is_bounded_linear_map
-- Next lemma is stated for real normed space but it would work as soon as the base field is an extension of ℝ
lemma bounded_continuous_linear_map
{E : Type*} [normed_space ℝ E] {F : Type*} [normed_space ℝ F] {L : E → F}
(lin : is_linear_map ℝ L) (cont : continuous L) : is_bounded_linear_map L :=
let ⟨δ, δ_pos, hδ⟩ := exists_delta_of_continuous cont zero_lt_one 0 in
have HL0 : L 0 = 0, from (lin.mk' _).map_zero,
have H : ∀{a}, ∥a∥ ≤ δ → ∥L a∥ < 1, by simpa only [HL0, dist_zero_right] using hδ,
lin.with_bound (δ⁻¹) $ assume x,
classical.by_cases (assume : x = 0, by simp only [this, HL0, norm_zero, mul_zero]) $
assume h : x ≠ 0,
let p := ∥x∥ * δ⁻¹, q := p⁻¹ in
have p_inv : p⁻¹ = δ*∥x∥⁻¹, by simp,
have norm_x_pos : ∥x∥ > 0 := (norm_pos_iff x).2 h,
have norm_x : ∥x∥ ≠ 0 := mt (norm_eq_zero x).1 h,
have p_pos : p > 0 := mul_pos norm_x_pos (inv_pos δ_pos),
have p0 : _ := ne_of_gt p_pos,
have q_pos : q > 0 := inv_pos p_pos,
have q0 : _ := ne_of_gt q_pos,
have ∥p⁻¹ • x∥ = δ := calc
∥p⁻¹ • x∥ = abs p⁻¹ * ∥x∥ : by rw norm_smul; refl
... = p⁻¹ * ∥x∥ : by rw [abs_of_nonneg $ le_of_lt q_pos]
... = δ : by simp [mul_assoc, inv_mul_cancel norm_x],
calc ∥L x∥ = (p * q) * ∥L x∥ : begin dsimp [q], rw [mul_inv_cancel p0, one_mul] end
... = p * ∥L (q • x)∥ : by simp [lin.smul, norm_smul, real.norm_eq_abs, abs_of_pos q_pos, mul_assoc]
... ≤ p * 1 : mul_le_mul_of_nonneg_left (le_of_lt $ H $ le_of_eq $ this) (le_of_lt p_pos)
... = δ⁻¹ * ∥x∥ : by rw [mul_one, mul_comm]
|
d7ed1d968f76732a878087dca1a5befee5733277 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/hott/360_2.hlean | 0669962f7a6998588d1e02fe2575eebbcbfa2637 | [
"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 | 345 | hlean | open is_trunc
--structure is_contr [class] (A : Type) : Type
section
parameters {P : Π(A : Type), A → Type}
definition my_contr {A : Type} [H : is_contr A] (a : A) : P A a := sorry
definition foo2
(A : Type)
(B : A → Type)
(a : A)
(x : B a)
(H : Π (a : A), is_contr (B a)) --(H : is_contr (B a))
: P (B a) x :=
by apply my_contr
end
|
6ff2ac8e0d7f88eeb67867999c2d12feb0125b33 | 437dc96105f48409c3981d46fb48e57c9ac3a3e4 | /src/topology/metric_space/gromov_hausdorff.lean | 3ecf61ef59b053f94a1e6d295b29a97d37692a52 | [
"Apache-2.0"
] | permissive | dan-c-k/mathlib | 08efec79bd7481ee6da9cc44c24a653bff4fbe0d | 96efc220f6225bc7a5ed8349900391a33a38cc56 | refs/heads/master | 1,658,082,847,093 | 1,589,013,201,000 | 1,589,013,201,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 55,764 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sébastien Gouëzel
-/
import topology.metric_space.closeds
import set_theory.cardinal
import topology.metric_space.gromov_hausdorff_realized
import topology.metric_space.completion
/-!
# Gromov-Hausdorff distance
This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces
up to isometry.
We introduce the space of all nonempty compact metric spaces, up to isometry,
called `GH_space`, and endow it with a metric space structure. The distance,
known as the Gromov-Hausdorff distance, is defined as follows: given two
nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance
between all possible isometric embeddings of `X` and `Y` in all metric spaces.
To define properly the Gromov-Hausdorff space, we consider the non-empty
compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type,
and define the distance as the infimum of the Hausdorff distance over all
embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description,
as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an
embedding called the Kuratowski embedding.
To prove that we have a distance, we should show that if spaces can be coupled
to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff
distance is realized, i.e., there is a coupling for which the Hausdorff distance
is exactly the Gromov-Hausdorff distance. This follows from a compactness
argument, essentially following from Arzela-Ascoli.
## Main results
We prove the most important properties of the Gromov-Hausdorff space: it is a polish space,
i.e., it is complete and second countable. We also prove the Gromov compactness criterion.
-/
noncomputable theory
open_locale classical topological_space
universes u v w
open classical set function topological_space filter metric quotient
open bounded_continuous_function nat Kuratowski_embedding
open sum (inl inr)
local attribute [instance] metric_space_sum
namespace Gromov_Hausdorff
section GH_space
/- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient
of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets.
Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty
compact type to `GH_space`. -/
/-- Equivalence relation identifying two nonempty compact sets which are isometric -/
private definition isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop :=
λx y, nonempty (x.val ≃ᵢ y.val)
/-- This is indeed an equivalence relation -/
private lemma is_equivalence_isometry_rel : equivalence isometry_rel :=
⟨λx, ⟨isometric.refl _⟩, λx y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩
/-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/
instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) :=
setoid.mk isometry_rel is_equivalence_isometry_rel
/-- The Gromov-Hausdorff space -/
definition GH_space : Type := quotient (isometry_rel.setoid)
/-- Map any nonempty compact type to `GH_space` -/
definition to_GH_space (α : Type u) [metric_space α] [compact_space α] [nonempty α] : GH_space :=
⟦nonempty_compacts.Kuratowski_embedding α⟧
instance : inhabited GH_space := ⟨quot.mk _ ⟨{0}, by simp⟩⟩
/-- A metric space representative of any abstract point in `GH_space` -/
definition GH_space.rep (p : GH_space) : Type := (quot.out p).val
lemma eq_to_GH_space_iff {α : Type u} [metric_space α] [compact_space α] [nonempty α] {p : nonempty_compacts ℓ_infty_ℝ} :
⟦p⟧ = to_GH_space α ↔ ∃Ψ : α → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p.val :=
begin
simp only [to_GH_space, quotient.eq],
split,
{ assume h,
rcases setoid.symm h with ⟨e⟩,
have f := (Kuratowski_embedding.isometry α).isometric_on_range.trans e,
use λx, f x,
split,
{ apply isometry_subtype_val.comp f.isometry },
{ rw [range_comp, f.range_coe, set.image_univ, set.range_coe_subtype] } },
{ rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩,
have f := ((Kuratowski_embedding.isometry α).isometric_on_range.symm.trans
isomΨ.isometric_on_range).symm,
have E : (range Ψ ≃ᵢ (nonempty_compacts.Kuratowski_embedding α).val) = (p.val ≃ᵢ range (Kuratowski_embedding α)),
by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl },
have g := cast E f,
exact ⟨g⟩ }
end
lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p.val :=
begin
refine eq_to_GH_space_iff.2 ⟨((λx, x) : p.val → ℓ_infty_ℝ), _, subtype.val_range⟩,
apply isometry_subtype_val
end
section
local attribute [reducible] GH_space.rep
instance rep_GH_space_metric_space {p : GH_space} : metric_space (p.rep) :=
by apply_instance
instance rep_GH_space_compact_space {p : GH_space} : compact_space (p.rep) :=
by apply_instance
instance rep_GH_space_nonempty {p : GH_space} : nonempty (p.rep) :=
by apply_instance
end
lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (p.rep) = p :=
begin
change to_GH_space (quot.out p).val = p,
rw ← eq_to_GH_space,
exact quot.out_eq p
end
/-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are isometric -/
lemma to_GH_space_eq_to_GH_space_iff_isometric {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type u} [metric_space β] [compact_space β] [nonempty β] :
to_GH_space α = to_GH_space β ↔ nonempty (α ≃ᵢ β) :=
⟨begin
simp only [to_GH_space, quotient.eq],
assume h,
rcases h with e,
have I : ((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val)
= ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have e' := cast I e,
have f := (Kuratowski_embedding.isometry α).isometric_on_range,
have g := (Kuratowski_embedding.isometry β).isometric_on_range.symm,
have h := (f.trans e').trans g,
exact ⟨h⟩
end,
begin
rintros ⟨e⟩,
simp only [to_GH_space, quotient.eq],
have f := (Kuratowski_embedding.isometry α).isometric_on_range.symm,
have g := (Kuratowski_embedding.isometry β).isometric_on_range,
have h := (f.trans e).trans g,
have I : ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))) =
((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have h' := cast I h,
exact ⟨h'⟩
end⟩
/-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum
Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition,
we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/
instance : has_dist (GH_space) :=
{ dist := λx y, Inf ((λp : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ, Hausdorff_dist p.1.val p.2.val) ''
(set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y})) }
/-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to
the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/
def GH_dist (α : Type u) (β : Type v) [metric_space α] [nonempty α] [compact_space α]
[metric_space β] [nonempty β] [compact_space β] : ℝ := dist (to_GH_space α) (to_GH_space β)
lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist (p.rep) (q.rep) :=
by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep]
/-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance
of isometric copies of the spaces, in any metric space. -/
theorem GH_dist_le_Hausdorff_dist {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type v} [metric_space β] [compact_space β] [nonempty β]
{γ : Type w} [metric_space γ] {Φ : α → γ} {Ψ : β → γ} (ha : isometry Φ) (hb : isometry Ψ) :
GH_dist α β ≤ Hausdorff_dist (range Φ) (range Ψ) :=
begin
/- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized
in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not
separable in general. We restrict to the union of the images of `α` and `β` in `γ`, which is
separable and therefore embeddable in `ℓ^∞(ℝ)`. -/
rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
letI : inhabited α := ⟨xα⟩,
letI : inhabited β := classical.inhabited_of_nonempty (by assumption),
let s : set γ := (range Φ) ∪ (range Ψ),
let Φ' : α → subtype s := λy, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩,
let Ψ' : β → subtype s := λy, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩,
have IΦ' : isometry Φ' := λx y, ha x y,
have IΨ' : isometry Ψ' := λx y, hb x y,
have : compact s, from (compact_range ha.continuous).union (compact_range hb.continuous),
letI : metric_space (subtype s) := by apply_instance,
haveI : compact_space (subtype s) := ⟨compact_iff_compact_univ.1 ‹compact s›⟩,
haveI : nonempty (subtype s) := ⟨Φ' xα⟩,
have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl },
have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl },
have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'),
{ rw [ΦΦ', ΨΨ', range_comp, range_comp],
exact Hausdorff_dist_image (isometry_subtype_val) },
rw this,
-- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding
let F := Kuratowski_embedding (subtype s),
have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) = Hausdorff_dist (range Φ') (range Ψ') :=
Hausdorff_dist_image (Kuratowski_embedding.isometry _),
rw ← this,
-- Let `A` and `B` be the images of `α` and `β` under this embedding. They are in `ℓ^∞(ℝ)`, and
-- their Hausdorff distance is the same as in the original space.
let A : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Φ'), ⟨(range_nonempty _).image _,
(compact_range IΦ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩,
let B : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Ψ'), ⟨(range_nonempty _).image _,
(compact_range IΨ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩,
have Aα : ⟦A⟧ = to_GH_space α,
{ rw eq_to_GH_space_iff,
exact ⟨λx, F (Φ' x), ⟨(Kuratowski_embedding.isometry _).comp IΦ', by rw range_comp⟩⟩ },
have Bβ : ⟦B⟧ = to_GH_space β,
{ rw eq_to_GH_space_iff,
exact ⟨λx, F (Ψ' x), ⟨(Kuratowski_embedding.isometry _).comp IΨ', by rw range_comp⟩⟩ },
refine cInf_le ⟨0,
begin simp [lower_bounds], assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _,
apply (mem_image _ _ _).2,
existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
simp [Aα, Bβ]
end
/-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance,
essentially by design. -/
lemma Hausdorff_dist_optimal {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type v} [metric_space β] [compact_space β] [nonempty β] :
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) = GH_dist α β :=
begin
inhabit α, inhabit β,
/- we only need to check the inequality `≤`, as the other one follows from the previous lemma.
As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance
in the optimal coupling is smaller than the Hausdorff distance of any coupling.
First, we check this for couplings which already have small Hausdorff distance: in this
case, the induced "distance" on `α ⊕ β` belongs to the candidates family introduced in the
definition of the optimal coupling, and the conclusion follows from the optimality
of the optimal coupling within this family.
-/
have A : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β →
Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β) →
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val),
{ assume p q hp hq bound,
rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩,
rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩,
have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β),
{ rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
have : ∃y ∈ range Ψ, dist (Φ xα) y < diam (univ : set α) + 1 + diam (univ : set β),
{ rw Ψrange,
have : Φ xα ∈ p.val := Φrange ▸ mem_range_self _,
exact exists_dist_lt_of_Hausdorff_dist_lt this bound
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) },
rcases this with ⟨y, hy, dy⟩,
rcases mem_range.1 hy with ⟨z, hzy⟩,
rw ← hzy at dy,
have DΦ : diam (range Φ) = diam (univ : set α) := Φisom.diam_range,
have DΨ : diam (range Ψ) = diam (univ : set β) := Ψisom.diam_range,
calc
diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xα) (Ψ z) + diam (range Ψ) :
diam_union (mem_range_self _) (mem_range_self _)
... ≤ diam (univ : set α) + (diam (univ : set α) + 1 + diam (univ : set β)) + diam (univ : set β) :
by { rw [DΦ, DΨ], apply add_le_add (add_le_add (le_refl _) (le_of_lt dy)) (le_refl _) }
... = 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by ring },
let f : α ⊕ β → ℓ_infty_ℝ := λx, match x with | inl y := Φ y | inr z := Ψ z end,
let F : (α ⊕ β) × (α ⊕ β) → ℝ := λp, dist (f p.1) (f p.2),
-- check that the induced "distance" is a candidate
have Fgood : F ∈ candidates α β,
{ simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero,
and_self, set.mem_set_of_eq],
repeat {split},
{ exact λx y, calc
F (inl x, inl y) = dist (Φ x) (Φ y) : rfl
... = dist x y : Φisom.dist_eq x y },
{ exact λx y, calc
F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl
... = dist x y : Ψisom.dist_eq x y },
{ exact λx y, dist_comm _ _ },
{ exact λx y z, dist_triangle _ _ _ },
{ exact λx y, calc
F (x, y) ≤ diam (range Φ ∪ range Ψ) :
begin
have A : ∀z : α ⊕ β, f z ∈ range Φ ∪ range Ψ,
{ assume z,
cases z,
{ apply mem_union_left, apply mem_range_self },
{ apply mem_union_right, apply mem_range_self } },
refine dist_le_diam_of_mem _ (A _) (A _),
rw [Φrange, Ψrange],
exact (p.2.2.union q.2.2).bounded,
end
... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : I } },
let Fb := candidates_b_of_candidates F Fgood,
have : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD Fb :=
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood),
refine le_trans this (le_of_forall_le_of_dense (λr hr, _)),
have I1 : ∀x : α, infi (λy:β, Fb (inl x, inr y)) ≤ r,
{ assume x,
have : f (inl x) ∈ p.val, by { rw [← Φrange], apply mem_range_self },
rcases exists_dist_lt_of_Hausdorff_dist_lt this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Ψ, by rwa [← Ψrange] at zq,
rcases mem_range.1 this with ⟨y, hy⟩,
calc infi (λy:β, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa using HD_below_aux1 0)
... = dist (Φ x) (Ψ y) : rfl
... = dist (f (inl x)) z : by rw hy
... ≤ r : le_of_lt hz },
have I2 : ∀y : β, infi (λx:α, Fb (inl x, inr y)) ≤ r,
{ assume y,
have : f (inr y) ∈ q.val, by { rw [← Ψrange], apply mem_range_self },
rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Φ, by rwa [← Φrange] at zq,
rcases mem_range.1 this with ⟨x, hx⟩,
calc infi (λx:α, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa using HD_below_aux2 0)
... = dist (Φ x) (Ψ y) : rfl
... = dist z (f (inr y)) : by rw hx
... ≤ r : le_of_lt hz },
simp [HD, csupr_le I1, csupr_le I2] },
/- Get the same inequality for any coupling. If the coupling is quite good, the desired
inequality has been proved above. If it is bad, then the inequality is obvious. -/
have B : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β →
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val),
{ assume p q hp hq,
by_cases h : Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β),
{ exact A p q hp hq h },
{ calc Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD (candidates_b_dist α β) :
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b)
... ≤ diam (univ : set α) + 1 + diam (univ : set β) : HD_candidates_b_dist_le
... ≤ Hausdorff_dist (p.val) (q.val) : not_lt.1 h } },
refine le_antisymm _ _,
{ apply le_cInf,
{ refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ },
{ rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩,
exact B p q hp hq } },
{ exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl α β) (isometry_optimal_GH_injr α β) }
end
/-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding
the optimal coupling through its Kuratowski embedding. -/
theorem GH_dist_eq_Hausdorff_dist (α : Type u) [metric_space α] [compact_space α] [nonempty α]
(β : Type v) [metric_space β] [compact_space β] [nonempty β] :
∃Φ : α → ℓ_infty_ℝ, ∃Ψ : β → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧
GH_dist α β = Hausdorff_dist (range Φ) (range Ψ) :=
begin
let F := Kuratowski_embedding (optimal_GH_coupling α β),
let Φ := F ∘ optimal_GH_injl α β,
let Ψ := F ∘ optimal_GH_injr α β,
refine ⟨Φ, Ψ, _, _, _⟩,
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl α β) },
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr α β) },
{ rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr α β),
image_univ, ← Hausdorff_dist_optimal],
exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm },
end
-- without the next two lines, `{ exact closed_of_compact (range Φ) hΦ }` in the next
-- proof is very slow, as the `t2_space` instance is very hard to find
local attribute [instance, priority 10] order_topology.t2_space
local attribute [instance, priority 10] order_closed_topology.to_t2_space
/-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/
instance GH_space_metric_space : metric_space GH_space :=
{ dist_self := λx, begin
rcases exists_rep x with ⟨y, hy⟩,
refine le_antisymm _ _,
{ apply cInf_le,
{ exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩},
{ simp, existsi [y, y], simpa } },
{ apply le_cInf,
{ exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ },
{ rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } },
end,
dist_comm := λx y, begin
have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist ((p.fst).val) ((p.snd).val)) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y})
= ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist ((p.fst).val) ((p.snd).val)) ∘ prod.swap) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) :=
by { congr, funext, simp, rw Hausdorff_dist_comm },
simp only [dist, A, image_comp, prod.swap, image_swap_prod],
end,
eq_of_dist_eq_zero := λx y hxy, begin
/- To show that two spaces at zero distance are isometric, we argue that the distance
is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance,
i.e., they coincide. Therefore, the original spaces are isometric. -/
rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩,
rw [← dist_GH_dist, hxy] at DΦΨ,
have : range Φ = range Ψ,
{ have hΦ : compact (range Φ) := compact_range Φisom.continuous,
have hΨ : compact (range Ψ) := compact_range Ψisom.continuous,
apply (Hausdorff_dist_zero_iff_eq_of_closed _ _ _).1 (DΦΨ.symm),
{ exact closed_of_compact (range Φ) hΦ },
{ exact closed_of_compact (range Ψ) hΨ },
{ exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _)
(range_nonempty _) hΦ.bounded hΨ.bounded } },
have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this,
have eΨ := cast T Ψisom.isometric_on_range.symm,
have e := Φisom.isometric_on_range.trans eΨ,
rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric],
exact ⟨e⟩
end,
dist_triangle := λx y z, begin
/- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling
between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y`and `Z` in a space `γ2`.
Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are
optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff
distance in `γ` to conclude. -/
let X := x.rep,
let Y := y.rep,
let Z := z.rep,
let γ1 := optimal_GH_coupling X Y,
let γ2 := optimal_GH_coupling Y Z,
let Φ : Y → γ1 := optimal_GH_injr X Y,
have hΦ : isometry Φ := isometry_optimal_GH_injr X Y,
let Ψ : Y → γ2 := optimal_GH_injl Y Z,
have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z,
let γ := glue_space hΦ hΨ,
letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ,
have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) = (to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) :=
to_glue_commute hΦ hΨ,
calc dist x z = dist (to_GH_space X) (to_GH_space Z) :
by rw [x.to_GH_space_rep, z.to_GH_space_rep]
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
GH_dist_le_Hausdorff_dist
((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y))
((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z))
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
+ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
begin
refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (range_nonempty _) _ _),
{ exact (compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injl X Y)))).bounded },
{ exact (compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injr X Y)))).bounded }
end
... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y)))
((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y)))
+ Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z)))
((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) :
by simp only [eq.symm range_comp, Comm, eq_self_iff_true, add_right_inj]
... = Hausdorff_dist (range (optimal_GH_injl X Y))
(range (optimal_GH_injr X Y))
+ Hausdorff_dist (range (optimal_GH_injl Y Z))
(range (optimal_GH_injr Y Z)) :
by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ),
Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)]
... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) :
by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist]
... = dist x y + dist y z:
by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep]
end }
end GH_space --section
end Gromov_Hausdorff
/-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this
in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/
definition topological_space.nonempty_compacts.to_GH_space {α : Type u} [metric_space α]
(p : nonempty_compacts α) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p.val
open topological_space
namespace Gromov_Hausdorff
section nonempty_compacts
variables {α : Type u} [metric_space α]
theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts α) :
dist p.to_GH_space q.to_GH_space ≤ dist p q :=
begin
have ha : isometry (subtype.val : p.val → α) := isometry_subtype_val,
have hb : isometry (subtype.val : q.val → α) := isometry_subtype_val,
have A : dist p q = Hausdorff_dist p.val q.val := rfl,
have I : p.val = range (subtype.val : p.val → α), by simp,
have J : q.val = range (subtype.val : q.val → α), by simp,
rw [I, J] at A,
rw A,
exact GH_dist_le_Hausdorff_dist ha hb
end
lemma to_GH_space_lipschitz :
lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) :=
lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist
lemma to_GH_space_continuous :
continuous (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) :=
to_GH_space_lipschitz.continuous
end nonempty_compacts
section
/- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their
Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are
`ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance
between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable coupling between
the two spaces, by gluing them (approximately) along the two matching subsets. -/
variables {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type v} [metric_space β] [compact_space β] [nonempty β]
-- we want to ignore these instances in the following theorem
local attribute [instance, priority 10] sum.topological_space sum.uniform_space
/-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and
isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by
`ε₁ + ε₂/2 + ε₃`. -/
theorem GH_dist_le_of_approx_subsets {s : set α} (Φ : s → β) {ε₁ ε₂ ε₃ : ℝ}
(hs : ∀x : α, ∃y ∈ s, dist x y ≤ ε₁) (hs' : ∀x : β, ∃y : s, dist x (Φ y) ≤ ε₃)
(H : ∀x y : s, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε₂) :
GH_dist α β ≤ ε₁ + ε₂ / 2 + ε₃ :=
begin
refine real.le_of_forall_epsilon_le (λδ δ0, _),
rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
rcases hs xα with ⟨xs, hxs, Dxs⟩,
have sne : s.nonempty := ⟨xs, hxs⟩,
letI : nonempty s := sne.to_subtype,
have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩),
have : ∀ p q : s, abs (dist p q - dist (Φ p) (Φ q)) ≤ 2 * (ε₂/2 + δ) := λp q, calc
abs (dist p q - dist (Φ p) (Φ q)) ≤ ε₂ : H p q
... ≤ 2 * (ε₂/2 + δ) : by linarith,
-- glue `α` and `β` along the almost matching subsets
letI : metric_space (α ⊕ β) := glue_metric_approx (λ x:s, (x:α)) (λx, Φ x) (ε₂/2 + δ) (by linarith) this,
let Fl := @sum.inl α β,
let Fr := @sum.inr α β,
have Il : isometry Fl := isometry_emetric_iff_metric.2 (λx y, rfl),
have Ir : isometry Fr := isometry_emetric_iff_metric.2 (λx y, rfl),
/- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images in the
coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff distances
of `α` and `s` (in the coupling or, equivalently in the original space), of `s` and `Φ s`, and of
`Φ s` and `β` (in the coupling or, equivalently, in the original space). The first term is bounded
by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is bounded by `ε₂/2`
as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by construction of the coupling
(in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive constant where positivity is used
to ensure that the coupling is really a metric space and not a premetric space on `α ⊕ β`). -/
have : GH_dist α β ≤ Hausdorff_dist (range Fl) (range Fr) :=
GH_dist_le_Hausdorff_dist Il Ir,
have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s)
+ Hausdorff_dist (Fl '' s) (range Fr),
{ have B : bounded (range Fl) := (compact_range Il.continuous).bounded,
exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (sne.image _) B (B.subset (image_subset_range _ _))) },
have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ))
+ Hausdorff_dist (Fr '' (range Φ)) (range Fr),
{ have B : bounded (range Fr) := (compact_range Ir.continuous).bounded,
exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded
((range_nonempty _).image _) (range_nonempty _)
(bounded.subset (image_subset_range _ _) B) B) },
have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁,
{ rw [← image_univ, Hausdorff_dist_image Il],
have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs,
refine Hausdorff_dist_le_of_mem_dist this (λx hx, hs x)
(λx hx, ⟨x, mem_univ _, by simpa⟩) },
have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ,
{ refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _,
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩,
rw ← xx',
use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)],
exact le_of_eq (glue_dist_glued_points (λ x:s, (x:α)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) },
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩,
rcases mem_range.1 y_in_s' with ⟨x, xy⟩,
use [Fl x, mem_image_of_mem _ x.2],
rw [← yx', ← xy, dist_comm],
exact le_of_eq (glue_dist_glued_points (@subtype.val α s) Φ (ε₂/2 + δ) x) } },
have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃,
{ rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir],
rcases exists_mem_of_nonempty β with ⟨xβ, _⟩,
rcases hs' xβ with ⟨xs', Dxs'⟩,
have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs',
refine Hausdorff_dist_le_of_mem_dist this (λx hx, ⟨x, mem_univ _, by simpa⟩) (λx _, _),
rcases hs' x with ⟨y, Dy⟩,
exact ⟨Φ y, mem_range_self _, Dy⟩ },
linarith
end
end --section
/-- The Gromov-Hausdorff space is second countable. -/
instance second_countable : second_countable_topology GH_space :=
begin
refine second_countable_of_countable_discretization (λδ δpos, _),
let ε := (2/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
have : ∀p:GH_space, ∃s : set (p.rep), finite s ∧ (univ ⊆ (⋃x∈s, ball x ε)) :=
λp, by simpa using finite_cover_balls_of_compact (@compact_univ p.rep _ _) εpos,
-- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space
-- `p.rep` representing `p`)
choose s hs using this,
have : ∀p:GH_space, ∀t:set (p.rep), finite t → ∃n:ℕ, ∃e:equiv t (fin n), true,
{ assume p t ht,
letI : fintype t := finite.fintype ht,
rcases fintype.exists_equiv_fin t with ⟨n, hn⟩,
rcases hn with e,
exact ⟨n, e, trivial⟩ },
choose N e hne using this,
-- cardinality of the nice finite subset `s p` of `p.rep`, called `N p`
let N := λp:GH_space, N p (s p) (hs p).1,
-- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p`
let E := λp:GH_space, e p (s p) (hs p).1,
-- A function `F` associating to `p : GH_space` the data of all distances between points
-- in the `ε`-dense set `s p`.
let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) :=
λp, ⟨N p, λa b, floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))⟩,
refine ⟨_, by apply_instance, F, λp q hpq, _⟩,
/- As the target space of F is countable, it suffices to show that two points
`p` and `q` with `F p = F q` are at distance `≤ δ`.
For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`)
to `q.rep` (representing `q`) which is almost an isometry on `s p`, and
with image `s q`. For this, we compose the identification of `s p` with `fin (N p)`
and the inverse of the identification of `s q` with `fin (N q)`. Together with
the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then
composing with the canonical inclusion we get `Φ`. -/
have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λx, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λx, Ψ x,
-- Use the almost isometry `Φ` to show that `p.rep` and `q.rep`
-- are within controlled Gromov-Hausdorff distance.
have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε,
{ refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_of_lt hy⟩ },
show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩,
let i := ((E q) ⟨y, ys⟩).1,
let hi := ((E q) ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw fin.ext_iff,
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_of_lt hy },
show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i := ((E p) x).1,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)).1, by { simp [Ψ] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j := ((E p) y).1,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] },
-- Express `dist x y` in terms of `F p`
have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y),
by simp only [F, (E p).symm_apply_apply],
have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y),
by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl },
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by simp only [F, (E q).symm_apply_apply],
have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] },
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
rw [Ap, Aq] at this,
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) =
abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm
... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ : by { simp [ε], ring }
end
/-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have
a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required
to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the
interesting direction that these conditions imply compactness. -/
lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ}
(ulim : tendsto u at_top (𝓝 0))
(hdiam : ∀p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C)
(hcov : ∀p ∈ t, ∀n:ℕ, ∃s : set (GH_space.rep p), cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) :
totally_bounded t :=
begin
/- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which
is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`,
up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to
reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/
refine metric.totally_bounded_of_finite_discretization (λδ δpos, _),
let ε := (1/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
-- choose `n` for which `u n < ε`
rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩,
have u_le_ε : u n ≤ ε,
{ have := hn n (le_refl _),
simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this,
exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) },
-- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n`
have : ∀p:GH_space, ∃s : set (p.rep), ∃N ≤ K n, ∃E : equiv s (fin N),
p ∈ t → univ ⊆ ⋃x∈s, ball x (u n),
{ assume p,
by_cases hp : p ∉ t,
{ have : nonempty (equiv (∅ : set (p.rep)) (fin 0)),
{ rw ← fintype.card_eq, simp },
use [∅, 0, bot_le, choice (this)] },
{ rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩,
rcases cardinal.lt_omega.1 (lt_of_le_of_lt scard (cardinal.nat_lt_omega _)) with ⟨N, hN⟩,
rw [hN, cardinal.nat_cast_le] at scard,
have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin],
cases quotient.exact this with E,
use [s, N, scard, E],
simp [hp, scover] } },
choose s N hN E hs using this,
-- Define a function `F` taking values in a finite type and associating to `p` enough data
-- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`.
let M := (floor (ε⁻¹ * max C 0)).to_nat,
let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) :=
λp, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩,
λa b, ⟨min M (floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))).to_nat,
lt_of_le_of_lt ( min_le_left _ _) (nat.lt_succ_self _) ⟩ ⟩,
refine ⟨_, by apply_instance, (λp, F p), _⟩,
-- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close
rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq,
have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λx, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λx, Ψ x,
have main : GH_dist (p.rep) (q.rep) ≤ ε + ε/2 + ε,
{ -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense
-- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows
-- from `GH_dist_le_of_approx_subsets`
refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ },
show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩,
let i := ((E q) ⟨y, ys⟩).1,
let hi := ((E q) ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw fin.ext_iff,
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_trans (le_of_lt hy) u_le_ε },
show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i := ((E p) x).1,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)).1, by { simp [Ψ] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j := ((E p) y).1,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] },
-- Express `dist x y` in terms of `F p`
have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = (floor (ε⁻¹ * dist x y)).to_nat := calc
((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 :
by { congr; apply (fin.ext_iff _ _).2; refl }
... = min M (floor (ε⁻¹ * dist x y)).to_nat :
by simp only [F, (E p).symm_apply_apply]
... = (floor (ε⁻¹ * dist x y)).to_nat :
begin
refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) (le_of_lt (inv_pos.2 εpos)),
change dist (x : p.rep) y ≤ C,
refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam p pt
end,
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat := calc
((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 :
by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }
... = min M (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat :
by simp only [F, (E q).symm_apply_apply]
... = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat :
begin
refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) (le_of_lt (inv_pos.2 εpos)),
change dist (Ψ x : q.rep) (Ψ y) ≤ C,
refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam q qt
end,
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
have : floor (ε⁻¹ * dist x y) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
{ rw [Ap, Aq] at this,
have D : 0 ≤ floor (ε⁻¹ * dist x y) :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
have D' : floor (ε⁻¹ * dist (Ψ x) (Ψ y)) ≥ 0 :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', this] },
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) =
abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm
... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ/2 : by { simp [ε], ring }
... < δ : half_lt_self δpos
end
section complete
/- We will show that a sequence `u n` of compact metric spaces satisfying
`dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space.
We need to exhibit the limiting compact metric space. For this, start from
a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)`
for all `n`, in a common metric space. Formally, this is done as follows.
Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space
`Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and
glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an
embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive
limit of the `Y n`, and finally let `Z` be the completion of `Z0`.
The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they
form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its
set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty
compact metric space we are looking for. -/
variables (X : ℕ → Type) [∀n, metric_space (X n)] [∀n, compact_space (X n)] [∀n, nonempty (X n)]
/-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding
of a type `A` in another metric space. -/
structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 :=
(space : Type)
(metric : metric_space space)
(embed : A → space)
(isom : isometry embed)
/-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each
`X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space
at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/
def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n
{ space := X 0,
metric := by apply_instance,
embed := id,
isom := λx y, rfl }
(λn a, by letI : metric_space a.space := a.metric; exact
{ space := glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)),
metric := metric.metric_space_glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)),
embed := (to_glue_r a.isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injr (X n) (X n.succ)),
isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X n.succ)) })
/-- The Gromov-Hausdorff space is complete. -/
instance : complete_space (GH_space) :=
begin
have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply _root_.pow_pos, norm_num },
-- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other
refine metric.complete_of_convergent_controlled_sequences (λn, (1/2)^n) this (λu hu, _),
-- `X n` is a representative of `u n`
let X := λn, (u n).rep,
-- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n`
let Y := aux_gluing X,
letI : ∀n, metric_space (Y n).space := λn, (Y n).metric,
have E : ∀n:ℕ, glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space :=
λn, by { simp [Y, aux_gluing], refl },
let c := λn, cast (E n),
have ic : ∀n, isometry (c n) := λn x y, rfl,
-- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction
let f : Πn, (Y n).space → (Y n.succ).space :=
λn, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))),
have I : ∀n, isometry (f n),
{ assume n,
apply isometry.comp,
{ assume x y, refl },
{ apply to_glue_l_isometry } },
-- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z`
let Z0 := metric.inductive_limit I,
let Z := uniform_space.completion Z0,
let Φ := to_inductive_limit I,
let coeZ := (coe : Z0 → Z),
-- let `X2 n` be the image of `X n` in the space `Z`
let X2 := λn, range (coeZ ∘ (Φ n) ∘ (Y n).embed),
have isom : ∀n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed),
{ assume n,
apply isometry.comp completion.coe_isometry _,
apply isometry.comp _ (Y n).isom,
apply to_inductive_limit_isometry },
-- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between
-- `u n` and `u (n+1)`, therefore bounded by `1/2^n`
have D2 : ∀n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n,
{ assume n,
have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injl (X n) (X n.succ))),
{ change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injl (X n) (X n.succ))),
simp only [X2, Φ],
rw [← to_inductive_limit_commute I],
simp only [f],
rw ← to_glue_commute },
rw range_comp at X2n,
have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injr (X n) (X n.succ))), by refl,
rw range_comp at X2nsucc,
rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist],
{ exact hu n n n.succ (le_refl n) (le_succ n) },
{ apply isometry.comp completion.coe_isometry _,
apply isometry.comp _ ((ic n).comp (to_glue_r_isometry _ _)),
apply to_inductive_limit_isometry } },
-- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which
-- is a metric space
let X3 : ℕ → nonempty_compacts Z := λn, ⟨X2 n,
⟨range_nonempty _, compact_range (isom n).continuous ⟩⟩,
-- `X3 n` is a Cauchy sequence by construction, as the successive distances are
-- bounded by `(1/2)^n`
have : cauchy_seq X3,
{ refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λn, _),
rw one_mul,
exact le_of_lt (D2 n) },
-- therefore, it converges to a limit `L`
rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩,
-- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L`
have M : tendsto (λn, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) :=
tendsto.comp (to_GH_space_continuous.tendsto _) hL,
-- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`.
have : ∀n, (X3 n).to_GH_space = u n,
{ assume n,
rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep,
to_GH_space_eq_to_GH_space_iff_isometric],
constructor,
convert (isom n).isometric_on_range.symm,
},
-- Finally, we have proved the convergence of `u n`
exact ⟨L.to_GH_space, by simpa [this] using M⟩
end
end complete--section
end Gromov_Hausdorff --namespace
|
4e71bc0c1da47f5bd0206d989868a20363fe574e | 54f4ad05b219d444b709f56c2f619dd87d14ec29 | /my_project/src/love13_rational_and_real_numbers_exercise_sheet.lean | 6e872650d4a148eb942fa43ca71db80aa150faff | [] | no_license | yizhou7/learning-lean | 8efcf838c7276e235a81bd291f467fa43ce56e0a | 91fb366c624df6e56e19555b2e482ce767cd8224 | refs/heads/master | 1,675,649,087,737 | 1,609,022,281,000 | 1,609,022,281,000 | 272,072,779 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,160 | lean | import .love05_inductive_predicates_demo
import .love13_rational_and_real_numbers_demo
/-! # LoVe Exercise 13: Rational and Real Numbers -/
set_option pp.beta true
namespace LoVe
/-! ## Question 1: Rationals
1.1. Prove the following lemma.
Hint: The lemma `fraction.mk.inj_eq` might be useful. -/
#check fraction.mk.inj_eq
lemma fraction.ext (a b : fraction) (hnum : fraction.num a = fraction.num b)
(hdenom : fraction.denom a = fraction.denom b) :
a = b :=
sorry
/-! 1.2. Extending the `fraction.has_mul` instance from the lecture, declare
`fraction` as an instance of `semigroup`.
Hint: Use the lemma `fraction.ext` above, and possibly `fraction.mul_num`, and
`fraction.mul_denom`. -/
#check fraction.ext
#check fraction.mul_num
#check fraction.mul_denom
@[instance] def fraction.semigroup : semigroup fraction :=
{ mul_assoc :=
sorry,
..fraction.has_mul }
/-! 1.3. Extending the `rat.has_mul` instance from the lecture, declare `rat` as
an instance of `semigroup`. -/
@[instance] def rat.semigroup : semigroup rat :=
{ mul_assoc :=
sorry,
..rat.has_mul }
end LoVe
-- lemma rat_test : ℚ
-- #eval 0 0 -- expected: 0
|
28192e05cf5ad94826d3065fa090de44185b2bcb | 6f1049e897f569e5c47237de40321e62f0181948 | /src/solutions/07bis_abstract_negations.lean | 434026eb89d9b3f2d8efebf333d330d74114743d | [
"Apache-2.0"
] | permissive | anrddh/tutorials | f654a0807b9523608544836d9a81939f8e1dceb8 | 3ba43804e7b632201c494cdaa8da5406f1a255f9 | refs/heads/master | 1,655,542,921,827 | 1,588,846,595,000 | 1,588,846,595,000 | 262,330,134 | 0 | 0 | null | 1,588,944,346,000 | 1,588,944,345,000 | null | UTF-8 | Lean | false | false | 2,443 | lean | import data.real.basic
open_locale classical
/-
Theoretical negations.
This file is for people interested in logic who want to fully understand
negations.
Here we don't use contrapose or push_neg. The goal is to prove lemmas
that are used by those tactics. Of course we can use
exfalso, by_contradiction et by_cases.
If this doesn't sound like fun then skip ahead to the next file.
-/
section negation_prop
variables P Q : Prop
-- 0055
example : (P → Q) ↔ (¬ Q → ¬ P) :=
begin
-- sorry
split,
{ intros h hnQ hP,
exact hnQ (h hP) },
{ intros h hP,
by_contradiction hnQ,
exact h hnQ hP },
-- sorry
end
-- 0056
lemma non_imp (P Q : Prop) : ¬ (P → Q) ↔ P ∧ ¬ Q :=
begin
-- sorry
split,
{ intro h,
by_contradiction H,
apply h,
intro hP,
by_contradiction H',
apply H,
exact ⟨hP, H'⟩ },
{ intros h h',
cases h with hP hnQ,
exact hnQ (h' hP) },
-- sorry
end
-- In the one, let's use the axiom
-- propext {P Q : Prop} : (P ↔ Q) → P = Q
-- 0057
example (P : Prop) : ¬ P ↔ P = false :=
begin
-- sorry
split,
{ intro h,
apply propext,
split,
{ intro h',
exact h h' },
{ intro h,
exfalso,
exact h } },
{ intro h,
rw h,
exact id },
-- sorry
end
end negation_prop
section negation_quantifiers
variables (X : Type) (P : X → Prop)
-- 0058
example : ¬ (∀ x, P x) ↔ ∃ x, ¬ P x :=
begin
-- sorry
split,
{ intro h,
by_contradiction H,
apply h,
intros x,
by_contradiction H',
apply H,
use [x, H'] },
{ rintros ⟨x, hx⟩ h',
exact hx (h' x) },
-- sorry
end
-- 0059
example : ¬ (∃ x, P x) ↔ ∀ x, ¬ P x :=
begin
-- sorry
split,
{ intros h x h',
apply h,
use [x, h'] },
{ rintros h ⟨x, hx⟩,
exact h x hx },
-- sorry
end
-- 0060
example (P : ℝ → Prop) : ¬ (∃ ε > 0, P ε) ↔ ∀ ε > 0, ¬ P ε :=
begin
-- sorry
split,
{ intros h ε ε_pos hP,
apply h,
use [ε, ε_pos, hP] },
{ rintros h ⟨ε, ε_pos, hP⟩,
exact h ε ε_pos hP },
-- sorry
end
-- 0061
example (P : ℝ → Prop) : ¬ (∀ x > 0, P x) ↔ ∃ x > 0, ¬ P x :=
begin
-- sorry
split,
{ intros h,
by_contradiction H,
apply h,
intros x x_pos,
by_contradiction HP,
apply H,
use [x, x_pos, HP] },
{ rintros ⟨x, xpos, hx⟩ h',
exact hx (h' x xpos) },
-- sorry
end
end negation_quantifiers
|
1f0edbf4ce5d50c4708f8bf875eca48ccf1502bd | 4727251e0cd73359b15b664c3170e5d754078599 | /archive/100-theorems-list/16_abel_ruffini.lean | 3b6d17fced1b4fce1a9bce912f5dd53518383d41 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 8,311 | 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 field_theory.abel_ruffini
import analysis.calculus.local_extr
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,
int.nat_cast_eq_coe_nat, 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, int.nat_cast_eq_coe_nat],
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 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
|
63ddf71752d17f9559e805b5e00c2287bcea08cd | 618003631150032a5676f229d13a079ac875ff77 | /src/tactic/ring2.lean | 96c740256c6fc1bd396cda400cede3d68b78f580 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 20,978 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import tactic.ring
import data.num.lemmas
import data.tree
/-!
# ring2
An experimental variant on the `ring` tactic that uses computational
reflection instead of proof generation. Useful for kernel benchmarking.
-/
namespace tree
/-- `(reflect' t u α)` quasiquotes a tree `(t: tree expr)` of quoted
values of type `α` at level `u` into an `expr` which reifies to a `tree α`
containing the reifications of the `expr`s from the original `t`. -/
protected meta def reflect' (u : level) (α : expr) : tree expr → expr
| tree.nil := (expr.const ``tree.nil [u] : expr) α
| (tree.node a t₁ t₂) :=
(expr.const ``tree.node [u] : expr) α a t₁.reflect' t₂.reflect'
/-- Returns an element indexed by `n`, or zero if `n` isn't a valid index.
See `tree.get`. -/
protected def get_or_zero {α} [has_zero α] (t : tree α) (n : pos_num) : α :=
t.get_or_else n 0
end tree
namespace tactic.ring2
/-- A reflected/meta representation of an expression in a commutative
semiring. This representation is a direct translation of such
expressions - see `horner_expr` for a normal form. -/
@[derive has_reflect]
inductive csring_expr
/- (atom n) is an opaque element of the csring. For example,
a local variable in the context. n indexes into a storage
of such atoms - a `tree α`. -/
| atom : pos_num → csring_expr
/- (const n) is technically the csring's one, added n times.
Or the zero if n is 0. -/
| const : num → csring_expr
| add : csring_expr → csring_expr → csring_expr
| mul : csring_expr → csring_expr → csring_expr
| pow : csring_expr → num → csring_expr
namespace csring_expr
instance : inhabited csring_expr := ⟨const 0⟩
/-- Evaluates a reflected `csring_expr` into an element of the
original `comm_semiring` type `α`, retrieving opaque elements
(atoms) from the tree `t`. -/
def eval {α} [comm_semiring α] (t : tree α) : csring_expr → α
| (atom n) := t.get_or_zero n
| (const n) := n
| (add x y) := eval x + eval y
| (mul x y) := eval x * eval y
| (pow x n) := eval x ^ (n : ℕ)
end csring_expr
/-- An efficient representation of expressions in a commutative
semiring using the sparse Horner normal form. This type admits
non-optimal instantiations (e.g. `P` can be represented as `P+0+0`),
so to get good performance out of it, care must be taken to maintain
an optimal, *canonical* form. -/
@[derive decidable_eq]
inductive horner_expr
/- (const n) is a constant n in the csring, similarly to the same
constructor in `csring_expr`. This one, however, can be negative. -/
| const : znum → horner_expr
/- (horner a x n b) is a*xⁿ + b, where x is the x-th atom
in the atom tree. -/
| horner : horner_expr → pos_num → num → horner_expr → horner_expr
namespace horner_expr
/-- True iff the `horner_expr` argument is a valid `csring_expr`.
For that to be the case, all its constants must be non-negative. -/
def is_cs : horner_expr → Prop
| (const n) := ∃ m:num, n = m.to_znum
| (horner a x n b) := is_cs a ∧ is_cs b
instance : has_zero horner_expr := ⟨const 0⟩
instance : has_one horner_expr := ⟨const 1⟩
instance : inhabited horner_expr := ⟨0⟩
/-- Represent a `csring_expr.atom` in Horner form. -/
def atom (n : pos_num) : horner_expr := horner 1 n 1 0
def to_string : horner_expr → string
| (const n) := _root_.repr n
| (horner a x n b) :=
"(" ++ to_string a ++ ") * x" ++ _root_.repr x ++ "^"
++ _root_.repr n ++ " + " ++ to_string b
instance : has_to_string horner_expr := ⟨to_string⟩
/-- Alternative constructor for (horner a x n b) which maintains canonical
form by simplifying special cases of `a`. -/
def horner' (a : horner_expr)
(x : pos_num) (n : num) (b : horner_expr) : horner_expr :=
match a with
| const q := if q = 0 then b else horner a x n b
| horner a₁ x₁ n₁ b₁ :=
if x₁ = x ∧ b₁ = 0 then horner a₁ x (n₁ + n) b
else horner a x n b
end
def add_const (k : znum) (e : horner_expr) : horner_expr :=
if k = 0 then e else begin
induction e with n a x n b A B,
{ exact const (k + n) },
{ exact horner a x n B }
end
def add_aux (a₁ : horner_expr) (A₁ : horner_expr → horner_expr) (x₁ : pos_num) :
horner_expr → num → horner_expr → (horner_expr → horner_expr) → horner_expr
| (const n₂) n₁ b₁ B₁ := add_const n₂ (horner a₁ x₁ n₁ b₁)
| (horner a₂ x₂ n₂ b₂) n₁ b₁ B₁ :=
let e₂ := horner a₂ x₂ n₂ b₂ in
match pos_num.cmp x₁ x₂ with
| ordering.lt := horner a₁ x₁ n₁ (B₁ e₂)
| ordering.gt := horner a₂ x₂ n₂ (add_aux b₂ n₁ b₁ B₁)
| ordering.eq :=
match num.sub' n₁ n₂ with
| znum.zero := horner' (A₁ a₂) x₁ n₁ (B₁ b₂)
| (znum.pos k) := horner (add_aux a₂ k 0 id) x₁ n₂ (B₁ b₂)
| (znum.neg k) := horner (A₁ (horner a₂ x₁ k 0)) x₁ n₁ (B₁ b₂)
end
end
def add : horner_expr → horner_expr → horner_expr
| (const n₁) e₂ := add_const n₁ e₂
| (horner a₁ x₁ n₁ b₁) e₂ := add_aux a₁ (add a₁) x₁ e₂ n₁ b₁ (add b₁)
/-begin
induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂,
{ exact add_const n₁ e₂ },
exact match e₂ with e₂ := begin
induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂ generalizing n₁ b₁;
let e₁ := horner a₁ x₁ n₁ b₁,
{ exact add_const n₂ e₁ },
let e₂ := horner a₂ x₂ n₂ b₂,
exact match pos_num.cmp x₁ x₂ with
| ordering.lt := horner a₁ x₁ n₁ (B₁ e₂)
| ordering.gt := horner a₂ x₂ n₂ (B₂ n₁ b₁)
| ordering.eq :=
match num.sub' n₁ n₂ with
| znum.zero := horner' (A₁ a₂) x₁ n₁ (B₁ b₂)
| (znum.pos k) := horner (A₂ k 0) x₁ n₂ (B₁ b₂)
| (znum.neg k) := horner (A₁ (horner a₂ x₁ k 0)) x₁ n₁ (B₁ b₂)
end
end
end end
end-/
def neg (e : horner_expr) : horner_expr :=
begin
induction e with n a x n b A B,
{ exact const (-n) },
{ exact horner A x n B }
end
def mul_const (k : znum) (e : horner_expr) : horner_expr :=
if k = 0 then 0 else if k = 1 then e else begin
induction e with n a x n b A B,
{ exact const (n * k) },
{ exact horner A x n B }
end
def mul_aux (a₁ x₁ n₁ b₁) (A₁ B₁ : horner_expr → horner_expr) :
horner_expr → horner_expr
| (const n₂) := mul_const n₂ (horner a₁ x₁ n₁ b₁)
| e₂@(horner a₂ x₂ n₂ b₂) :=
match pos_num.cmp x₁ x₂ with
| ordering.lt := horner (A₁ e₂) x₁ n₁ (B₁ e₂)
| ordering.gt := horner (mul_aux a₂) x₂ n₂ (mul_aux b₂)
| ordering.eq := let haa := horner' (mul_aux a₂) x₁ n₂ 0 in
if b₂ = 0 then haa else haa.add (horner (A₁ b₂) x₁ n₁ (B₁ b₂))
end
def mul : horner_expr → horner_expr → horner_expr
| (const n₁) := mul_const n₁
| (horner a₁ x₁ n₁ b₁) := mul_aux a₁ x₁ n₁ b₁ (mul a₁) (mul b₁).
/-begin
induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂,
{ exact mul_const n₁ e₂ },
induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂;
let e₁ := horner a₁ x₁ n₁ b₁,
{ exact mul_const n₂ e₁ },
let e₂ := horner a₂ x₂ n₂ b₂,
cases pos_num.cmp x₁ x₂,
{ exact horner (A₁ e₂) x₁ n₁ (B₁ e₂) },
{ let haa := horner' A₂ x₁ n₂ 0,
exact if b₂ = 0 then haa else
haa.add (horner (A₁ b₂) x₁ n₁ (B₁ b₂)) },
{ exact horner A₂ x₂ n₂ B₂ }
end-/
instance : has_add horner_expr := ⟨add⟩
instance : has_neg horner_expr := ⟨neg⟩
instance : has_mul horner_expr := ⟨mul⟩
def pow (e : horner_expr) : num → horner_expr
| 0 := 1
| (num.pos p) := begin
induction p with p ep p ep,
{ exact e },
{ exact (ep.mul ep).mul e },
{ exact ep.mul ep }
end
def inv (e : horner_expr) : horner_expr := 0
/-- Brings expressions into Horner normal form. -/
def of_csexpr : csring_expr → horner_expr
| (csring_expr.atom n) := atom n
| (csring_expr.const n) := const n.to_znum
| (csring_expr.add x y) := (of_csexpr x).add (of_csexpr y)
| (csring_expr.mul x y) := (of_csexpr x).mul (of_csexpr y)
| (csring_expr.pow x n) := (of_csexpr x).pow n
/-- Evaluates a reflected `horner_expr` - see `csring_expr.eval`. -/
def cseval {α} [comm_semiring α] (t : tree α) : horner_expr → α
| (const n) := n.abs
| (horner a x n b) := tactic.ring.horner (cseval a) (t.get_or_zero x) n (cseval b)
theorem cseval_atom {α} [comm_semiring α] (t : tree α)
(n : pos_num) : (atom n).is_cs ∧ cseval t (atom n) = t.get_or_zero n :=
⟨⟨⟨1, rfl⟩, ⟨0, rfl⟩⟩, (tactic.ring.horner_atom _).symm⟩
theorem cseval_add_const {α} [comm_semiring α] (t : tree α)
(k : num) {e : horner_expr} (cs : e.is_cs) :
(add_const k.to_znum e).is_cs ∧
cseval t (add_const k.to_znum e) = k + cseval t e :=
begin
simp [add_const],
cases k; simp! *,
simp [show znum.pos k ≠ 0, from dec_trivial],
induction e with n a x n b A B; simp *,
{ rcases cs with ⟨n, rfl⟩,
refine ⟨⟨n + num.pos k, by simp [add_comm]; refl⟩, _⟩,
cases n; simp! },
{ rcases B cs.2 with ⟨csb, h⟩, simp! [*, cs.1],
rw [← tactic.ring.horner_add_const, add_comm], rw add_comm }
end
theorem cseval_horner' {α} [comm_semiring α] (t : tree α)
(a x n b) (h₁ : is_cs a) (h₂ : is_cs b) :
(horner' a x n b).is_cs ∧ cseval t (horner' a x n b) =
tactic.ring.horner (cseval t a) (t.get_or_zero x) n (cseval t b) :=
begin
cases a with n₁ a₁ x₁ n₁ b₁; simp [horner']; split_ifs,
{ simp! [*, tactic.ring.horner] },
{ exact ⟨⟨h₁, h₂⟩, rfl⟩ },
{ refine ⟨⟨h₁.1, h₂⟩, eq.symm _⟩, simp! *,
apply tactic.ring.horner_horner, simp },
{ exact ⟨⟨h₁, h₂⟩, rfl⟩ }
end
theorem cseval_add {α} [comm_semiring α] (t : tree α)
{e₁ e₂ : horner_expr} (cs₁ : e₁.is_cs) (cs₂ : e₂.is_cs) :
(add e₁ e₂).is_cs ∧
cseval t (add e₁ e₂) = cseval t e₁ + cseval t e₂ :=
begin
induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂; simp!,
{ rcases cs₁ with ⟨n₁, rfl⟩,
simpa using cseval_add_const t n₁ cs₂ },
induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂ generalizing n₁ b₁,
{ rcases cs₂ with ⟨n₂, rfl⟩,
simp! [cseval_add_const t n₂ cs₁, add_comm] },
cases cs₁ with csa₁ csb₁, cases id cs₂ with csa₂ csb₂,
simp!, have C := pos_num.cmp_to_nat x₁ x₂,
cases pos_num.cmp x₁ x₂; simp!,
{ rcases B₁ csb₁ cs₂ with ⟨csh, h⟩,
refine ⟨⟨csa₁, csh⟩, eq.symm _⟩,
apply tactic.ring.horner_add_const,
exact h.symm },
{ cases C,
have B0 : is_cs 0 → ∀ {e₂ : horner_expr}, is_cs e₂ →
is_cs (add 0 e₂) ∧ cseval t (add 0 e₂) = cseval t 0 + cseval t e₂ :=
λ _ e₂ c, ⟨c, (zero_add _).symm⟩,
cases e : num.sub' n₁ n₂ with k k; simp!,
{ have : n₁ = n₂,
{ have := congr_arg (coe : znum → ℤ) e,
simp at this,
have := sub_eq_zero.1 this,
rw [← num.to_nat_to_int, ← num.to_nat_to_int] at this,
exact num.to_nat_inj.1 (int.coe_nat_inj this) },
subst n₂,
rcases cseval_horner' _ _ _ _ _ _ _ with ⟨csh, h⟩,
{ refine ⟨csh, h.trans (eq.symm _)⟩,
simp *,
apply tactic.ring.horner_add_horner_eq; try {refl} },
all_goals {simp! *} },
{ simp [B₁ csb₁ csb₂, add_comm],
rcases A₂ csa₂ _ _ B0 ⟨csa₁, 0, rfl⟩ with ⟨csh, h⟩,
refine ⟨csh, eq.symm _⟩,
rw [show id = add 0, from rfl, h],
apply tactic.ring.horner_add_horner_gt,
{ change (_ + k : ℕ) = _,
rw [← int.coe_nat_inj', int.coe_nat_add,
eq_comm, ← sub_eq_iff_eq_add'],
simpa using congr_arg (coe : znum → ℤ) e },
{ refl },
{ apply add_comm } },
{ have : (horner a₂ x₁ (num.pos k) 0).is_cs := ⟨csa₂, 0, rfl⟩,
simp [B₁ csb₁ csb₂, A₁ csa₁ this],
symmetry, apply tactic.ring.horner_add_horner_lt,
{ change (_ + k : ℕ) = _,
rw [← int.coe_nat_inj', int.coe_nat_add,
eq_comm, ← sub_eq_iff_eq_add', ← neg_inj', neg_sub],
simpa using congr_arg (coe : znum → ℤ) e },
all_goals { refl } } },
{ rcases B₂ csb₂ _ _ B₁ ⟨csa₁, csb₁⟩ with ⟨csh, h⟩,
refine ⟨⟨csa₂, csh⟩, eq.symm _⟩,
apply tactic.ring.const_add_horner,
simp [h] }
end
theorem cseval_mul_const {α} [comm_semiring α] (t : tree α)
(k : num) {e : horner_expr} (cs : e.is_cs) :
(mul_const k.to_znum e).is_cs ∧
cseval t (mul_const k.to_znum e) = cseval t e * k :=
begin
simp [mul_const],
split_ifs with h h,
{ cases (num.to_znum_inj.1 h : k = 0),
exact ⟨⟨0, rfl⟩, (mul_zero _).symm⟩ },
{ cases (num.to_znum_inj.1 h : k = 1),
exact ⟨cs, (mul_one _).symm⟩ },
induction e with n a x n b A B; simp *,
{ rcases cs with ⟨n, rfl⟩,
suffices, refine ⟨⟨n * k, this⟩, _⟩,
swap, {cases n; cases k; refl},
rw [show _, from this], simp! },
{ cases cs, simp! *,
symmetry, apply tactic.ring.horner_mul_const; refl }
end
theorem cseval_mul {α} [comm_semiring α] (t : tree α)
{e₁ e₂ : horner_expr} (cs₁ : e₁.is_cs) (cs₂ : e₂.is_cs) :
(mul e₁ e₂).is_cs ∧
cseval t (mul e₁ e₂) = cseval t e₁ * cseval t e₂ :=
begin
induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂; simp!,
{ rcases cs₁ with ⟨n₁, rfl⟩,
simpa [mul_comm] using cseval_mul_const t n₁ cs₂ },
induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂,
{ rcases cs₂ with ⟨n₂, rfl⟩,
simpa! using cseval_mul_const t n₂ cs₁ },
cases cs₁ with csa₁ csb₁, cases id cs₂ with csa₂ csb₂,
simp!, have C := pos_num.cmp_to_nat x₁ x₂,
cases A₂ csa₂ with csA₂ hA₂,
cases pos_num.cmp x₁ x₂; simp!,
{ simp [A₁ csa₁ cs₂, B₁ csb₁ cs₂],
symmetry, apply tactic.ring.horner_mul_const; refl },
{ cases cseval_horner' t _ x₁ n₂ 0 csA₂ ⟨0, rfl⟩ with csh₁ h₁,
cases C, split_ifs,
{ subst b₂,
refine ⟨csh₁, h₁.trans (eq.symm _)⟩,
apply tactic.ring.horner_mul_horner_zero; try {refl},
simp! [hA₂] },
{ cases A₁ csa₁ csb₂ with csA₁ hA₁,
cases cseval_add t csh₁ _ with csh₂ h₂,
{ refine ⟨csh₂, h₂.trans (eq.symm _)⟩,
apply tactic.ring.horner_mul_horner; try {refl},
simp! * },
exact ⟨csA₁, (B₁ csb₁ csb₂).1⟩ } },
{ simp [A₂ csa₂, B₂ csb₂], rw [mul_comm, eq_comm],
apply tactic.ring.horner_const_mul,
{apply mul_comm}, {refl} },
end
theorem cseval_pow {α} [comm_semiring α] (t : tree α)
{x : horner_expr} (cs : x.is_cs) :
∀ (n : num), (pow x n).is_cs ∧
cseval t (pow x n) = cseval t x ^ (n : ℕ)
| 0 := ⟨⟨1, rfl⟩, (pow_zero _).symm⟩
| (num.pos p) := begin
simp [pow], induction p with p ep p ep,
{ simp * },
{ simp [pow_bit1],
cases cseval_mul t ep.1 ep.1 with cs₀ h₀,
cases cseval_mul t cs₀ cs with cs₁ h₁,
simp * },
{ simp [pow_bit0],
cases cseval_mul t ep.1 ep.1 with cs₀ h₀,
simp * }
end
/-- For any given tree `t` of atoms and any reflected expression `r`,
the Horner form of `r` is a valid csring expression, and under `t`,
the Horner form evaluates to the same thing as `r`. -/
theorem cseval_of_csexpr {α} [comm_semiring α] (t : tree α) :
∀ (r : csring_expr), (of_csexpr r).is_cs ∧ cseval t (of_csexpr r) = r.eval t
| (csring_expr.atom n) := cseval_atom _ _
| (csring_expr.const n) := ⟨⟨n, rfl⟩, by cases n; refl⟩
| (csring_expr.add x y) :=
let ⟨cs₁, h₁⟩ := cseval_of_csexpr x,
⟨cs₂, h₂⟩ := cseval_of_csexpr y,
⟨cs, h⟩ := cseval_add t cs₁ cs₂ in ⟨cs, by simp! [h, *]⟩
| (csring_expr.mul x y) :=
let ⟨cs₁, h₁⟩ := cseval_of_csexpr x,
⟨cs₂, h₂⟩ := cseval_of_csexpr y,
⟨cs, h⟩ := cseval_mul t cs₁ cs₂ in ⟨cs, by simp! [h, *]⟩
| (csring_expr.pow x n) :=
let ⟨cs, h⟩ := cseval_of_csexpr x,
⟨cs, h⟩ := cseval_pow t cs n in ⟨cs, by simp! [h, *]⟩
end horner_expr
/-- The main proof-by-reflection theorem. Given reflected csring expressions
`r₁` and `r₂` plus a storage `t` of atoms, if both expressions go to the
same Horner normal form, then the original non-reflected expressions are
equal. `H` follows from kernel reduction and is therefore `rfl`. -/
theorem correctness {α} [comm_semiring α] (t : tree α) (r₁ r₂ : csring_expr)
(H : horner_expr.of_csexpr r₁ = horner_expr.of_csexpr r₂) :
r₁.eval t = r₂.eval t :=
by repeat {rw ← (horner_expr.cseval_of_csexpr t _).2}; rw H
/-- Reflects a csring expression into a `csring_expr`, together
with a dlist of atoms, i.e. opaque variables over which the
expression is a polynomial. -/
meta def reflect_expr : expr → csring_expr × dlist expr
| `(%%e₁ + %%e₂) :=
let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in
(r₁.add r₂, l₁ ++ l₂)
/-| `(%%e₁ - %%e₂) :=
let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in
(r₁.add r₂.neg, l₁ ++ l₂)
| `(- %%e) := let (r, l) := reflect_expr e in (r.neg, l)-/
| `(%%e₁ * %%e₂) :=
let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in
(r₁.mul r₂, l₁ ++ l₂)
/-| `(has_inv.inv %%e) := let (r, l) := reflect_expr e in (r.neg, l)
| `(%%e₁ / %%e₂) :=
let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in
(r₁.mul r₂.inv, l₁ ++ l₂)-/
| e@`(%%e₁ ^ %%e₂) :=
match reflect_expr e₁, expr.to_nat e₂ with
| (r₁, l₁), some n₂ := (r₁.pow (num.of_nat' n₂), l₁)
| (r₁, l₁), none := (csring_expr.atom 1, dlist.singleton e)
end
| e := match expr.to_nat e with
| some n := (csring_expr.const (num.of_nat' n), dlist.empty)
| none := (csring_expr.atom 1, dlist.singleton e)
end
/-- In the output of `reflect_expr`, `atom`s are initialized with incorrect indices.
The indices cannot be computed until the whole tree is built, so another pass over
the expressions is needed - this is what `replace` does. The computation (expressed
in the state monad) fixes up `atom`s to match their positions in the atom tree.
The initial state is a list of all atom occurrences in the goal, left-to-right. -/
meta def csring_expr.replace (t : tree expr) : csring_expr → state_t (list expr) option csring_expr
| (csring_expr.atom _) := do e ← get,
p ← monad_lift (t.index_of (<) e.head),
put e.tail, pure (csring_expr.atom p)
| (csring_expr.const n) := pure (csring_expr.const n)
| (csring_expr.add x y) := csring_expr.add <$> x.replace <*> y.replace
| (csring_expr.mul x y) := csring_expr.mul <$> x.replace <*> y.replace
| (csring_expr.pow x n) := (λ x, csring_expr.pow x n) <$> x.replace
--| (csring_expr.neg x) := csring_expr.neg <$> x.replace
--| (csring_expr.inv x) := csring_expr.inv <$> x.replace
end tactic.ring2
namespace tactic
namespace interactive
open interactive interactive.types lean.parser
open tactic.ring2
local postfix `?`:9001 := optional
/-- `ring2` solves equations in the language of rings.
It supports only the commutative semiring operations, i.e. it does not normalize subtraction or division.
This variant on the `ring` tactic uses kernel computation instead
of proof generation. In general, you should use `ring` instead of `ring2`. -/
meta def ring2 : tactic unit :=
do `[repeat {rw ← nat.pow_eq_pow}],
`(%%e₁ = %%e₂) ← target
| fail "ring2 tactic failed: the goal is not an equality",
α ← infer_type e₁,
expr.sort (level.succ u) ← infer_type α,
let (r₁, l₁) := reflect_expr e₁,
let (r₂, l₂) := reflect_expr e₂,
let L := (l₁ ++ l₂).to_list,
let s := tree.of_rbnode (rbtree_of L).1,
(r₁, L) ← (state_t.run (r₁.replace s) L : option _),
(r₂, _) ← (state_t.run (r₂.replace s) L : option _),
let se : expr := s.reflect' u α,
let er₁ : expr := reflect r₁,
let er₂ : expr := reflect r₂,
cs ← mk_app ``comm_semiring [α] >>= mk_instance,
e ← to_expr ``(correctness %%se %%er₁ %%er₂ rfl)
<|> fail ("ring2 tactic failed, cannot show equality:\n"
++ to_string (horner_expr.of_csexpr r₁) ++
"\n =?=\n" ++ to_string (horner_expr.of_csexpr r₂)),
tactic.exact e
add_tactic_doc
{ name := "ring2",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ring2],
tags := ["arithmetic", "simplification", "decision procedure"] }
end interactive
end tactic
namespace conv.interactive
open conv
meta def ring2 : conv unit := discharge_eq_lhs tactic.interactive.ring2
end conv.interactive
|
e878b4f48581328da46604876c43ae0ad25fc4ad | 5df84495ec6c281df6d26411cc20aac5c941e745 | /src/formal_ml/random_variable_identical.lean | 9fbbdaab36e3a5d3c4266620d3f72378221d81a9 | [
"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,974 | lean | /-
Copyright 2021 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.sum
import formal_ml.lattice
import formal_ml.measurable_space
import formal_ml.classical
import data.equiv.list
import formal_ml.prod_measure
import formal_ml.finite_pi_measure
import formal_ml.probability_space
import formal_ml.monotone_class
/-!
This file focuses on more esoteric proofs that random variables are identical.
In particular, given two random variables X Y with a common measurable space as a codomain,
where the codomain is generated by some set of measurable sets S.
X and Y are identical if they are identical on measurable sets in S, assuming S
has some particular properties. The first is that S is an algebra, i.e. S has the
universal set and is closed under set difference.
An alternative is that S is (basically) a semi-algebra, i.e. it has the empty set
and is closed under intersection, and semi-closed under complement. Normally, a
semi-algebra would require the universal set, but that is not required for this
purpose.
This is most useful for proving independent and identical random variables, when
considered as an aggregate random variable, are identical.
The core is the monotone class theorem, measurable_space.generate_from_monotone_class.
-/
lemma random_variable_identical_on_algebra''' {Ω₁ Ω₂ α:Type*} (s: set (set α))
(A:s.is_algebra)
{P₁:probability_space Ω₁} {P₂:probability_space Ω₂}
{X₁:P₁ →ᵣ (measurable_space.generate_from s)}
{X₂:P₂ →ᵣ (measurable_space.generate_from s)}:
(∀ (T:measurable_setB (measurable_space.generate_from s)),
T.val ∈ s → Pr[X₁ ∈ᵣ T] = Pr[X₂ ∈ᵣ T]) →
random_variable_identical X₁ X₂ :=
begin
intros h3 U,
cases U,
have AM := A.monotone_class,
have h7:∀ {T':set α}, s.monotone_class T' →
(measurable_space.generate_from s).measurable_set' T',
{ intros T h7_1,
rw measurable_space.generate_from_monotone_class at h7_1,
simp [measurable_space.generate_from],
apply h7_1, apply A },
have h4:measurable_space.generate_measurable s U_val,
{ simp [measurable_space.generate_from] at U_property,
apply U_property },
have h5:s.monotone_class U_val,
{ rw measurable_space.generate_from_monotone_class,
apply h4, apply A },
induction h5 with U' h_U' f h_rec h_mono h_ind f h_rec h_mono h_ind,
{ apply h3, apply h_U' },
{ have h6:(∀ᵣ i, X₁ ∈ᵣ ⟨f i, h7 (h_rec i)⟩) = (X₁ ∈ᵣ ⟨set.Inter f, U_property⟩) ,
{ apply event.eq, simp, ext ω, split; intros h6_1; simp at h6_1; simp [h6_1], },
rw ← h6,
have h7:(∀ᵣ i, X₂ ∈ᵣ ⟨f i, h7 (h_rec i)⟩) = (X₂ ∈ᵣ ⟨set.Inter f, U_property⟩) ,
{ apply event.eq, simp, ext ω, split; intros h7_1; simp at h7_1; simp [h7_1], },
rw ← h7,
rw Pr_forall_revent_eq_infi,
rw Pr_forall_revent_eq_infi,
have h8:(λ (i : ℕ), Pr[X₁ ∈ᵣ ⟨f i, _⟩]) = λ (i : ℕ), Pr[X₂ ∈ᵣ ⟨f i, _⟩],
{ ext1 i, apply h_ind,
rw ← measurable_space.generate_from_monotone_class,
apply h_rec, apply A },
rw h8,
simp, apply h_mono,
simp, apply h_mono },
{ have h9:(∃ᵣ i, X₁ ∈ᵣ ⟨f i, h7 (h_rec i)⟩) = (X₁ ∈ᵣ ⟨set.Union f, U_property⟩) ,
{ apply event.eq, simp, ext ω, split; intros h9_1; simp at h9_1; simp [h9_1], },
rw ← h9,
have h10:(∃ᵣ i, X₂ ∈ᵣ ⟨f i, h7 (h_rec i)⟩) = (X₂ ∈ᵣ ⟨set.Union f, U_property⟩) ,
{ apply event.eq, simp, ext ω, split; intros h10_1; simp at h10_1; simp [h10_1] },
rw ← h10,
rw Pr_exists_revent_eq_supr,
rw Pr_exists_revent_eq_supr,
have h11:(λ (i : ℕ), Pr[X₁ ∈ᵣ ⟨f i, _⟩]) = λ (i : ℕ), Pr[X₂ ∈ᵣ ⟨f i, _⟩],
{ ext1 i, apply h_ind,
rw ← measurable_space.generate_from_monotone_class,
apply h_rec, apply A },
rw h11,
simp, apply h_mono,
simp, apply h_mono },
end
lemma random_variable_identical_on_algebra {Ω₁ Ω₂ α:Type*} (s: set (set α))
{P₁:probability_space Ω₁} {P₂:probability_space Ω₂}
{X₁:P₁ →ᵣ (measurable_space.generate_from s)}
{X₂:P₂ →ᵣ (measurable_space.generate_from s)}:
(set.univ ∈ s) →
(∀ a b, a∈ s → b ∈ s → a \ b ∈ s) →
(∀ (T:measurable_setB (measurable_space.generate_from s)),
T.val ∈ s → Pr[X₁ ∈ᵣ T] = Pr[X₂ ∈ᵣ T]) →
random_variable_identical X₁ X₂ :=
begin
intros h1 h2 h3,
apply random_variable_identical_on_algebra''',
apply set.is_algebra.mk h1 h2,
apply h3,
end
/- This allows for the measurable space to be generated from a different
set. -/
lemma random_variable_identical_on_algebra' {Ω₁ Ω₂ α:Type*} (s: set (set α))
(M:measurable_space α)
{P₁:probability_space Ω₁} {P₂:probability_space Ω₂}
{X₁:P₁ →ᵣ M}
{X₂:P₂ →ᵣ M}:
(set.univ ∈ s) →
(∀ a b, a∈ s → b ∈ s → a \ b ∈ s) →
(M = measurable_space.generate_from s) →
(∀ (T:measurable_setB M),
T.val ∈ s → Pr[X₁ ∈ᵣ T] = Pr[X₂ ∈ᵣ T]) →
random_variable_identical X₁ X₂ :=
begin
intros h1 h2 h3 h4 T',
tactic.unfreeze_local_instances,
subst M,
apply random_variable_identical_on_algebra,
apply h1,
apply h2,
apply h4,
end
#check measurable_space.generate_from
lemma random_variable_identical_on_algebra'' {Ω₁ Ω₂ α:Type*} (s t: set (set α))
{P₁:probability_space Ω₁} {P₂:probability_space Ω₂}
{X₁:P₁ →ᵣ (measurable_space.generate_from t)}
{X₂:P₂ →ᵣ (measurable_space.generate_from t)}:
(set.univ ∈ s) →
(∀ a b, a∈ s → b ∈ s → a \ b ∈ s) →
(t ⊆ s) →
(∀ a∈ s, (measurable_space.generate_from t).measurable_set' a) →
(∀ (T:measurable_setB (measurable_space.generate_from t)),
T.val ∈ s → Pr[X₁ ∈ᵣ T] = Pr[X₂ ∈ᵣ T]) →
random_variable_identical X₁ X₂ :=
begin
intros h1 h2 h3 h4 h5,
have h6:(measurable_space.generate_from t) = (measurable_space.generate_from s),
{ apply le_antisymm;
apply measurable_space.generate_from_le;
intros a h_a,
{ simp [measurable_space.generate_from],
apply measurable_space.generate_measurable.basic,
apply h3, apply h_a },
apply h4, apply h_a },
apply random_variable_identical_on_algebra',
apply h1,
apply h2,
apply h6,
apply h5,
end
lemma equality_disjoint_union_closure {Ω₁ Ω₂ α:Type*} (S : set (set α))
{P₁:probability_space Ω₁} {P₂:probability_space Ω₂}
{X₁:P₁ →ᵣ (measurable_space.generate_from S)}
{X₂:P₂ →ᵣ (measurable_space.generate_from S)}:
(∀ (T:measurable_setB (measurable_space.generate_from S)),
T.val ∈ S → Pr[X₁ ∈ᵣ T] = Pr[X₂ ∈ᵣ T]) →
(∀ (T:measurable_setB (measurable_space.generate_from S)),
T.val ∈ S.disjoint_union_closure → Pr[X₁ ∈ᵣ T] = Pr[X₂ ∈ᵣ T]) :=
begin
intros h4,
intros T h_T, cases T,
rw set.mem_disjoint_union_closure_iff at h_T,
cases h_T with m h_T,
cases h_T with f h_T,
cases h_T with h_f h_T,
cases h_T with h_f_pairwise h_s_def,
simp at h_s_def,
subst T_val,
have h_X1:X₁ ∈ᵣ ⟨set.Union f, T_property⟩ = (eany (λ (i:fin m), X₁ ∈ᵣ ⟨f i,
measurable_space.measurable_set_generate_from (h_f i)⟩)),
{ apply event.eq, ext ω, split; intros h_X1_1; simp at h_X1_1; cases h_X1_1 with i
h_X1_1; simp [h_X1_1]; apply exists.intro i; apply h_X1_1 },
have h_X2:X₂ ∈ᵣ ⟨set.Union f, T_property⟩ = (eany (λ (i:fin m), X₂ ∈ᵣ ⟨f i,
measurable_space.measurable_set_generate_from (h_f i)⟩)),
{ apply event.eq, ext ω, split; intros h_X1_1; simp at h_X1_1; cases h_X1_1 with i
h_X1_1; simp [h_X1_1]; apply exists.intro i; apply h_X1_1 },
rw h_X1, rw h_X2,
rw Pr_eany_sum,
rw Pr_eany_sum,
{ congr, ext1 b, apply h4, simp, apply h_f },
{ intros i j h_ne, simp only [function.on_fun], apply disjoint_preimage,
apply h_f_pairwise, apply h_ne },
{ intros i j h_ne, simp only [function.on_fun], apply disjoint_preimage,
apply h_f_pairwise, apply h_ne },
end
#check 3
#check 3
lemma random_variable_identical_on_semialgebra''' {Ω₁ Ω₂ α:Type*} (S : set (set α))
(A:S.is_semialgebra)
{P₁:probability_space Ω₁} {P₂:probability_space Ω₂}
{X₁:P₁ →ᵣ (measurable_space.generate_from S)}
{X₂:P₂ →ᵣ (measurable_space.generate_from S)}:
(∀ (T:measurable_setB (measurable_space.generate_from S)),
T.val ∈ S → Pr[X₁ ∈ᵣ T] = Pr[X₂ ∈ᵣ T]) →
random_variable_identical X₁ X₂ :=
begin
intros h4,
have CA := A.disjoint_union_closure,
apply random_variable_identical_on_algebra'' S.disjoint_union_closure,
{ apply CA.univ },
{ apply CA.diff },
{ intros a h_a, apply set.disjoint_union_closure_self, apply h_a },
{ intros s h_s,
rw set.mem_disjoint_union_closure_iff at h_s,
cases h_s with m h_s,
cases h_s with f h_s,
cases h_s with h_f h_s,
cases h_s with h_f_pairwise h_s_def,
subst s,
haveI:fintype (fin m) := fin.fintype m,
haveI:encodable (fin m) := fintype.encodable (fin m),
simp, apply measurable_set.Union,
intro b, apply measurable_space.measurable_set_generate_from,
apply h_f },
{ apply equality_disjoint_union_closure,
apply h4 },
end
#check 12
#check 3
lemma random_variable_identical_on_semialgebra {Ω₁ Ω₂ α:Type*} (S : set (set α))
{P₁:probability_space Ω₁} {P₂:probability_space Ω₂}
{X₁:P₁ →ᵣ (measurable_space.generate_from S)}
{X₂:P₂ →ᵣ (measurable_space.generate_from S)}:
(∀ s t∈ S, s ∩ t ∈ S) →
(∀ s ∈ S, sᶜ ∈ S.disjoint_union_closure) →
(∅ ∈ S) →
(@set.univ α ∈ S) →
(∀ (T:measurable_setB (measurable_space.generate_from S)),
T.val ∈ S → Pr[X₁ ∈ᵣ T] = Pr[X₂ ∈ᵣ T]) →
random_variable_identical X₁ X₂ :=
begin
intros h1 h2 h3 h_univ h4,
have A := set.is_semialgebra.mk h_univ h3 h1 h2,
apply random_variable_identical_on_semialgebra''',
apply A,
apply h4,
end
/- TODO: technically, could remove empty set or the universe, and it would
still be true. -/
lemma random_variable_identical_on_semialgebra' {Ω₁ Ω₂ α:Type*} (S : set (set α))
(M:measurable_space α)
{P₁:probability_space Ω₁} {P₂:probability_space Ω₂}
{X₁:P₁ →ᵣ M}
{X₂:P₂ →ᵣ M}:
(∀ s t∈ S, s ∩ t ∈ S) →
(∀ s ∈ S, sᶜ ∈ S.disjoint_union_closure) →
(∅ ∈ S) →
(set.univ ∈ S) →
(M = measurable_space.generate_from S) →
(∀ (T:measurable_setB M),
T.val ∈ S → Pr[X₁ ∈ᵣ T] = Pr[X₂ ∈ᵣ T]) →
random_variable_identical X₁ X₂ :=
begin
intros h1 h2 h3 h_univ h4 h5,
tactic.unfreeze_local_instances,
subst M,
apply random_variable_identical_on_semialgebra,
apply h1,
apply h2,
apply h3,
apply h_univ,
apply h5,
end
lemma random_variable_identical_on_semialgebra'' {Ω₁ Ω₂ α:Type*} (s t: set (set α))
{P₁:probability_space Ω₁} {P₂:probability_space Ω₂}
{X₁:P₁ →ᵣ (measurable_space.generate_from t)}
{X₂:P₂ →ᵣ (measurable_space.generate_from t)}:
(∀ a b∈ s, a ∩ b ∈ s) →
(∀ a ∈ s, aᶜ ∈ s.disjoint_union_closure) →
(∅ ∈ s) →
(set.univ ∈ s) →
(t ⊆ s) →
(∀ a∈ s, (measurable_space.generate_from t).measurable_set' a) →
(∀ (T:measurable_setB (measurable_space.generate_from t)),
T.val ∈ s → Pr[X₁ ∈ᵣ T] = Pr[X₂ ∈ᵣ T]) →
random_variable_identical X₁ X₂ :=
begin
intros h1 h2 h_empty h_univ h3 h4 h5,
have h6:(measurable_space.generate_from t) = (measurable_space.generate_from s),
{ apply le_antisymm;
apply measurable_space.generate_from_le;
intros a h_a,
{ simp [measurable_space.generate_from],
apply measurable_space.generate_measurable.basic,
apply h3, apply h_a },
apply h4, apply h_a },
apply random_variable_identical_on_semialgebra',
apply h1,
apply h2,
apply h_empty,
apply h_univ,
apply h6,
apply h5,
end
|
a104e3ade0a09919f14ceb90c66b925c76e73c22 | 649957717d58c43b5d8d200da34bf374293fe739 | /src/category_theory/monoidal/category_aux.lean | 6e3382df90afe9f9e4eba1ae54ddea0d7c54ab56 | [
"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 | 3,221 | lean | /-
-- Copyright (c) 2018 Michael Jendrusch. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Michael Jendrusch, Scott Morrison
--
-- Auxiliary definitions for the definition of a monoidal category.
-/
import category_theory.products
universes v u
open category_theory
namespace category_theory
@[reducible] def tensor_obj_type
(C : Type u) [category.{v} C] :=
C → C → C
@[reducible] def tensor_hom_type
{C : Type u} [category.{v} C] (tensor_obj : tensor_obj_type C) : Sort (imax (u+1) (u+1) (u+1) (u+1) v) :=
Π {X₁ Y₁ X₂ Y₂ : C}, (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((tensor_obj X₁ X₂) ⟶ (tensor_obj Y₁ Y₂))
def assoc_obj
{C : Type u} [category.{v} C] (tensor_obj : tensor_obj_type C) : Sort (max (u+1) v) :=
Π X Y Z : C, (tensor_obj (tensor_obj X Y) Z) ≅ (tensor_obj X (tensor_obj Y Z))
def assoc_natural
{C : Type u} [category.{v} C]
(tensor_obj : tensor_obj_type C)
(tensor_hom : tensor_hom_type tensor_obj)
(assoc : assoc_obj tensor_obj) : Prop :=
∀ {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃),
(tensor_hom (tensor_hom f₁ f₂) f₃) ≫ (assoc Y₁ Y₂ Y₃).hom = (assoc X₁ X₂ X₃).hom ≫ (tensor_hom f₁ (tensor_hom f₂ f₃))
def left_unitor_obj
{C : Type u} [category.{v} C]
(tensor_obj : tensor_obj_type C)
(tensor_unit : C) : Sort (max (u+1) v) :=
Π X : C, (tensor_obj tensor_unit X) ≅ X
def left_unitor_natural
{C : Type u} [category.{v} C]
(tensor_obj : tensor_obj_type C)
(tensor_hom : tensor_hom_type tensor_obj)
(tensor_unit : C)
(left_unitor : left_unitor_obj tensor_obj tensor_unit) : Prop :=
∀ {X Y : C} (f : X ⟶ Y),
(tensor_hom (𝟙 tensor_unit) f) ≫ (left_unitor Y).hom = (left_unitor X).hom ≫ f
def right_unitor_obj
{C : Type u} [category.{v} C]
(tensor_obj : tensor_obj_type C)
(tensor_unit : C) : Sort (max (u+1) v 1) :=
Π (X : C), (tensor_obj X tensor_unit) ≅ X
def right_unitor_natural
{C : Type u} [category.{v} C]
(tensor_obj : tensor_obj_type C)
(tensor_hom : tensor_hom_type tensor_obj)
(tensor_unit : C)
(right_unitor : right_unitor_obj tensor_obj tensor_unit) : Prop :=
∀ {X Y : C} (f : X ⟶ Y),
(tensor_hom f (𝟙 tensor_unit)) ≫ (right_unitor Y).hom = (right_unitor X).hom ≫ f
@[reducible] def pentagon
{C : Type u} [category.{v} C]
{tensor_obj : tensor_obj_type C}
(tensor_hom : tensor_hom_type tensor_obj)
(assoc : assoc_obj tensor_obj) : Prop :=
∀ W X Y Z : C,
(tensor_hom (assoc W X Y).hom (𝟙 Z)) ≫ (assoc W (tensor_obj X Y) Z).hom ≫ (tensor_hom (𝟙 W) (assoc X Y Z).hom)
= (assoc (tensor_obj W X) Y Z).hom ≫ (assoc W X (tensor_obj Y Z)).hom
@[reducible] def triangle
{C : Type u} [category.{v} C]
{tensor_obj : tensor_obj_type C} {tensor_unit : C}
(tensor_hom : tensor_hom_type tensor_obj)
(left_unitor : left_unitor_obj tensor_obj tensor_unit)
(right_unitor : right_unitor_obj tensor_obj tensor_unit)
(assoc : assoc_obj tensor_obj) : Prop :=
∀ X Y : C,
(assoc X tensor_unit Y).hom ≫ (tensor_hom (𝟙 X) (left_unitor Y).hom)
= tensor_hom (right_unitor X).hom (𝟙 Y)
end category_theory
|
0afc421847c618e6e475986d8b40b4af470cc604 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/topology/separation.lean | 23673b896eabee349da7a1c77965ddb32c7741ea | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 57,585 | 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
/-!
# 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_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.
* `regular_space`: A T₃ space (sometimes referred to as regular, but authors vary on
whether this includes T₂; `mathlib` does), 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₃.
## 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_disjoing_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.
* `tot_sep_of_zero_dim`: If `α` has a clopen basis, 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 set filter
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
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 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 union_left {a b c : set α} : separated a c → separated b c → separated (a ∪ b) c :=
λ ⟨U, V, oU, oV, aU, bV, UV⟩ ⟨W, X, oW, oX, aW, bX, WX⟩,
⟨U ∪ W, V ∩ X, is_open.union oU oW, is_open.inter oV oX,
union_subset_union aU aW, subset_inter bV bX, set.disjoint_union_left.mpr
⟨disjoint_of_subset_right (inter_subset_left _ _) UV,
disjoint_of_subset_right (inter_subset_right _ _) WX⟩⟩
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
where for every pair `x ≠ y`, there is an open set containing one but not the other. -/
class t0_space (α : Type u) [topological_space α] : Prop :=
(t0 : ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U)))
/-- 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,
by_cases hnt : ∃ (x y : α) (hx : x ∈ V) (hy : y ∈ V), x ≠ y,
{ exfalso,
obtain ⟨x, y, hx, hy, hne⟩ := hnt,
obtain ⟨U, hU, hsep⟩ := t0_space.t0 _ _ hne,
have : ∀ (z w : α) (hz : z ∈ V) (hw : w ∈ V) (hz' : z ∈ U) (hw' : ¬ w ∈ U), false,
{ intros z w hz hw hz' hw',
have uvne : (V ∩ Uᶜ).nonempty,
{ use w, simp only [hw, hw', set.mem_inter_eq, not_false_iff, and_self, set.mem_compl_eq], },
specialize hV (V ∩ Uᶜ) (set.inter_subset_left _ _) uvne
(is_closed.inter Vcls (is_closed_compl_iff.mpr hU)),
have : V ⊆ Uᶜ,
{ rw ←hV, exact set.inter_subset_right _ _ },
exact this hz hz', },
cases hsep,
{ exact this x y hx hy hsep.1 hsep.2 },
{ exact this y x hy hx hsep.1 hsep.2 } },
{ push_neg at hnt,
obtain ⟨z, hz⟩ := Vne,
refine ⟨z, Vsub hz, _⟩,
convert Vcls,
ext,
simp only [set.mem_singleton_iff, set.mem_compl_eq],
split,
{ rintro rfl, exact hz, },
{ exact λ hx, hnt x z hx hz, }, },
end
/-- Given an open `finset` `S` in a T₀ space, there is some `x ∈ S` such that `{x}` is open. -/
theorem exists_open_singleton_of_open_finset [t0_space α] (s : finset α) (sne : s.nonempty)
(hso : is_open (s : set α)) :
∃ x ∈ s, is_open ({x} : set α):=
begin
induction s using finset.strong_induction_on with s ihs,
by_cases hs : set.subsingleton (s : set α),
{ rcases sne with ⟨x, hx⟩,
refine ⟨x, hx, _⟩,
have : (s : set α) = {x}, from hs.eq_singleton_of_mem hx,
rwa this at hso },
{ dunfold set.subsingleton at hs,
push_neg at hs,
rcases hs with ⟨x, hx, y, hy, hxy⟩,
rcases t0_space.t0 x y hxy with ⟨U, hU, hxyU⟩,
wlog H : x ∈ U ∧ y ∉ U := hxyU using [x y, y x],
obtain ⟨z, hzs, hz⟩ : ∃ z ∈ s.filter (λ z, z ∈ U), is_open ({z} : set α),
{ refine ihs _ (finset.filter_ssubset.2 ⟨y, hy, H.2⟩) ⟨x, finset.mem_filter.2 ⟨hx, H.1⟩⟩ _,
rw [finset.coe_filter],
exact is_open.inter hso hU },
exact ⟨z, (finset.mem_filter.1 hzs).1, hz⟩ }
end
theorem exists_open_singleton_of_fintype [t0_space α] [f : fintype α] [ha : nonempty α] :
∃ x:α, is_open ({x}:set α) :=
begin
refine ha.elim (λ x, _),
have : is_open ((finset.univ : finset α) : set α), { simp },
rcases exists_open_singleton_of_open_finset _ ⟨x, finset.mem_univ x⟩ this with ⟨x, _, hx⟩,
exact ⟨x, hx⟩
end
instance subtype.t0_space [t0_space α] {p : α → Prop} : t0_space (subtype p) :=
⟨λ x y hxy, let ⟨U, hU, hxyU⟩ := t0_space.t0 (x:α) y ((not_congr subtype.ext_iff_val).1 hxy) in
⟨(coe : subtype p → α) ⁻¹' U, is_open_induced hU, hxyU⟩⟩
/-- 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
instance subtype.t1_space {α : Type u} [topological_space α] [t1_space α] {p : α → Prop} :
t1_space (subtype p) :=
⟨λ ⟨x, hx⟩, is_closed_induced_iff.2 $ ⟨{x}, is_closed_singleton, set.ext $ λ y,
by simp [subtype.ext_iff_val]⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance t1_space.t0_space [t1_space α] : t0_space α :=
⟨λ x y h, ⟨{z | z ≠ y}, is_open_ne, or.inl ⟨h, not_not_intro rfl⟩⟩⟩
lemma t1_iff_exists_open : t1_space α ↔
∀ (x y), x ≠ y → (∃ (U : set α) (hU : is_open U), x ∈ U ∧ y ∉ U) :=
begin
split,
{ introsI t1 x y hxy,
exact ⟨{y}ᶜ, is_open_compl_iff.mpr (t1_space.t1 y),
mem_compl_singleton_iff.mpr hxy,
not_not.mpr rfl⟩},
{ intro h,
constructor,
intro x,
rw ← is_open_compl_iff,
have p : ⋃₀ {U : set α | (x ∉ U) ∧ (is_open U)} = {x}ᶜ,
{ apply subset.antisymm; intros t ht,
{ rcases ht with ⟨A, ⟨hxA, hA⟩, htA⟩,
rw [mem_compl_eq, mem_singleton_iff],
rintro rfl,
contradiction },
{ obtain ⟨U, hU, hh⟩ := h t x (mem_compl_singleton_iff.mp ht),
exact ⟨U, ⟨hh.2, hU⟩, hh.1⟩}},
rw ← p,
exact is_open_sUnion (λ B hB, hB.2) }
end
lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : {x}ᶜ ∈ 𝓝 y :=
is_open.mem_nhds is_open_compl_singleton $ by rwa [mem_compl_eq, mem_singleton_iff]
@[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.mono subset_closure, λ h, h.closure⟩
lemma is_closed_map_const {α β} [topological_space α] [topological_space β] [t1_space β] {y : β} :
is_closed_map (function.const α y) :=
begin
apply is_closed_map.of_nonempty, intros s hs h2s, simp_rw [h2s.image_const, is_closed_singleton]
end
lemma discrete_of_t1_of_finite {X : Type*} [topological_space X] [t1_space X] [fintype X] :
discrete_topology X :=
begin
apply singletons_open_iff_discrete.mp,
intros x,
rw [← is_closed_compl_iff, ← bUnion_of_singleton ({x} : set X)ᶜ],
exact is_closed_bUnion (finite.of_fintype _) (λ y _, is_closed_singleton)
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}ᶜ] 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) :=
begin
constructor,
rw discrete_topology.eq_bot Y,
exact induced_bot hf
end
/-- 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. -/
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 ∧ u ∩ v = ∅)
lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) :
∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ :=
t2_space.t2 x y h
@[priority 100] -- see Note [lower instance priority]
instance t2_space.t1_space [t2_space α] : t1_space α :=
⟨λ x, is_open_compl_iff.1 $ is_open_iff_forall_mem_open.2 $ λ y hxy,
let ⟨u, v, hu, hv, hyu, hxv, huv⟩ := t2_separation (mt mem_singleton_of_eq hxy) in
⟨u, λ z hz1 hz2, (ext_iff.1 huv x).1 ⟨mem_singleton_iff.1 hz2 ▸ hz1, hxv⟩, hu, hyu⟩⟩
lemma eq_of_nhds_ne_bot [ht : t2_space α] {x y : α} (h : ne_bot (𝓝 x ⊓ 𝓝 y)) : x = y :=
classical.by_contradiction $ assume : x ≠ y,
let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in
absurd huv $ (inf_ne_bot_iff.1 h (is_open.mem_nhds hu hx) (is_open.mem_nhds hv hy)).ne_empty
/-- 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 :=
⟨assume h, by exactI λ x y, eq_of_nhds_ne_bot,
assume h, ⟨assume x y xy,
have 𝓝 x ⊓ 𝓝 y = ⊥ := not_ne_bot.1 $ mt h xy,
let ⟨u', hu', v', hv', u'v'⟩ := empty_in_sets_eq_bot.mpr this,
⟨u, uu', uo, hu⟩ := mem_nhds_iff.mp hu',
⟨v, vv', vo, hv⟩ := mem_nhds_iff.mp hv' in
⟨u, v, uo, vo, hu, hv, disjoint.eq_bot $ disjoint.mono uu' vv' u'v'⟩⟩⟩
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 is_closed_diagonal [t2_space α] : is_closed (diagonal α) :=
begin
refine is_closed_iff_cluster_pt.mpr _,
rintro ⟨a₁, a₂⟩ h,
refine eq_of_nhds_ne_bot ⟨λ this : 𝓝 a₁ ⊓ 𝓝 a₂ = ⊥, h.ne _⟩,
obtain ⟨t₁, (ht₁ : t₁ ∈ 𝓝 a₁), t₂, (ht₂ : t₂ ∈ 𝓝 a₂), (h' : t₁ ∩ t₂ ⊆ ∅)⟩ :=
by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this,
rw [nhds_prod_eq, ←empty_in_sets_eq_bot],
apply filter.sets_of_superset,
apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)),
exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩,
show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩
end
lemma t2_iff_is_closed_diagonal : t2_space α ↔ is_closed (diagonal α) :=
begin
split,
{ introI h,
exact is_closed_diagonal },
{ intro h,
constructor,
intros x y hxy,
have : (x, y) ∈ (diagonal α)ᶜ, by rwa [mem_compl_iff],
obtain ⟨t, t_sub, t_op, xyt⟩ : ∃ t ⊆ (diagonal α)ᶜ, is_open t ∧ (x, y) ∈ t :=
is_open_iff_forall_mem_open.mp h.is_open_compl _ this,
rcases is_open_prod_iff.mp t_op x y xyt with ⟨U, V, U_op, V_op, xU, yV, H⟩,
use [U, V, U_op, V_op, xU, yV],
have := subset.trans H t_sub,
rw eq_empty_iff_forall_not_mem,
rintros z ⟨zU, zV⟩,
have : ¬ (z, z) ∈ diagonal α := this (mk_mem_prod zU zV),
exact this rfl },
end
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
(by { rw [ne.def, ← finset.mem_singleton], exact (disjoint_singleton.mp ab.symm) }),
refine ⟨U, V, oU, oV, _, _, set.disjoint_iff_inter_eq_empty.mpr 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 (singleton_disjoint.mpr h)
end separated
@[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : 𝓝 a = 𝓝 b ↔ a = b :=
⟨assume h, eq_of_nhds_ne_bot $ by rw [h, inf_idem]; exact nhds_ne_bot, assume h, h ▸ rfl⟩
@[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : 𝓝 a ≤ 𝓝 b ↔ a = b :=
⟨assume h, eq_of_nhds_ne_bot $ by rw [inf_of_le_left h]; exact nhds_ne_bot, assume h, h ▸ le_refl _⟩
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_const_nhds_iff [t2_space α] {l : filter α} [ne_bot l] {c d : α} :
tendsto (λ x, c) l (𝓝 d) ↔ c = d :=
⟨λ h, tendsto_nhds_unique (tendsto_const_nhds) h, λ h, h ▸ tendsto_const_nhds⟩
/-- 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 clousures
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 ∧
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, subset_eq_empty (powerset_mono.mpr
(closure_inter_subset_inter_closure U V) subset_closure) hUV⟩⟩
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_refl _)
@[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 t2_space_discrete {α : Type*} [topological_space α] [discrete_topology α] : t2_space α :=
{ t2 := assume x y hxy, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, rfl, rfl,
eq_empty_iff_forall_not_mem.2 $ by intros z hz;
cases eq_of_mem_singleton hz.1; cases eq_of_mem_singleton hz.2; cc⟩ }
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 ∧ 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,
by rw [←preimage_inter, uv, preimage_empty]⟩
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 ∧ 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, by rw [image_inter hf.inj, uv, image_empty]⟩
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⟩,
range_inl_inter_range_inr⟩ },
{ exact ⟨_, _, is_open_range_inr, is_open_range_inl, ⟨x, rfl⟩, ⟨y, rfl⟩,
range_inr_inter_range_inl⟩ },
{ 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 [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
/-- If two continuous maps are equal on `s`, then they are equal on the closure of `s`. -/
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 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 diagonal_eq_range_diagonal_map {α : Type*} : {p:α×α | p.1 = p.2} = range (λx, (x,x)) :=
ext $ assume p, iff.intro
(assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩)
(assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx)
lemma prod_subset_compl_diagonal_iff_disjoint {α : Type*} {s t : set α} :
set.prod s t ⊆ {p:α×α | p.1 = p.2}ᶜ ↔ s ∩ t = ∅ :=
by rw [eq_empty_iff_forall_not_mem, subset_compl_comm,
diagonal_eq_range_diagonal_map, range_subset_iff]; simp
lemma compact_compact_separated [t2_space α] {s t : set α}
(hs : is_compact s) (ht : is_compact t) (hst : s ∩ t = ∅) :
∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ 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 : is_compact {x})
(by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in
have v ⊆ sᶜ, from
subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)),
⟨v, this, vo, by simpa using xv⟩
/-- 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)
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
rcases compact_compact_separated (hK.diff hU) (hK.diff hV)
(by rwa [diff_inter_diff, diff_eq_empty]) with ⟨O₁, O₂, h1O₁, h1O₂, h2O₁, h2O₂, hO⟩,
refine ⟨_, _, hK.diff h1O₁, hK.diff h1O₂,
by rwa [diff_subset_comm], by rwa [diff_subset_comm], by rw [← diff_inter, hO, 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 (is_compact.diff kc uo)
(by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in
have wn : wᶜ ∈ 𝓝 x, from
mem_nhds_iff.mpr
⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩,
⟨k \ w,
filter.inter_mem_sets 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
end separation
section regularity
/-- A T₃ space, also known as a regular space (although this condition sometimes
omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist
disjoint open sets containing `x` and `C` respectively. -/
class regular_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 = ⊥)
@[priority 100] -- see Note [lower instance priority]
instance regular_space.t1_space [regular_space α] : t1_space α :=
begin
rw t1_iff_exists_open,
intros x y hxy,
obtain ⟨U, hU, h⟩ := t0_space.t0 x y hxy,
cases h,
{ exact ⟨U, hU, h⟩ },
{ obtain ⟨R, hR, hh⟩ := regular_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 [regular_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 regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃),
let ⟨t, ht₁, ht₂, ht₃⟩ := this in
⟨tᶜ,
mem_sets_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 [regular_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_sets_of_superset s_in hst⟩⟩
instance subtype.regular_space [regular_space α] {p : α → Prop} : regular_space (subtype p) :=
⟨begin
intros s a hs ha,
rcases is_closed_induced_iff.1 hs with ⟨s, hs', rfl⟩,
rcases regular_space.regular hs' ha with ⟨t, ht, hst, hat⟩,
refine ⟨coe ⁻¹' t, is_open_induced ht, preimage_mono hst, _⟩,
rw [nhds_within, nhds_induced, ← comap_principal, ← comap_inf, ← nhds_within, hat, comap_bot]
end⟩
variable (α)
@[priority 100] -- see Note [lower instance priority]
instance regular_space.t2_space [regular_space α] : t2_space α :=
⟨λ x y hxy,
let ⟨s, hs, hys, hxs⟩ := regular_space.regular is_closed_singleton
(mt mem_singleton_iff.1 hxy),
⟨t, hxt, u, hsu, htu⟩ := empty_in_sets_eq_bot.2 hxs,
⟨v, hvt, hv, hxv⟩ := mem_nhds_iff.1 hxt in
⟨v, s, hv, hs, hxv, singleton_subset_iff.1 hys,
eq_empty_of_subset_empty $ λ z ⟨hzv, hzs⟩, htu ⟨hvt hzv, hsu hzs⟩⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance regular_space.t2_5_space [regular_space α] : t2_5_space α :=
⟨λ x y hxy,
let ⟨U, V, hU, hV, hh_1, hh_2, hUV⟩ := t2_space.t2 x y hxy,
hxcV := not_not.mpr ((interior_maximal (subset_compl_iff_disjoint.mpr hUV) hU) hh_1),
⟨R, hR, hh⟩ := regular_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, subset_eq_empty ((closure V).inter_subset_inter_left
(subset.trans (closure_minimal hA (is_closed_compl_iff.mpr hR)) (compl_subset_compl.mpr hh.1)))
(compl_inter_self (closure V)), 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 [regular_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₂ ∧ 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₁, V₁, mem_sets_of_superset V₁_in h₁, V₁_in,
U₂, V₂, mem_sets_of_superset V₂_in h₂, V₂_in],
tauto
end
end regularity
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.regular_space [normal_space α] : regular_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_in_sets_eq_bot.1 $ filter.mem_inf_sets.2
⟨v, is_open.mem_nhds hv (singleton_subset_iff.1 hxv), u, filter.mem_principal_self u,
inter_comm u v ▸ huv⟩⟩ }
-- 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 α :=
begin
refine ⟨assume s t hs ht st, _⟩,
simp only [disjoint_iff],
exact compact_compact_separated hs.is_compact ht.is_compact st.eq_bot
end
end normality
/-- 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 _ _inst_1 (⋂ (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_empty,
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 (disjoint_iff.2 ab_empty) 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.
suffices : ∃ (Z : set α), is_clopen Z ∧ x ∈ Z ∧ Z ⊆ u ∪ v,
{ cases this with Z H,
rw [disjoint_iff_inter_eq_empty] at huv,
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 (inter_comm u v ▸ huv),
by_cases (x ∈ u),
-- The x ∈ u case.
{ left,
suffices : (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), ↑Z) ⊆ u,
{ rw ←set.disjoint_iff_inter_eq_empty at huv,
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,
{ rw [inter_comm, ←set.disjoint_iff_inter_eq_empty] at huv,
replace hab : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ a ∪ b := hab,
replace this : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ v := this,
exact disjoint.left_le_of_le_sup_left hab (huv.mono this hau) },
{ 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 := ((is_closed_compl_iff.2 (hu.union hv)).is_compact.inter_Inter_nonempty
(λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z) (λ Z, Z.2.1.2)),
rw [←not_imp_not, not_forall, not_nonempty_iff_eq_empty, inter_comm] at H1,
have huv_union := subset.trans hab (union_subset_union hau hbv),
rw [← compl_compl (u ∪ v), subset_compl_iff_disjoint] at huv_union,
cases H1 huv_union with Zi H2,
refine ⟨(⋂ (U ∈ Zi), subtype.val U), _, _, _⟩,
{ exact is_clopen_bInter (λ Z hZ, Z.2.1) },
{ exact mem_bInter_iff.2 (λ Z hZ, Z.2.2) },
{ rwa [not_nonempty_iff_eq_empty, inter_comm, ←subset_compl_iff_disjoint, compl_compl] at H2 }
end
section profinite
open topological_space
variables [t2_space α]
/-- A Hausdorff space with a clopen basis is totally separated. -/
lemma tot_sep_of_zero_dim (h : is_topological_basis {s : set α | is_clopen s}) :
totally_separated_space α :=
begin
constructor,
rintros x - y - hxy,
obtain ⟨u, v, hu, hv, xu, yv, disj⟩ := t2_separation hxy,
obtain ⟨w, hw : is_clopen w, xw, wu⟩ := (is_topological_basis.mem_nhds_iff h).1
(is_open.mem_nhds hu xu),
refine ⟨w, wᶜ, hw.1, (is_clopen_compl_iff.2 hw).1, xw, _, _, set.inter_compl_self w⟩,
{ intro h,
have : y ∈ u ∩ v := ⟨wu h, yv⟩,
rwa disj at this },
rw set.union_compl_self,
end
variables [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,
simpa using hyp wᶜ w (is_open_compl_iff.mpr hw.2) hw.1 hx hy },
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},
suffices : ∃ Z : N, Z.val ⊆ U,
{ rcases this with ⟨⟨s, hs, hs'⟩, hs''⟩,
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
open topological_space
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 tot_sep_of_zero_dim loc_compact_Haus_tot_disc_of_zero_dim, },
apply totally_separated_space.totally_disconnected_space,
end
end locally_compact
section connected_component_setoid
local attribute [instance] connected_component_setoid
/-- `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 ⟨λ x y, quotient.induction_on x (quotient.induction_on y (λ a b ne, _))⟩,
rw connected_component_nrel_iff 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, disjoint_iff_inter_eq_empty, inter_comm] at h,
-- Now we show that this can be reduced to some clopen containing ⟦b⟧ being disjoint to ⟦a⟧
cases is_closed_connected_component.is_compact.elim_finite_subfamily_closed _ _ h
with fin_a ha,
swap, { exact λ Z, Z.2.1.2 },
set U : set α := (⋂ (i : {Z // is_clopen Z ∧ b ∈ Z}) (H : i ∈ fin_a), i) with hU,
rw ←hU at ha,
have hu_clopen : is_clopen U := is_clopen_bInter (λ i j, i.2.1),
-- This clopen and its complement will separate the points corresponding to ⟦a⟧ and ⟦b⟧
use [quotient.mk '' U, quotient.mk '' Uᶜ],
-- Using the fact that clopens are unions of connected components, we show that
-- U and Uᶜ is the preimage of a clopen set in the quotient
have hu : quotient.mk ⁻¹' (quotient.mk '' U) = U :=
(connected_components_preimage_image U ▸ eq.symm) hu_clopen.eq_union_connected_components,
have huc : quotient.mk ⁻¹' (quotient.mk '' Uᶜ) = Uᶜ :=
(connected_components_preimage_image Uᶜ ▸ eq.symm)
(is_clopen.compl hu_clopen).eq_union_connected_components,
-- showing that U and Uᶜ are open and separates ⟦a⟧ and ⟦b⟧
refine ⟨_,_,_,_,_⟩,
{ rw [(quotient_map_iff.1 quotient_map_quotient_mk).2 _, hu],
exact hu_clopen.1 },
{ rw [(quotient_map_iff.1 quotient_map_quotient_mk).2 _, huc],
exact is_open_compl_iff.2 hu_clopen.2 },
{ exact mem_image_of_mem _ (mem_Inter.2 (λ Z, mem_Inter.2 (λ Zmem, Z.2.2))) },
{ apply mem_image_of_mem,
exact mem_of_subset_of_mem (subset_compl_iff_disjoint.2 ha) (@mem_connected_component _ _ a) },
apply preimage_injective.2 (@surjective_quotient_mk _ _),
rw [preimage_inter, preimage_empty, hu, huc, inter_compl_self _],
end
end connected_component_setoid
|
f4a612b4e2df4373d9b7b1213aa0f3cd50f7672f | 626e312b5c1cb2d88fca108f5933076012633192 | /src/data/finset/lattice.lean | 6faa7408e6ebb5ccf7c3166a3c95fa885e445c00 | [
"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 | 42,620 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.finset.fold
import data.multiset.lattice
import order.order_dual
import order.complete_lattice
/-!
# Lattice operations on finsets
-/
variables {α β γ : Type*}
namespace finset
open multiset order_dual
/-! ### sup -/
section sup
variables [semilattice_sup_bot α]
/-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/
def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f
variables {s s₁ s₂ : finset β} {f : β → α}
lemma sup_def : s.sup f = (s.1.map f).sup := rfl
@[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ :=
fold_empty
@[simp] lemma sup_cons {b : β} (h : b ∉ s) : (cons b s h).sup f = f b ⊔ s.sup f :=
fold_cons h
@[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f :=
fold_insert_idem
lemma sup_image [decidable_eq β] (s : finset γ) (f : γ → β) (g : β → α):
(s.image f).sup g = s.sup (g ∘ f) :=
fold_image_idem
@[simp] lemma sup_map (s : finset γ) (f : γ ↪ β) (g : β → α) :
(s.map f).sup g = s.sup (g ∘ f) :=
fold_map
@[simp] lemma sup_singleton {b : β} : ({b} : finset β).sup f = f b :=
sup_singleton
lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f :=
finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih,
by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc]
theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g :=
by subst hs; exact finset.fold_congr hfg
@[simp] lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) :=
begin
apply iff.trans multiset.sup_le,
simp only [multiset.mem_map, and_imp, exists_imp_distrib],
exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩,
end
lemma sup_const {s : finset β} (h : s.nonempty) (c : α) : s.sup (λ _, c) = c :=
eq_of_forall_ge_iff $ λ b, sup_le_iff.trans h.forall_const
lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a :=
sup_le_iff.2
lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f :=
sup_le_iff.1 (le_refl _) _ hb
lemma sup_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.sup f ≤ s.sup g :=
sup_le (λ b hb, le_trans (h b hb) (le_sup hb))
lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f :=
sup_le $ assume b hb, le_sup (h hb)
@[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : s.sup f < a ↔ (∀ b ∈ s, f b < a) :=
⟨(λ hs b hb, lt_of_le_of_lt (le_sup hb) hs), finset.cons_induction_on s (λ _, ha)
(λ c t hc, by simpa only [sup_cons, sup_lt_iff, mem_cons, forall_eq_or_imp] using and.imp_right)⟩
@[simp] lemma le_sup_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : a ≤ s.sup f ↔ ∃ b ∈ s, a ≤ f b :=
⟨finset.cons_induction_on s (λ h, absurd h (not_le_of_lt ha))
(λ c t hc ih, by simpa using @or.rec _ _ (∃ b, (b = c ∨ b ∈ t) ∧ a ≤ f b)
(λ h, ⟨c, or.inl rfl, h⟩) (λ h, let ⟨b, hb, hle⟩ := ih h in ⟨b, or.inr hb, hle⟩)),
(λ ⟨b, hb, hle⟩, trans hle (le_sup hb))⟩
@[simp] lemma lt_sup_iff [is_total α (≤)] {a : α} : a < s.sup f ↔ ∃ b ∈ s, a < f b :=
⟨finset.cons_induction_on s (λ h, absurd h not_lt_bot)
(λ c t hc ih, by simpa using @or.rec _ _ (∃ b, (b = c ∨ b ∈ t) ∧ a < f b)
(λ h, ⟨c, or.inl rfl, h⟩) (λ h, let ⟨b, hb, hlt⟩ := ih h in ⟨b, or.inr hb, hlt⟩)),
(λ ⟨b, hb, hlt⟩, lt_of_lt_of_le hlt (le_sup hb))⟩
lemma comp_sup_eq_sup_comp [semilattice_sup_bot γ] {s : finset β}
{f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) (bot : g ⊥ = ⊥) :
g (s.sup f) = s.sup (g ∘ f) :=
finset.cons_induction_on s bot (λ c t hc ih, by rw [sup_cons, sup_cons, g_sup, ih])
lemma comp_sup_eq_sup_comp_of_is_total [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ]
(g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) :=
comp_sup_eq_sup_comp g mono_g.map_sup bot
/-- Computating `sup` in a subtype (closed under `sup`) is the same as computing it in `α`. -/
lemma sup_coe {P : α → Prop}
{Pbot : P ⊥} {Psup : ∀{{x y}}, P x → P y → P (x ⊔ y)}
(t : finset β) (f : β → {x : α // P x}) :
(@sup _ _ (subtype.semilattice_sup_bot Pbot Psup) t f : α) = t.sup (λ x, f x) :=
by { rw [comp_sup_eq_sup_comp coe]; intros; refl }
@[simp] lemma sup_to_finset {α β} [decidable_eq β]
(s : finset α) (f : α → multiset β) :
(s.sup f).to_finset = s.sup (λ x, (f x).to_finset) :=
comp_sup_eq_sup_comp multiset.to_finset to_finset_union rfl
theorem subset_range_sup_succ (s : finset ℕ) : s ⊆ range (s.sup id).succ :=
λ n hn, mem_range.2 $ nat.lt_succ_of_le $ le_sup hn
theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n :=
⟨_, s.subset_range_sup_succ⟩
lemma sup_induction {p : α → Prop} (hb : p ⊥) (hp : ∀ (a₁ a₂ : α), p a₁ → p a₂ → p (a₁ ⊔ a₂))
(hs : ∀ b ∈ s, p (f b)) : p (s.sup f) :=
begin
induction s using finset.cons_induction with c s hc ih,
{ exact hb, },
{ rw sup_cons,
apply hp,
{ exact hs c (mem_cons.2 (or.inl rfl)), },
{ exact ih (λ b h, hs b (mem_cons.2 (or.inr h))), }, },
end
lemma sup_le_of_le_directed {α : Type*} [semilattice_sup_bot α] (s : set α)
(hs : s.nonempty) (hdir : directed_on (≤) s) (t : finset α):
(∀ x ∈ t, ∃ y ∈ s, x ≤ y) → ∃ x, x ∈ s ∧ t.sup id ≤ x :=
begin
classical,
apply finset.induction_on t,
{ simpa only [forall_prop_of_true, and_true, forall_prop_of_false, bot_le, not_false_iff,
sup_empty, forall_true_iff, not_mem_empty], },
{ intros a r har ih h,
have incs : ↑r ⊆ ↑(insert a r), by { rw finset.coe_subset, apply finset.subset_insert, },
-- x ∈ s is above the sup of r
obtain ⟨x, ⟨hxs, hsx_sup⟩⟩ := ih (λ x hx, h x $ incs hx),
-- y ∈ s is above a
obtain ⟨y, hys, hay⟩ := h a (finset.mem_insert_self a r),
-- z ∈ s is above x and y
obtain ⟨z, hzs, ⟨hxz, hyz⟩⟩ := hdir x hxs y hys,
use [z, hzs],
rw [sup_insert, id.def, _root_.sup_le_iff],
exact ⟨le_trans hay hyz, le_trans hsx_sup hxz⟩, },
end
-- If we acquire sublattices
-- the hypotheses should be reformulated as `s : subsemilattice_sup_bot`
lemma sup_mem
(s : set α) (w₁ : ⊥ ∈ s) (w₂ : ∀ x y ∈ s, x ⊔ y ∈ s)
{ι : Type*} (t : finset ι) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) :
t.sup p ∈ s :=
@sup_induction _ _ _ _ _ (∈ s) w₁ w₂ h
end sup
lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) :=
le_antisymm
(finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha)
(supr_le $ assume a, supr_le $ assume ha, le_sup ha)
lemma sup_id_eq_Sup [complete_lattice α] (s : finset α) : s.sup id = Sup s :=
by simp [Sup_eq_supr, sup_eq_supr]
lemma sup_eq_Sup_image [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = Sup (f '' s) :=
begin
classical,
rw [←finset.coe_image, ←sup_id_eq_Sup, sup_image, function.comp.left_id],
end
/-! ### inf -/
section inf
variables [semilattice_inf_top α]
/-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/
def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f
variables {s s₁ s₂ : finset β} {f : β → α}
lemma inf_def : s.inf f = (s.1.map f).inf := rfl
@[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ :=
fold_empty
@[simp] lemma inf_cons {b : β} (h : b ∉ s) : (cons b s h).inf f = f b ⊓ s.inf f :=
@sup_cons (order_dual α) _ _ _ _ _ h
@[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f :=
fold_insert_idem
lemma inf_image [decidable_eq β] (s : finset γ) (f : γ → β) (g : β → α):
(s.image f).inf g = s.inf (g ∘ f) :=
fold_image_idem
@[simp] lemma inf_map (s : finset γ) (f : γ ↪ β) (g : β → α) :
(s.map f).inf g = s.inf (g ∘ f) :=
fold_map
@[simp] lemma inf_singleton {b : β} : ({b} : finset β).inf f = f b :=
inf_singleton
lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f :=
@sup_union (order_dual α) _ _ _ _ _ _
theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g :=
by subst hs; exact finset.fold_congr hfg
lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ ∀ b ∈ s, a ≤ f b :=
@sup_le_iff (order_dual α) _ _ _ _ _
lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b :=
le_inf_iff.1 (le_refl _) _ hb
lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f :=
le_inf_iff.2
lemma inf_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.inf f ≤ s.inf g :=
le_inf (λ b hb, le_trans (inf_le hb) (h b hb))
lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f :=
le_inf $ assume b hb, inf_le (h hb)
@[simp] lemma lt_inf_iff [is_total α (≤)] {a : α} (ha : a < ⊤) : a < s.inf f ↔ (∀ b ∈ s, a < f b) :=
@sup_lt_iff (order_dual α) _ _ _ _ _ _ ha
@[simp] lemma inf_le_iff [is_total α (≤)] {a : α} (ha : a < ⊤) : s.inf f ≤ a ↔ (∃ b ∈ s, f b ≤ a) :=
@le_sup_iff (order_dual α) _ _ _ _ _ _ ha
@[simp] lemma inf_lt_iff [is_total α (≤)] {a : α} : s.inf f < a ↔ (∃ b ∈ s, f b < a) :=
@lt_sup_iff (order_dual α) _ _ _ _ _ _
lemma comp_inf_eq_inf_comp [semilattice_inf_top γ] {s : finset β}
{f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) (top : g ⊤ = ⊤) :
g (s.inf f) = s.inf (g ∘ f) :=
@comp_sup_eq_sup_comp (order_dual α) _ (order_dual γ) _ _ _ _ _ g_inf top
lemma comp_inf_eq_inf_comp_of_is_total [h : is_total α (≤)] {γ : Type} [semilattice_inf_top γ]
(g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) :=
comp_inf_eq_inf_comp g mono_g.map_inf top
/-- Computating `inf` in a subtype (closed under `inf`) is the same as computing it in `α`. -/
lemma inf_coe {P : α → Prop}
{Ptop : P ⊤} {Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)}
(t : finset β) (f : β → {x : α // P x}) :
(@inf _ _ (subtype.semilattice_inf_top Ptop Pinf) t f : α) = t.inf (λ x, f x) :=
@sup_coe (order_dual α) _ _ _ Ptop Pinf t f
lemma inf_induction {p : α → Prop} (ht : p ⊤) (hp : ∀ (a₁ a₂ : α), p a₁ → p a₂ → p (a₁ ⊓ a₂))
(hs : ∀ b ∈ s, p (f b)) : p (s.inf f) :=
@sup_induction (order_dual α) _ _ _ _ _ ht hp hs
lemma inf_mem
(s : set α) (w₁ : ⊤ ∈ s) (w₂ : ∀ x y ∈ s, x ⊓ y ∈ s)
{ι : Type*} (t : finset ι) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) :
t.inf p ∈ s :=
@inf_induction _ _ _ _ _ (∈ s) w₁ w₂ h
end inf
lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) :=
@sup_eq_supr _ (order_dual β) _ _ _
lemma inf_id_eq_Inf [complete_lattice α] (s : finset α) : s.inf id = Inf s :=
@sup_id_eq_Sup (order_dual α) _ _
lemma inf_eq_Inf_image [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = Inf (f '' s) :=
@sup_eq_Sup_image _ (order_dual β) _ _ _
section sup'
variables [semilattice_sup α]
lemma sup_of_mem {s : finset β} (f : β → α) {b : β} (h : b ∈ s) :
∃ (a : α), s.sup (coe ∘ f : β → with_bot α) = ↑a :=
Exists.imp (λ a, Exists.fst) (@le_sup (with_bot α) _ _ _ _ _ h (f b) rfl)
/-- Given nonempty finset `s` then `s.sup' H f` is the supremum of its image under `f` in (possibly
unbounded) join-semilattice `α`, where `H` is a proof of nonemptiness. If `α` has a bottom element
you may instead use `finset.sup` which does not require `s` nonempty. -/
def sup' (s : finset β) (H : s.nonempty) (f : β → α) : α :=
option.get $ let ⟨b, hb⟩ := H in option.is_some_iff_exists.2 (sup_of_mem f hb)
variables {s : finset β} (H : s.nonempty) (f : β → α)
@[simp] lemma coe_sup' : ((s.sup' H f : α) : with_bot α) = s.sup (coe ∘ f) :=
by rw [sup', ←with_bot.some_eq_coe, option.some_get]
@[simp] lemma sup'_cons {b : β} {hb : b ∉ s} {h : (cons b s hb).nonempty} :
(cons b s hb).sup' h f = f b ⊔ s.sup' H f :=
by { rw ←with_bot.coe_eq_coe, simp only [coe_sup', sup_cons, with_bot.coe_sup], }
@[simp] lemma sup'_insert [decidable_eq β] {b : β} {h : (insert b s).nonempty} :
(insert b s).sup' h f = f b ⊔ s.sup' H f :=
by { rw ←with_bot.coe_eq_coe, simp only [coe_sup', sup_insert, with_bot.coe_sup], }
@[simp] lemma sup'_singleton {b : β} {h : ({b} : finset β).nonempty} :
({b} : finset β).sup' h f = f b := rfl
lemma sup'_le {a : α} (hs : ∀ b ∈ s, f b ≤ a) : s.sup' H f ≤ a :=
by { rw [←with_bot.coe_le_coe, coe_sup'], exact sup_le (λ b h, with_bot.coe_le_coe.2 $ hs b h), }
lemma le_sup' {b : β} (h : b ∈ s) : f b ≤ s.sup' ⟨b, h⟩ f :=
by { rw [←with_bot.coe_le_coe, coe_sup'], exact le_sup h, }
@[simp] lemma sup'_const (a : α) : s.sup' H (λ b, a) = a :=
begin
apply le_antisymm,
{ apply sup'_le, intros, apply le_refl, },
{ apply le_sup' (λ b, a) H.some_spec, }
end
@[simp] lemma sup'_le_iff {a : α} : s.sup' H f ≤ a ↔ ∀ b ∈ s, f b ≤ a :=
iff.intro (λ h b hb, trans (le_sup' f hb) h) (sup'_le H f)
@[simp] lemma sup'_lt_iff [is_total α (≤)] {a : α} : s.sup' H f < a ↔ (∀ b ∈ s, f b < a) :=
begin
rw [←with_bot.coe_lt_coe, coe_sup', sup_lt_iff (with_bot.bot_lt_coe a)],
exact ball_congr (λ b hb, with_bot.coe_lt_coe),
end
@[simp] lemma le_sup'_iff [is_total α (≤)] {a : α} : a ≤ s.sup' H f ↔ (∃ b ∈ s, a ≤ f b) :=
begin
rw [←with_bot.coe_le_coe, coe_sup', le_sup_iff (with_bot.bot_lt_coe a)],
exact bex_congr (λ b hb, with_bot.coe_le_coe),
end
@[simp] lemma lt_sup'_iff [is_total α (≤)] {a : α} : a < s.sup' H f ↔ (∃ b ∈ s, a < f b) :=
begin
rw [←with_bot.coe_lt_coe, coe_sup', lt_sup_iff],
exact bex_congr (λ b hb, with_bot.coe_lt_coe),
end
lemma comp_sup'_eq_sup'_comp [semilattice_sup γ] {s : finset β} (H : s.nonempty)
{f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) :
g (s.sup' H f) = s.sup' H (g ∘ f) :=
begin
rw [←with_bot.coe_eq_coe, coe_sup'],
let g' : with_bot α → with_bot γ := with_bot.rec_bot_coe ⊥ (λ x, ↑(g x)),
show g' ↑(s.sup' H f) = s.sup (λ a, g' ↑(f a)),
rw coe_sup',
refine comp_sup_eq_sup_comp g' _ rfl,
intros f₁ f₂,
cases f₁,
{ rw [with_bot.none_eq_bot, bot_sup_eq], exact bot_sup_eq.symm, },
{ cases f₂, refl,
exact congr_arg coe (g_sup f₁ f₂), },
end
lemma sup'_induction {p : α → Prop} (hp : ∀ (a₁ a₂ : α), p a₁ → p a₂ → p (a₁ ⊔ a₂))
(hs : ∀ b ∈ s, p (f b)) : p (s.sup' H f) :=
begin
show @with_bot.rec_bot_coe α (λ _, Prop) true p ↑(s.sup' H f),
rw coe_sup',
refine sup_induction trivial _ hs,
intros a₁ a₂ h₁ h₂,
cases a₁,
{ rw [with_bot.none_eq_bot, bot_sup_eq], exact h₂, },
{ cases a₂, exact h₁, exact hp a₁ a₂ h₁ h₂, },
end
lemma exists_mem_eq_sup' [is_total α (≤)] : ∃ b, b ∈ s ∧ s.sup' H f = f b :=
begin
induction s using finset.cons_induction with c s hc ih,
{ exact false.elim (not_nonempty_empty H), },
{ rcases s.eq_empty_or_nonempty with rfl | hs,
{ exact ⟨c, mem_singleton_self c, rfl⟩, },
{ rcases ih hs with ⟨b, hb, h'⟩,
rw [sup'_cons hs, h'],
cases total_of (≤) (f b) (f c) with h h,
{ exact ⟨c, mem_cons.2 (or.inl rfl), sup_eq_left.2 h⟩, },
{ exact ⟨b, mem_cons.2 (or.inr hb), sup_eq_right.2 h⟩, }, }, },
end
lemma sup'_mem
(s : set α) (w : ∀ x y ∈ s, x ⊔ y ∈ s)
{ι : Type*} (t : finset ι) (H : t.nonempty) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) :
t.sup' H p ∈ s :=
sup'_induction H p w h
end sup'
section inf'
variables [semilattice_inf α]
lemma inf_of_mem {s : finset β} (f : β → α) {b : β} (h : b ∈ s) :
∃ (a : α), s.inf (coe ∘ f : β → with_top α) = ↑a :=
@sup_of_mem (order_dual α) _ _ _ f _ h
/-- Given nonempty finset `s` then `s.inf' H f` is the infimum of its image under `f` in (possibly
unbounded) meet-semilattice `α`, where `H` is a proof of nonemptiness. If `α` has a top element you
may instead use `finset.inf` which does not require `s` nonempty. -/
def inf' (s : finset β) (H : s.nonempty) (f : β → α) : α :=
@sup' (order_dual α) _ _ s H f
variables {s : finset β} (H : s.nonempty) (f : β → α)
@[simp] lemma coe_inf' : ((s.inf' H f : α) : with_top α) = s.inf (coe ∘ f) :=
@coe_sup' (order_dual α) _ _ _ H f
@[simp] lemma inf'_cons {b : β} {hb : b ∉ s} {h : (cons b s hb).nonempty} :
(cons b s hb).inf' h f = f b ⊓ s.inf' H f :=
@sup'_cons (order_dual α) _ _ _ H f _ _ _
@[simp] lemma inf'_insert [decidable_eq β] {b : β} {h : (insert b s).nonempty} :
(insert b s).inf' h f = f b ⊓ s.inf' H f :=
@sup'_insert (order_dual α) _ _ _ H f _ _ _
@[simp] lemma inf'_singleton {b : β} {h : ({b} : finset β).nonempty} :
({b} : finset β).inf' h f = f b := rfl
lemma le_inf' {a : α} (hs : ∀ b ∈ s, a ≤ f b) : a ≤ s.inf' H f :=
@sup'_le (order_dual α) _ _ _ H f _ hs
lemma inf'_le {b : β} (h : b ∈ s) : s.inf' ⟨b, h⟩ f ≤ f b :=
@le_sup' (order_dual α) _ _ _ f _ h
@[simp] lemma inf'_const (a : α) : s.inf' H (λ b, a) = a :=
@sup'_const (order_dual α) _ _ _ _ _
@[simp] lemma le_inf'_iff {a : α} : a ≤ s.inf' H f ↔ ∀ b ∈ s, a ≤ f b :=
@sup'_le_iff (order_dual α) _ _ _ H f _
@[simp] lemma lt_inf'_iff [is_total α (≤)] {a : α} : a < s.inf' H f ↔ (∀ b ∈ s, a < f b) :=
@sup'_lt_iff (order_dual α) _ _ _ H f _ _
@[simp] lemma inf'_le_iff [is_total α (≤)] {a : α} : s.inf' H f ≤ a ↔ (∃ b ∈ s, f b ≤ a) :=
@le_sup'_iff (order_dual α) _ _ _ H f _ _
@[simp] lemma inf'_lt_iff [is_total α (≤)] {a : α} : s.inf' H f < a ↔ (∃ b ∈ s, f b < a) :=
@lt_sup'_iff (order_dual α) _ _ _ H f _ _
lemma comp_inf'_eq_inf'_comp [semilattice_inf γ] {s : finset β} (H : s.nonempty)
{f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) :
g (s.inf' H f) = s.inf' H (g ∘ f) :=
@comp_sup'_eq_sup'_comp (order_dual α) _ (order_dual γ) _ _ _ H f g g_inf
lemma inf'_induction {p : α → Prop} (hp : ∀ (a₁ a₂ : α), p a₁ → p a₂ → p (a₁ ⊓ a₂))
(hs : ∀ b ∈ s, p (f b)) : p (s.inf' H f) :=
@sup'_induction (order_dual α) _ _ _ H f _ hp hs
lemma exists_mem_eq_inf' [is_total α (≤)] : ∃ b, b ∈ s ∧ s.inf' H f = f b :=
@exists_mem_eq_sup' (order_dual α) _ _ _ H f _
lemma inf'_mem (s : set α) (w : ∀ x y ∈ s, x ⊓ y ∈ s)
{ι : Type*} (t : finset ι) (H : t.nonempty) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) :
t.inf' H p ∈ s :=
inf'_induction H p w h
end inf'
section sup
variable [semilattice_sup_bot α]
lemma sup'_eq_sup {s : finset β} (H : s.nonempty) (f : β → α) : s.sup' H f = s.sup f :=
le_antisymm (sup'_le H f (λ b, le_sup)) (sup_le (λ b, le_sup' f))
lemma sup_closed_of_sup_closed {s : set α} (t : finset α) (htne : t.nonempty) (h_subset : ↑t ⊆ s)
(h : ∀⦃a b⦄, a ∈ s → b ∈ s → a ⊔ b ∈ s) : t.sup id ∈ s :=
sup'_eq_sup htne id ▸ sup'_induction _ _ h h_subset
lemma exists_mem_eq_sup [is_total α (≤)] (s : finset β) (h : s.nonempty) (f : β → α) :
∃ b, b ∈ s ∧ s.sup f = f b :=
sup'_eq_sup h f ▸ exists_mem_eq_sup' h f
end sup
section inf
variable [semilattice_inf_top α]
lemma inf'_eq_inf {s : finset β} (H : s.nonempty) (f : β → α) : s.inf' H f = s.inf f :=
@sup'_eq_sup (order_dual α) _ _ _ H f
lemma inf_closed_of_inf_closed {s : set α} (t : finset α) (htne : t.nonempty) (h_subset : ↑t ⊆ s)
(h : ∀⦃a b⦄, a ∈ s → b ∈ s → a ⊓ b ∈ s) : t.inf id ∈ s :=
@sup_closed_of_sup_closed (order_dual α) _ _ t htne h_subset h
lemma exists_mem_eq_inf [is_total α (≤)] (s : finset β) (h : s.nonempty) (f : β → α) :
∃ a, a ∈ s ∧ s.inf f = f a :=
@exists_mem_eq_sup (order_dual α) _ _ _ _ h f
end inf
section sup
variables {C : β → Type*} [Π (b : β), semilattice_sup_bot (C b)]
@[simp]
protected lemma sup_apply (s : finset α) (f : α → Π (b : β), C b) (b : β) :
s.sup f b = s.sup (λ a, f a b) :=
comp_sup_eq_sup_comp (λ x : Π b : β, C b, x b) (λ i j, rfl) rfl
end sup
section inf
variables {C : β → Type*} [Π (b : β), semilattice_inf_top (C b)]
@[simp]
protected lemma inf_apply (s : finset α) (f : α → Π (b : β), C b) (b : β) :
s.inf f b = s.inf (λ a, f a b) :=
@finset.sup_apply _ _ (λ b, order_dual (C b)) _ s f b
end inf
section sup'
variables {C : β → Type*} [Π (b : β), semilattice_sup (C b)]
@[simp]
protected lemma sup'_apply {s : finset α} (H : s.nonempty) (f : α → Π (b : β), C b) (b : β) :
s.sup' H f b = s.sup' H (λ a, f a b) :=
comp_sup'_eq_sup'_comp H (λ x : Π b : β, C b, x b) (λ i j, rfl)
end sup'
section inf'
variables {C : β → Type*} [Π (b : β), semilattice_inf (C b)]
@[simp]
protected lemma inf'_apply {s : finset α} (H : s.nonempty) (f : α → Π (b : β), C b) (b : β) :
s.inf' H f b = s.inf' H (λ a, f a b) :=
@finset.sup'_apply _ _ (λ b, order_dual (C b)) _ _ H f b
end inf'
/-! ### max and min of finite sets -/
section max_min
variables [linear_order α]
/-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty,
and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see
`s.max'`. -/
protected def max : finset α → option α :=
fold (option.lift_or_get max) none some
theorem max_eq_sup_with_bot (s : finset α) :
s.max = @sup (with_bot α) α _ s some := rfl
@[simp] theorem max_empty : (∅ : finset α).max = none := rfl
@[simp] theorem max_insert {a : α} {s : finset α} :
(insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem
@[simp] theorem max_singleton {a : α} : finset.max {a} = some a :=
by { rw [← insert_emptyc_eq], exact max_insert }
theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max :=
(@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst
theorem max_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.max :=
let ⟨a, ha⟩ := h in max_of_mem ha
theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ :=
⟨λ h, s.eq_empty_or_nonempty.elim id
(λ H, let ⟨a, ha⟩ := max_of_nonempty H in by rw h at ha; cases ha),
λ h, h.symm ▸ max_empty⟩
theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s :=
finset.induction_on s (λ _ H, by cases H)
(λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max),
begin
by_cases p : b = a,
{ induction p, exact mem_insert_self b s },
{ cases option.lift_or_get_choice max_choice (some b) s.max with q q;
rw [max_insert, q] at h,
{ cases h, cases p rfl },
{ exact mem_insert_of_mem (ih h) } }
end)
theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b :=
by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩;
cases h₂.symm.trans hb; assumption
/-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty,
and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see
`s.min'`. -/
protected def min : finset α → option α :=
fold (option.lift_or_get min) none some
theorem min_eq_inf_with_top (s : finset α) :
s.min = @inf (with_top α) α _ s some := rfl
@[simp] theorem min_empty : (∅ : finset α).min = none := rfl
@[simp] theorem min_insert {a : α} {s : finset α} :
(insert a s).min = option.lift_or_get min (some a) s.min :=
fold_insert_idem
@[simp] theorem min_singleton {a : α} : finset.min {a} = some a :=
by { rw ← insert_emptyc_eq, exact min_insert }
theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min :=
(@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst
theorem min_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.min :=
let ⟨a, ha⟩ := h in min_of_mem ha
theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ :=
⟨λ h, s.eq_empty_or_nonempty.elim id
(λ H, let ⟨a, ha⟩ := min_of_nonempty H in by rw h at ha; cases ha),
λ h, h.symm ▸ min_empty⟩
theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s :=
@mem_of_max (order_dual α) _ s
theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b :=
by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩;
cases h₂.symm.trans hb; assumption
/-- Given a nonempty finset `s` in a linear order `α `, then `s.min' h` is its minimum, as an
element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.min`,
taking values in `option α`. -/
def min' (s : finset α) (H : s.nonempty) : α :=
@option.get _ s.min $
let ⟨k, hk⟩ := H in
let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb]
/-- Given a nonempty finset `s` in a linear order `α `, then `s.max' h` is its maximum, as an
element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.max`,
taking values in `option α`. -/
def max' (s : finset α) (H : s.nonempty) : α :=
@option.get _ s.max $
let ⟨k, hk⟩ := H in
let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb]
variables (s : finset α) (H : s.nonempty)
theorem min'_mem : s.min' H ∈ s := mem_of_min $ by simp [min']
theorem min'_le (x) (H2 : x ∈ s) : s.min' ⟨x, H2⟩ ≤ x := min_le_of_mem H2 $ option.get_mem _
theorem le_min' (x) (H2 : ∀ y ∈ s, x ≤ y) : x ≤ s.min' H := H2 _ $ min'_mem _ _
theorem is_least_min' : is_least ↑s (s.min' H) := ⟨min'_mem _ _, min'_le _⟩
@[simp] lemma le_min'_iff {x} : x ≤ s.min' H ↔ ∀ y ∈ s, x ≤ y :=
le_is_glb_iff (is_least_min' s H).is_glb
/-- `{a}.min' _` is `a`. -/
@[simp] lemma min'_singleton (a : α) :
({a} : finset α).min' (singleton_nonempty _) = a :=
by simp [min']
theorem max'_mem : s.max' H ∈ s := mem_of_max $ by simp [max']
theorem le_max' (x) (H2 : x ∈ s) : x ≤ s.max' ⟨x, H2⟩ := le_max_of_mem H2 $ option.get_mem _
theorem max'_le (x) (H2 : ∀ y ∈ s, y ≤ x) : s.max' H ≤ x := H2 _ $ max'_mem _ _
theorem is_greatest_max' : is_greatest ↑s (s.max' H) := ⟨max'_mem _ _, le_max' _⟩
@[simp] lemma max'_le_iff {x} : s.max' H ≤ x ↔ ∀ y ∈ s, y ≤ x :=
is_lub_le_iff (is_greatest_max' s H).is_lub
@[simp] lemma max'_lt_iff {x} : s.max' H < x ↔ ∀ y ∈ s, y < x :=
⟨λ Hlt y hy, (s.le_max' y hy).trans_lt Hlt, λ H, H _ $ s.max'_mem _⟩
@[simp] lemma lt_min'_iff {x} : x < s.min' H ↔ ∀ y ∈ s, x < y :=
@max'_lt_iff (order_dual α) _ _ H _
lemma max'_eq_sup' : s.max' H = s.sup' H id :=
eq_of_forall_ge_iff $ λ a, (max'_le_iff _ _).trans (sup'_le_iff _ _).symm
lemma min'_eq_inf' : s.min' H = s.inf' H id :=
@max'_eq_sup' (order_dual α) _ s H
/-- `{a}.max' _` is `a`. -/
@[simp] lemma max'_singleton (a : α) :
({a} : finset α).max' (singleton_nonempty _) = a :=
by simp [max']
theorem min'_lt_max' {i j} (H1 : i ∈ s) (H2 : j ∈ s) (H3 : i ≠ j) :
s.min' ⟨i, H1⟩ < s.max' ⟨i, H1⟩ :=
is_glb_lt_is_lub_of_ne (s.is_least_min' _).is_glb (s.is_greatest_max' _).is_lub H1 H2 H3
/--
If there's more than 1 element, the min' is less than the max'. An alternate version of
`min'_lt_max'` which is sometimes more convenient.
-/
lemma min'_lt_max'_of_card (h₂ : 1 < card s) :
s.min' (finset.card_pos.mp $ lt_trans zero_lt_one h₂) <
s.max' (finset.card_pos.mp $ lt_trans zero_lt_one h₂) :=
begin
rcases one_lt_card.1 h₂ with ⟨a, ha, b, hb, hab⟩,
exact s.min'_lt_max' ha hb hab
end
lemma max'_eq_of_dual_min' {s : finset α} (hs : s.nonempty) :
max' s hs = of_dual (min' (image to_dual s) (nonempty.image hs to_dual)) :=
begin
rw [of_dual, to_dual, equiv.coe_fn_mk, equiv.coe_fn_symm_mk, id.def],
simp_rw (@image_id (order_dual α) (s : finset (order_dual α))),
refl,
end
lemma min'_eq_of_dual_max' {s : finset α} (hs : s.nonempty) :
min' s hs = of_dual (max' (image to_dual s) (nonempty.image hs to_dual)) :=
begin
rw [of_dual, to_dual, equiv.coe_fn_mk, equiv.coe_fn_symm_mk, id.def],
simp_rw (@image_id (order_dual α) (s : finset (order_dual α))),
refl,
end
@[simp] lemma of_dual_max_eq_min_of_dual {a b : α} :
of_dual (max a b) = min (of_dual a) (of_dual b) := rfl
@[simp] lemma of_dual_min_eq_max_of_dual {a b : α} :
of_dual (min a b) = max (of_dual a) (of_dual b) := rfl
lemma max'_subset {s t : finset α} (H : s.nonempty) (hst : s ⊆ t) :
s.max' H ≤ t.max' (H.mono hst) :=
le_max' _ _ (hst (s.max'_mem H))
lemma min'_subset {s t : finset α} (H : s.nonempty) (hst : s ⊆ t) :
t.min' (H.mono hst) ≤ s.min' H :=
min'_le _ _ (hst (s.min'_mem H))
lemma max'_insert (a : α) (s : finset α) (H : s.nonempty) :
(insert a s).max' (s.insert_nonempty a) = max (s.max' H) a :=
(is_greatest_max' _ _).unique $
by { rw [coe_insert, max_comm], exact (is_greatest_max' _ _).insert _ }
lemma min'_insert (a : α) (s : finset α) (H : s.nonempty) :
(insert a s).min' (s.insert_nonempty a) = min (s.min' H) a :=
(is_least_min' _ _).unique $
by { rw [coe_insert, min_comm], exact (is_least_min' _ _).insert _ }
lemma lt_max'_of_mem_erase_max' [decidable_eq α] {a : α} (ha : a ∈ s.erase (s.max' H)) :
a < s.max' H :=
lt_of_le_of_ne (le_max' _ _ (mem_of_mem_erase ha)) $ ne_of_mem_of_not_mem ha $ not_mem_erase _ _
lemma min'_lt_of_mem_erase_min' [decidable_eq α] {a : α} (ha : a ∈ s.erase (s.min' H)) :
s.min' H < a :=
@lt_max'_of_mem_erase_max' (order_dual α) _ s H _ a ha
/-- Induction principle for `finset`s in a linearly ordered type: a predicate is true on all
`s : finset α` provided that:
* it is true on the empty `finset`,
* for every `s : finset α` and an element `a` strictly greater than all elements of `s`, `p s`
implies `p (insert a s)`. -/
@[elab_as_eliminator]
lemma induction_on_max [decidable_eq α] {p : finset α → Prop} (s : finset α) (h0 : p ∅)
(step : ∀ a s, (∀ x ∈ s, x < a) → p s → p (insert a s)) : p s :=
begin
induction s using finset.strong_induction_on with s ihs,
rcases s.eq_empty_or_nonempty with rfl|hne,
{ exact h0 },
{ have H : s.max' hne ∈ s, from max'_mem s hne,
rw ← insert_erase H,
exact step _ _ (λ x, s.lt_max'_of_mem_erase_max' hne) (ihs _ $ erase_ssubset H) }
end
/-- Induction principle for `finset`s in a linearly ordered type: a predicate is true on all
`s : finset α` provided that:
* it is true on the empty `finset`,
* for every `s : finset α` and an element `a` strictly less than all elements of `s`, `p s`
implies `p (insert a s)`. -/
@[elab_as_eliminator]
lemma induction_on_min [decidable_eq α] {p : finset α → Prop} (s : finset α) (h0 : p ∅)
(step : ∀ a s, (∀ x ∈ s, a < x) → p s → p (insert a s)) : p s :=
@induction_on_max (order_dual α) _ _ _ s h0 step
end max_min
section exists_max_min
variables [linear_order α]
lemma exists_max_image (s : finset β) (f : β → α) (h : s.nonempty) :
∃ x ∈ s, ∀ x' ∈ s, f x' ≤ f x :=
begin
cases max_of_nonempty (h.image f) with y hy,
rcases mem_image.mp (mem_of_max hy) with ⟨x, hx, rfl⟩,
exact ⟨x, hx, λ x' hx', le_max_of_mem (mem_image_of_mem f hx') hy⟩,
end
lemma exists_min_image (s : finset β) (f : β → α) (h : s.nonempty) :
∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' :=
@exists_max_image (order_dual α) β _ s f h
end exists_max_min
end finset
namespace multiset
lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) :
count b (s.sup f) = s.sup (λa, count b (f a)) :=
begin
letI := classical.dec_eq α,
refine s.induction _ _,
{ exact count_zero _ },
{ assume i s his ih,
rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih],
refl }
end
lemma mem_sup {α β} [decidable_eq β] {s : finset α} {f : α → multiset β}
{x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v :=
begin
classical,
apply s.induction_on,
{ simp },
{ intros a s has hxs,
rw [finset.sup_insert, multiset.sup_eq_union, multiset.mem_union],
split,
{ intro hxi,
cases hxi with hf hf,
{ refine ⟨a, _, hf⟩,
simp only [true_or, eq_self_iff_true, finset.mem_insert] },
{ rcases hxs.mp hf with ⟨v, hv, hfv⟩,
refine ⟨v, _, hfv⟩,
simp only [hv, or_true, finset.mem_insert] } },
{ rintros ⟨v, hv, hfv⟩,
rw [finset.mem_insert] at hv,
rcases hv with rfl | hv,
{ exact or.inl hfv },
{ refine or.inr (hxs.mpr ⟨v, hv, hfv⟩) } } },
end
end multiset
namespace finset
lemma mem_sup {α β} [decidable_eq β] {s : finset α} {f : α → finset β}
{x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v :=
begin
change _ ↔ ∃ v ∈ s, x ∈ (f v).val,
rw [←multiset.mem_sup, ←multiset.mem_to_finset, sup_to_finset],
simp_rw [val_to_finset],
end
lemma sup_eq_bUnion {α β} [decidable_eq β] (s : finset α) (t : α → finset β) :
s.sup t = s.bUnion t :=
by { ext, rw [mem_sup, mem_bUnion], }
end finset
section lattice
variables {ι : Type*} {ι' : Sort*} [complete_lattice α]
/-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : finset ι` of suprema
`⨆ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `supr_eq_supr_finset'` for a version
that works for `ι : Sort*`. -/
lemma supr_eq_supr_finset (s : ι → α) :
(⨆i, s i) = (⨆t:finset ι, ⨆i∈t, s i) :=
begin
classical,
exact le_antisymm
(supr_le $ assume b, le_supr_of_le {b} $ le_supr_of_le b $ le_supr_of_le
(by simp) $ le_refl _)
(supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _)
end
/-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : finset ι` of suprema
`⨆ i ∈ t, s i`. This version works for `ι : Sort*`. See `supr_eq_supr_finset` for a version
that assumes `ι : Type*` but has no `plift`s. -/
lemma supr_eq_supr_finset' (s : ι' → α) :
(⨆i, s i) = (⨆t:finset (plift ι'), ⨆i∈t, s (plift.down i)) :=
by rw [← supr_eq_supr_finset, ← equiv.plift.surjective.supr_comp]; refl
/-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : finset ι` of infima
`⨆ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `infi_eq_infi_finset'` for a version
that works for `ι : Sort*`. -/
lemma infi_eq_infi_finset (s : ι → α) :
(⨅i, s i) = (⨅t:finset ι, ⨅i∈t, s i) :=
@supr_eq_supr_finset (order_dual α) _ _ _
/-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : finset ι` of infima
`⨆ i ∈ t, s i`. This version works for `ι : Sort*`. See `infi_eq_infi_finset` for a version
that assumes `ι : Type*` but has no `plift`s. -/
lemma infi_eq_infi_finset' (s : ι' → α) :
(⨅i, s i) = (⨅t:finset (plift ι'), ⨅i∈t, s (plift.down i)) :=
@supr_eq_supr_finset' (order_dual α) _ _ _
end lattice
namespace set
variables {ι : Type*} {ι' : Sort*}
/-- Union of an indexed family of sets `s : ι → set α` is equal to the union of the unions
of finite subfamilies. This version assumes `ι : Type*`. See also `Union_eq_Union_finset'` for
a version that works for `ι : Sort*`. -/
lemma Union_eq_Union_finset (s : ι → set α) :
(⋃i, s i) = (⋃t:finset ι, ⋃i∈t, s i) :=
supr_eq_supr_finset s
/-- Union of an indexed family of sets `s : ι → set α` is equal to the union of the unions
of finite subfamilies. This version works for `ι : Sort*`. See also `Union_eq_Union_finset` for
a version that assumes `ι : Type*` but avoids `plift`s in the right hand side. -/
lemma Union_eq_Union_finset' (s : ι' → set α) :
(⋃i, s i) = (⋃t:finset (plift ι'), ⋃i∈t, s (plift.down i)) :=
supr_eq_supr_finset' s
/-- Intersection of an indexed family of sets `s : ι → set α` is equal to the intersection of the
intersections of finite subfamilies. This version assumes `ι : Type*`. See also
`Inter_eq_Inter_finset'` for a version that works for `ι : Sort*`. -/
lemma Inter_eq_Inter_finset (s : ι → set α) :
(⋂i, s i) = (⋂t:finset ι, ⋂i∈t, s i) :=
infi_eq_infi_finset s
/-- Intersection of an indexed family of sets `s : ι → set α` is equal to the intersection of the
intersections of finite subfamilies. This version works for `ι : Sort*`. See also
`Inter_eq_Inter_finset` for a version that assumes `ι : Type*` but avoids `plift`s in the right
hand side. -/
lemma Inter_eq_Inter_finset' (s : ι' → set α) :
(⋂i, s i) = (⋂t:finset (plift ι'), ⋂i∈t, s (plift.down i)) :=
infi_eq_infi_finset' s
end set
namespace finset
open function
/-! ### Interaction with big lattice/set operations -/
section lattice
lemma supr_coe [has_Sup β] (f : α → β) (s : finset α) :
(⨆ x ∈ (↑s : set α), f x) = ⨆ x ∈ s, f x :=
rfl
lemma infi_coe [has_Inf β] (f : α → β) (s : finset α) :
(⨅ x ∈ (↑s : set α), f x) = ⨅ x ∈ s, f x :=
rfl
variables [complete_lattice β]
theorem supr_singleton (a : α) (s : α → β) : (⨆ x ∈ ({a} : finset α), s x) = s a :=
by simp
theorem infi_singleton (a : α) (s : α → β) : (⨅ x ∈ ({a} : finset α), s x) = s a :=
by simp
lemma supr_option_to_finset (o : option α) (f : α → β) :
(⨆ x ∈ o.to_finset, f x) = ⨆ x ∈ o, f x :=
by simp
lemma infi_option_to_finset (o : option α) (f : α → β) :
(⨅ x ∈ o.to_finset, f x) = ⨅ x ∈ o, f x :=
@supr_option_to_finset _ (order_dual β) _ _ _
variables [decidable_eq α]
theorem supr_union {f : α → β} {s t : finset α} :
(⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) :=
by simp [supr_or, supr_sup_eq]
theorem infi_union {f : α → β} {s t : finset α} :
(⨅ x ∈ s ∪ t, f x) = (⨅ x ∈ s, f x) ⊓ (⨅ x ∈ t, f x) :=
@supr_union α (order_dual β) _ _ _ _ _
lemma supr_insert (a : α) (s : finset α) (t : α → β) :
(⨆ x ∈ insert a s, t x) = t a ⊔ (⨆ x ∈ s, t x) :=
by { rw insert_eq, simp only [supr_union, finset.supr_singleton] }
lemma infi_insert (a : α) (s : finset α) (t : α → β) :
(⨅ x ∈ insert a s, t x) = t a ⊓ (⨅ x ∈ s, t x) :=
@supr_insert α (order_dual β) _ _ _ _ _
lemma supr_finset_image {f : γ → α} {g : α → β} {s : finset γ} :
(⨆ x ∈ s.image f, g x) = (⨆ y ∈ s, g (f y)) :=
by rw [← supr_coe, coe_image, supr_image, supr_coe]
lemma sup_finset_image {β γ : Type*} [semilattice_sup_bot β]
(f : γ → α) (g : α → β) (s : finset γ) :
(s.image f).sup g = s.sup (g ∘ f) :=
begin
classical,
induction s using finset.induction_on with a s' ha ih; simp *
end
lemma infi_finset_image {f : γ → α} {g : α → β} {s : finset γ} :
(⨅ x ∈ s.image f, g x) = (⨅ y ∈ s, g (f y)) :=
by rw [← infi_coe, coe_image, infi_image, infi_coe]
lemma supr_insert_update {x : α} {t : finset α} (f : α → β) {s : β} (hx : x ∉ t) :
(⨆ (i ∈ insert x t), function.update f x s i) = (s ⊔ ⨆ (i ∈ t), f i) :=
begin
simp only [finset.supr_insert, update_same],
rcongr i hi, apply update_noteq, rintro rfl, exact hx hi
end
lemma infi_insert_update {x : α} {t : finset α} (f : α → β) {s : β} (hx : x ∉ t) :
(⨅ (i ∈ insert x t), update f x s i) = (s ⊓ ⨅ (i ∈ t), f i) :=
@supr_insert_update α (order_dual β) _ _ _ _ f _ hx
lemma supr_bUnion (s : finset γ) (t : γ → finset α) (f : α → β) :
(⨆ y ∈ s.bUnion t, f y) = ⨆ (x ∈ s) (y ∈ t x), f y :=
by simp [@supr_comm _ α, supr_and]
lemma infi_bUnion (s : finset γ) (t : γ → finset α) (f : α → β) :
(⨅ y ∈ s.bUnion t, f y) = ⨅ (x ∈ s) (y ∈ t x), f y :=
@supr_bUnion _ (order_dual β) _ _ _ _ _ _
end lattice
theorem set_bUnion_coe (s : finset α) (t : α → set β) :
(⋃ x ∈ (↑s : set α), t x) = ⋃ x ∈ s, t x :=
rfl
theorem set_bInter_coe (s : finset α) (t : α → set β) :
(⋂ x ∈ (↑s : set α), t x) = ⋂ x ∈ s, t x :=
rfl
theorem set_bUnion_singleton (a : α) (s : α → set β) :
(⋃ x ∈ ({a} : finset α), s x) = s a :=
supr_singleton a s
theorem set_bInter_singleton (a : α) (s : α → set β) :
(⋂ x ∈ ({a} : finset α), s x) = s a :=
infi_singleton a s
@[simp] lemma set_bUnion_preimage_singleton (f : α → β) (s : finset β) :
(⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s :=
set.bUnion_preimage_singleton f s
lemma set_bUnion_option_to_finset (o : option α) (f : α → set β) :
(⋃ x ∈ o.to_finset, f x) = ⋃ x ∈ o, f x :=
supr_option_to_finset o f
lemma set_bInter_option_to_finset (o : option α) (f : α → set β) :
(⋂ x ∈ o.to_finset, f x) = ⋂ x ∈ o, f x :=
infi_option_to_finset o f
variables [decidable_eq α]
lemma set_bUnion_union (s t : finset α) (u : α → set β) :
(⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) :=
supr_union
lemma set_bInter_inter (s t : finset α) (u : α → set β) :
(⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) :=
infi_union
lemma set_bUnion_insert (a : α) (s : finset α) (t : α → set β) :
(⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) :=
supr_insert a s t
lemma set_bInter_insert (a : α) (s : finset α) (t : α → set β) :
(⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) :=
infi_insert a s t
lemma set_bUnion_finset_image {f : γ → α} {g : α → set β} {s : finset γ} :
(⋃x ∈ s.image f, g x) = (⋃y ∈ s, g (f y)) :=
supr_finset_image
lemma set_bInter_finset_image {f : γ → α} {g : α → set β} {s : finset γ} :
(⋂ x ∈ s.image f, g x) = (⋂ y ∈ s, g (f y)) :=
infi_finset_image
lemma set_bUnion_insert_update {x : α} {t : finset α} (f : α → set β) {s : set β} (hx : x ∉ t) :
(⋃ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∪ ⋃ (i ∈ t), f i) :=
supr_insert_update f hx
lemma set_bInter_insert_update {x : α} {t : finset α} (f : α → set β) {s : set β} (hx : x ∉ t) :
(⋂ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∩ ⋂ (i ∈ t), f i) :=
infi_insert_update f hx
lemma set_bUnion_bUnion (s : finset γ) (t : γ → finset α) (f : α → set β) :
(⋃ y ∈ s.bUnion t, f y) = ⋃ (x ∈ s) (y ∈ t x), f y :=
supr_bUnion s t f
lemma set_bInter_bUnion (s : finset γ) (t : γ → finset α) (f : α → set β) :
(⋂ y ∈ s.bUnion t, f y) = ⋂ (x ∈ s) (y ∈ t x), f y :=
infi_bUnion s t f
end finset
|
f7d7ad280f801d274914bece49c02fdf47a99b10 | 6de8ea38e7f58ace8fbf74ba3ad0bf3b3d1d7ab5 | /solutions2/Problem2/solutions.lean | 7c466bf3c95d4b4196a12971e64a62bf8ea825fc | [] | no_license | KinanBab/CS591K1-Labs | 72f4e2c7d230d4e4f548a343a47bf815272b1f58 | d4569bf99d20c22cd56721024688cda247d1447f | refs/heads/master | 1,587,016,758,873 | 1,558,148,366,000 | 1,558,148,366,000 | 165,329,114 | 5 | 2 | null | 1,550,689,848,000 | 1,547,252,664,000 | TeX | UTF-8 | Lean | false | false | 3,302 | lean | import .lambda
-- Problem 2: Lambda Calculus and Church Numerals (30 points for full credit, >=45 possible points with bonus)
-- From nat to Church Numerals
@[simp] def zero := term.abs 1 (term.abs 0 (term.var 0)) -- λf. λx. x
@[simp] def succ :=
term.abs 2
(term.abs 1
(term.abs 0
(term.app
(term.var 1)
(term.app
(term.app (term.var 2) (term.var 1) )
(term.var 0)
)
)
)
) -- λn. λf. λx. [f]( [ [n](f) ] (x) )
-- From nat to Church Numerals
@[simp] def from_nat' : nat -> term
| 0 := term.var 0
| (nat.succ n') := term.app (term.var 1) (from_nat' n')
@[simp] def from_nat : nat -> term
| n := (term.abs 1 (term.abs 0 (from_nat' n)))
-- From Church Numerals to nat
@[simp] def to_nat : term -> nat
| (term.var x) := 0
| (term.abs x t') := to_nat t'
| (term.app t t') := 1 + to_nat t'
-- Part A: Correctness of representation (5 points)
theorem repr_correct (n: nat) : to_nat (from_nat n) = n :=
begin
-- #check nat.add_one
-- Proof goes here
induction n,
simp,
simp,
rewrite nat.add_one,
simp,
assumption,
end
-- Part B: Correctness of zero (5 points)
theorem zero_correct : (from_nat 0) = zero :=
begin
simp,
end
-- Part C: Correctness of successor (20 points)
-- Start by proving this helpful lemma, substituting a variable with
-- itself is useless.
lemma sub_useless (n: nat) (t: term) :
(substitute (term.var n) n t) = t :=
begin
-- use cases H: (<expression)
-- to perform case analysis on expression while storing the case in Hypothesis H
-- Proof goes here
induction t,
simp, cases H: (to_bool (t = n)),
simp,
simp,
simp at H,
apply eq.symm,
assumption,
simp, cases H: (to_bool (t_a = n)),
simp, assumption,
simp,
simp, apply and.intro,
assumption, assumption,
end
-- The main theorem
-- The proof will basically be repeated application of the correct constructor
-- either beta.app or beta.appl, or beta.appr, or beta.abs
-- depending on the form of the expression
-- THIS IS HIGHLY AUTOMATABLE, if you can automate it to any extent, you will get bonus points
-- proportional to how automated your solution is.
theorem succ_correct (n: nat) :
(term.app succ (from_nat n)) l↠β (from_nat (nat.succ n)) :=
begin
-- You can use these facts without proof
-- Rewrite with the corresponding fact if you
-- ever have something like ite (to_bool (<number> = <number>))
-- inside your expressions (after dsimp or simp with a substitute)
have H02: (to_bool (0 = 2) = ff), admit,
have H12: (to_bool (1 = 2) = ff), admit,
simp,
constructor, -- rStar.trans
apply beta.app,
dsimp,
rewrite H12,
rewrite H02,
simp,
constructor, -- rStar.trans
constructor, -- beta.abs
constructor, -- beta.abs
apply beta.appr,
apply beta.appl,
apply beta.app,
constructor, -- rStar.trans
constructor, -- beta.abs
constructor, -- beta.abs
apply beta.appr,
apply beta.app,
rewrite sub_useless,
rewrite sub_useless,
constructor, -- rStar.base
end
-- Bonus: Predecessor (15 points)
-- Encode and prove that predecessor is correct, you may ignore the case where the number is zero
-- Find its definitnion here: https://en.wikipedia.org/wiki/Church_encoding
|
a126dc13752f77eb430069596ce82e4c5a17525b | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Init/Data/Int/Basic.lean | d073f1bc839f4f7ad4950d909f0d82eee3b2ce78 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 4,709 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
The integers, with addition, multiplication, and subtraction.
-/
prelude
import Init.Coe
import Init.Data.Nat.Div
import Init.Data.List.Basic
open Nat
/-! # the Type, coercions, and notation -/
inductive Int : Type where
| ofNat : Nat → Int
| negSucc : Nat → Int
attribute [extern "lean_nat_to_int"] Int.ofNat
attribute [extern "lean_int_neg_succ_of_nat"] Int.negSucc
instance : Coe Nat Int := ⟨Int.ofNat⟩
instance : OfNat Int n where
ofNat := Int.ofNat n
namespace Int
instance : Inhabited Int := ⟨ofNat 0⟩
def negOfNat : Nat → Int
| 0 => 0
| succ m => negSucc m
set_option bootstrap.genMatcherCode false in
@[extern "lean_int_neg"]
protected def neg (n : @& Int) : Int :=
match n with
| ofNat n => negOfNat n
| negSucc n => succ n
def subNatNat (m n : Nat) : Int :=
match (n - m : Nat) with
| 0 => ofNat (m - n) -- m ≥ n
| (succ k) => negSucc k
set_option bootstrap.genMatcherCode false in
@[extern "lean_int_add"]
protected def add (m n : @& Int) : Int :=
match m, n with
| ofNat m, ofNat n => ofNat (m + n)
| ofNat m, negSucc n => subNatNat m (succ n)
| negSucc m, ofNat n => subNatNat n (succ m)
| negSucc m, negSucc n => negSucc (succ (m + n))
set_option bootstrap.genMatcherCode false in
@[extern "lean_int_mul"]
protected def mul (m n : @& Int) : Int :=
match m, n with
| ofNat m, ofNat n => ofNat (m * n)
| ofNat m, negSucc n => negOfNat (m * succ n)
| negSucc m, ofNat n => negOfNat (succ m * n)
| negSucc m, negSucc n => ofNat (succ m * succ n)
/--
The `Neg Int` default instance must have priority higher than `low` since
the default instance `OfNat Nat n` has `low` priority.
```
#check -42
```
-/
@[defaultInstance mid]
instance : Neg Int where
neg := Int.neg
instance : Add Int where
add := Int.add
instance : Mul Int where
mul := Int.mul
@[extern "lean_int_sub"]
protected def sub (m n : @& Int) : Int :=
m + (- n)
instance : Sub Int where
sub := Int.sub
inductive NonNeg : Int → Prop where
| mk (n : Nat) : NonNeg (ofNat n)
protected def le (a b : Int) : Prop := NonNeg (b - a)
instance : LE Int where
le := Int.le
protected def lt (a b : Int) : Prop := (a + 1) ≤ b
instance : LT Int where
lt := Int.lt
set_option bootstrap.genMatcherCode false in
@[extern "lean_int_dec_eq"]
protected def decEq (a b : @& Int) : Decidable (a = b) :=
match a, b with
| ofNat a, ofNat b => match decEq a b with
| isTrue h => isTrue <| h ▸ rfl
| isFalse h => isFalse <| fun h' => Int.noConfusion h' (fun h' => absurd h' h)
| negSucc a, negSucc b => match decEq a b with
| isTrue h => isTrue <| h ▸ rfl
| isFalse h => isFalse <| fun h' => Int.noConfusion h' (fun h' => absurd h' h)
| ofNat _, negSucc _ => isFalse <| fun h => Int.noConfusion h
| negSucc _, ofNat _ => isFalse <| fun h => Int.noConfusion h
instance : DecidableEq Int := Int.decEq
set_option bootstrap.genMatcherCode false in
@[extern "lean_int_dec_nonneg"]
private def decNonneg (m : @& Int) : Decidable (NonNeg m) :=
match m with
| ofNat m => isTrue <| NonNeg.mk m
| negSucc _ => isFalse <| fun h => nomatch h
@[extern "lean_int_dec_le"]
instance decLe (a b : @& Int) : Decidable (a ≤ b) :=
decNonneg _
@[extern "lean_int_dec_lt"]
instance decLt (a b : @& Int) : Decidable (a < b) :=
decNonneg _
set_option bootstrap.genMatcherCode false in
@[extern "lean_nat_abs"]
def natAbs (m : @& Int) : Nat :=
match m with
| ofNat m => m
| negSucc m => m.succ
instance : OfNat Int n where
ofNat := Int.ofNat n
@[extern "lean_int_div"]
def div : (@& Int) → (@& Int) → Int
| ofNat m, ofNat n => ofNat (m / n)
| ofNat m, negSucc n => -ofNat (m / succ n)
| negSucc m, ofNat n => -ofNat (succ m / n)
| negSucc m, negSucc n => ofNat (succ m / succ n)
@[extern "lean_int_mod"]
def mod : (@& Int) → (@& Int) → Int
| ofNat m, ofNat n => ofNat (m % n)
| ofNat m, negSucc n => ofNat (m % succ n)
| negSucc m, ofNat n => -ofNat (succ m % n)
| negSucc m, negSucc n => -ofNat (succ m % succ n)
instance : Div Int where
div := Int.div
instance : Mod Int where
mod := Int.mod
def toNat : Int → Nat
| ofNat n => n
| negSucc _ => 0
def natMod (m n : Int) : Nat := (m % n).toNat
protected def pow (m : Int) : Nat → Int
| 0 => 1
| succ n => Int.pow m n * m
instance : HPow Int Nat Int where
hPow := Int.pow
instance : LawfulBEq Int where
eq_of_beq h := by simp [BEq.beq] at h; assumption
rfl := by simp [BEq.beq]
end Int
|
3717dad8e173207e52561ec6f3c38da7b9caa857 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/order/locally_finite.lean | f6194e68b8b8101efb951593b82c77997c61cdb2 | [
"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 | 43,894 | lean | /-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.finset.preimage
import data.set.intervals.unordered_interval
/-!
# Locally finite orders
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines locally finite orders.
A locally finite order is an order for which all bounded intervals are finite. This allows to make
sense of `Icc`/`Ico`/`Ioc`/`Ioo` as lists, multisets, or finsets.
Further, if the order is bounded above (resp. below), then we can also make sense of the
"unbounded" intervals `Ici`/`Ioi` (resp. `Iic`/`Iio`).
Many theorems about these intervals can be found in `data.finset.locally_finite`.
## Examples
Naturally occurring locally finite orders are `ℕ`, `ℤ`, `ℕ+`, `fin n`, `α × β` the product of two
locally finite orders, `α →₀ β` the finitely supported functions to a locally finite order `β`...
## Main declarations
In a `locally_finite_order`,
* `finset.Icc`: Closed-closed interval as a finset.
* `finset.Ico`: Closed-open interval as a finset.
* `finset.Ioc`: Open-closed interval as a finset.
* `finset.Ioo`: Open-open interval as a finset.
* `finset.uIcc`: Unordered closed interval as a finset.
* `multiset.Icc`: Closed-closed interval as a multiset.
* `multiset.Ico`: Closed-open interval as a multiset.
* `multiset.Ioc`: Open-closed interval as a multiset.
* `multiset.Ioo`: Open-open interval as a multiset.
In a `locally_finite_order_top`,
* `finset.Ici`: Closed-infinite interval as a finset.
* `finset.Ioi`: Open-infinite interval as a finset.
* `multiset.Ici`: Closed-infinite interval as a multiset.
* `multiset.Ioi`: Open-infinite interval as a multiset.
In a `locally_finite_order_bot`,
* `finset.Iic`: Infinite-open interval as a finset.
* `finset.Iio`: Infinite-closed interval as a finset.
* `multiset.Iic`: Infinite-open interval as a multiset.
* `multiset.Iio`: Infinite-closed interval as a multiset.
## Instances
A `locally_finite_order` instance can be built
* for a subtype of a locally finite order. See `subtype.locally_finite_order`.
* for the product of two locally finite orders. See `prod.locally_finite_order`.
* for any fintype (but not as an instance). See `fintype.to_locally_finite_order`.
* from a definition of `finset.Icc` alone. See `locally_finite_order.of_Icc`.
* by pulling back `locally_finite_order β` through an order embedding `f : α →o β`. See
`order_embedding.locally_finite_order`.
Instances for concrete types are proved in their respective files:
* `ℕ` is in `data.nat.interval`
* `ℤ` is in `data.int.interval`
* `ℕ+` is in `data.pnat.interval`
* `fin n` is in `data.fin.interval`
* `finset α` is in `data.finset.interval`
* `Σ i, α i` is in `data.sigma.interval`
Along, you will find lemmas about the cardinality of those finite intervals.
## TODO
Provide the `locally_finite_order` instance for `α ×ₗ β` where `locally_finite_order α` and
`fintype β`.
Provide the `locally_finite_order` instance for `α →₀ β` where `β` is locally finite. Provide the
`locally_finite_order` instance for `Π₀ i, β i` where all the `β i` are locally finite.
From `linear_order α`, `no_max_order α`, `locally_finite_order α`, we can also define an
order isomorphism `α ≃ ℕ` or `α ≃ ℤ`, depending on whether we have `order_bot α` or
`no_min_order α` and `nonempty α`. When `order_bot α`, we can match `a : α` to `(Iio a).card`.
We can provide `succ_order α` from `linear_order α` and `locally_finite_order α` using
```lean
lemma exists_min_greater [linear_order α] [locally_finite_order α] {x ub : α} (hx : x < ub) :
∃ lub, x < lub ∧ ∀ y, x < y → lub ≤ y :=
begin -- very non golfed
have h : (finset.Ioc x ub).nonempty := ⟨ub, finset.mem_Ioc_iff.2 ⟨hx, le_rfl⟩⟩,
use finset.min' (finset.Ioc x ub) h,
split,
{ have := finset.min'_mem _ h,
simp * at * },
rintro y hxy,
obtain hy | hy := le_total y ub,
apply finset.min'_le,
simp * at *,
exact (finset.min'_le _ _ (finset.mem_Ioc_iff.2 ⟨hx, le_rfl⟩)).trans hy,
end
```
Note that the converse is not true. Consider `{-2^z | z : ℤ} ∪ {2^z | z : ℤ}`. Any element has a
successor (and actually a predecessor as well), so it is a `succ_order`, but it's not locally finite
as `Icc (-1) 1` is infinite.
-/
open finset function
/-- A locally finite order is an order where bounded intervals are finite. When you don't care too
much about definitional equality, you can use `locally_finite_order.of_Icc` or
`locally_finite_order.of_finite_Icc` to build a locally finite order from just `finset.Icc`. -/
class locally_finite_order (α : Type*) [preorder α] :=
(finset_Icc : α → α → finset α)
(finset_Ico : α → α → finset α)
(finset_Ioc : α → α → finset α)
(finset_Ioo : α → α → finset α)
(finset_mem_Icc : ∀ a b x : α, x ∈ finset_Icc a b ↔ a ≤ x ∧ x ≤ b)
(finset_mem_Ico : ∀ a b x : α, x ∈ finset_Ico a b ↔ a ≤ x ∧ x < b)
(finset_mem_Ioc : ∀ a b x : α, x ∈ finset_Ioc a b ↔ a < x ∧ x ≤ b)
(finset_mem_Ioo : ∀ a b x : α, x ∈ finset_Ioo a b ↔ a < x ∧ x < b)
/-- A locally finite order top is an order where all intervals bounded above are finite. This is
slightly weaker than `locally_finite_order` + `order_top` as it allows empty types. -/
class locally_finite_order_top (α : Type*) [preorder α] :=
(finset_Ioi : α → finset α)
(finset_Ici : α → finset α)
(finset_mem_Ici : ∀ a x : α, x ∈ finset_Ici a ↔ a ≤ x)
(finset_mem_Ioi : ∀ a x : α, x ∈ finset_Ioi a ↔ a < x)
/-- A locally finite order bot is an order where all intervals bounded below are finite. This is
slightly weaker than `locally_finite_order` + `order_bot` as it allows empty types. -/
class locally_finite_order_bot (α : Type*) [preorder α] :=
(finset_Iio : α → finset α)
(finset_Iic : α → finset α)
(finset_mem_Iic : ∀ a x : α, x ∈ finset_Iic a ↔ x ≤ a)
(finset_mem_Iio : ∀ a x : α, x ∈ finset_Iio a ↔ x < a)
/-- A constructor from a definition of `finset.Icc` alone, the other ones being derived by removing
the ends. As opposed to `locally_finite_order.of_Icc`, this one requires `decidable_rel (≤)` but
only `preorder`. -/
def locally_finite_order.of_Icc' (α : Type*) [preorder α] [decidable_rel ((≤) : α → α → Prop)]
(finset_Icc : α → α → finset α) (mem_Icc : ∀ a b x, x ∈ finset_Icc a b ↔ a ≤ x ∧ x ≤ b) :
locally_finite_order α :=
{ finset_Icc := finset_Icc,
finset_Ico := λ a b, (finset_Icc a b).filter (λ x, ¬b ≤ x),
finset_Ioc := λ a b, (finset_Icc a b).filter (λ x, ¬x ≤ a),
finset_Ioo := λ a b, (finset_Icc a b).filter (λ x, ¬x ≤ a ∧ ¬b ≤ x),
finset_mem_Icc := mem_Icc,
finset_mem_Ico := λ a b x, by rw [finset.mem_filter, mem_Icc, and_assoc, lt_iff_le_not_le],
finset_mem_Ioc := λ a b x, by rw [finset.mem_filter, mem_Icc, and.right_comm, lt_iff_le_not_le],
finset_mem_Ioo := λ a b x, by rw [finset.mem_filter, mem_Icc, and_and_and_comm, lt_iff_le_not_le,
lt_iff_le_not_le] }
/-- A constructor from a definition of `finset.Icc` alone, the other ones being derived by removing
the ends. As opposed to `locally_finite_order.of_Icc`, this one requires `partial_order` but only
`decidable_eq`. -/
def locally_finite_order.of_Icc (α : Type*) [partial_order α] [decidable_eq α]
(finset_Icc : α → α → finset α) (mem_Icc : ∀ a b x, x ∈ finset_Icc a b ↔ a ≤ x ∧ x ≤ b) :
locally_finite_order α :=
{ finset_Icc := finset_Icc,
finset_Ico := λ a b, (finset_Icc a b).filter (λ x, x ≠ b),
finset_Ioc := λ a b, (finset_Icc a b).filter (λ x, a ≠ x),
finset_Ioo := λ a b, (finset_Icc a b).filter (λ x, a ≠ x ∧ x ≠ b),
finset_mem_Icc := mem_Icc,
finset_mem_Ico := λ a b x, by rw [finset.mem_filter, mem_Icc, and_assoc, lt_iff_le_and_ne],
finset_mem_Ioc := λ a b x, by rw [finset.mem_filter, mem_Icc, and.right_comm, lt_iff_le_and_ne],
finset_mem_Ioo := λ a b x, by rw [finset.mem_filter, mem_Icc, and_and_and_comm, lt_iff_le_and_ne,
lt_iff_le_and_ne] }
/-- A constructor from a definition of `finset.Iic` alone, the other ones being derived by removing
the ends. As opposed to `locally_finite_order_top.of_Ici`, this one requires `decidable_rel (≤)` but
only `preorder`. -/
def locally_finite_order_top.of_Ici' (α : Type*) [preorder α] [decidable_rel ((≤) : α → α → Prop)]
(finset_Ici : α → finset α) (mem_Ici : ∀ a x, x ∈ finset_Ici a ↔ a ≤ x) :
locally_finite_order_top α :=
{ finset_Ici := finset_Ici,
finset_Ioi := λ a, (finset_Ici a).filter (λ x, ¬x ≤ a),
finset_mem_Ici := mem_Ici,
finset_mem_Ioi := λ a x, by rw [mem_filter, mem_Ici, lt_iff_le_not_le] }
/-- A constructor from a definition of `finset.Iic` alone, the other ones being derived by removing
the ends. As opposed to `locally_finite_order_top.of_Ici'`, this one requires `partial_order` but
only `decidable_eq`. -/
def locally_finite_order_top.of_Ici (α : Type*) [partial_order α] [decidable_eq α]
(finset_Ici : α → finset α) (mem_Ici : ∀ a x, x ∈ finset_Ici a ↔ a ≤ x) :
locally_finite_order_top α :=
{ finset_Ici := finset_Ici,
finset_Ioi := λ a, (finset_Ici a).filter (λ x, a ≠ x),
finset_mem_Ici := mem_Ici,
finset_mem_Ioi := λ a x, by rw [mem_filter, mem_Ici, lt_iff_le_and_ne] }
/-- A constructor from a definition of `finset.Iic` alone, the other ones being derived by removing
the ends. As opposed to `locally_finite_order.of_Icc`, this one requires `decidable_rel (≤)` but
only `preorder`. -/
def locally_finite_order_bot.of_Iic' (α : Type*) [preorder α] [decidable_rel ((≤) : α → α → Prop)]
(finset_Iic : α → finset α) (mem_Iic : ∀ a x, x ∈ finset_Iic a ↔ x ≤ a) :
locally_finite_order_bot α :=
{ finset_Iic := finset_Iic,
finset_Iio := λ a, (finset_Iic a).filter (λ x, ¬a ≤ x),
finset_mem_Iic := mem_Iic,
finset_mem_Iio := λ a x, by rw [mem_filter, mem_Iic, lt_iff_le_not_le] }
/-- A constructor from a definition of `finset.Iic` alone, the other ones being derived by removing
the ends. As opposed to `locally_finite_order_top.of_Ici'`, this one requires `partial_order` but
only `decidable_eq`. -/
def locally_finite_order_top.of_Iic (α : Type*) [partial_order α] [decidable_eq α]
(finset_Iic : α → finset α) (mem_Iic : ∀ a x, x ∈ finset_Iic a ↔ x ≤ a) :
locally_finite_order_bot α :=
{ finset_Iic := finset_Iic,
finset_Iio := λ a, (finset_Iic a).filter (λ x, x ≠ a),
finset_mem_Iic := mem_Iic,
finset_mem_Iio := λ a x, by rw [mem_filter, mem_Iic, lt_iff_le_and_ne] }
variables {α β : Type*}
/-- An empty type is locally finite.
This is not an instance as it would not be defeq to more specific instances. -/
@[reducible] -- See note [reducible non-instances]
protected def _root_.is_empty.to_locally_finite_order [preorder α] [is_empty α] :
locally_finite_order α :=
{ finset_Icc := is_empty_elim,
finset_Ico := is_empty_elim,
finset_Ioc := is_empty_elim,
finset_Ioo := is_empty_elim,
finset_mem_Icc := is_empty_elim,
finset_mem_Ico := is_empty_elim,
finset_mem_Ioc := is_empty_elim,
finset_mem_Ioo := is_empty_elim }
/-- An empty type is locally finite.
This is not an instance as it would not be defeq to more specific instances. -/
@[reducible] -- See note [reducible non-instances]
protected def _root_.is_empty.to_locally_finite_order_top [preorder α] [is_empty α] :
locally_finite_order_top α :=
{ finset_Ici := is_empty_elim,
finset_Ioi := is_empty_elim,
finset_mem_Ici := is_empty_elim,
finset_mem_Ioi := is_empty_elim }
/-- An empty type is locally finite.
This is not an instance as it would not be defeq to more specific instances. -/
@[reducible] -- See note [reducible non-instances]
protected def _root_.is_empty.to_locally_finite_order_bot [preorder α] [is_empty α] :
locally_finite_order_bot α :=
{ finset_Iic := is_empty_elim,
finset_Iio := is_empty_elim,
finset_mem_Iic := is_empty_elim,
finset_mem_Iio := is_empty_elim }
/-! ### Intervals as finsets -/
namespace finset
section preorder
variables [preorder α]
section locally_finite_order
variables [locally_finite_order α] {a b x : α}
/-- The finset of elements `x` such that `a ≤ x` and `x ≤ b`. Basically `set.Icc a b` as a finset.
-/
def Icc (a b : α) : finset α := locally_finite_order.finset_Icc a b
/-- The finset of elements `x` such that `a ≤ x` and `x < b`. Basically `set.Ico a b` as a finset.
-/
def Ico (a b : α) : finset α := locally_finite_order.finset_Ico a b
/-- The finset of elements `x` such that `a < x` and `x ≤ b`. Basically `set.Ioc a b` as a finset.
-/
def Ioc (a b : α) : finset α := locally_finite_order.finset_Ioc a b
/-- The finset of elements `x` such that `a < x` and `x < b`. Basically `set.Ioo a b` as a finset.
-/
def Ioo (a b : α) : finset α := locally_finite_order.finset_Ioo a b
@[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b :=
locally_finite_order.finset_mem_Icc a b x
@[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b :=
locally_finite_order.finset_mem_Ico a b x
@[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b :=
locally_finite_order.finset_mem_Ioc a b x
@[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b :=
locally_finite_order.finset_mem_Ioo a b x
@[simp, norm_cast]
lemma coe_Icc (a b : α) : (Icc a b : set α) = set.Icc a b := set.ext $ λ _, mem_Icc
@[simp, norm_cast]
lemma coe_Ico (a b : α) : (Ico a b : set α) = set.Ico a b := set.ext $ λ _, mem_Ico
@[simp, norm_cast]
lemma coe_Ioc (a b : α) : (Ioc a b : set α) = set.Ioc a b := set.ext $ λ _, mem_Ioc
@[simp, norm_cast]
lemma coe_Ioo (a b : α) : (Ioo a b : set α) = set.Ioo a b := set.ext $ λ _, mem_Ioo
end locally_finite_order
section locally_finite_order_top
variables [locally_finite_order_top α] {a x : α}
/-- The finset of elements `x` such that `a ≤ x`. Basically `set.Ici a` as a finset. -/
def Ici (a : α) : finset α := locally_finite_order_top.finset_Ici a
/-- The finset of elements `x` such that `a < x`. Basically `set.Ioi a` as a finset. -/
def Ioi (a : α) : finset α := locally_finite_order_top.finset_Ioi a
@[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := locally_finite_order_top.finset_mem_Ici _ _
@[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := locally_finite_order_top.finset_mem_Ioi _ _
@[simp, norm_cast] lemma coe_Ici (a : α) : (Ici a : set α) = set.Ici a := set.ext $ λ _, mem_Ici
@[simp, norm_cast] lemma coe_Ioi (a : α) : (Ioi a : set α) = set.Ioi a := set.ext $ λ _, mem_Ioi
end locally_finite_order_top
section locally_finite_order_bot
variables [locally_finite_order_bot α] {a x : α}
/-- The finset of elements `x` such that `a ≤ x`. Basically `set.Iic a` as a finset. -/
def Iic (a : α) : finset α := locally_finite_order_bot.finset_Iic a
/-- The finset of elements `x` such that `a < x`. Basically `set.Iio a` as a finset. -/
def Iio (a : α) : finset α := locally_finite_order_bot.finset_Iio a
@[simp] lemma mem_Iic : x ∈ Iic a ↔ x ≤ a := locally_finite_order_bot.finset_mem_Iic _ _
@[simp] lemma mem_Iio : x ∈ Iio a ↔ x < a := locally_finite_order_bot.finset_mem_Iio _ _
@[simp, norm_cast] lemma coe_Iic (a : α) : (Iic a : set α) = set.Iic a := set.ext $ λ _, mem_Iic
@[simp, norm_cast] lemma coe_Iio (a : α) : (Iio a : set α) = set.Iio a := set.ext $ λ _, mem_Iio
end locally_finite_order_bot
section order_top
variables [locally_finite_order α] [order_top α] {a x : α}
@[priority 100] -- See note [lower priority instance]
instance _root_.locally_finite_order.to_locally_finite_order_top : locally_finite_order_top α :=
{ finset_Ici := λ b, Icc b ⊤,
finset_Ioi := λ b, Ioc b ⊤,
finset_mem_Ici := λ a x, by rw [mem_Icc, and_iff_left le_top],
finset_mem_Ioi := λ a x, by rw [mem_Ioc, and_iff_left le_top] }
lemma Ici_eq_Icc (a : α) : Ici a = Icc a ⊤ := rfl
lemma Ioi_eq_Ioc (a : α) : Ioi a = Ioc a ⊤ := rfl
end order_top
section order_bot
variables [order_bot α] [locally_finite_order α] {b x : α}
@[priority 100] -- See note [lower priority instance]
instance locally_finite_order.to_locally_finite_order_bot : locally_finite_order_bot α :=
{ finset_Iic := Icc ⊥,
finset_Iio := Ico ⊥,
finset_mem_Iic := λ a x, by rw [mem_Icc, and_iff_right bot_le],
finset_mem_Iio := λ a x, by rw [mem_Ico, and_iff_right bot_le] }
lemma Iic_eq_Icc : Iic = Icc (⊥ : α) := rfl
lemma Iio_eq_Ico : Iio = Ico (⊥ : α) := rfl
end order_bot
end preorder
section lattice
variables [lattice α] [locally_finite_order α] {a b x : α}
/-- `finset.uIcc a b` is the set of elements lying between `a` and `b`, with `a` and `b` included.
Note that we define it more generally in a lattice as `finset.Icc (a ⊓ b) (a ⊔ b)`. In a
product type, `finset.uIcc` corresponds to the bounding box of the two elements. -/
def uIcc (a b : α) : finset α := Icc (a ⊓ b) (a ⊔ b)
localized "notation (name := finset.uIcc) `[`a `, ` b `]` := finset.uIcc a b"
in finset_interval
@[simp] lemma mem_uIcc : x ∈ uIcc a b ↔ a ⊓ b ≤ x ∧ x ≤ a ⊔ b := mem_Icc
@[simp, norm_cast] lemma coe_uIcc (a b : α) : ([a, b] : set α) = set.uIcc a b := coe_Icc _ _
end lattice
end finset
/-! ### Intervals as multisets -/
namespace multiset
variables [preorder α]
section locally_finite_order
variables [locally_finite_order α]
/-- The multiset of elements `x` such that `a ≤ x` and `x ≤ b`. Basically `set.Icc a b` as a
multiset. -/
def Icc (a b : α) : multiset α := (finset.Icc a b).val
/-- The multiset of elements `x` such that `a ≤ x` and `x < b`. Basically `set.Ico a b` as a
multiset. -/
def Ico (a b : α) : multiset α := (finset.Ico a b).val
/-- The multiset of elements `x` such that `a < x` and `x ≤ b`. Basically `set.Ioc a b` as a
multiset. -/
def Ioc (a b : α) : multiset α := (finset.Ioc a b).val
/-- The multiset of elements `x` such that `a < x` and `x < b`. Basically `set.Ioo a b` as a
multiset. -/
def Ioo (a b : α) : multiset α := (finset.Ioo a b).val
@[simp] lemma mem_Icc {a b x : α} : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b :=
by rw [Icc, ←finset.mem_def, finset.mem_Icc]
@[simp] lemma mem_Ico {a b x : α} : x ∈ Ico a b ↔ a ≤ x ∧ x < b :=
by rw [Ico, ←finset.mem_def, finset.mem_Ico]
@[simp] lemma mem_Ioc {a b x : α} : x ∈ Ioc a b ↔ a < x ∧ x ≤ b :=
by rw [Ioc, ←finset.mem_def, finset.mem_Ioc]
@[simp] lemma mem_Ioo {a b x : α} : x ∈ Ioo a b ↔ a < x ∧ x < b :=
by rw [Ioo, ←finset.mem_def, finset.mem_Ioo]
end locally_finite_order
section locally_finite_order_top
variables [locally_finite_order_top α]
/-- The multiset of elements `x` such that `a ≤ x`. Basically `set.Ici a` as a multiset. -/
def Ici (a : α) : multiset α := (finset.Ici a).val
/-- The multiset of elements `x` such that `a < x`. Basically `set.Ioi a` as a multiset. -/
def Ioi (a : α) : multiset α := (finset.Ioi a).val
@[simp] lemma mem_Ici {a x : α} : x ∈ Ici a ↔ a ≤ x := by rw [Ici, ←finset.mem_def, finset.mem_Ici]
@[simp] lemma mem_Ioi {a x : α} : x ∈ Ioi a ↔ a < x := by rw [Ioi, ←finset.mem_def, finset.mem_Ioi]
end locally_finite_order_top
section locally_finite_order_bot
variables [locally_finite_order_bot α]
/-- The multiset of elements `x` such that `x ≤ b`. Basically `set.Iic b` as a multiset. -/
def Iic (b : α) : multiset α := (finset.Iic b).val
/-- The multiset of elements `x` such that `x < b`. Basically `set.Iio b` as a multiset. -/
def Iio (b : α) : multiset α := (finset.Iio b).val
@[simp] lemma mem_Iic {b x : α} : x ∈ Iic b ↔ x ≤ b := by rw [Iic, ←finset.mem_def, finset.mem_Iic]
@[simp] lemma mem_Iio {b x : α} : x ∈ Iio b ↔ x < b := by rw [Iio, ←finset.mem_def, finset.mem_Iio]
end locally_finite_order_bot
end multiset
/-! ### Finiteness of `set` intervals -/
namespace set
section preorder
variables [preorder α] [locally_finite_order α] (a b : α)
instance fintype_Icc : fintype (Icc a b) := fintype.of_finset (finset.Icc a b) $ λ x, finset.mem_Icc
instance fintype_Ico : fintype (Ico a b) := fintype.of_finset (finset.Ico a b) $ λ x, finset.mem_Ico
instance fintype_Ioc : fintype (Ioc a b) := fintype.of_finset (finset.Ioc a b) $ λ x, finset.mem_Ioc
instance fintype_Ioo : fintype (Ioo a b) := fintype.of_finset (finset.Ioo a b) $ λ x, finset.mem_Ioo
lemma finite_Icc : (Icc a b).finite := (Icc a b).to_finite
lemma finite_Ico : (Ico a b).finite := (Ico a b).to_finite
lemma finite_Ioc : (Ioc a b).finite := (Ioc a b).to_finite
lemma finite_Ioo : (Ioo a b).finite := (Ioo a b).to_finite
end preorder
section order_top
variables [preorder α] [locally_finite_order_top α] (a : α)
instance fintype_Ici : fintype (Ici a) := fintype.of_finset (finset.Ici a) $ λ x, finset.mem_Ici
instance fintype_Ioi : fintype (Ioi a) := fintype.of_finset (finset.Ioi a) $ λ x, finset.mem_Ioi
lemma finite_Ici : (Ici a).finite := (Ici a).to_finite
lemma finite_Ioi : (Ioi a).finite := (Ioi a).to_finite
end order_top
section order_bot
variables [preorder α] [locally_finite_order_bot α] (b : α)
instance fintype_Iic : fintype (Iic b) := fintype.of_finset (finset.Iic b) $ λ x, finset.mem_Iic
instance fintype_Iio : fintype (Iio b) := fintype.of_finset (finset.Iio b) $ λ x, finset.mem_Iio
lemma finite_Iic : (Iic b).finite := (Iic b).to_finite
lemma finite_Iio : (Iio b).finite := (Iio b).to_finite
end order_bot
section lattice
variables [lattice α] [locally_finite_order α] (a b : α)
instance fintype_uIcc : fintype (uIcc a b) :=
fintype.of_finset (finset.uIcc a b) $ λ x, finset.mem_uIcc
@[simp] lemma finite_interval : (uIcc a b).finite := (uIcc _ _).to_finite
end lattice
end set
/-! ### Instances -/
open finset
section preorder
variables [preorder α] [preorder β]
/-- A noncomputable constructor from the finiteness of all closed intervals. -/
noncomputable def locally_finite_order.of_finite_Icc (h : ∀ a b : α, (set.Icc a b).finite) :
locally_finite_order α :=
@locally_finite_order.of_Icc' α _ (classical.dec_rel _)
(λ a b, (h a b).to_finset)
(λ a b x, by rw [set.finite.mem_to_finset, set.mem_Icc])
/-- A fintype is a locally finite order.
This is not an instance as it would not be defeq to better instances such as
`fin.locally_finite_order`.
-/
@[reducible]
def fintype.to_locally_finite_order [fintype α] [@decidable_rel α (<)] [@decidable_rel α (≤)] :
locally_finite_order α :=
{ finset_Icc := λ a b, (set.Icc a b).to_finset,
finset_Ico := λ a b, (set.Ico a b).to_finset,
finset_Ioc := λ a b, (set.Ioc a b).to_finset,
finset_Ioo := λ a b, (set.Ioo a b).to_finset,
finset_mem_Icc := λ a b x, by simp only [set.mem_to_finset, set.mem_Icc],
finset_mem_Ico := λ a b x, by simp only [set.mem_to_finset, set.mem_Ico],
finset_mem_Ioc := λ a b x, by simp only [set.mem_to_finset, set.mem_Ioc],
finset_mem_Ioo := λ a b x, by simp only [set.mem_to_finset, set.mem_Ioo] }
instance : subsingleton (locally_finite_order α) :=
subsingleton.intro (λ h₀ h₁, begin
cases h₀,
cases h₁,
have hIcc : h₀_finset_Icc = h₁_finset_Icc,
{ ext a b x, rw [h₀_finset_mem_Icc, h₁_finset_mem_Icc] },
have hIco : h₀_finset_Ico = h₁_finset_Ico,
{ ext a b x, rw [h₀_finset_mem_Ico, h₁_finset_mem_Ico] },
have hIoc : h₀_finset_Ioc = h₁_finset_Ioc,
{ ext a b x, rw [h₀_finset_mem_Ioc, h₁_finset_mem_Ioc] },
have hIoo : h₀_finset_Ioo = h₁_finset_Ioo,
{ ext a b x, rw [h₀_finset_mem_Ioo, h₁_finset_mem_Ioo] },
simp_rw [hIcc, hIco, hIoc, hIoo],
end)
instance : subsingleton (locally_finite_order_top α) :=
subsingleton.intro $ λ h₀ h₁, begin
cases h₀,
cases h₁,
have hIci : h₀_finset_Ici = h₁_finset_Ici,
{ ext a b x, rw [h₀_finset_mem_Ici, h₁_finset_mem_Ici] },
have hIoi : h₀_finset_Ioi = h₁_finset_Ioi,
{ ext a b x, rw [h₀_finset_mem_Ioi, h₁_finset_mem_Ioi] },
simp_rw [hIci, hIoi],
end
instance : subsingleton (locally_finite_order_bot α) :=
subsingleton.intro $ λ h₀ h₁, begin
cases h₀,
cases h₁,
have hIic : h₀_finset_Iic = h₁_finset_Iic,
{ ext a b x, rw [h₀_finset_mem_Iic, h₁_finset_mem_Iic] },
have hIio : h₀_finset_Iio = h₁_finset_Iio,
{ ext a b x, rw [h₀_finset_mem_Iio, h₁_finset_mem_Iio] },
simp_rw [hIic, hIio],
end
-- Should this be called `locally_finite_order.lift`?
/-- Given an order embedding `α ↪o β`, pulls back the `locally_finite_order` on `β` to `α`. -/
protected noncomputable def order_embedding.locally_finite_order [locally_finite_order β]
(f : α ↪o β) : locally_finite_order α :=
{ finset_Icc := λ a b, (Icc (f a) (f b)).preimage f (f.to_embedding.injective.inj_on _),
finset_Ico := λ a b, (Ico (f a) (f b)).preimage f (f.to_embedding.injective.inj_on _),
finset_Ioc := λ a b, (Ioc (f a) (f b)).preimage f (f.to_embedding.injective.inj_on _),
finset_Ioo := λ a b, (Ioo (f a) (f b)).preimage f (f.to_embedding.injective.inj_on _),
finset_mem_Icc := λ a b x, by rw [mem_preimage, mem_Icc, f.le_iff_le, f.le_iff_le],
finset_mem_Ico := λ a b x, by rw [mem_preimage, mem_Ico, f.le_iff_le, f.lt_iff_lt],
finset_mem_Ioc := λ a b x, by rw [mem_preimage, mem_Ioc, f.lt_iff_lt, f.le_iff_le],
finset_mem_Ioo := λ a b x, by rw [mem_preimage, mem_Ioo, f.lt_iff_lt, f.lt_iff_lt] }
open order_dual
section locally_finite_order
variables [locally_finite_order α] (a b : α)
/-- Note we define `Icc (to_dual a) (to_dual b)` as `Icc α _ _ b a` (which has type `finset α` not
`finset αᵒᵈ`!) instead of `(Icc b a).map to_dual.to_embedding` as this means the
following is defeq:
```
lemma this : (Icc (to_dual (to_dual a)) (to_dual (to_dual b)) : _) = (Icc a b : _) := rfl
```
-/
instance : locally_finite_order αᵒᵈ :=
{ finset_Icc := λ a b, @Icc α _ _ (of_dual b) (of_dual a),
finset_Ico := λ a b, @Ioc α _ _ (of_dual b) (of_dual a),
finset_Ioc := λ a b, @Ico α _ _ (of_dual b) (of_dual a),
finset_Ioo := λ a b, @Ioo α _ _ (of_dual b) (of_dual a),
finset_mem_Icc := λ a b x, mem_Icc.trans (and_comm _ _),
finset_mem_Ico := λ a b x, mem_Ioc.trans (and_comm _ _),
finset_mem_Ioc := λ a b x, mem_Ico.trans (and_comm _ _),
finset_mem_Ioo := λ a b x, mem_Ioo.trans (and_comm _ _) }
lemma Icc_to_dual : Icc (to_dual a) (to_dual b) = (Icc b a).map to_dual.to_embedding :=
by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Icc, mem_Icc], exact and_comm _ _ }
lemma Ico_to_dual : Ico (to_dual a) (to_dual b) = (Ioc b a).map to_dual.to_embedding :=
by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Ico, mem_Ioc], exact and_comm _ _ }
lemma Ioc_to_dual : Ioc (to_dual a) (to_dual b) = (Ico b a).map to_dual.to_embedding :=
by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Ioc, mem_Ico], exact and_comm _ _ }
lemma Ioo_to_dual : Ioo (to_dual a) (to_dual b) = (Ioo b a).map to_dual.to_embedding :=
by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Ioo, mem_Ioo], exact and_comm _ _ }
lemma Icc_of_dual (a b : αᵒᵈ) : Icc (of_dual a) (of_dual b) = (Icc b a).map of_dual.to_embedding :=
by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Icc, mem_Icc], exact and_comm _ _ }
lemma Ico_of_dual (a b : αᵒᵈ) : Ico (of_dual a) (of_dual b) = (Ioc b a).map of_dual.to_embedding :=
by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Ico, mem_Ioc], exact and_comm _ _ }
lemma Ioc_of_dual (a b : αᵒᵈ) : Ioc (of_dual a) (of_dual b) = (Ico b a).map of_dual.to_embedding :=
by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Ioc, mem_Ico], exact and_comm _ _ }
lemma Ioo_of_dual (a b : αᵒᵈ) : Ioo (of_dual a) (of_dual b) = (Ioo b a).map of_dual.to_embedding :=
by { refine eq.trans _ map_refl.symm, ext c, rw [mem_Ioo, mem_Ioo], exact and_comm _ _ }
end locally_finite_order
section locally_finite_order_top
variables [locally_finite_order_top α]
/-- Note we define `Iic (to_dual a)` as `Ici a` (which has type `finset α` not `finset αᵒᵈ`!)
instead of `(Ici a).map to_dual.to_embedding` as this means the following is defeq:
```
lemma this : (Iic (to_dual (to_dual a)) : _) = (Iic a : _) := rfl
```
-/
instance : locally_finite_order_bot αᵒᵈ :=
{ finset_Iic := λ a, @Ici α _ _ (of_dual a),
finset_Iio := λ a, @Ioi α _ _ (of_dual a),
finset_mem_Iic := λ a x, mem_Ici,
finset_mem_Iio := λ a x, mem_Ioi }
lemma Iic_to_dual (a : α) : Iic (to_dual a) = (Ici a).map to_dual.to_embedding := map_refl.symm
lemma Iio_to_dual (a : α) : Iio (to_dual a) = (Ioi a).map to_dual.to_embedding := map_refl.symm
lemma Ici_of_dual (a : αᵒᵈ) : Ici (of_dual a) = (Iic a).map of_dual.to_embedding := map_refl.symm
lemma Ioi_of_dual (a : αᵒᵈ) : Ioi (of_dual a) = (Iio a).map of_dual.to_embedding := map_refl.symm
end locally_finite_order_top
section locally_finite_order_top
variables [locally_finite_order_bot α]
/-- Note we define `Ici (to_dual a)` as `Iic a` (which has type `finset α` not `finset αᵒᵈ`!)
instead of `(Iic a).map to_dual.to_embedding` as this means the following is defeq:
```
lemma this : (Ici (to_dual (to_dual a)) : _) = (Ici a : _) := rfl
```
-/
instance : locally_finite_order_top αᵒᵈ :=
{ finset_Ici := λ a, @Iic α _ _ (of_dual a),
finset_Ioi := λ a, @Iio α _ _ (of_dual a),
finset_mem_Ici := λ a x, mem_Iic,
finset_mem_Ioi := λ a x, mem_Iio }
lemma Ici_to_dual (a : α) : Ici (to_dual a) = (Iic a).map to_dual.to_embedding := map_refl.symm
lemma Ioi_to_dual (a : α) : Ioi (to_dual a) = (Iio a).map to_dual.to_embedding := map_refl.symm
lemma Iic_of_dual (a : αᵒᵈ) : Iic (of_dual a) = (Ici a).map of_dual.to_embedding := map_refl.symm
lemma Iio_of_dual (a : αᵒᵈ) : Iio (of_dual a) = (Ioi a).map of_dual.to_embedding := map_refl.symm
end locally_finite_order_top
namespace prod
instance [locally_finite_order α] [locally_finite_order β]
[decidable_rel ((≤) : α × β → α × β → Prop)] :
locally_finite_order (α × β) :=
locally_finite_order.of_Icc' (α × β)
(λ a b, Icc a.fst b.fst ×ˢ Icc a.snd b.snd)
(λ a b x, by { rw [mem_product, mem_Icc, mem_Icc, and_and_and_comm], refl })
instance [locally_finite_order_top α] [locally_finite_order_top β]
[decidable_rel ((≤) : α × β → α × β → Prop)] :
locally_finite_order_top (α × β) :=
locally_finite_order_top.of_Ici' (α × β)
(λ a, Ici a.fst ×ˢ Ici a.snd) (λ a x, by { rw [mem_product, mem_Ici, mem_Ici], refl })
instance [locally_finite_order_bot α] [locally_finite_order_bot β]
[decidable_rel ((≤) : α × β → α × β → Prop)] :
locally_finite_order_bot (α × β) :=
locally_finite_order_bot.of_Iic' (α × β)
(λ a, Iic a.fst ×ˢ Iic a.snd) (λ a x, by { rw [mem_product, mem_Iic, mem_Iic], refl })
lemma Icc_eq [locally_finite_order α] [locally_finite_order β]
[decidable_rel ((≤) : α × β → α × β → Prop)] (p q : α × β) :
finset.Icc p q = finset.Icc p.1 q.1 ×ˢ finset.Icc p.2 q.2 := rfl
@[simp] lemma Icc_mk_mk [locally_finite_order α] [locally_finite_order β]
[decidable_rel ((≤) : α × β → α × β → Prop)] (a₁ a₂ : α) (b₁ b₂ : β) :
finset.Icc (a₁, b₁) (a₂, b₂) = finset.Icc a₁ a₂ ×ˢ finset.Icc b₁ b₂ := rfl
lemma card_Icc [locally_finite_order α] [locally_finite_order β]
[decidable_rel ((≤) : α × β → α × β → Prop)] (p q : α × β) :
(finset.Icc p q).card = (finset.Icc p.1 q.1).card * (finset.Icc p.2 q.2).card :=
finset.card_product _ _
end prod
end preorder
namespace prod
variables [lattice α] [lattice β]
lemma uIcc_eq [locally_finite_order α] [locally_finite_order β]
[decidable_rel ((≤) : α × β → α × β → Prop)] (p q : α × β) :
finset.uIcc p q = finset.uIcc p.1 q.1 ×ˢ finset.uIcc p.2 q.2 := rfl
@[simp] lemma uIcc_mk_mk [locally_finite_order α] [locally_finite_order β]
[decidable_rel ((≤) : α × β → α × β → Prop)] (a₁ a₂ : α) (b₁ b₂ : β) :
finset.uIcc (a₁, b₁) (a₂, b₂) = finset.uIcc a₁ a₂ ×ˢ finset.uIcc b₁ b₂ := rfl
lemma card_uIcc [locally_finite_order α] [locally_finite_order β]
[decidable_rel ((≤) : α × β → α × β → Prop)] (p q : α × β) :
(finset.uIcc p q).card = (finset.uIcc p.1 q.1).card * (finset.uIcc p.2 q.2).card :=
prod.card_Icc _ _
end prod
/-!
#### `with_top`, `with_bot`
Adding a `⊤` to a locally finite `order_top` keeps it locally finite.
Adding a `⊥` to a locally finite `order_bot` keeps it locally finite.
-/
namespace with_top
variables (α) [partial_order α] [order_top α] [locally_finite_order α]
local attribute [pattern] coe
local attribute [simp] option.mem_iff
instance : locally_finite_order (with_top α) :=
{ finset_Icc := λ a b, match a, b with
| ⊤, ⊤ := {⊤}
| ⊤, (b : α) := ∅
| (a : α), ⊤ := insert_none (Ici a)
| (a : α), (b : α) := (Icc a b).map embedding.coe_option
end,
finset_Ico := λ a b, match a, b with
| ⊤, _ := ∅
| (a : α), ⊤ := (Ici a).map embedding.coe_option
| (a : α), (b : α) := (Ico a b).map embedding.coe_option
end,
finset_Ioc := λ a b, match a, b with
| ⊤, _ := ∅
| (a : α), ⊤ := insert_none (Ioi a)
| (a : α), (b : α) := (Ioc a b).map embedding.coe_option
end,
finset_Ioo := λ a b, match a, b with
| ⊤, _ := ∅
| (a : α), ⊤ := (Ioi a).map embedding.coe_option
| (a : α), (b : α) := (Ioo a b).map embedding.coe_option
end,
finset_mem_Icc := λ a b x, match a, b, x with
| ⊤, ⊤, x := mem_singleton.trans (le_antisymm_iff.trans $ and_comm _ _)
| ⊤, (b : α), x := iff_of_false (not_mem_empty _)
(λ h, (h.1.trans h.2).not_lt $ coe_lt_top _)
| (a : α), ⊤, ⊤ := by simp [with_top.locally_finite_order._match_1]
| (a : α), ⊤, (x : α) := by simp [with_top.locally_finite_order._match_1, coe_eq_coe]
| (a : α), (b : α), ⊤ := by simp [with_top.locally_finite_order._match_1]
| (a : α), (b : α), (x : α) := by simp [with_top.locally_finite_order._match_1, coe_eq_coe]
end,
finset_mem_Ico := λ a b x, match a, b, x with
| ⊤, b, x := iff_of_false (not_mem_empty _)
(λ h, not_top_lt $ h.1.trans_lt h.2)
| (a : α), ⊤, ⊤ := by simp [with_top.locally_finite_order._match_2]
| (a : α), ⊤, (x : α) := by simp [with_top.locally_finite_order._match_2, coe_eq_coe,
coe_lt_top]
| (a : α), (b : α), ⊤ := by simp [with_top.locally_finite_order._match_2]
| (a : α), (b : α), (x : α) := by simp [with_top.locally_finite_order._match_2, coe_eq_coe,
coe_lt_coe]
end,
finset_mem_Ioc := λ a b x, match a, b, x with
| ⊤, b, x := iff_of_false (not_mem_empty _)
(λ h, not_top_lt $ h.1.trans_le h.2)
| (a : α), ⊤, ⊤ := by simp [with_top.locally_finite_order._match_3, coe_lt_top]
| (a : α), ⊤, (x : α) := by simp [with_top.locally_finite_order._match_3, coe_eq_coe,
coe_lt_coe]
| (a : α), (b : α), ⊤ := by simp [with_top.locally_finite_order._match_3]
| (a : α), (b : α), (x : α) := by simp [with_top.locally_finite_order._match_3, coe_eq_coe,
coe_lt_coe]
end,
finset_mem_Ioo := λ a b x, match a, b, x with
| ⊤, b, x := iff_of_false (not_mem_empty _)
(λ h, not_top_lt $ h.1.trans h.2)
| (a : α), ⊤, ⊤ := by simp [with_top.locally_finite_order._match_4, coe_lt_top]
| (a : α), ⊤, (x : α) := by simp [with_top.locally_finite_order._match_4, coe_eq_coe,
coe_lt_coe, coe_lt_top]
| (a : α), (b : α), ⊤ := by simp [with_top.locally_finite_order._match_4]
| (a : α), (b : α), (x : α) := by simp [with_top.locally_finite_order._match_4, coe_eq_coe,
coe_lt_coe]
end }
variables (a b : α)
lemma Icc_coe_top : Icc (a : with_top α) ⊤ = insert_none (Ici a) := rfl
lemma Icc_coe_coe : Icc (a : with_top α) b = (Icc a b).map embedding.coe_option := rfl
lemma Ico_coe_top : Ico (a : with_top α) ⊤ = (Ici a).map embedding.coe_option := rfl
lemma Ico_coe_coe : Ico (a : with_top α) b = (Ico a b).map embedding.coe_option := rfl
lemma Ioc_coe_top : Ioc (a : with_top α) ⊤ = insert_none (Ioi a) := rfl
lemma Ioc_coe_coe : Ioc (a : with_top α) b = (Ioc a b).map embedding.coe_option := rfl
lemma Ioo_coe_top : Ioo (a : with_top α) ⊤ = (Ioi a).map embedding.coe_option := rfl
lemma Ioo_coe_coe : Ioo (a : with_top α) b = (Ioo a b).map embedding.coe_option := rfl
end with_top
namespace with_bot
variables (α) [partial_order α] [order_bot α] [locally_finite_order α]
instance : locally_finite_order (with_bot α) :=
@order_dual.locally_finite_order (with_top αᵒᵈ) _ _
variables (a b : α)
lemma Icc_bot_coe : Icc (⊥ : with_bot α) b = insert_none (Iic b) := rfl
lemma Icc_coe_coe : Icc (a : with_bot α) b = (Icc a b).map embedding.coe_option := rfl
lemma Ico_bot_coe : Ico (⊥ : with_bot α) b = insert_none (Iio b) := rfl
lemma Ico_coe_coe : Ico (a : with_bot α) b = (Ico a b).map embedding.coe_option := rfl
lemma Ioc_bot_coe : Ioc (⊥ : with_bot α) b = (Iic b).map embedding.coe_option := rfl
lemma Ioc_coe_coe : Ioc (a : with_bot α) b = (Ioc a b).map embedding.coe_option := rfl
lemma Ioo_bot_coe : Ioo (⊥ : with_bot α) b = (Iio b).map embedding.coe_option := rfl
lemma Ioo_coe_coe : Ioo (a : with_bot α) b = (Ioo a b).map embedding.coe_option := rfl
end with_bot
namespace order_iso
variables [preorder α] [preorder β]
/-! #### Transfer locally finite orders across order isomorphisms -/
/-- Transfer `locally_finite_order` across an `order_iso`. -/
@[reducible] -- See note [reducible non-instances]
def locally_finite_order [locally_finite_order β] (f : α ≃o β) : locally_finite_order α :=
{ finset_Icc := λ a b, (Icc (f a) (f b)).map f.symm.to_equiv.to_embedding,
finset_Ico := λ a b, (Ico (f a) (f b)).map f.symm.to_equiv.to_embedding,
finset_Ioc := λ a b, (Ioc (f a) (f b)).map f.symm.to_equiv.to_embedding,
finset_Ioo := λ a b, (Ioo (f a) (f b)).map f.symm.to_equiv.to_embedding,
finset_mem_Icc := by simp,
finset_mem_Ico := by simp,
finset_mem_Ioc := by simp,
finset_mem_Ioo := by simp }
/-- Transfer `locally_finite_order_top` across an `order_iso`. -/
@[reducible] -- See note [reducible non-instances]
def locally_finite_order_top [locally_finite_order_top β]
(f : α ≃o β) : locally_finite_order_top α :=
{ finset_Ici := λ a, (Ici (f a)).map f.symm.to_equiv.to_embedding,
finset_Ioi := λ a, (Ioi (f a)).map f.symm.to_equiv.to_embedding,
finset_mem_Ici := by simp,
finset_mem_Ioi := by simp }
/-- Transfer `locally_finite_order_bot` across an `order_iso`. -/
@[reducible] -- See note [reducible non-instances]
def locally_finite_order_bot [locally_finite_order_bot β]
(f : α ≃o β) : locally_finite_order_bot α :=
{ finset_Iic := λ a, (Iic (f a)).map f.symm.to_equiv.to_embedding,
finset_Iio := λ a, (Iio (f a)).map f.symm.to_equiv.to_embedding,
finset_mem_Iic := by simp,
finset_mem_Iio := by simp }
end order_iso
/-! #### Subtype of a locally finite order -/
variables [preorder α] (p : α → Prop) [decidable_pred p]
instance [locally_finite_order α] : locally_finite_order (subtype p) :=
{ finset_Icc := λ a b, (Icc (a : α) b).subtype p,
finset_Ico := λ a b, (Ico (a : α) b).subtype p,
finset_Ioc := λ a b, (Ioc (a : α) b).subtype p,
finset_Ioo := λ a b, (Ioo (a : α) b).subtype p,
finset_mem_Icc := λ a b x, by simp_rw [finset.mem_subtype, mem_Icc, subtype.coe_le_coe],
finset_mem_Ico := λ a b x, by simp_rw [finset.mem_subtype, mem_Ico, subtype.coe_le_coe,
subtype.coe_lt_coe],
finset_mem_Ioc := λ a b x, by simp_rw [finset.mem_subtype, mem_Ioc, subtype.coe_le_coe,
subtype.coe_lt_coe],
finset_mem_Ioo := λ a b x, by simp_rw [finset.mem_subtype, mem_Ioo, subtype.coe_lt_coe] }
instance [locally_finite_order_top α] : locally_finite_order_top (subtype p) :=
{ finset_Ici := λ a, (Ici (a : α)).subtype p,
finset_Ioi := λ a, (Ioi (a : α)).subtype p,
finset_mem_Ici := λ a x, by simp_rw [finset.mem_subtype, mem_Ici, subtype.coe_le_coe],
finset_mem_Ioi := λ a x, by simp_rw [finset.mem_subtype, mem_Ioi, subtype.coe_lt_coe] }
instance [locally_finite_order_bot α] : locally_finite_order_bot (subtype p) :=
{ finset_Iic := λ a, (Iic (a : α)).subtype p,
finset_Iio := λ a, (Iio (a : α)).subtype p,
finset_mem_Iic := λ a x, by simp_rw [finset.mem_subtype, mem_Iic, subtype.coe_le_coe],
finset_mem_Iio := λ a x, by simp_rw [finset.mem_subtype, mem_Iio, subtype.coe_lt_coe] }
namespace finset
section locally_finite_order
variables [locally_finite_order α] (a b : subtype p)
lemma subtype_Icc_eq : Icc a b = (Icc (a : α) b).subtype p := rfl
lemma subtype_Ico_eq : Ico a b = (Ico (a : α) b).subtype p := rfl
lemma subtype_Ioc_eq : Ioc a b = (Ioc (a : α) b).subtype p := rfl
lemma subtype_Ioo_eq : Ioo a b = (Ioo (a : α) b).subtype p := rfl
variables (hp : ∀ ⦃a b x⦄, a ≤ x → x ≤ b → p a → p b → p x)
include hp
lemma map_subtype_embedding_Icc : (Icc a b).map (embedding.subtype p) = Icc a b :=
begin
rw subtype_Icc_eq,
refine finset.subtype_map_of_mem (λ x hx, _),
rw mem_Icc at hx,
exact hp hx.1 hx.2 a.prop b.prop,
end
lemma map_subtype_embedding_Ico : (Ico a b).map (embedding.subtype p) = Ico a b :=
begin
rw subtype_Ico_eq,
refine finset.subtype_map_of_mem (λ x hx, _),
rw mem_Ico at hx,
exact hp hx.1 hx.2.le a.prop b.prop,
end
lemma map_subtype_embedding_Ioc : (Ioc a b).map (embedding.subtype p) = Ioc a b :=
begin
rw subtype_Ioc_eq,
refine finset.subtype_map_of_mem (λ x hx, _),
rw mem_Ioc at hx,
exact hp hx.1.le hx.2 a.prop b.prop,
end
lemma map_subtype_embedding_Ioo : (Ioo a b).map (embedding.subtype p) = Ioo a b :=
begin
rw subtype_Ioo_eq,
refine finset.subtype_map_of_mem (λ x hx, _),
rw mem_Ioo at hx,
exact hp hx.1.le hx.2.le a.prop b.prop,
end
end locally_finite_order
section locally_finite_order_top
variables [locally_finite_order_top α] (a : subtype p)
lemma subtype_Ici_eq : Ici a = (Ici (a : α)).subtype p := rfl
lemma subtype_Ioi_eq : Ioi a = (Ioi (a : α)).subtype p := rfl
variables (hp : ∀ ⦃a x⦄, a ≤ x → p a → p x)
include hp
lemma map_subtype_embedding_Ici : (Ici a).map (embedding.subtype p) = Ici a :=
by { rw subtype_Ici_eq, exact finset.subtype_map_of_mem (λ x hx, hp (mem_Ici.1 hx) a.prop) }
lemma map_subtype_embedding_Ioi : (Ioi a).map (embedding.subtype p) = Ioi a :=
by { rw subtype_Ioi_eq, exact finset.subtype_map_of_mem (λ x hx, hp (mem_Ioi.1 hx).le a.prop) }
end locally_finite_order_top
section locally_finite_order_bot
variables [locally_finite_order_bot α] (a : subtype p)
lemma subtype_Iic_eq : Iic a = (Iic (a : α)).subtype p := rfl
lemma subtype_Iio_eq : Iio a = (Iio (a : α)).subtype p := rfl
variables (hp : ∀ ⦃a x⦄, x ≤ a → p a → p x)
include hp
lemma map_subtype_embedding_Iic : (Iic a).map (embedding.subtype p) = Iic a :=
by { rw subtype_Iic_eq, exact finset.subtype_map_of_mem (λ x hx, hp (mem_Iic.1 hx) a.prop) }
lemma map_subtype_embedding_Iio : (Iio a).map (embedding.subtype p) = Iio a :=
by { rw subtype_Iio_eq, exact finset.subtype_map_of_mem (λ x hx, hp (mem_Iio.1 hx).le a.prop) }
end locally_finite_order_bot
end finset
|
4a055d36883881fdf645a6918753e30ffab09577 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/measure_theory/function/special_functions/basic.lean | b2d848d277d4e1930b2d9b9c8bd2194a6757e06d | [
"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 | 8,253 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.special_functions.pow
import measure_theory.constructions.borel_space
/-!
# Measurability of real and complex functions
We show that most standard real and complex functions are measurable, notably `exp`, `cos`, `sin`,
`cosh`, `sinh`, `log`, `pow`, `arcsin`, `arccos`.
See also `measure_theory.function.special_functions.arctan` and
`measure_theory.function.special_functions.inner`, which have been split off to minimize imports.
-/
noncomputable theory
open_locale nnreal ennreal
namespace real
@[measurability] lemma measurable_exp : measurable exp := continuous_exp.measurable
@[measurability] lemma measurable_log : measurable log :=
measurable_of_measurable_on_compl_singleton 0 $ continuous.measurable $
continuous_on_iff_continuous_restrict.1 continuous_on_log
@[measurability] lemma measurable_sin : measurable sin := continuous_sin.measurable
@[measurability] lemma measurable_cos : measurable cos := continuous_cos.measurable
@[measurability] lemma measurable_sinh : measurable sinh := continuous_sinh.measurable
@[measurability] lemma measurable_cosh : measurable cosh := continuous_cosh.measurable
@[measurability] lemma measurable_arcsin : measurable arcsin := continuous_arcsin.measurable
@[measurability] lemma measurable_arccos : measurable arccos := continuous_arccos.measurable
end real
namespace complex
@[measurability] lemma measurable_re : measurable re := continuous_re.measurable
@[measurability] lemma measurable_im : measurable im := continuous_im.measurable
@[measurability] lemma measurable_of_real : measurable (coe : ℝ → ℂ) :=
continuous_of_real.measurable
@[measurability] lemma measurable_exp : measurable exp := continuous_exp.measurable
@[measurability] lemma measurable_sin : measurable sin := continuous_sin.measurable
@[measurability] lemma measurable_cos : measurable cos := continuous_cos.measurable
@[measurability] lemma measurable_sinh : measurable sinh := continuous_sinh.measurable
@[measurability] lemma measurable_cosh : measurable cosh := continuous_cosh.measurable
@[measurability] lemma measurable_arg : measurable arg :=
have A : measurable (λ x : ℂ, real.arcsin (x.im / x.abs)),
from real.measurable_arcsin.comp (measurable_im.div measurable_norm),
have B : measurable (λ x : ℂ, real.arcsin ((-x).im / x.abs)),
from real.measurable_arcsin.comp ((measurable_im.comp measurable_neg).div measurable_norm),
measurable.ite (is_closed_le continuous_const continuous_re).measurable_set A $
measurable.ite (is_closed_le continuous_const continuous_im).measurable_set
(B.add_const _) (B.sub_const _)
@[measurability] lemma measurable_log : measurable log :=
(measurable_of_real.comp $ real.measurable_log.comp measurable_norm).add $
(measurable_of_real.comp measurable_arg).mul_const I
end complex
namespace is_R_or_C
variables {𝕜 : Type*} [is_R_or_C 𝕜]
@[measurability] lemma measurable_re : measurable (re : 𝕜 → ℝ) := continuous_re.measurable
@[measurability] lemma measurable_im : measurable (im : 𝕜 → ℝ) := continuous_im.measurable
end is_R_or_C
section real_composition
open real
variables {α : Type*} {m : measurable_space α} {f : α → ℝ} (hf : measurable f)
@[measurability] lemma measurable.exp : measurable (λ x, real.exp (f x)) :=
real.measurable_exp.comp hf
@[measurability] lemma measurable.log : measurable (λ x, log (f x)) :=
measurable_log.comp hf
@[measurability] lemma measurable.cos : measurable (λ x, real.cos (f x)) :=
real.measurable_cos.comp hf
@[measurability] lemma measurable.sin : measurable (λ x, real.sin (f x)) :=
real.measurable_sin.comp hf
@[measurability] lemma measurable.cosh : measurable (λ x, real.cosh (f x)) :=
real.measurable_cosh.comp hf
@[measurability] lemma measurable.sinh : measurable (λ x, real.sinh (f x)) :=
real.measurable_sinh.comp hf
@[measurability] lemma measurable.sqrt : measurable (λ x, sqrt (f x)) :=
continuous_sqrt.measurable.comp hf
end real_composition
section complex_composition
open complex
variables {α : Type*} {m : measurable_space α} {f : α → ℂ} (hf : measurable f)
@[measurability] lemma measurable.cexp : measurable (λ x, complex.exp (f x)) :=
complex.measurable_exp.comp hf
@[measurability] lemma measurable.ccos : measurable (λ x, complex.cos (f x)) :=
complex.measurable_cos.comp hf
@[measurability] lemma measurable.csin : measurable (λ x, complex.sin (f x)) :=
complex.measurable_sin.comp hf
@[measurability] lemma measurable.ccosh : measurable (λ x, complex.cosh (f x)) :=
complex.measurable_cosh.comp hf
@[measurability] lemma measurable.csinh : measurable (λ x, complex.sinh (f x)) :=
complex.measurable_sinh.comp hf
@[measurability] lemma measurable.carg : measurable (λ x, arg (f x)) :=
measurable_arg.comp hf
@[measurability] lemma measurable.clog : measurable (λ x, log (f x)) :=
measurable_log.comp hf
end complex_composition
section is_R_or_C_composition
variables {α 𝕜 : Type*} [is_R_or_C 𝕜] {m : measurable_space α}
{f : α → 𝕜} {μ : measure_theory.measure α}
include m
@[measurability] lemma measurable.re (hf : measurable f) : measurable (λ x, is_R_or_C.re (f x)) :=
is_R_or_C.measurable_re.comp hf
@[measurability] lemma ae_measurable.re (hf : ae_measurable f μ) :
ae_measurable (λ x, is_R_or_C.re (f x)) μ :=
is_R_or_C.measurable_re.comp_ae_measurable hf
@[measurability] lemma measurable.im (hf : measurable f) : measurable (λ x, is_R_or_C.im (f x)) :=
is_R_or_C.measurable_im.comp hf
@[measurability] lemma ae_measurable.im (hf : ae_measurable f μ) :
ae_measurable (λ x, is_R_or_C.im (f x)) μ :=
is_R_or_C.measurable_im.comp_ae_measurable hf
omit m
end is_R_or_C_composition
section
variables {α 𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space α]
{f : α → 𝕜} {μ : measure_theory.measure α}
@[measurability] lemma is_R_or_C.measurable_of_real : measurable (coe : ℝ → 𝕜) :=
is_R_or_C.continuous_of_real.measurable
lemma measurable_of_re_im
(hre : measurable (λ x, is_R_or_C.re (f x)))
(him : measurable (λ x, is_R_or_C.im (f x))) : measurable f :=
begin
convert (is_R_or_C.measurable_of_real.comp hre).add
((is_R_or_C.measurable_of_real.comp him).mul_const is_R_or_C.I),
{ ext1 x,
exact (is_R_or_C.re_add_im _).symm },
all_goals { apply_instance },
end
lemma ae_measurable_of_re_im
(hre : ae_measurable (λ x, is_R_or_C.re (f x)) μ)
(him : ae_measurable (λ x, is_R_or_C.im (f x)) μ) : ae_measurable f μ :=
begin
convert (is_R_or_C.measurable_of_real.comp_ae_measurable hre).add
((is_R_or_C.measurable_of_real.comp_ae_measurable him).mul_const is_R_or_C.I),
{ ext1 x,
exact (is_R_or_C.re_add_im _).symm },
all_goals { apply_instance },
end
end
section pow_instances
instance complex.has_measurable_pow : has_measurable_pow ℂ ℂ :=
⟨measurable.ite (measurable_fst (measurable_set_singleton 0))
(measurable.ite (measurable_snd (measurable_set_singleton 0)) measurable_one measurable_zero)
(measurable_fst.clog.mul measurable_snd).cexp⟩
instance real.has_measurable_pow : has_measurable_pow ℝ ℝ :=
⟨complex.measurable_re.comp $ ((complex.measurable_of_real.comp measurable_fst).pow
(complex.measurable_of_real.comp measurable_snd))⟩
instance nnreal.has_measurable_pow : has_measurable_pow ℝ≥0 ℝ :=
⟨(measurable_fst.coe_nnreal_real.pow measurable_snd).subtype_mk⟩
instance ennreal.has_measurable_pow : has_measurable_pow ℝ≥0∞ ℝ :=
begin
refine ⟨ennreal.measurable_of_measurable_nnreal_prod _ _⟩,
{ simp_rw ennreal.coe_rpow_def,
refine measurable.ite _ measurable_const
(measurable_fst.pow measurable_snd).coe_nnreal_ennreal,
exact measurable_set.inter (measurable_fst (measurable_set_singleton 0))
(measurable_snd measurable_set_Iio), },
{ simp_rw ennreal.top_rpow_def,
refine measurable.ite measurable_set_Ioi measurable_const _,
exact measurable.ite (measurable_set_singleton 0) measurable_const measurable_const, },
end
end pow_instances
-- Guard against import creep:
assert_not_exists inner_product_space
assert_not_exists real.arctan
|
3ecf7078058f64b8f7b9068d70ec4fbb1065b5c3 | 1a61aba1b67cddccce19532a9596efe44be4285f | /hott/types/eq.hlean | 9b3738250175431e9df45169d6456ed1ea513749 | [
"Apache-2.0"
] | permissive | eigengrau/lean | 07986a0f2548688c13ba36231f6cdbee82abf4c6 | f8a773be1112015e2d232661ce616d23f12874d0 | refs/heads/master | 1,610,939,198,566 | 1,441,352,386,000 | 1,441,352,494,000 | 41,903,576 | 0 | 0 | null | 1,441,352,210,000 | 1,441,352,210,000 | null | UTF-8 | Lean | false | false | 21,413 | hlean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Partially ported from Coq HoTT
Theorems about path types (identity types)
-/
import types.sigma
open eq sigma sigma.ops equiv is_equiv equiv.ops is_trunc
-- TODO: Rename transport_eq_... and pathover_eq_... to eq_transport_... and eq_pathover_...
namespace eq
/- Path spaces -/
section
variables {A B : Type} {a a₁ a₂ a₃ a₄ a' : A} {b b1 b2 : B} {f g : A → B} {h : B → A}
{p p' p'' : a₁ = a₂}
/- The path spaces of a path space are not, of course, determined; they are just the
higher-dimensional structure of the original space. -/
/- some lemmas about whiskering or other higher paths -/
theorem whisker_left_con_right (p : a₁ = a₂) {q q' q'' : a₂ = a₃} (r : q = q') (s : q' = q'')
: whisker_left p (r ⬝ s) = whisker_left p r ⬝ whisker_left p s :=
begin
induction p, induction r, induction s, reflexivity
end
theorem whisker_right_con_right (q : a₂ = a₃) (r : p = p') (s : p' = p'')
: whisker_right (r ⬝ s) q = whisker_right r q ⬝ whisker_right s q :=
begin
induction q, induction r, induction s, reflexivity
end
theorem whisker_left_con_left (p : a₁ = a₂) (p' : a₂ = a₃) {q q' : a₃ = a₄} (r : q = q')
: whisker_left (p ⬝ p') r = !con.assoc ⬝ whisker_left p (whisker_left p' r) ⬝ !con.assoc' :=
begin
induction p', induction p, induction r, induction q, reflexivity
end
theorem whisker_right_con_left {p p' : a₁ = a₂} (q : a₂ = a₃) (q' : a₃ = a₄) (r : p = p')
: whisker_right r (q ⬝ q') = !con.assoc' ⬝ whisker_right (whisker_right r q) q' ⬝ !con.assoc :=
begin
induction q', induction q, induction r, induction p, reflexivity
end
theorem whisker_left_inv_left (p : a₂ = a₁) {q q' : a₂ = a₃} (r : q = q')
: !con_inv_cancel_left⁻¹ ⬝ whisker_left p (whisker_left p⁻¹ r) ⬝ !con_inv_cancel_left = r :=
begin
induction p, induction r, induction q, reflexivity
end
theorem whisker_left_inv (p : a₁ = a₂) {q q' : a₂ = a₃} (r : q = q')
: whisker_left p r⁻¹ = (whisker_left p r)⁻¹ :=
by induction r; reflexivity
theorem whisker_right_inv {p p' : a₁ = a₂} (q : a₂ = a₃) (r : p = p')
: whisker_right r⁻¹ q = (whisker_right r q)⁻¹ :=
by induction r; reflexivity
theorem ap_eq_ap10 {f g : A → B} (p : f = g) (a : A) : ap (λh, h a) p = ap10 p a :=
by induction p;reflexivity
theorem inverse2_right_inv (r : p = p') : r ◾ inverse2 r ⬝ con.right_inv p' = con.right_inv p :=
by induction r;induction p;reflexivity
theorem inverse2_left_inv (r : p = p') : inverse2 r ◾ r ⬝ con.left_inv p' = con.left_inv p :=
by induction r;induction p;reflexivity
theorem ap_con_right_inv (f : A → B) (p : a₁ = a₂)
: ap_con f p p⁻¹ ⬝ whisker_left _ (ap_inv f p) ⬝ con.right_inv (ap f p)
= ap (ap f) (con.right_inv p) :=
by induction p;reflexivity
theorem ap_con_left_inv (f : A → B) (p : a₁ = a₂)
: ap_con f p⁻¹ p ⬝ whisker_right (ap_inv f p) _ ⬝ con.left_inv (ap f p)
= ap (ap f) (con.left_inv p) :=
by induction p;reflexivity
theorem idp_con_whisker_left {q q' : a₂ = a₃} (r : q = q') :
!idp_con⁻¹ ⬝ whisker_left idp r = r ⬝ !idp_con⁻¹ :=
by induction r;induction q;reflexivity
theorem whisker_left_idp_con {q q' : a₂ = a₃} (r : q = q') :
whisker_left idp r ⬝ !idp_con = !idp_con ⬝ r :=
by induction r;induction q;reflexivity
theorem idp_con_idp {p : a = a} (q : p = idp) : idp_con p ⬝ q = ap (λp, idp ⬝ p) q :=
by cases q;reflexivity
definition ap_weakly_constant [unfold 8] {A B : Type} {f : A → B} {b : B} (p : Πx, f x = b)
{x y : A} (q : x = y) : ap f q = p x ⬝ (p y)⁻¹ :=
by induction q;exact !con.right_inv⁻¹
definition inv2_inv {p q : a = a'} (r : p = q) : inverse2 r⁻¹ = (inverse2 r)⁻¹ :=
by induction r;reflexivity
definition inv2_con {p p' p'' : a = a'} (r : p = p') (r' : p' = p'')
: inverse2 (r ⬝ r') = inverse2 r ⬝ inverse2 r' :=
by induction r';induction r;reflexivity
definition con2_inv {p₁ q₁ : a₁ = a₂} {p₂ q₂ : a₂ = a₃} (r₁ : p₁ = q₁) (r₂ : p₂ = q₂)
: (r₁ ◾ r₂)⁻¹ = r₁⁻¹ ◾ r₂⁻¹ :=
by induction r₁;induction r₂;reflexivity
theorem eq_con_inv_of_con_eq_whisker_left {A : Type} {a a₂ a₃ : A}
{p : a = a₂} {q q' : a₂ = a₃} {r : a = a₃} (s' : q = q') (s : p ⬝ q' = r) :
eq_con_inv_of_con_eq (whisker_left p s' ⬝ s)
= eq_con_inv_of_con_eq s ⬝ whisker_left r (inverse2 s')⁻¹ :=
by induction s';induction q;induction s;reflexivity
theorem right_inv_eq_idp {A : Type} {a : A} {p : a = a} (r : p = idpath a) :
con.right_inv p = r ◾ inverse2 r :=
by cases r;reflexivity
/- Transporting in path spaces.
There are potentially a lot of these lemmas, so we adopt a uniform naming scheme:
- `l` means the left endpoint varies
- `r` means the right endpoint varies
- `F` means application of a function to that (varying) endpoint.
-/
definition transport_eq_l (p : a₁ = a₂) (q : a₁ = a₃)
: transport (λx, x = a₃) p q = p⁻¹ ⬝ q :=
by induction p; induction q; reflexivity
definition transport_eq_r (p : a₂ = a₃) (q : a₁ = a₂)
: transport (λx, a₁ = x) p q = q ⬝ p :=
by induction p; induction q; reflexivity
definition transport_eq_lr (p : a₁ = a₂) (q : a₁ = a₁)
: transport (λx, x = x) p q = p⁻¹ ⬝ q ⬝ p :=
by induction p; rewrite [▸*,idp_con]
definition transport_eq_Fl (p : a₁ = a₂) (q : f a₁ = b)
: transport (λx, f x = b) p q = (ap f p)⁻¹ ⬝ q :=
by induction p; induction q; reflexivity
definition transport_eq_Fr (p : a₁ = a₂) (q : b = f a₁)
: transport (λx, b = f x) p q = q ⬝ (ap f p) :=
by induction p; reflexivity
definition transport_eq_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁)
: transport (λx, f x = g x) p q = (ap f p)⁻¹ ⬝ q ⬝ (ap g p) :=
by induction p; rewrite [▸*,idp_con]
definition transport_eq_FlFr_D {B : A → Type} {f g : Πa, B a}
(p : a₁ = a₂) (q : f a₁ = g a₁)
: transport (λx, f x = g x) p q = (apd f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apd g p) :=
by induction p; rewrite [▸*,idp_con,ap_id]
definition transport_eq_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁)
: transport (λx, h (f x) = x) p q = (ap h (ap f p))⁻¹ ⬝ q ⬝ p :=
by induction p; rewrite [▸*,idp_con]
definition transport_eq_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁))
: transport (λx, x = h (f x)) p q = p⁻¹ ⬝ q ⬝ (ap h (ap f p)) :=
by induction p; rewrite [▸*,idp_con]
/- Pathovers -/
-- In the comment we give the fibration of the pathover
-- we should probably try to do everything just with pathover_eq (defined in cubical.square),
-- the following definitions may be removed in future.
definition pathover_eq_l (p : a₁ = a₂) (q : a₁ = a₃) : q =[p] p⁻¹ ⬝ q := /-(λx, x = a₃)-/
by induction p; induction q; exact idpo
definition pathover_eq_r (p : a₂ = a₃) (q : a₁ = a₂) : q =[p] q ⬝ p := /-(λx, a₁ = x)-/
by induction p; induction q; exact idpo
definition pathover_eq_lr (p : a₁ = a₂) (q : a₁ = a₁) : q =[p] p⁻¹ ⬝ q ⬝ p := /-(λx, x = x)-/
by induction p; rewrite [▸*,idp_con]; exact idpo
definition pathover_eq_Fl (p : a₁ = a₂) (q : f a₁ = b) : q =[p] (ap f p)⁻¹ ⬝ q := /-(λx, f x = b)-/
by induction p; induction q; exact idpo
definition pathover_eq_Fr (p : a₁ = a₂) (q : b = f a₁) : q =[p] q ⬝ (ap f p) := /-(λx, b = f x)-/
by induction p; exact idpo
definition pathover_eq_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) : q =[p] (ap f p)⁻¹ ⬝ q ⬝ (ap g p) :=
/-(λx, f x = g x)-/
by induction p; rewrite [▸*,idp_con]; exact idpo
definition pathover_eq_FlFr_D {B : A → Type} {f g : Πa, B a} (p : a₁ = a₂) (q : f a₁ = g a₁)
: q =[p] (apd f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apd g p) := /-(λx, f x = g x)-/
by induction p; rewrite [▸*,idp_con,ap_id];exact idpo
definition pathover_eq_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) : q =[p] (ap h (ap f p))⁻¹ ⬝ q ⬝ p :=
/-(λx, h (f x) = x)-/
by induction p; rewrite [▸*,idp_con];exact idpo
definition pathover_eq_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) : q =[p] p⁻¹ ⬝ q ⬝ (ap h (ap f p)) :=
/-(λx, x = h (f x))-/
by induction p; rewrite [▸*,idp_con];exact idpo
definition pathover_eq_r_idp (p : a₁ = a₂) : idp =[p] p := /-(λx, a₁ = x)-/
by induction p; exact idpo
definition pathover_eq_l_idp (p : a₁ = a₂) : idp =[p] p⁻¹ := /-(λx, x = a₁)-/
by induction p; exact idpo
definition pathover_eq_l_idp' (p : a₁ = a₂) : idp =[p⁻¹] p := /-(λx, x = a₂)-/
by induction p; exact idpo
-- The Functorial action of paths is [ap].
/- Equivalences between path spaces -/
/- [ap_closed] is in init.equiv -/
definition equiv_ap (f : A → B) [H : is_equiv f] (a₁ a₂ : A)
: (a₁ = a₂) ≃ (f a₁ = f a₂) :=
equiv.mk (ap f) _
/- Path operations are equivalences -/
definition is_equiv_eq_inverse (a₁ a₂ : A) : is_equiv (inverse : a₁ = a₂ → a₂ = a₁) :=
is_equiv.mk inverse inverse inv_inv inv_inv (λp, eq.rec_on p idp)
local attribute is_equiv_eq_inverse [instance]
definition eq_equiv_eq_symm (a₁ a₂ : A) : (a₁ = a₂) ≃ (a₂ = a₁) :=
equiv.mk inverse _
definition is_equiv_concat_left [constructor] [instance] (p : a₁ = a₂) (a₃ : A)
: is_equiv (concat p : a₂ = a₃ → a₁ = a₃) :=
is_equiv.mk (concat p) (concat p⁻¹)
(con_inv_cancel_left p)
(inv_con_cancel_left p)
(λq, by induction p;induction q;reflexivity)
local attribute is_equiv_concat_left [instance]
definition equiv_eq_closed_left [constructor] (a₃ : A) (p : a₁ = a₂) : (a₁ = a₃) ≃ (a₂ = a₃) :=
equiv.mk (concat p⁻¹) _
definition is_equiv_concat_right [constructor] [instance] (p : a₂ = a₃) (a₁ : A)
: is_equiv (λq : a₁ = a₂, q ⬝ p) :=
is_equiv.mk (λq, q ⬝ p) (λq, q ⬝ p⁻¹)
(λq, inv_con_cancel_right q p)
(λq, con_inv_cancel_right q p)
(λq, by induction p;induction q;reflexivity)
local attribute is_equiv_concat_right [instance]
definition equiv_eq_closed_right [constructor] (a₁ : A) (p : a₂ = a₃) : (a₁ = a₂) ≃ (a₁ = a₃) :=
equiv.mk (λq, q ⬝ p) _
definition eq_equiv_eq_closed [constructor] (p : a₁ = a₂) (q : a₃ = a₄) : (a₁ = a₃) ≃ (a₂ = a₄) :=
equiv.trans (equiv_eq_closed_left a₃ p) (equiv_eq_closed_right a₂ q)
definition is_equiv_whisker_left [constructor] (p : a₁ = a₂) (q r : a₂ = a₃)
: is_equiv (whisker_left p : q = r → p ⬝ q = p ⬝ r) :=
begin
fapply adjointify,
{intro s, apply (!cancel_left s)},
{intro s,
apply concat, {apply whisker_left_con_right},
apply concat, rotate_left 1, apply (whisker_left_inv_left p s),
apply concat2,
{apply concat, {apply whisker_left_con_right},
apply concat2,
{induction p, induction q, reflexivity},
{reflexivity}},
{induction p, induction r, reflexivity}},
{intro s, induction s, induction q, induction p, reflexivity}
end
definition eq_equiv_con_eq_con_left [constructor] (p : a₁ = a₂) (q r : a₂ = a₃)
: (q = r) ≃ (p ⬝ q = p ⬝ r) :=
equiv.mk _ !is_equiv_whisker_left
definition is_equiv_whisker_right [constructor] {p q : a₁ = a₂} (r : a₂ = a₃)
: is_equiv (λs, whisker_right s r : p = q → p ⬝ r = q ⬝ r) :=
begin
fapply adjointify,
{intro s, apply (!cancel_right s)},
{intro s, induction r, cases s, induction q, reflexivity},
{intro s, induction s, induction r, induction p, reflexivity}
end
definition eq_equiv_con_eq_con_right [constructor] (p q : a₁ = a₂) (r : a₂ = a₃)
: (p = q) ≃ (p ⬝ r = q ⬝ r) :=
equiv.mk _ !is_equiv_whisker_right
/-
The following proofs can be simplified a bit by concatenating previous equivalences.
However, these proofs have the advantage that the inverse is definitionally equal to
what we would expect
-/
definition is_equiv_con_eq_of_eq_inv_con [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (con_eq_of_eq_inv_con : p = r⁻¹ ⬝ q → r ⬝ p = q) :=
begin
fapply adjointify,
{ apply eq_inv_con_of_con_eq},
{ intro s, induction r, rewrite [↑[con_eq_of_eq_inv_con,eq_inv_con_of_con_eq],
con.assoc,con.assoc,con.left_inv,▸*,-con.assoc,con.right_inv,▸* at *,idp_con s]},
{ intro s, induction r, rewrite [↑[con_eq_of_eq_inv_con,eq_inv_con_of_con_eq],
con.assoc,con.assoc,con.right_inv,▸*,-con.assoc,con.left_inv,▸* at *,idp_con s] },
end
definition eq_inv_con_equiv_con_eq [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: (p = r⁻¹ ⬝ q) ≃ (r ⬝ p = q) :=
equiv.mk _ !is_equiv_con_eq_of_eq_inv_con
definition is_equiv_con_eq_of_eq_con_inv [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (con_eq_of_eq_con_inv : r = q ⬝ p⁻¹ → r ⬝ p = q) :=
begin
fapply adjointify,
{ apply eq_con_inv_of_con_eq},
{ intro s, induction p, rewrite [↑[con_eq_of_eq_con_inv,eq_con_inv_of_con_eq]]},
{ intro s, induction p, rewrite [↑[con_eq_of_eq_con_inv,eq_con_inv_of_con_eq]] },
end
definition eq_con_inv_equiv_con_eq [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: (r = q ⬝ p⁻¹) ≃ (r ⬝ p = q) :=
equiv.mk _ !is_equiv_con_eq_of_eq_con_inv
definition is_equiv_inv_con_eq_of_eq_con [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₁ = a₂)
: is_equiv (inv_con_eq_of_eq_con : p = r ⬝ q → r⁻¹ ⬝ p = q) :=
begin
fapply adjointify,
{ apply eq_con_of_inv_con_eq},
{ intro s, induction r, rewrite [↑[inv_con_eq_of_eq_con,eq_con_of_inv_con_eq],
con.assoc,con.assoc,con.left_inv,▸*,-con.assoc,con.right_inv,▸* at *,idp_con s]},
{ intro s, induction r, rewrite [↑[inv_con_eq_of_eq_con,eq_con_of_inv_con_eq],
con.assoc,con.assoc,con.right_inv,▸*,-con.assoc,con.left_inv,▸* at *,idp_con s] },
end
definition eq_con_equiv_inv_con_eq [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₁ = a₂)
: (p = r ⬝ q) ≃ (r⁻¹ ⬝ p = q) :=
equiv.mk _ !is_equiv_inv_con_eq_of_eq_con
definition is_equiv_con_inv_eq_of_eq_con [constructor] (p : a₃ = a₁) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (con_inv_eq_of_eq_con : r = q ⬝ p → r ⬝ p⁻¹ = q) :=
begin
fapply adjointify,
{ apply eq_con_of_con_inv_eq},
{ intro s, induction p, rewrite [↑[con_inv_eq_of_eq_con,eq_con_of_con_inv_eq]]},
{ intro s, induction p, rewrite [↑[con_inv_eq_of_eq_con,eq_con_of_con_inv_eq]] },
end
definition eq_con_equiv_con_inv_eq (p : a₃ = a₁) (q : a₂ = a₃) (r : a₂ = a₁)
: (r = q ⬝ p) ≃ (r ⬝ p⁻¹ = q) :=
equiv.mk _ !is_equiv_con_inv_eq_of_eq_con
local attribute is_equiv_inv_con_eq_of_eq_con
is_equiv_con_inv_eq_of_eq_con
is_equiv_con_eq_of_eq_con_inv
is_equiv_con_eq_of_eq_inv_con [instance]
definition is_equiv_eq_con_of_inv_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (eq_con_of_inv_con_eq : r⁻¹ ⬝ q = p → q = r ⬝ p) :=
is_equiv_inv inv_con_eq_of_eq_con
definition is_equiv_eq_con_of_con_inv_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (eq_con_of_con_inv_eq : q ⬝ p⁻¹ = r → q = r ⬝ p) :=
is_equiv_inv con_inv_eq_of_eq_con
definition is_equiv_eq_con_inv_of_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (eq_con_inv_of_con_eq : r ⬝ p = q → r = q ⬝ p⁻¹) :=
is_equiv_inv con_eq_of_eq_con_inv
definition is_equiv_eq_inv_con_of_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (eq_inv_con_of_con_eq : r ⬝ p = q → p = r⁻¹ ⬝ q) :=
is_equiv_inv con_eq_of_eq_inv_con
definition is_equiv_con_inv_eq_idp [constructor] (p q : a₁ = a₂)
: is_equiv (con_inv_eq_idp : p = q → p ⬝ q⁻¹ = idp) :=
begin
fapply adjointify,
{ apply eq_of_con_inv_eq_idp},
{ intro s, induction q, esimp at *, cases s, reflexivity},
{ intro s, induction s, induction p, reflexivity},
end
definition is_equiv_inv_con_eq_idp [constructor] (p q : a₁ = a₂)
: is_equiv (inv_con_eq_idp : p = q → q⁻¹ ⬝ p = idp) :=
begin
fapply adjointify,
{ apply eq_of_inv_con_eq_idp},
{ intro s, induction q, esimp [eq_of_inv_con_eq_idp] at *,
eapply is_equiv_rect (eq_equiv_con_eq_con_left idp p idp), clear s,
intro s, cases s, reflexivity},
{ intro s, induction s, induction p, reflexivity},
end
definition eq_equiv_con_inv_eq_idp [constructor] (p q : a₁ = a₂) : (p = q) ≃ (p ⬝ q⁻¹ = idp) :=
equiv.mk _ !is_equiv_con_inv_eq_idp
definition eq_equiv_inv_con_eq_idp [constructor] (p q : a₁ = a₂) : (p = q) ≃ (q⁻¹ ⬝ p = idp) :=
equiv.mk _ !is_equiv_inv_con_eq_idp
/- Pathover Equivalences -/
definition pathover_eq_equiv_l (p : a₁ = a₂) (q : a₁ = a₃) (r : a₂ = a₃) : q =[p] r ≃ q = p ⬝ r :=
/-(λx, x = a₃)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_r (p : a₂ = a₃) (q : a₁ = a₂) (r : a₁ = a₃) : q =[p] r ≃ q ⬝ p = r :=
/-(λx, a₁ = x)-/
by induction p; apply pathover_idp
definition pathover_eq_equiv_lr (p : a₁ = a₂) (q : a₁ = a₁) (r : a₂ = a₂)
: q =[p] r ≃ q ⬝ p = p ⬝ r := /-(λx, x = x)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_Fl (p : a₁ = a₂) (q : f a₁ = b) (r : f a₂ = b)
: q =[p] r ≃ q = ap f p ⬝ r := /-(λx, f x = b)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_Fr (p : a₁ = a₂) (q : b = f a₁) (r : b = f a₂)
: q =[p] r ≃ q ⬝ ap f p = r := /-(λx, b = f x)-/
by induction p; apply pathover_idp
definition pathover_eq_equiv_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) (r : f a₂ = g a₂)
: q =[p] r ≃ q ⬝ ap g p = ap f p ⬝ r := /-(λx, f x = g x)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) (r : h (f a₂) = a₂)
: q =[p] r ≃ q ⬝ p = ap h (ap f p) ⬝ r :=
/-(λx, h (f x) = x)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) (r : a₂ = h (f a₂))
: q =[p] r ≃ q ⬝ ap h (ap f p) = p ⬝ r :=
/-(λx, x = h (f x))-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
-- a lot of this library still needs to be ported from Coq HoTT
-- encode decode method
open is_trunc
definition encode_decode_method' (a₀ a : A) (code : A → Type) (c₀ : code a₀)
(decode : Π(a : A) (c : code a), a₀ = a)
(encode_decode : Π(a : A) (c : code a), c₀ =[decode a c] c)
(decode_encode : decode a₀ c₀ = idp) : (a₀ = a) ≃ code a :=
begin
fapply equiv.MK,
{ intro p, exact p ▸ c₀},
{ apply decode},
{ intro c, apply tr_eq_of_pathover, apply encode_decode},
{ intro p, induction p, apply decode_encode},
end
end
section
parameters {A : Type} (a₀ : A) (code : A → Type) (H : is_contr (Σa, code a))
(p : (center (Σa, code a)).1 = a₀)
include p
definition encode {a : A} (q : a₀ = a) : code a :=
(p ⬝ q) ▸ (center (Σa, code a)).2
definition decode' {a : A} (c : code a) : a₀ = a :=
(is_hprop.elim ⟨a₀, encode idp⟩ ⟨a, c⟩)..1
definition decode {a : A} (c : code a) : a₀ = a :=
(decode' (encode idp))⁻¹ ⬝ decode' c
definition total_space_method (a : A) : (a₀ = a) ≃ code a :=
begin
fapply equiv.MK,
{ exact encode},
{ exact decode},
{ intro c,
unfold [encode, decode, decode'],
induction p, esimp, rewrite [is_hprop_elim_self,▸*,+idp_con], apply tr_eq_of_pathover,
eapply @sigma.rec_on _ _ (λx, x.2 =[(is_hprop.elim ⟨x.1, x.2⟩ ⟨a, c⟩)..1] c)
(center (sigma code)), -- BUG(?): induction fails
intro a c, apply eq_pr2},
{ intro q, induction q, esimp, apply con.left_inv, },
end
end
definition encode_decode_method {A : Type} (a₀ a : A) (code : A → Type) (c₀ : code a₀)
(decode : Π(a : A) (c : code a), a₀ = a)
(encode_decode : Π(a : A) (c : code a), c₀ =[decode a c] c) : (a₀ = a) ≃ code a :=
begin
fapply total_space_method,
{ fapply @is_contr.mk,
{ exact ⟨a₀, c₀⟩},
{ intro p, fapply sigma_eq,
apply decode, exact p.2,
apply encode_decode}},
{ reflexivity}
end
end eq
|
96c25e87a32ece92adb32b734c728f688a0cad0c | e38e95b38a38a99ecfa1255822e78e4b26f65bb0 | /src/certigrad/compute_grad_slow_correct.lean | 9ada92e6df53038e1ef9ca16121fb275c01b5dd5 | [
"Apache-2.0"
] | permissive | ColaDrill/certigrad | fefb1be3670adccd3bed2f3faf57507f156fd501 | fe288251f623ac7152e5ce555f1cd9d3a20203c2 | refs/heads/master | 1,593,297,324,250 | 1,499,903,753,000 | 1,499,903,753,000 | 97,075,797 | 1 | 0 | null | 1,499,916,210,000 | 1,499,916,210,000 | null | UTF-8 | Lean | false | false | 20,450 | lean | /-
Copyright (c) 2017 Daniel Selsam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Daniel Selsam
Proof that the simple, non-memoized version of stochastic backpropagation
is correct.
-/
import .graph .estimators .predicates .compute_grad .lemmas .tgrads .tactics
namespace certigrad
namespace theorems
open list
lemma compute_grad_slow_correct {costs : list ID} :
∀ {nodes : list node} {inputs : env} {tgt : reference},
well_formed_at costs nodes inputs tgt →
grads_exist_at nodes inputs tgt →
pdfs_exist_at nodes inputs →
is_gdifferentiable (λ m, ⟦sum_costs m costs⟧) tgt inputs nodes dvec.head →
is_nabla_gintegrable (λ m, ⟦sum_costs m costs⟧) tgt inputs nodes dvec.head →
is_gintegrable (λ m, ⟦compute_grad_slow costs nodes m tgt⟧) inputs nodes dvec.head →
can_differentiate_under_integrals costs nodes inputs tgt →
∇ (λ θ₀, E (graph.to_dist (λ m, ⟦sum_costs m costs⟧) (env.insert tgt θ₀ inputs) nodes) dvec.head) (env.get tgt inputs)
=
E (graph.to_dist (λ m, ⟦compute_grad_slow costs nodes m tgt⟧) inputs nodes) dvec.head
| [] inputs tgt :=
assume (H_wf : well_formed_at costs [] inputs tgt)
(H_gs_exist : grads_exist_at [] inputs tgt)
(H_pdfs_exist : pdfs_exist_at [] inputs)
(H_gdiff : true)
(H_nabla_gint : true)
(H_grad_gint : true)
(H_diff_under_int : true),
begin
dunfold graph.to_dist,
simp [E.E_ret],
dunfold dvec.head compute_grad_slow sum_costs,
rw T.grad_sumr _ _ _ (sum_costs_differentiable costs tgt inputs),
apply congr_arg,
apply map_congr_fn_pred,
intros cost H_cost_in_costs,
assertv H_em : tgt = (cost, []) ∨ tgt ≠ (cost, []) := decidable.em _,
cases H_em with H_eq H_neq,
-- case 1: tgt = (cost, [])
{ rw H_eq, simp [env.get_insert_same, T.grad_id] },
-- case 2: tgt ≠ (cost, [])
{ simp [λ (x : T tgt.2), env.get_insert_diff x inputs (ne.symm H_neq), H_neq, T.grad_const] }
end
| (⟨ref, parents, operator.det op⟩ :: nodes) inputs tgt :=
assume H_wf H_gs_exist H_pdfs_exist H_gdiff H_nabla_gint H_grad_gint H_diff_under_int,
let θ := env.get tgt inputs in
let x := op^.f (env.get_ks parents inputs) in
let next_inputs := env.insert ref x inputs in
-- 0. Collect useful helpers
have H_ref_in_refs : ref ∈ ref :: map node.ref nodes, from mem_of_cons_same,
have H_ref_notin_parents : ref ∉ parents, from ref_notin_parents H_wf^.ps_in_env H_wf^.uids,
have H_tgt_neq_ref : tgt ≠ ref, from ref_ne_tgt H_wf^.m_contains_tgt H_wf^.uids,
have H_get_ks_next_inputs : env.get_ks parents next_inputs = env.get_ks parents inputs,
begin dsimp, rw (env.get_ks_insert_diff H_ref_notin_parents) end,
have H_get_ref_next : env.get ref next_inputs = op^.f (env.get_ks parents inputs),
begin dsimp, rw env.get_insert_same end,
have H_can_insert : env.get tgt next_inputs = env.get tgt inputs,
begin dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end,
have H_insert_next : ∀ (y : T ref.2), env.insert ref y inputs = env.insert ref y next_inputs,
begin intro y, dsimp, rw env.insert_insert_same end,
have H_wfs : well_formed_at costs nodes next_inputs tgt ∧ well_formed_at costs nodes next_inputs ref, from wf_at_next H_wf,
have H_gs_exist_tgt : grads_exist_at nodes next_inputs tgt, from H_gs_exist^.left,
have H_pdfs_exist_next : pdfs_exist_at nodes next_inputs, from H_pdfs_exist,
have H_grad_gint_tgt : is_gintegrable (λ m, ⟦compute_grad_slow costs nodes m tgt⟧) next_inputs nodes dvec.head, from
(iff.mpr (is_gintegrable_k_add _ _ _ _) H_grad_gint)^.left,
have H_nabla_gint_tgt : is_nabla_gintegrable (λ m, ⟦sum_costs m costs⟧) tgt next_inputs nodes dvec.head, from H_nabla_gint^.left,
have H_grad_gint₁ : is_gintegrable (λ (m : env), ⟦compute_grad_slow costs nodes m tgt⟧)
(env.insert ref (det.op.f op (env.get_ks parents inputs)) inputs)
nodes
dvec.head,
begin dunfold is_gintegrable compute_grad_slow at H_grad_gint, apply (iff.mpr (is_gintegrable_k_add _ _ _ _) H_grad_gint)^.left end,
have H_grad_gint₂ : is_gintegrable
(λ (m : env),
⟦sumr
(map
(λ (idx : ℕ),
det.op.pb op (env.get_ks parents m) (env.get ref m) (compute_grad_slow costs nodes m ref) idx (tgt.snd))
(filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents))))⟧)
(env.insert ref (det.op.f op (env.get_ks parents inputs)) inputs)
nodes
dvec.head,
begin dunfold is_gintegrable compute_grad_slow at H_grad_gint, apply (iff.mpr (is_gintegrable_k_add _ _ _ _) H_grad_gint)^.right end,
begin
dunfold graph.to_dist operator.to_dist compute_grad_slow,
simp [E.E_bind, E.E_ret],
dunfold dvec.head,
rw E.E_k_add _ _ _ _ H_grad_gint₁ H_grad_gint₂,
simp only,
rw E.E_k_sum_map _ _ nodes _ H_pdfs_exist H_grad_gint₂,
-- 1. Use the general estimator on the LHS
pose g := (λ (v : dvec T parents^.p2) (θ : T tgt.2), E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧) (env.insert ref (det.op.f op v) (env.insert tgt θ inputs)) nodes) dvec.head),
assert H_diff₁ : T.is_cdifferentiable (λ (θ₀ : T (tgt.snd)), g (env.get_ks parents (env.insert tgt θ inputs)) θ₀) θ,
{ exact H_gdiff^.left },
assert H_diff₂ : T.is_cdifferentiable (λ (θ₀ : T (tgt.snd)), sumr (map (λ (idx : ℕ), g (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ inputs)) idx) θ)
(filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents)))))
θ,
{ exact H_gdiff^.right^.left },
rw (T.multiple_args_general parents tgt inputs g θ H_diff₁ H_diff₂),
dsimp,
-- 2. Make the first terms equal, recursively
simp [env.insert_get_same H_wf^.m_contains_tgt],
pose H_almost_tgt := (eq.symm (compute_grad_slow_correct H_wfs^.left H_gs_exist_tgt H_pdfs_exist_next H_gdiff^.right^.right^.left H_nabla_gint_tgt H_grad_gint_tgt H_diff_under_int^.left)),
rw (env.get_insert_diff _ _ H_tgt_neq_ref) at H_almost_tgt,
erw H_almost_tgt,
dsimp,
simp [λ (θ : T tgt.2), env.insert_insert_flip x θ inputs (ne.symm H_tgt_neq_ref)],
apply congr_arg,
-- 3. Time for the second term: get rid of sum and use map_filter_congr
apply (congr_arg sumr),
apply map_filter_congr,
intros idx H_idx_in_riota H_tgt_dnth_parents_idx,
assertv H_tgt_at_idx : at_idx parents idx tgt := ⟨in_riota_lt H_idx_in_riota, H_tgt_dnth_parents_idx⟩,
assertv H_tshape_at_idx : at_idx parents^.p2 idx tgt.2 := at_idx_p2 H_tgt_at_idx,
assertv H_tgt_in_parents : tgt ∈ parents := mem_of_at_idx H_tgt_at_idx,
-- 4. Put the LHS in terms of T.tmulT
rw (T.grad_chain_rule (λ (θ : T tgt.2), det.op.f op (dvec.update_at θ (env.get_ks parents inputs) idx))
(λ (x : T ref.2), E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧)
(env.insert ref x inputs)
nodes)
dvec.head)),
-- 5. Replace `m` with `inputs`/`next_inputs` so that we can use `pb_correct`
assert H_swap_m_for_inputs :
graph.to_dist (λ (m : env),
⟦op^.pb (env.get_ks parents m)
(env.get ref m)
(compute_grad_slow costs nodes m ref)
idx
tgt.2⟧)
next_inputs
nodes
=
(graph.to_dist (λ (m : env),
⟦op^.pb (env.get_ks parents next_inputs)
x
(compute_grad_slow costs nodes m ref)
idx
tgt.2⟧)
next_inputs
nodes),
begin
apply graph.to_dist_congr,
exact H_wfs^.right^.uids,
dsimp,
intros m H_envs_match,
apply dvec.singleton_congr,
assert H_parents_match : env.get_ks parents m = env.get_ks parents next_inputs,
begin
apply env.get_ks_env_eq,
intros parent H_parent_in_parents,
apply H_envs_match,
apply env.has_key_insert,
exact (H_wf^.ps_in_env^.left parent H_parent_in_parents)
end,
assert H_ref_matches : env.get ref m = x,
begin
assertv H_env_has_key_ref : env.has_key ref next_inputs := env.has_key_insert_same _ _,
rw [H_envs_match ref H_env_has_key_ref, env.get_insert_same]
end,
simp [H_parents_match, H_ref_matches],
end,
rw H_swap_m_for_inputs,
clear H_swap_m_for_inputs,
-- 6. Use pb_correct
assertv H_f_pre : op^.pre (env.get_ks parents next_inputs) := eq.rec_on (eq.symm H_get_ks_next_inputs) (H_gs_exist^.right H_tgt_in_parents)^.left,
simp [λ (m : env), op^.pb_correct (env.get_ks parents next_inputs) x (by rw H_get_ks_next_inputs) (compute_grad_slow costs nodes m ref) H_tshape_at_idx H_f_pre],
-- 7. Push E over tmulT and cancel the first terms
simp [E.E_k_tmulT, H_get_ks_next_inputs, env.dvec_get_get_ks inputs H_tgt_at_idx],
apply congr_arg,
-- 8. Final recursive case
assertv H_gs_exist_ref : grads_exist_at nodes next_inputs ref := (H_gs_exist^.right H_tgt_in_parents)^.right,
assert H_grad_gint_ref : is_gintegrable (λ m, ⟦compute_grad_slow costs nodes m ref⟧) next_inputs nodes dvec.head,
begin
assertv H_op_called : is_gintegrable (λ m, ⟦det.op.pb op (env.get_ks parents m) (env.get ref m) (compute_grad_slow costs nodes m ref) idx (tgt.snd)⟧)
next_inputs nodes dvec.head :=
is_gintegrable_of_sumr_map (λ m idx, det.op.pb op (env.get_ks parents m) (env.get ref m) (compute_grad_slow costs nodes m ref) idx (tgt.snd))
next_inputs nodes _ H_grad_gint₂ idx (in_filter _ _ _ H_idx_in_riota H_tgt_dnth_parents_idx),
assert H_op_called_swap : is_gintegrable (λ m, ⟦det.op.pb op (env.get_ks parents next_inputs) x (compute_grad_slow costs nodes m ref) idx (tgt.snd)⟧)
next_inputs nodes dvec.head,
{
apply is_gintegrable_k_congr _ _ _ _ _ H_wfs^.right^.uids _ H_op_called,
intros m H_envs_match,
-- TODO(dhs): this is copy-pasted from above
assert H_parents_match : env.get_ks parents m = env.get_ks parents next_inputs,
begin
apply env.get_ks_env_eq,
intros parent H_parent_in_parents,
apply H_envs_match,
apply env.has_key_insert,
exact (H_wf^.ps_in_env^.left parent H_parent_in_parents)
end,
assert H_ref_matches : env.get ref m = x,
begin
assertv H_env_has_key_ref : env.has_key ref next_inputs := env.has_key_insert_same _ _,
rw [H_envs_match ref H_env_has_key_ref, env.get_insert_same]
end,
simp only [H_parents_match, H_ref_matches],
},
simp only [λ (m : env), op^.pb_correct (env.get_ks parents next_inputs) x (by rw H_get_ks_next_inputs) (compute_grad_slow costs nodes m ref) H_tshape_at_idx H_f_pre] at H_op_called_swap,
exact iff.mpr (is_gintegrable_tmulT _ _ _ _) H_op_called_swap
end,
assert H_gdiff_ref : is_gdifferentiable (λ m, ⟦sum_costs m costs⟧) ref next_inputs nodes dvec.head,
{ exact H_gdiff^.right^.right^.right H_idx_in_riota H_tgt_dnth_parents_idx },
assert H_nabla_gint_ref : is_nabla_gintegrable (λ m, ⟦sum_costs m costs⟧) ref next_inputs nodes dvec.head,
{ exact H_nabla_gint^.right H_idx_in_riota H_tgt_dnth_parents_idx },
pose H_correct_ref := compute_grad_slow_correct H_wfs^.right H_gs_exist_ref H_pdfs_exist_next
H_gdiff_ref H_nabla_gint_ref H_grad_gint_ref (H_diff_under_int^.right H_tgt_in_parents),
simp [H_get_ref_next] at H_correct_ref,
dsimp at H_correct_ref,
simp [env.insert_insert_same] at H_correct_ref,
dsimp,
simp [env.dvec_update_at_env inputs H_tgt_at_idx],
exact H_correct_ref
end
| (⟨ref, parents, operator.rand op⟩ :: nodes) inputs tgt :=
assume H_wf H_gs_exist H_pdfs_exist H_gdiff H_nabla_gint H_grad_gint H_diff_under_int,
let θ := env.get tgt inputs in
let next_inputs := λ (y : T ref.2), env.insert ref y inputs in
-- 0. Collect useful helpers
have H_ref_in_refs : ref ∈ ref :: map node.ref nodes, from mem_of_cons_same,
have H_ref_notin_parents : ref ∉ parents, from ref_notin_parents H_wf^.ps_in_env H_wf^.uids,
have H_tgt_neq_ref : tgt ≠ ref, from ref_ne_tgt H_wf^.m_contains_tgt H_wf^.uids,
have H_insert_θ : env.insert tgt θ inputs = inputs, by rw env.insert_get_same H_wf^.m_contains_tgt,
have H_parents_match : ∀ y, env.get_ks parents (next_inputs y) = env.get_ks parents inputs,
begin intro y, dsimp, rw (env.get_ks_insert_diff H_ref_notin_parents), end,
have H_can_insert_y : ∀ y, env.get tgt (next_inputs y) = env.get tgt inputs,
begin intro y, dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end,
have H_wfs : ∀ y, well_formed_at costs nodes (next_inputs y) tgt ∧ well_formed_at costs nodes (next_inputs y) ref,
from assume y, wf_at_next H_wf,
have H_parents_match : ∀ y, env.get_ks parents (next_inputs y) = env.get_ks parents inputs,
begin intro y, dsimp, rw (env.get_ks_insert_diff H_ref_notin_parents), end,
have H_can_insert_y : ∀ y, env.get tgt (next_inputs y) = env.get tgt inputs,
begin intro y, dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end,
have H_op_pre : op^.pre (env.get_ks parents inputs), from H_pdfs_exist^.left,
begin
dunfold graph.to_dist operator.to_dist,
simp [E.E_bind],
-- 1. Rewrite with the hybrid estimator
definev g : T ref.2 → T tgt.2 → ℝ :=
(λ (x : T ref.2) (θ₀ : T tgt.2),
E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧)
(env.insert ref x (env.insert tgt θ₀ inputs))
nodes)
dvec.head),
definev θ : T tgt.2 := env.get tgt inputs,
assert H_diff₁ : T.is_cdifferentiable (λ (θ₀ : T (tgt.snd)), E (sprog.prim op (env.get_ks parents (env.insert tgt θ inputs))) (λ (y : dvec T [ref.snd]), g y^.head θ₀)) θ,
{ exact H_gdiff^.left },
assert H_diff₂ : T.is_cdifferentiable (λ (θ₀ : T (tgt.snd)), sumr (map (λ (idx : ℕ),
E (sprog.prim op (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ inputs)) idx))
(λ (y : dvec T [ref.snd]), g y^.head θ))
(filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents))))) θ,
{ exact H_gdiff^.right^.left },
assert H_eint₁ : E.is_eintegrable (sprog.prim op (env.get_ks parents (env.insert tgt θ inputs))) (λ (x : dvec T [ref.snd]), ∇ (g x^.head) θ),
begin
dsimp [E.is_eintegrable, dvec.head],
simp only [env.insert_get_same H_wf^.m_contains_tgt],
exact H_nabla_gint^.left
end,
assert H_eint₂ : E.is_eintegrable (sprog.prim op (env.get_ks parents (env.insert tgt θ inputs)))
(λ (x : dvec T [ref.snd]),
sumr
(map
(λ (idx : ℕ),
g x^.head θ ⬝ ∇
(λ (θ₀ : T (tgt.snd)),
T.log
(rand.op.pdf op (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ inputs)) idx)
(dvec.head x)))
θ)
(filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents))))),
begin
dsimp [E.is_eintegrable, dvec.head],
simp only [env.insert_get_same H_wf^.m_contains_tgt],
exact H_nabla_gint^.right^.left,
end,
assert H_g_diff : ∀ (x : T (ref.snd)), T.is_cdifferentiable (g x) θ,
begin
intros y,
dsimp,
simp [λ θ₀, env.insert_insert_flip y θ₀ inputs (ne.symm H_tgt_neq_ref)],
simp [eq.symm (H_can_insert_y y)],
apply pd_is_cdifferentiable _ _ _ _ (H_wfs _)^.left (H_gs_exist^.right _) (H_pdfs_exist^.right _) (H_diff_under_int^.right _)
end,
assertv H_g_uint : T.is_uniformly_integrable_around (λ (θ₀ : T (tgt.snd)) (x : T (ref.snd)), rand.op.pdf op (env.get_ks parents (env.insert tgt θ inputs)) x ⬝ g x θ₀) θ :=
can_diff_under_ints_alt1 H_diff_under_int,
assertv H_g_grad_uint : T.is_uniformly_integrable_around (λ (θ₀ : T (tgt.snd)) (x : T (ref.snd)), ∇ (λ (θ₁ : T (tgt.snd)), rand.op.pdf op (env.get_ks parents (env.insert tgt θ inputs)) x ⬝ g x θ₁) θ₀) θ :=
H_diff_under_int^.left^.right^.left^.right,
assert H_d'_pdf_cdiff: ∀ (idx : ℕ), at_idx parents idx tgt →
∀ (v : T (ref.snd)), T.is_cdifferentiable (λ (x₀ : T (tgt.snd)), rand.op.pdf op (dvec.update_at x₀ (env.get_ks parents (env.insert tgt θ inputs)) idx) v) θ,
begin
intros idx H_at_idx y,
assertv H_tgt_in_parents : tgt ∈ parents := mem_of_at_idx H_at_idx,
assertv H_pre_satisfied : op^.pre (env.get_ks parents inputs) := H_gs_exist^.left H_tgt_in_parents,
simp [H_insert_θ],
dunfold E, dsimp,
simp [eq.symm (env.dvec_get_get_ks inputs H_at_idx)],
exact (op^.pdf_cdiff (at_idx_p2 H_at_idx) H_pre_satisfied)
end,
assertv H_d'_uint : ∀ (idx : ℕ), at_idx parents idx tgt →
T.is_uniformly_integrable_around (λ (θ₀ : T (tgt.snd)) (x : T (ref.snd)), rand.op.pdf op (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ inputs)) idx) x ⬝ g x θ) θ := H_diff_under_int^.left^.right^.right^.left,
assertv H_d'_grad_uint : ∀ (idx : ℕ), at_idx parents idx tgt →
T.is_uniformly_integrable_around (λ (θ₀ : T (tgt.snd)) (x : T (ref.snd)),
∇ (λ (θ₀ : T (tgt.snd)), rand.op.pdf op (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ inputs)) idx) x ⬝ g x θ) θ₀) θ :=
H_diff_under_int^.left^.right^.right^.right,
dsimp,
rw (estimators.hybrid_general inputs H_wf^.m_contains_tgt op H_op_pre g θ rfl
H_g_diff H_g_uint H_g_grad_uint
H_d'_pdf_cdiff H_d'_uint H_d'_grad_uint H_diff₁ H_diff₂ H_eint₁ H_eint₂),
-- 2. Cancel first stochastic choice
dsimp,
simp [env.insert_get_same H_wf^.m_contains_tgt],
apply congr_arg,
apply funext,
intro y,
cases y with ignore y ignore dnil,
cases dnil,
dunfold dvec.head,
assert H_get_ks_next_inputs : env.get_ks parents (next_inputs y) = env.get_ks parents inputs,
begin dsimp, rw (env.get_ks_insert_diff H_ref_notin_parents) end,
assert H_get_ref_next : env.get ref (next_inputs y) = y,
begin dsimp, rw env.get_insert_same end,
-- 3. Push E over sum on RHS
dunfold compute_grad_slow,
assert H_grad_gint₁ : is_gintegrable (λ (m : env), ⟦compute_grad_slow costs nodes m tgt⟧) (env.insert ref y inputs) nodes dvec.head,
{ dsimp [is_gintegrable, compute_grad_slow] at H_grad_gint, apply (iff.mpr (is_gintegrable_k_add _ _ _ _) (H_grad_gint^.right y))^.left },
assert H_grad_gint₂ : is_gintegrable
(λ (m : env),
⟦sumr
(map
(λ (idx : ℕ),
sum_downstream_costs nodes costs ref m ⬝ rand.op.glogpdf op (env.get_ks parents m) (env.get ref m) idx
(tgt.snd))
(filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents))))⟧)
(env.insert ref y inputs)
nodes
dvec.head,
{ dsimp [is_gintegrable, compute_grad_slow] at H_grad_gint, apply (iff.mpr (is_gintegrable_k_add _ _ _ _) (H_grad_gint^.right y))^.right },
rw E.E_k_add _ _ _ _ H_grad_gint₁ H_grad_gint₂,
-- 4. Cancel the first terms
assert H_gdiff_tgt : is_gdifferentiable (λ (m : env), ⟦sum_costs m costs⟧) tgt (next_inputs y) nodes dvec.head,
{ exact H_gdiff^.right^.right y },
assert H_grad_gint_tgt : is_gintegrable (λ (m : env), ⟦compute_grad_slow costs nodes m tgt⟧) (next_inputs y) nodes dvec.head,
{ exact (iff.mpr (is_gintegrable_k_add _ _ _ _) (H_grad_gint^.right y))^.left },
assert H_nabla_gint_tgt : is_nabla_gintegrable (λ m, ⟦sum_costs m costs⟧) tgt (next_inputs y) nodes dvec.head,
{ exact H_nabla_gint^.right^.right y },
-- TODO(dhs): confirm ERW is only needed because of the `definev`
erw -(compute_grad_slow_correct (H_wfs _)^.left (H_gs_exist^.right y) (H_pdfs_exist^.right _) H_gdiff_tgt H_nabla_gint_tgt H_grad_gint_tgt (H_diff_under_int^.right y)),
dsimp,
simp [λ (θ : T tgt.2), env.insert_insert_flip θ y inputs H_tgt_neq_ref],
rw (env.get_insert_diff _ _ H_tgt_neq_ref),
apply congr_arg,
-- 5. Push E over sumr and expose map
rw E.E_k_sum_map _ _ _ _ (H_pdfs_exist^.right _) H_grad_gint₂,
apply congr_arg,
-- 6. Apply map_filter_congr
exact map_filter_expand_helper _ _ _ _ _ _ H_wf H_gs_exist _
end
end theorems
end certigrad
|
4043bdd5038b0efdb5c131a99a33eccf4f5464a1 | 3bdd27ffdff3ffa22d4bb010eba695afcc96bc4a | /src/sperner.lean | bc18cfc464576a2efcdcface08b8fa1ff532fdd9 | [] | no_license | mmasdeu/brouwerfixedpoint | 684d712c982c6a8b258b4e2c6b2eab923f2f1289 | 548270f79ecf12d7e20a256806ccb9fcf57b87e2 | refs/heads/main | 1,690,539,793,996 | 1,631,801,831,000 | 1,631,801,831,000 | 368,139,809 | 4 | 3 | null | 1,624,453,250,000 | 1,621,246,034,000 | Lean | UTF-8 | Lean | false | false | 9,811 | lean | import tactic
import data.set.finite
import data.real.basic
import data.real.ereal
import linear_algebra.affine_space.independent
import analysis.convex.basic
import topology.sequences
noncomputable theory
open set affine topological_space
open_locale affine filter big_operators
variables {V : Type*} [add_comm_group V] [module ℝ V]
variables [affine_space V V]
variables {k n : ℕ}
variables (Δ : simplex ℝ V n)
def pts (C : simplex ℝ V k) : set V := convex_hull (C.points '' univ)
structure triangulation :=
(simps : set (@simplex ℝ V V _ _ _ _ n) )
(cov : (⋃ s ∈ simps, (pts s)) = pts Δ)
--(inter : ∀ s t ∈ simps, (pts s) ∩ (pts t) ≠ ∅ → ∃ (m : ℕ) (st m),
-- (pts s) ∩ (pts t) = pts st)
-- exercici: escriure la condició d'intersecció fent servir "face".
lemma fixed_point_of_epsilon_fixed (X : Type) [metric_space X]
[hsq : seq_compact_space X]
(f : X → X) (hf : continuous f)
(h : ∀ (ε : ℝ), 0 < ε → ∃ x, dist x (f x) < ε) :
∃ x : X, f x = x :=
begin
have hpos : ∀ (n : ℕ), 0 < 1 / ((n+1) : ℝ), by apply nat.one_div_pos_of_nat,
let a : ℕ → X := λ n, classical.some (h (1 / ((n+1) : ℝ)) (hpos n)),
have ha : ∀ n, dist (a n) (f (a n)) < 1 / ((n+1) : ℝ) :=
λ n, classical.some_spec (h (1 / ((n+1) : ℝ)) (hpos n)),
have exists_lim : ∃ (z ∈ univ) (Φ : ℕ → ℕ),
strict_mono Φ ∧ filter.tendsto (a ∘ Φ) filter.at_top (nhds z),
{ apply hsq.seq_compact_univ,
exact λ n, by trivial },
obtain ⟨z, ⟨_, ⟨Φ, ⟨hΦ1, hΦ2⟩⟩⟩ ⟩ := exists_lim,
use z,
suffices : ∀ ε > 0, dist z (f z) ≤ ε,
{
rw [←dist_le_zero, dist_comm],
exact le_of_forall_le_of_dense this,
},
intros ε hε,
have H1 : ∀ δ, 0 < δ → ∃ (n : ℕ), ∀ m ≥ n, dist z ((a ∘ Φ) m) < δ,
{
intros δ hδ,
rw seq_tendsto_iff at hΦ2,
specialize hΦ2 (metric.ball z (δ)) (by rwa [metric.mem_ball, dist_self]) (metric.is_open_ball),
simp only [metric.mem_ball, dist_comm] at hΦ2,
exact hΦ2,
},
have H2 : ∃ (n : ℕ), ∀ m ≥ n, dist ((a∘Φ) m) (f ((a∘Φ) m)) ≤ ε/3,
{
have hkey : ∃ (n : ℕ), 1 / ((n+1):ℝ) < ε/3,
{ have hnlarge : ∃ (n : ℕ), (n :ℝ) > 3 / ε := exists_nat_gt (3 / ε),
obtain ⟨n, hn⟩:= hnlarge,
use n,
refine (inv_lt_inv _ (hpos n)).mp _, by linarith,
field_simp,
linarith },
obtain ⟨n, hn⟩ := hkey,
use n,
intros m hm,
specialize ha (Φ m),
have hmn : 1 / ((m + 1) : ℝ) ≤ 1 / ((n + 1) : ℝ), by exact nat.one_div_le_one_div hm,
have hinc : 1 / ((Φ m) + 1:ℝ) ≤ 1 / ((m + 1):ℝ), by exact nat.one_div_le_one_div (strict_mono.id_le hΦ1 m),
linarith,
},
have H3 : ∃ (n : ℕ), ∀ m ≥ n, dist (f ((a∘Φ) m)) (f z) < ε/3 :=
let ⟨δ, ⟨hδpos, h'⟩⟩ := (metric.continuous_iff.1 hf) z (ε/3) (by linarith), ⟨n1, hn1⟩ := H1 δ hδpos in
⟨n1, λ m hm, let h := hn1 m hm in h' (a (Φ m)) (by rwa dist_comm)⟩,
obtain ⟨⟨n1, hn1⟩, ⟨n2, hn2⟩, ⟨n3, hn3⟩⟩ := ⟨H1 (ε / 3) (by linarith), H2, H3⟩,
let n := max (max n1 n2) n3,
specialize hn1 n (le_of_max_le_left (le_max_left (max n1 n2) n3)),
specialize hn2 n (le_trans (le_max_right n1 n2) (le_max_left (max n1 n2) n3)),
specialize hn3 n (le_max_right (max n1 n2) n3),
calc
dist z (f z) ≤ dist z ((a ∘ Φ) n)
+ dist ((a ∘ Φ) n) (f ((a ∘ Φ) n))
+ dist (f ((a ∘ Φ) n)) (f z) : dist_triangle4 z ((a ∘ Φ) n) (f ((a ∘ Φ) n)) (f z)
... ≤ ε/3 + ε/3 + ε/3 : by { linarith [hn1, hn2, hn3] }
... = ε : by {ring},
end
lemma le_min_right_or_left {α : Type*} [linear_order α] (a b : α) : a ≤ min a b ∨ b ≤ min a b :=
by cases (le_total a b) with h; simp [true_or, le_min rfl.ge h]; exact or.inr h
lemma max_le_right_or_left {α : Type*} [linear_order α] (a b : α) : max a b ≤ a ∨ max a b ≤ b :=
by cases (le_total a b) with h; simp [true_or, max_le rfl.ge h]; exact or.inr h
lemma edist_lt_of_diam_lt {X : Type*} [pseudo_emetric_space X] (s : set X) {d : ennreal} :
emetric.diam s < d → ∀ (x ∈ s) (y ∈ s), edist x y < d :=
λ h x hx y hy, gt_of_gt_of_ge h (emetric.edist_le_diam_of_mem hx hy)
lemma enndiameter_growth' {X : Type} [pseudo_emetric_space X] {S : set X}
{f : X → X} (hf : uniform_continuous_on f S) : ∀ ε > 0, ∃ δ > 0,
∀ T ⊆ S, emetric.diam T < δ → emetric.diam (f '' T) ≤ ε :=
λ ε hε, let ⟨δ, hδ, H⟩ := emetric.uniform_continuous_on_iff.1 hf ε hε in
⟨δ, hδ, λ R hR hdR, emetric.diam_image_le_iff.2
(λ x hx y hy, le_of_lt (H (hR hx) (hR hy) (edist_lt_of_diam_lt R hdR x hx y hy)))⟩
lemma enndiameter_growth {X : Type} [pseudo_emetric_space X] {S : set X}
{f : X → X} (hf : uniform_continuous_on f S) : ∀ ε > 0, ∃ δ > 0,
∀ T ⊆ S, emetric.diam T < δ → emetric.diam (f '' T) < ε :=
begin
intros ε hε,
set γ := min 1 (ε/2) with hhγ,
have hγ : γ > 0,
{ cases (le_min_right_or_left 1 (ε/2)),
{ exact lt_of_lt_of_le (ennreal.zero_lt_one) h },
{ exact lt_of_lt_of_le (ennreal.div_pos_iff.2 ⟨ne_of_gt hε, ennreal.two_ne_top⟩) h } },
obtain ⟨δ, hδ, H⟩ := enndiameter_growth' hf γ hγ,
have hγε: γ < ε,
{ cases (lt_or_ge 1 ε),
{ exact lt_of_le_of_lt (min_le_left 1 (ε/2)) h },
{ have hεtop := ne_of_lt (lt_of_le_of_lt h (lt_of_le_of_ne le_top ennreal.one_ne_top)),
exact lt_of_le_of_lt (min_le_right 1 (ε/2)) (ennreal.half_lt_self (ne_of_gt hε) hεtop) } },
exact ⟨δ, hδ, (λ R hR hdR, lt_of_le_of_lt (H R hR hdR) hγε)⟩,
end
lemma diameter_growth (X : Type) [metric_space X] (S : set X)
(f : X → X) (hf : uniform_continuous_on f S) (ε : ℝ) (hε : 0 < ε) :
∃ δ > 0, ∀ T ⊆ S, metric.bounded T → metric.diam T ≤ δ →
metric.bounded (f '' T) ∧ metric.diam (f '' T) ≤ ε :=
begin
sorry
end
variables {d : ℕ}
local notation `E` := fin d → ℝ
def H := {x : E | (∑ (i : fin d), x i) = 1}
variables (f: E → E)
lemma of_real_neg_real_equiv {x : ℝ} (hx : 0 ≤ x) : (ennreal.of_real x : ereal) = (x : ereal) :=
begin
rw (ennreal.of_real_eq_coe_nnreal hx),
exact rfl,
end
lemma abs_sub_leq (a b : real) (r : ennreal) (h1 : (a : ereal) ≤ (b : ereal) + r) (h2 : (a : ereal) ≥ (b : ereal) - r) :
ennreal.of_real (abs (a - b)) ≤ r :=
begin
cases (abs_choice (a - b)),
{ have : (a : ereal) - (b : ereal) ≤ (r : ereal),
{ rcases (ereal.cases (r : ereal)) with h_1 | ⟨x, hx⟩ | h_3,
{ have hr0: (r : ereal) < 0,
{ rw h_1,
exact ereal.bot_lt_zero },
have h0r:= ereal.coe_ennreal_nonneg r,
rw lt_iff_not_ge at hr0,
contradiction },
{ let hb := le_of_eq (eq.refl (-↑b)),
obtain hh := add_le_add h1 hb,
have hr : b + x + -b = x, by ring,
have hbr : (b : ereal) + (r : ereal) + - (b :ereal) = (r : ereal),
{ rw hx,
exact (congr_arg coe (eq.symm hr)).symm },
rwa ← hbr },
{ rw h_3,
exact with_top.le_none } },
exact ereal.coe_ennreal_le_coe_ennreal_iff.mp (by rwa [of_real_neg_real_equiv (abs_nonneg (a - b)), h]) },
{ have hab : -(a - b) = b - a, by ring,
have : (b : ereal) - (a : ereal) ≤ (r : ereal),
{ rcases (ereal.cases (r : ereal)) with h_1 |⟨x, hx⟩ | h_3,
{ have hr0: (r : ereal) < 0,
{ rw h_1,
exact ereal.bot_lt_zero },
have h0r:= ereal.coe_ennreal_nonneg r,
rw lt_iff_not_ge at hr0,
contradiction },
{
rw hx at *,
change (((b - a) : ℝ) : ereal) ≤ x,
change (a : ereal ) ≥ (((b - x) : ℝ) : ereal) at h2,
simp only [ge_iff_le, eq_self_iff_true, neg_sub, ereal.coe_le_coe_iff] at *,
linarith },
{ rw h_3,
exact with_top.le_none } },
exact ereal.coe_ennreal_le_coe_ennreal_iff.mp (by rwa [of_real_neg_real_equiv (abs_nonneg (a - b)), h, hab]) },
end
example (x y : E) : edist x y = ennreal.of_real (∑ i, (x i - y i)^2) :=
begin
sorry
end
lemma points_coordinates_bounded_distance (x y : E) (i : fin d) :
ennreal.of_real (abs (x i - y i)) ≤ edist x y :=
begin
unfold edist,
sorry
end
lemma points_coordinates_bounded_diam (S : set E) (x y : E) (hx : x ∈ S) (hy : y ∈ S)
(i : fin d) : ennreal.of_real (abs (x i - y i)) ≤ emetric.diam S :=
begin
sorry
end
-- per tota coordenada i, existeix un vertex v tal que la coordenada i-èssima
-- és la primera que complex que f(v)_i < f(v)
def is_sperner_set (f: E → E) (S : set E) :=
∀ i: fin d, ∃ v : E, v ∈ S ∧
(∀ j < i, (f v) j ≥ (v j)) ∧ (((f v) i) < v i)
lemma epsilon_fixed_condition
{f : E → E} {S : set E} (hs : S ⊆ H) (hd : 0 < d)
(hf : uniform_continuous_on f S)
{ε : real} (hε : 0 < ε)
: ∃ δ, 0 < δ ∧
∀ T ⊆ S,
metric.bounded T → metric.diam T < δ →
is_sperner_set f T →
∀ x ∈ T, dist (f x) x < ε :=
begin
let ε₁ := ε / (2 * d),
have h₁ := div_pos hε (mul_pos zero_lt_two (nat.cast_pos.mpr hd)),
obtain ⟨δ₀, hδ₀pos, hδ₀⟩ := metric.uniform_continuous_on_iff.mp hf ε₁ h₁,
let δ := min δ₀ (ε₁/2),
use δ,
split,
{ cases le_min_right_or_left δ₀ (ε₁/2),
{ exact gt_of_ge_of_gt h hδ₀pos },
{ exact lt_min hδ₀pos (half_pos h₁) } },
intros T hTS hbT hdT hfT x hx,
have hmost : ∀ (i : fin d) (hi : (i : ℕ) ≠ d-1),
abs (((f x) i)-(x i))
≤ δ + (metric.diam (f '' T)),
{
intros i hi,
rw abs_sub_le_iff,
split,
{
sorry
},
{
sorry
}
},
have hlast : abs(((f x) ⟨d-1, buffer.lt_aux_2 hd⟩)) - x ⟨d-1, buffer.lt_aux_2 hd⟩ ≤ (d-1) * (δ + (metric.diam (f '' T))),
{
sorry
},
sorry
end
|
d9ad28bb7bb3f3e060caf61306d2111bada312df | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/data/list/min_max.lean | 226817b043d99e3ab8afef794abf6e580cd4bc5e | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 11,131 | lean | /-
Copyright (c) 2019 Minchao Wu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Minchao Wu, Chris Hughes
-/
import data.list.basic
/-
# Minimum and maximum of lists
## Main definitions
The main definitions are `argmax`, `argmin`, `minimum` and `maximum` for lists.
`argmax f l` returns `some a`, where `a` of `l` that maximises `f a`. If there are `a b` such that
`f a = f b`, it returns whichever of `a` or `b` comes first in the list.
`argmax f []` = none`
`minimum l` returns an `with_top α`, the smallest element of `l` for nonempty lists, and `⊤` for
`[]`
-/
namespace list
variables {α : Type*} {β : Type*} [decidable_linear_order β]
/-- Auxiliary definition to define `argmax` -/
def argmax₂ (f : α → β) (a : option α) (b : α) : option α :=
option.cases_on a (some b) (λ c, if f b ≤ f c then some c else some b)
/-- `argmax f l` returns `some a`, where `a` of `l` that maximises `f a`. If there are `a b` such
that `f a = f b`, it returns whichever of `a` or `b` comes first in the list.
`argmax f []` = none` -/
def argmax (f : α → β) (l : list α) : option α :=
l.foldl (argmax₂ f) none
/-- `argmin f l` returns `some a`, where `a` of `l` that minimises `f a`. If there are `a b` such
that `f a = f b`, it returns whichever of `a` or `b` comes first in the list.
`argmin f []` = none` -/
def argmin (f : α → β) (l : list α) :=
@argmax _ (order_dual β) _ f l
@[simp] lemma argmax_two_self (f : α → β) (a : α) : argmax₂ f (some a) a = a :=
if_pos (le_refl _)
@[simp] lemma argmax_nil (f : α → β) : argmax f [] = none := rfl
@[simp] lemma argmin_nil (f : α → β) : argmin f [] = none := rfl
@[simp] lemma argmax_singleton {f : α → β} {a : α} : argmax f [a] = some a := rfl
@[simp] lemma argmin_singleton {f : α → β} {a : α} : argmin f [a] = a := rfl
@[simp] lemma foldl_argmax₂_eq_none {f : α → β} {l : list α} {o : option α} :
l.foldl (argmax₂ f) o = none ↔ l = [] ∧ o = none :=
list.reverse_rec_on l (by simp) $
(assume tl hd, by simp [argmax₂];
cases foldl (argmax₂ f) o tl; simp; try {split_ifs}; simp)
private theorem le_of_foldl_argmax₂ {f : α → β} {l} : Π {a m : α} {o : option α}, a ∈ l →
m ∈ foldl (argmax₂ f) o l → f a ≤ f m :=
list.reverse_rec_on l
(λ _ _ _ h, absurd h $ not_mem_nil _)
begin
intros tl _ ih _ _ _ h ho,
rw [foldl_append, foldl_cons, foldl_nil, argmax₂] at ho,
cases hf : foldl (argmax₂ f) o tl,
{ rw [hf] at ho,
rw [foldl_argmax₂_eq_none] at hf,
simp [hf.1, hf.2, *] at * },
rw [hf, option.mem_def] at ho,
dsimp only at ho,
cases mem_append.1 h with h h,
{ refine le_trans (ih h hf) _,
have := @le_of_lt _ _ (f val) (f m),
split_ifs at ho;
simp * at * },
{ split_ifs at ho;
simp * at * }
end
private theorem foldl_argmax₂_mem (f : α → β) (l) : Π (a m : α),
m ∈ foldl (argmax₂ f) (some a) l → m ∈ a :: l :=
list.reverse_rec_on l (by simp [eq_comm])
begin
assume tl hd ih a m,
simp only [foldl_append, foldl_cons, foldl_nil, argmax₂],
cases hf : foldl (argmax₂ f) (some a) tl,
{ simp {contextual := tt} },
{ dsimp only, split_ifs,
{ finish [ih _ _ hf] },
{ simp {contextual := tt} } }
end
theorem argmax_mem {f : α → β} : Π {l : list α} {m : α}, m ∈ argmax f l → m ∈ l
| [] m := by simp
| (hd::tl) m := by simpa [argmax, argmax₂] using foldl_argmax₂_mem f tl hd m
theorem argmin_mem {f : α → β} : Π {l : list α} {m : α}, m ∈ argmin f l → m ∈ l :=
@argmax_mem _ (order_dual β) _ _
@[simp] theorem argmax_eq_none {f : α → β} {l : list α} : l.argmax f = none ↔ l = [] :=
by simp [argmax]
@[simp] theorem argmin_eq_none {f : α → β} {l : list α} : l.argmin f = none ↔ l = [] :=
@argmax_eq_none _ (order_dual β) _ _ _
theorem le_argmax_of_mem {f : α → β} {a m : α} {l : list α} : a ∈ l → m ∈ argmax f l → f a ≤ f m :=
le_of_foldl_argmax₂
theorem argmin_le_of_mem {f : α → β} {a m : α} {l : list α} : a ∈ l → m ∈ argmin f l → f m ≤ f a:=
@le_argmax_of_mem _ (order_dual β) _ _ _ _ _
theorem argmax_concat (f : α → β) (a : α) (l : list α) : argmax f (l ++ [a]) =
option.cases_on (argmax f l) (some a) (λ c, if f a ≤ f c then some c else some a) :=
by rw [argmax, argmax]; simp [argmax₂]
theorem argmin_concat (f : α → β) (a : α) (l : list α) : argmin f (l ++ [a]) =
option.cases_on (argmin f l) (some a) (λ c, if f c ≤ f a then some c else some a) :=
@argmax_concat _ (order_dual β) _ _ _ _
theorem argmax_cons (f : α → β) (a : α) (l : list α) : argmax f (a :: l) =
option.cases_on (argmax f l) (some a) (λ c, if f c ≤ f a then some a else some c) :=
list.reverse_rec_on l rfl $
assume hd tl ih, begin
rw [← cons_append, argmax_concat, ih, argmax_concat],
cases h : argmax f hd with m,
{ simp [h] },
{ simp [h], dsimp,
by_cases ham : f m ≤ f a,
{ rw if_pos ham, dsimp,
by_cases htlm : f tl ≤ f m,
{ rw if_pos htlm, dsimp,
rw [if_pos (le_trans htlm ham), if_pos ham] },
{ rw if_neg htlm } },
{ rw if_neg ham, dsimp,
by_cases htlm : f tl ≤ f m,
{ rw if_pos htlm, dsimp,
rw if_neg ham },
{ rw if_neg htlm, dsimp,
rw [if_neg (not_le_of_gt (lt_trans (lt_of_not_ge ham) (lt_of_not_ge htlm)))] } } }
end
theorem argmin_cons (f : α → β) (a : α) (l : list α) : argmin f (a :: l) =
option.cases_on (argmin f l) (some a) (λ c, if f a ≤ f c then some a else some c) :=
@argmax_cons _ (order_dual β) _ _ _ _
theorem index_of_argmax [decidable_eq α] {f : α → β} : Π {l : list α} {m : α}, m ∈ argmax f l →
∀ {a}, a ∈ l → f m ≤ f a → l.index_of m ≤ l.index_of a
| [] m _ _ _ _ := by simp
| (hd::tl) m hm a ha ham := begin
simp only [index_of_cons, argmax_cons, option.mem_def] at ⊢ hm,
cases h : argmax f tl,
{ rw h at hm,
simp * at * },
{ rw h at hm,
dsimp only at hm,
cases ha with hahd hatl,
{ clear index_of_argmax,
subst hahd,
split_ifs at hm,
{ subst hm },
{ subst hm, contradiction } },
{ have := index_of_argmax h hatl, clear index_of_argmax,
split_ifs at *;
refl <|> exact nat.zero_le _ <|> simp [*, nat.succ_le_succ_iff, -not_le] at * } }
end
theorem index_of_argmin [decidable_eq α] {f : α → β} : Π {l : list α} {m : α}, m ∈ argmin f l →
∀ {a}, a ∈ l → f a ≤ f m → l.index_of m ≤ l.index_of a :=
@index_of_argmax _ (order_dual β) _ _ _
theorem mem_argmax_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} :
m ∈ argmax f l ↔ m ∈ l ∧ (∀ a ∈ l, f a ≤ f m) ∧
(∀ a ∈ l, f m ≤ f a → l.index_of m ≤ l.index_of a) :=
⟨λ hm, ⟨argmax_mem hm, λ a ha, le_argmax_of_mem ha hm, λ _, index_of_argmax hm⟩,
begin
rintros ⟨hml, ham, hma⟩,
cases harg : argmax f l with n,
{ simp * at * },
{ have := le_antisymm (hma n (argmax_mem harg) (le_argmax_of_mem hml harg))
(index_of_argmax harg hml (ham _ (argmax_mem harg))),
rw [(index_of_inj hml (argmax_mem harg)).1 this, option.mem_def] }
end⟩
theorem argmax_eq_some_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} :
argmax f l = some m ↔ m ∈ l ∧ (∀ a ∈ l, f a ≤ f m) ∧
(∀ a ∈ l, f m ≤ f a → l.index_of m ≤ l.index_of a) := mem_argmax_iff
theorem mem_argmin_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} :
m ∈ argmin f l ↔ m ∈ l ∧ (∀ a ∈ l, f m ≤ f a) ∧
(∀ a ∈ l, f a ≤ f m → l.index_of m ≤ l.index_of a) :=
@mem_argmax_iff _ (order_dual β) _ _ _ _ _
theorem argmin_eq_some_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} :
argmin f l = some m ↔ m ∈ l ∧ (∀ a ∈ l, f m ≤ f a) ∧
(∀ a ∈ l, f a ≤ f m → l.index_of m ≤ l.index_of a) := mem_argmin_iff
variable [decidable_linear_order α]
/-- `maximum l` returns an `with_bot α`, the largest element of `l` for nonempty lists, and `⊥` for
`[]` -/
def maximum (l : list α) : with_bot α := argmax id l
/-- `minimum l` returns an `with_top α`, the smallest element of `l` for nonempty lists, and `⊤` for
`[]` -/
def minimum (l : list α) : with_top α := argmin id l
@[simp] lemma maximum_nil : maximum ([] : list α) = ⊥ := rfl
@[simp] lemma minimum_nil : minimum ([] : list α) = ⊤ := rfl
@[simp] lemma maximum_singleton (a : α) : maximum [a] = a := rfl
@[simp] lemma minimum_singleton (a : α) : minimum [a] = a := rfl
theorem maximum_mem {l : list α} {m : α} : (maximum l : with_top α) = m → m ∈ l := argmax_mem
theorem minimum_mem {l : list α} {m : α} : (minimum l : with_bot α) = m → m ∈ l := argmin_mem
@[simp] theorem maximum_eq_none {l : list α} : l.maximum = none ↔ l = [] := argmax_eq_none
@[simp] theorem minimum_eq_none {l : list α} : l.minimum = none ↔ l = [] := argmin_eq_none
theorem le_maximum_of_mem {a m : α} {l : list α} : a ∈ l → (maximum l : with_bot α) = m → a ≤ m :=
le_argmax_of_mem
theorem minimum_le_of_mem {a m : α} {l : list α} : a ∈ l → (minimum l : with_top α) = m → m ≤ a :=
argmin_le_of_mem
theorem le_maximum_of_mem' {a : α} {l : list α} (ha : a ∈ l) : (a : with_bot α) ≤ maximum l :=
option.cases_on (maximum l) (λ _ h, absurd ha ((h rfl).symm ▸ not_mem_nil _))
(λ m hm _, with_bot.coe_le_coe.2 $ hm _ rfl)
(λ m, @le_maximum_of_mem _ _ _ m _ ha)
(@maximum_eq_none _ _ l).1
theorem le_minimum_of_mem' {a : α} {l : list α} (ha : a ∈ l) : minimum l ≤ (a : with_top α) :=
@le_maximum_of_mem' (order_dual α) _ _ _ ha
theorem maximum_concat (a : α) (l : list α) : maximum (l ++ [a]) = max (maximum l) a :=
begin
rw max_comm,
simp only [maximum, argmax_concat, id],
cases h : argmax id l,
{ rw [max_eq_left], refl, exact bot_le },
change (coe : α → with_bot α) with some,
rw [max_comm],
simp [max]
end
theorem minimum_concat (a : α) (l : list α) : minimum (l ++ [a]) = min (minimum l) a :=
@maximum_concat (order_dual α) _ _ _
theorem maximum_cons (a : α) (l : list α) : maximum (a :: l) = max a (maximum l) :=
list.reverse_rec_on l (by simp [@max_eq_left (with_bot α) _ _ _ bot_le])
(λ tl hd ih, by rw [← cons_append, maximum_concat, ih, maximum_concat, max_assoc])
theorem minimum_cons (a : α) (l : list α) : minimum (a :: l) = min a (minimum l) :=
@maximum_cons (order_dual α) _ _ _
theorem maximum_eq_coe_iff {m : α} {l : list α} :
maximum l = m ↔ m ∈ l ∧ (∀ a ∈ l, a ≤ m) :=
begin
unfold_coes,
simp only [maximum, argmax_eq_some_iff, id],
split,
{ simp only [true_and, forall_true_iff] {contextual := tt} },
{ simp only [true_and, forall_true_iff] {contextual := tt},
intros h a hal hma,
rw [le_antisymm hma (h.2 a hal)] }
end
theorem minimum_eq_coe_iff {m : α} {l : list α} :
minimum l = m ↔ m ∈ l ∧ (∀ a ∈ l, m ≤ a) :=
@maximum_eq_coe_iff (order_dual α) _ _ _
end list
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.