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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5c351350daf8e4b4a3625ba2f270ee9cfd6acd67 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/topology/metric_space/emetric_space.lean | 3459098e93208766f8c56fd5cb8be606232587b1 | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 46,763 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
-/
import data.real.ennreal
import data.finset.intervals
import topology.uniform_space.uniform_embedding
import topology.uniform_space.pi
import topology.uniform_space.uniform_convergence
/-!
# Extended metric spaces
This file is devoted to the definition and study of `emetric_spaces`, i.e., metric
spaces in which the distance is allowed to take the value ∞. This extended distance is
called `edist`, and takes values in `ℝ≥0∞`.
Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces
and topological spaces. For example: open and closed sets, compactness, completeness, continuity and
uniform continuity.
The class `emetric_space` therefore extends `uniform_space` (and `topological_space`).
Since a lot of elementary properties don't require `eq_of_edist_eq_zero` we start setting up the
theory of `pseudo_emetric_space`, where we don't require `edist x y = 0 → x = y` and we specialize
to `emetric_space` at the end.
-/
open set filter classical
noncomputable theory
open_locale uniformity topological_space big_operators filter nnreal ennreal
universes u v w
variables {α : Type u} {β : Type v}
/-- Characterizing uniformities associated to a (generalized) distance function `D`
in terms of the elements of the uniformity. -/
theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β)
(D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) :
U = ⨅ ε>z, 𝓟 {p:α×α | D p.1 p.2 < ε} :=
le_antisymm
(le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩)
(λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in
mem_infi_of_mem ε $ mem_infi_of_mem ε0 $ mem_principal.2 $ λ ⟨a, b⟩, h)
/-- `has_edist α` means that `α` is equipped with an extended distance. -/
class has_edist (α : Type*) := (edist : α → α → ℝ≥0∞)
export has_edist (edist)
/-- Creating a uniform space from an extended distance. -/
def uniform_space_of_edist
(edist : α → α → ℝ≥0∞)
(edist_self : ∀ x : α, edist x x = 0)
(edist_comm : ∀ x y : α, edist x y = edist y x)
(edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α :=
uniform_space.of_core {
uniformity := (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt},
comp :=
le_infi $ assume ε, le_infi $ assume h,
have (2 : ℝ≥0∞) = (2 : ℕ) := by simp,
have A : 0 < ε / 2 := ennreal.div_pos_iff.2
⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩,
lift'_le
(mem_infi_of_mem (ε / 2) $ mem_infi_of_mem A (subset.refl _)) $
have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε,
from assume a b c hac hcb,
calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _
... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb
... = ε : by rw [ennreal.add_halves],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] }
-- the uniform structure is embedded in the emetric space structure
-- to avoid instance diamond issues. See Note [forgetful inheritance].
/-- Extended (pseudo) metric spaces, with an extended distance `edist` possibly taking the
value ∞
Each pseudo_emetric space induces a canonical `uniform_space` and hence a canonical
`topological_space`.
This is enforced in the type class definition, by extending the `uniform_space` structure. When
instantiating a `pseudo_emetric_space` structure, the uniformity fields are not necessary, they
will be filled in by default. There is a default value for the uniformity, that can be substituted
in cases of interest, for instance when instantiating a `pseudo_emetric_space` structure
on a product.
Continuity of `edist` is proved in `topology.instances.ennreal`
-/
class pseudo_emetric_space (α : Type u) extends has_edist α : Type u :=
(edist_self : ∀ x : α, edist x x = 0)
(edist_comm : ∀ x y : α, edist x y = edist y x)
(edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z)
(to_uniform_space : uniform_space α :=
uniform_space_of_edist edist edist_self edist_comm edist_triangle)
(uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} . control_laws_tac)
/- Pseudoemetric spaces are less common than metric spaces. Therefore, we work in a dedicated
namespace, while notions associated to metric spaces are mostly in the root namespace. -/
variables [pseudo_emetric_space α]
@[priority 100] -- see Note [lower instance priority]
instance pseudo_emetric_space.to_uniform_space' : uniform_space α :=
pseudo_emetric_space.to_uniform_space
export pseudo_emetric_space (edist_self edist_comm edist_triangle)
attribute [simp] edist_self
/-- Triangle inequality for the extended distance -/
theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y :=
by rw edist_comm z; apply edist_triangle
theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z :=
by rw edist_comm y; apply edist_triangle
lemma edist_triangle4 (x y z t : α) :
edist x t ≤ edist x y + edist y z + edist z t :=
calc
edist x t ≤ edist x z + edist z t : edist_triangle x z t
... ≤ (edist x y + edist y z) + edist z t : add_le_add_right (edist_triangle x y z) _
/-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/
lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) :
edist (f m) (f n) ≤ ∑ i in finset.Ico m n, edist (f i) (f (i + 1)) :=
begin
revert n,
refine nat.le_induction _ _,
{ simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self],
-- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too.
exact le_refl (0:ℝ≥0∞) },
{ assume n hn hrec,
calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _
... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _)
... = ∑ i in finset.Ico m (n+1), _ :
by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp }
end
/-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/
lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) :
edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) :=
finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n)
/-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced
with an upper estimate. -/
lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n)
{d : ℕ → ℝ≥0∞} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) :
edist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i :=
le_trans (edist_le_Ico_sum_edist f hmn) $
finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2
/-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced
with an upper estimate. -/
lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ)
{d : ℕ → ℝ≥0∞} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) :
edist (f 0) (f n) ≤ ∑ i in finset.range n, d i :=
finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd)
/-- Reformulation of the uniform structure in terms of the extended distance -/
theorem uniformity_pseudoedist :
𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} :=
pseudo_emetric_space.uniformity_edist
theorem uniformity_basis_edist :
(𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) :=
(@uniformity_pseudoedist α _).symm ▸ has_basis_binfi_principal
(λ r hr p hp, ⟨min r p, lt_min hr hp,
λ x hx, lt_of_lt_of_le hx (min_le_left _ _),
λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩)
⟨1, ennreal.zero_lt_one⟩
/-- Characterization of the elements of the uniformity in terms of the extended distance -/
theorem mem_uniformity_edist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) :=
uniformity_basis_edist.mem_uniformity_iff
/-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`,
`uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/
protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) :=
begin
refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases hf ε ε₀ with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ }
end
/-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/
protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) :=
begin
refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases exists_between ε₀ with ⟨ε', hε'⟩,
rcases hf ε' hε'.1 with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ }
end
theorem uniformity_basis_edist_le :
(𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) :=
emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩)
theorem uniformity_basis_edist' (ε' : ℝ≥0∞) (hε' : 0 < ε') :
(𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) :=
emetric.mk_uniformity_basis (λ _, and.left)
(λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in
⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩)
theorem uniformity_basis_edist_le' (ε' : ℝ≥0∞) (hε' : 0 < ε') :
(𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) :=
emetric.mk_uniformity_basis_le (λ _, and.left)
(λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in
⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩)
theorem uniformity_basis_edist_nnreal :
(𝓤 α).has_basis (λ ε : ℝ≥0, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) :=
emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2)
(λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in
⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩)
theorem uniformity_basis_edist_inv_nat :
(𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) :=
emetric.mk_uniformity_basis
(λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n)
(λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩)
theorem uniformity_basis_edist_inv_two_pow :
(𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < 2⁻¹ ^ n}) :=
emetric.mk_uniformity_basis
(λ n _, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _)
(λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_two_pow_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩)
/-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/
theorem edist_mem_uniformity {ε:ℝ≥0∞} (ε0 : 0 < ε) :
{p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α :=
mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩
namespace emetric
theorem uniformity_has_countable_basis : is_countably_generated (𝓤 α) :=
is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩
/-- ε-δ characterization of uniform continuity on a set for pseudoemetric spaces -/
theorem uniform_continuous_on_iff [pseudo_emetric_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b}, a ∈ s → b ∈ s → edist a b < δ → edist (f a) (f b) < ε :=
uniformity_basis_edist.uniform_continuous_on_iff uniformity_basis_edist
/-- ε-δ characterization of uniform continuity on pseudoemetric spaces -/
theorem uniform_continuous_iff [pseudo_emetric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε :=
uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist
/-- ε-δ characterization of uniform embeddings on pseudoemetric spaces -/
theorem uniform_embedding_iff [pseudo_emetric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
/-- If a map between pseudoemetric spaces is a uniform embedding then the edistance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y`. -/
theorem controlled_of_uniform_embedding [pseudo_emetric_space β] {f : α → β} :
uniform_embedding f →
(∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) :=
begin
assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩,
end
/-- ε-δ characterization of Cauchy sequences on pseudoemetric spaces -/
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε :=
by rw ← ne_bot_iff; exact uniformity_basis_edist.cauchy_iff
/-- A very useful criterion to show that a space is complete is to show that all sequences
which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are
converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to
`0`, which makes it possible to use arguments of converging series, while this is impossible
to do in general for arbitrary Cauchy sequences. -/
theorem complete_of_convergent_controlled_sequences (B : ℕ → ℝ≥0∞) (hB : ∀n, 0 < B n)
(H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) →
∃x, tendsto u at_top (𝓝 x)) :
complete_space α :=
uniform_space.complete_of_convergent_controlled_sequences
uniformity_has_countable_basis
(λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H
/-- A sequentially complete pseudoemetric space is complete. -/
theorem complete_of_cauchy_seq_tendsto :
(∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α :=
uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis
/-- Expressing locally uniform convergence on a set using `edist`. -/
lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_locally_uniformly_on F f p s ↔
∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε :=
begin
refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩,
rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩,
rcases H ε εpos x hx with ⟨t, ht, Ht⟩,
exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩
end
/-- Expressing uniform convergence on a set using `edist`. -/
lemma tendsto_uniformly_on_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε :=
begin
refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩,
rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩,
exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx))
end
/-- Expressing locally uniform convergence using `edist`. -/
lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_locally_uniformly F f p ↔
∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε :=
by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff,
mem_univ, forall_const, exists_prop, nhds_within_univ]
/-- Expressing uniform convergence using `edist`. -/
lemma tendsto_uniformly_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε :=
by simp only [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff, mem_univ, forall_const]
end emetric
open emetric
/-- Auxiliary function to replace the uniformity on a pseudoemetric space with
a uniformity which is equal to the original one, but maybe not defeq.
This is useful if one wants to construct a pseudoemetric space with a
specified uniformity. See Note [forgetful inheritance] explaining why having definitionally
the right uniformity is often important.
-/
def pseudo_emetric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_emetric_space α)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
pseudo_emetric_space α :=
{ edist := @edist _ m.to_has_edist,
edist_self := edist_self,
edist_comm := edist_comm,
edist_triangle := edist_triangle,
to_uniform_space := U,
uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist α _) }
/-- The extended pseudometric induced by a function taking values in a pseudoemetric space. -/
def pseudo_emetric_space.induced {α β} (f : α → β)
(m : pseudo_emetric_space β) : pseudo_emetric_space α :=
{ edist := λ x y, edist (f x) (f y),
edist_self := λ x, edist_self _,
edist_comm := λ x y, edist_comm _ _,
edist_triangle := λ x y z, edist_triangle _ _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_edist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)),
refine λ s, mem_comap.trans _,
split; intro H,
{ rcases H with ⟨r, ru, rs⟩,
rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h },
{ rcases H with ⟨ε, ε0, hε⟩,
exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ }
end }
/-- Pseudoemetric space instance on subsets of pseudoemetric spaces -/
instance {α : Type*} {p : α → Prop} [t : pseudo_emetric_space α] :
pseudo_emetric_space (subtype p) := t.induced coe
/-- The extended psuedodistance on a subset of a pseudoemetric space is the restriction of
the original pseudodistance, by definition -/
theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl
/-- The product of two pseudoemetric spaces, with the max distance, is an extended
pseudometric spaces. We make sure that the uniform structure thus constructed is the one
corresponding to the product of uniform spaces, to avoid diamond problems. -/
instance prod.pseudo_emetric_space_max [pseudo_emetric_space β] : pseudo_emetric_space (α × β) :=
{ edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2),
edist_self := λ x, by simp,
edist_comm := λ x y, by simp [edist_comm],
edist_triangle := λ x y z, max_le
(le_trans (edist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _)))
(le_trans (edist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))),
uniformity_edist := begin
refine uniformity_prod.trans _,
simp [pseudo_emetric_space.uniformity_edist, comap_infi],
rw ← infi_inf_eq, congr, funext,
rw ← infi_inf_eq, congr, funext,
simp [inf_principal, ext_iff, max_lt_iff]
end,
to_uniform_space := prod.uniform_space }
lemma prod.edist_eq [pseudo_emetric_space β] (x y : α × β) :
edist x y = max (edist x.1 y.1) (edist x.2 y.2) :=
rfl
section pi
open finset
variables {π : β → Type*} [fintype β]
/-- The product of a finite number of pseudoemetric spaces, with the max distance, is still
a pseudoemetric space.
This construction would also work for infinite products, but it would not give rise
to the product topology. Hence, we only formalize it in the good situation of finitely many
spaces. -/
instance pseudo_emetric_space_pi [∀b, pseudo_emetric_space (π b)] :
pseudo_emetric_space (Πb, π b) :=
{ edist := λ f g, finset.sup univ (λb, edist (f b) (g b)),
edist_self := assume f, bot_unique $ finset.sup_le $ by simp,
edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _,
edist_triangle := assume f g h,
begin
simp only [finset.sup_le_iff],
assume b hb,
exact le_trans (edist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb))
end,
to_uniform_space := Pi.uniform_space _,
uniformity_edist := begin
simp only [Pi.uniformity, pseudo_emetric_space.uniformity_edist, comap_infi, gt_iff_lt,
preimage_set_of_eq, comap_principal],
rw infi_comm, congr, funext ε,
rw infi_comm, congr, funext εpos,
change 0 < ε at εpos,
simp [set.ext_iff, εpos]
end }
lemma edist_pi_def [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) :
edist f g = finset.sup univ (λb, edist (f b) (g b)) := rfl
@[simp]
lemma edist_pi_const [nonempty β] (a b : α) :
edist (λ x : β, a) (λ _, b) = edist a b := finset.sup_const univ_nonempty (edist a b)
lemma edist_le_pi_edist [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) (b : β) :
edist (f b) (g b) ≤ edist f g :=
finset.le_sup (finset.mem_univ b)
lemma edist_pi_le_iff [Π b, pseudo_emetric_space (π b)] {f g : Π b, π b} {d : ℝ≥0∞} :
edist f g ≤ d ↔ ∀ b, edist (f b) (g b) ≤ d :=
finset.sup_le_iff.trans $ by simp only [finset.mem_univ, forall_const]
end pi
namespace emetric
variables {x y z : α} {ε ε₁ ε₂ : ℝ≥0∞} {s : set α}
/-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/
def ball (x : α) (ε : ℝ≥0∞) : set α := {y | edist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl
/-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/
def closed_ball (x : α) (ε : ℝ≥0∞) := {y | edist y x ≤ ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl
@[simp] theorem closed_ball_top (x : α) : closed_ball x ∞ = univ :=
eq_univ_of_forall $ λ y, @le_top _ _ (edist y x)
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y hy, le_of_lt hy
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε :=
lt_of_le_of_lt (zero_le _) hy
theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε :=
show edist x x < ε, by rw edist_self; assumption
theorem mem_closed_ball_self : x ∈ closed_ball x ε :=
show edist x x ≤ ε, by rw edist_self; exact bot_le
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by simp [edist_comm]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩,
not_lt_of_le (edist_triangle_left x y z)
(lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h)
theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y ≠ ∞) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, calc
edist z y ≤ edist z x + edist x y : edist_triangle _ _ _
... = edist x y + edist z x : add_comm _ _
... < edist x y + ε₁ : ennreal.add_lt_add_left h' zx
... ≤ ε₂ : h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
begin
have : 0 < ε - edist y x := by simpa using h,
refine ⟨ε - edist y x, this, ball_subset _ (ne_top_of_lt h)⟩,
rw ennreal.add_sub_cancel_of_le (le_of_lt h),
exact le_refl ε
end
theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 :=
eq_empty_iff_forall_not_mem.trans
⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))),
λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩
/-- Relation “two points are at a finite edistance” is an equivalence relation. -/
def edist_lt_top_setoid : setoid α :=
{ r := λ x y, edist x y < ⊤,
iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top },
λ x y h, by rwa edist_comm,
λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ }
@[simp] lemma ball_zero : ball x 0 = ∅ :=
by rw [emetric.ball_eq_empty_iff]
theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (ball x) :=
nhds_basis_uniformity uniformity_basis_edist
theorem nhds_basis_closed_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (closed_ball x) :=
nhds_basis_uniformity uniformity_basis_edist_le
theorem nhds_eq : 𝓝 x = (⨅ε>0, 𝓟 (ball x ε)) :=
nhds_basis_eball.eq_binfi
theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp [is_open_iff_nhds, mem_nhds_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem is_closed_ball_top : is_closed (ball x ⊤) :=
is_open_compl_iff.1 $ is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $
ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩
theorem ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x :=
is_open_ball.mem_nhds (mem_ball_self ε0)
theorem closed_ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x :=
mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball
theorem ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) :
(ball x r).prod (ball y r) = ball (x, y) r :=
ext $ λ z, max_lt_iff.symm
theorem closed_ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) :
(closed_ball x r).prod (closed_ball y r) = closed_ball (x, y) r :=
ext $ λ z, max_le_iff.symm
/-- ε-characterization of the closure in pseudoemetric spaces -/
theorem mem_closure_iff :
x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε :=
(mem_closure_iff_nhds_basis nhds_basis_eball).trans $
by simp only [mem_ball, edist_comm x]
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε :=
nhds_basis_eball.tendsto_right_iff
theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε :=
(at_top_basis.tendsto_iff nhds_basis_eball).trans $
by simp only [exists_prop, true_and, mem_Ici, mem_ball]
/-- In a pseudoemetric space, Cauchy sequences are characterized by the fact that, eventually,
the pseudoedistance between its elements is arbitrarily small -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε :=
uniformity_basis_edist.cauchy_seq_iff
/-- A variation around the emetric characterization of Cauchy sequences -/
theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ ∀ε>(0 : ℝ≥0∞), ∃N, ∀n≥N, edist (u n) (u N) < ε :=
uniformity_basis_edist.cauchy_seq_iff'
/-- A variation of the emetric characterization of Cauchy sequences that deals with
`ℝ≥0` upper bounds. -/
theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ ∀ ε : ℝ≥0, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε :=
uniformity_basis_edist_nnreal.cauchy_seq_iff'
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (edist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩
theorem totally_bounded_iff' {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru,
⟨t, _, ft, h⟩ := H ε ε0 in
⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩
section first_countable
@[priority 100] -- see Note [lower instance priority]
instance (α : Type u) [pseudo_emetric_space α] :
topological_space.first_countable_topology α :=
uniform_space.first_countable_topology uniformity_has_countable_basis
end first_countable
section compact
/-- For a set `s` in a pseudo emetric space, if for every `ε > 0` there exists a countable
set that is `ε`-dense in `s`, then there exists a countable subset `t ⊆ s` that is dense in `s`. -/
lemma subset_countable_closure_of_almost_dense_set (s : set α)
(hs : ∀ ε > 0, ∃ t : set α, countable t ∧ s ⊆ ⋃ x ∈ t, closed_ball x ε) :
∃ t ⊆ s, (countable t ∧ s ⊆ closure t) :=
begin
rcases s.eq_empty_or_nonempty with rfl|⟨x₀, hx₀⟩,
{ exact ⟨∅, empty_subset _, countable_empty, empty_subset _⟩ },
choose! T hTc hsT using (λ n : ℕ, hs n⁻¹ (by simp)),
have : ∀ r x, ∃ y ∈ s, closed_ball x r ∩ s ⊆ closed_ball y (r * 2),
{ intros r x,
rcases (closed_ball x r ∩ s).eq_empty_or_nonempty with he|⟨y, hxy, hys⟩,
{ refine ⟨x₀, hx₀, _⟩, rw he, exact empty_subset _ },
{ refine ⟨y, hys, λ z hz, _⟩,
calc edist z y ≤ edist z x + edist y x : edist_triangle_right _ _ _
... ≤ r + r : add_le_add hz.1 hxy
... = r * 2 : (mul_two r).symm } },
choose f hfs hf,
refine ⟨⋃ n : ℕ, (f n⁻¹) '' (T n), Union_subset $ λ n, image_subset_iff.2 (λ z hz, hfs _ _),
countable_Union $ λ n, (hTc n).image _, _⟩,
refine λ x hx, mem_closure_iff.2 (λ ε ε0, _),
rcases ennreal.exists_inv_nat_lt (ennreal.half_pos ε0.lt.ne').ne' with ⟨n, hn⟩,
rcases mem_bUnion_iff.1 (hsT n hx) with ⟨y, hyn, hyx⟩,
refine ⟨f n⁻¹ y, mem_Union.2 ⟨n, mem_image_of_mem _ hyn⟩, _⟩,
calc edist x (f n⁻¹ y) ≤ n⁻¹ * 2 : hf _ _ ⟨hyx, hx⟩
... < ε : ennreal.mul_lt_of_lt_div hn
end
/-- A compact set in a pseudo emetric space is separable, i.e., it is a subset of the closure of a
countable set. -/
lemma subset_countable_closure_of_compact {s : set α} (hs : is_compact s) :
∃ t ⊆ s, (countable t ∧ s ⊆ closure t) :=
begin
refine subset_countable_closure_of_almost_dense_set s (λ ε hε, _),
rcases totally_bounded_iff'.1 hs.totally_bounded ε hε with ⟨t, hts, htf, hst⟩,
exact ⟨t, htf.countable,
subset.trans hst (bUnion_subset_bUnion_right $ λ _ _, ball_subset_closed_ball)⟩
end
end compact
section second_countable
open topological_space
variables (α)
/-- A separable pseudoemetric space is second countable: one obtains a countable basis by taking
the balls centered at points in a dense subset, and with rational radii. We do not register
this as an instance, as there is already an instance going in the other direction
from second countable spaces to separable spaces, and we want to avoid loops. -/
lemma second_countable_of_separable [separable_space α] :
second_countable_topology α :=
uniform_space.second_countable_of_separable uniformity_has_countable_basis
/-- A sigma compact pseudo emetric space has second countable topology. This is not an instance
to avoid a loop with `sigma_compact_space_of_locally_compact_second_countable`. -/
lemma second_countable_of_sigma_compact [sigma_compact_space α] :
second_countable_topology α :=
begin
suffices : separable_space α, by exactI second_countable_of_separable α,
choose T hTsub hTc hsubT
using λ n, subset_countable_closure_of_compact (is_compact_compact_covering α n),
refine ⟨⟨⋃ n, T n, countable_Union hTc, λ x, _⟩⟩,
rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩,
exact closure_mono (subset_Union _ n) (hsubT _ hn)
end
variable {α}
lemma second_countable_of_almost_dense_set
(hs : ∀ ε > 0, ∃ t : set α, countable t ∧ (⋃ x ∈ t, closed_ball x ε) = univ) :
second_countable_topology α :=
begin
suffices : separable_space α, by exactI second_countable_of_separable α,
rcases subset_countable_closure_of_almost_dense_set (univ : set α) (λ ε ε0, _)
with ⟨t, -, htc, ht⟩,
{ exact ⟨⟨t, htc, λ x, ht (mem_univ x)⟩⟩ },
{ rcases hs ε ε0 with ⟨t, htc, ht⟩,
exact ⟨t, htc, univ_subset_iff.2 ht⟩ }
end
end second_countable
section diam
/-- The diameter of a set in a pseudoemetric space, named `emetric.diam` -/
def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y
lemma diam_le_iff {d : ℝ≥0∞} :
diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d :=
by simp only [diam, supr_le_iff]
lemma diam_image_le_iff {d : ℝ≥0∞} {f : β → α} {s : set β} :
diam (f '' s) ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist (f x) (f y) ≤ d :=
by simp only [diam_le_iff, ball_image_iff]
lemma edist_le_of_diam_le {d} (hx : x ∈ s) (hy : y ∈ s) (hd : diam s ≤ d) : edist x y ≤ d :=
diam_le_iff.1 hd x hx y hy
/-- If two points belong to some set, their edistance is bounded by the diameter of the set -/
lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s :=
edist_le_of_diam_le hx hy le_rfl
/-- If the distance between any two points in a set is bounded by some constant, this constant
bounds the diameter. -/
lemma diam_le {d : ℝ≥0∞} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff.2 h
/-- The diameter of a subsingleton vanishes. -/
lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 :=
nonpos_iff_eq_zero.1 $ diam_le $
λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_rfl
/-- The diameter of the empty set vanishes -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
diam_subsingleton subsingleton_empty
/-- The diameter of a singleton vanishes -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
diam_subsingleton subsingleton_singleton
lemma diam_Union_mem_option {ι : Type*} (o : option ι) (s : ι → set α) :
diam (⋃ i ∈ o, s i) = ⨆ i ∈ o, diam (s i) :=
by cases o; simp
lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) :=
eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff, ball_insert_iff,
edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and,
forall_and_distrib, and_self, ← and_assoc]
lemma diam_pair : diam ({x, y} : set α) = edist x y :=
by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right]
lemma diam_triple :
diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) :=
by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton,
ennreal.max_zero_right, ennreal.sup_eq_max]
/-- The diameter is monotonous with respect to inclusion -/
lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t :=
diam_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy)
/-- The diameter of a union is controlled by the diameter of the sets, and the edistance
between two points in the sets. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) :
diam (s ∪ t) ≤ diam s + edist x y + diam t :=
begin
have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc
edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _
... ≤ diam s + edist x y + diam t :
add_le_add (add_le_add (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb),
refine diam_le (λa ha b hb, _),
cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b,
{ calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b
... ≤ diam s + (edist x y + diam t) : le_self_add
... = diam s + edist x y + diam t : (add_assoc _ _ _).symm },
{ exact A a h'a b h'b },
{ have Z := A b h'b a h'a, rwa [edist_comm] at Z },
{ calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b
... ≤ (diam s + edist x y) + diam t : le_add_self }
end
lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t :=
let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt
lemma diam_closed_ball {r : ℝ≥0∞} : diam (closed_ball x r) ≤ 2 * r :=
diam_le $ λa ha b hb, calc
edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _
... ≤ r + r : add_le_add ha hb
... = 2 * r : (two_mul r).symm
lemma diam_ball {r : ℝ≥0∞} : diam (ball x r) ≤ 2 * r :=
le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball
lemma diam_pi_le_of_le {π : β → Type*} [fintype β] [∀ b, pseudo_emetric_space (π b)]
{s : Π (b : β), set (π b)} {c : ℝ≥0∞} (h : ∀ b, diam (s b) ≤ c) :
diam (set.pi univ s) ≤ c :=
begin
apply diam_le (λ x hx y hy, edist_pi_le_iff.mpr _),
rw [mem_univ_pi] at hx hy,
exact λ b, diam_le_iff.1 (h b) (x b) (hx b) (y b) (hy b),
end
end diam
end emetric --namespace
/-- We now define `emetric_space`, extending `pseudo_emetric_space`. -/
class emetric_space (α : Type u) extends pseudo_emetric_space α : Type u :=
(eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y)
variables {γ : Type w} [emetric_space γ]
@[priority 100] -- see Note [lower instance priority]
instance emetric_space.to_uniform_space' : uniform_space γ :=
pseudo_emetric_space.to_uniform_space
export emetric_space (eq_of_edist_eq_zero)
/-- Characterize the equality of points by the vanishing of their extended distance -/
@[simp] theorem edist_eq_zero {x y : γ} : edist x y = 0 ↔ x = y :=
iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _)
@[simp] theorem zero_eq_edist {x y : γ} : 0 = edist x y ↔ x = y :=
iff.intro (assume h, eq_of_edist_eq_zero (h.symm))
(assume : x = y, this ▸ (edist_self _).symm)
theorem edist_le_zero {x y : γ} : (edist x y ≤ 0) ↔ x = y :=
nonpos_iff_eq_zero.trans edist_eq_zero
@[simp] theorem edist_pos {x y : γ} : 0 < edist x y ↔ x ≠ y := by simp [← not_le]
/-- Two points coincide if their distance is `< ε` for all positive ε -/
theorem eq_of_forall_edist_le {x y : γ} (h : ∀ε > 0, edist x y ≤ ε) : x = y :=
eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h)
/-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/
theorem uniform_embedding_iff' [emetric_space β] {f : γ → β} :
uniform_embedding f ↔
(∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, edist a b < δ → edist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, edist (f a) (f b) < ε → edist a b < δ) :=
begin
split,
{ assume h,
exact ⟨emetric.uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩ },
{ rintros ⟨h₁, h₂⟩,
refine uniform_embedding_iff.2 ⟨_, emetric.uniform_continuous_iff.2 h₁, h₂⟩,
assume x y hxy,
have : edist x y ≤ 0,
{ refine le_of_forall_lt' (λδ δpos, _),
rcases h₂ δ δpos with ⟨ε, εpos, hε⟩,
have : edist (f x) (f y) < ε, by simpa [hxy],
exact hε this },
simpa using this }
end
/-- An emetric space is separated -/
@[priority 100] -- see Note [lower instance priority]
instance to_separated : separated_space γ :=
separated_def.2 $ λ x y h, eq_of_forall_edist_le $
λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0))
/-- If a `pseudo_emetric_space` is separated, then it is an `emetric_space`. -/
def emetric_of_t2_pseudo_emetric_space {α : Type*} [pseudo_emetric_space α]
(h : separated_space α) : emetric_space α :=
{ eq_of_edist_eq_zero := λ x y hdist,
begin
refine separated_def.1 h x y (λ s hs, _),
obtain ⟨ε, hε, H⟩ := mem_uniformity_edist.1 hs,
exact H (show edist x y < ε, by rwa [hdist])
end
..‹pseudo_emetric_space α› }
/-- Auxiliary function to replace the uniformity on an emetric space with
a uniformity which is equal to the original one, but maybe not defeq.
This is useful if one wants to construct an emetric space with a
specified uniformity. See Note [forgetful inheritance] explaining why having definitionally
the right uniformity is often important.
-/
def emetric_space.replace_uniformity {γ} [U : uniform_space γ] (m : emetric_space γ)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
emetric_space γ :=
{ edist := @edist _ m.to_has_edist,
edist_self := edist_self,
eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _,
edist_comm := edist_comm,
edist_triangle := edist_triangle,
to_uniform_space := U,
uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist γ _) }
/-- The extended metric induced by an injective function taking values in a emetric space. -/
def emetric_space.induced {γ β} (f : γ → β) (hf : function.injective f)
(m : emetric_space β) : emetric_space γ :=
{ edist := λ x y, edist (f x) (f y),
edist_self := λ x, edist_self _,
eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h),
edist_comm := λ x y, edist_comm _ _,
edist_triangle := λ x y z, edist_triangle _ _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_edist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)),
refine λ s, mem_comap.trans _,
split; intro H,
{ rcases H with ⟨r, ru, rs⟩,
rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h },
{ rcases H with ⟨ε, ε0, hε⟩,
exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ }
end }
/-- Emetric space instance on subsets of emetric spaces -/
instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) :=
t.induced coe (λ x y, subtype.ext_iff_val.2)
/-- The product of two emetric spaces, with the max distance, is an extended
metric spaces. We make sure that the uniform structure thus constructed is the one
corresponding to the product of uniform spaces, to avoid diamond problems. -/
instance prod.emetric_space_max [emetric_space β] : emetric_space (γ × β) :=
{ eq_of_edist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
have A : x.fst = y.fst := edist_le_zero.1 h₁,
have B : x.snd = y.snd := edist_le_zero.1 h₂,
exact prod.ext_iff.2 ⟨A, B⟩
end,
..prod.pseudo_emetric_space_max }
/-- Reformulation of the uniform structure in terms of the extended distance -/
theorem uniformity_edist :
𝓤 γ = ⨅ ε>0, 𝓟 {p:γ×γ | edist p.1 p.2 < ε} :=
pseudo_emetric_space.uniformity_edist
section pi
open finset
variables {π : β → Type*} [fintype β]
/-- The product of a finite number of emetric spaces, with the max distance, is still
an emetric space.
This construction would also work for infinite products, but it would not give rise
to the product topology. Hence, we only formalize it in the good situation of finitely many
spaces. -/
instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) :=
{ eq_of_edist_eq_zero := assume f g eq0,
begin
have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0,
simp only [finset.sup_le_iff] at eq1,
exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b),
end,
..pseudo_emetric_space_pi }
end pi
namespace emetric
/-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set. -/
lemma countable_closure_of_compact {s : set γ} (hs : is_compact s) :
∃ t ⊆ s, (countable t ∧ s = closure t) :=
begin
rcases subset_countable_closure_of_compact hs with ⟨t, hts, htc, hsub⟩,
exact ⟨t, hts, htc, subset.antisymm hsub (closure_minimal hts hs.is_closed)⟩
end
section diam
variables {s : set γ}
lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton :=
⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩
lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y :=
begin
have := not_congr (@diam_eq_zero_iff _ _ s),
dunfold set.subsingleton at this,
push_neg at this,
simpa only [pos_iff_ne_zero, exists_prop] using this
end
end diam
end emetric
|
c355681c2ed2274ebce97ddb0ba94a07ac2a9f8b | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/topology/constructions.lean | fb74a51e79daa15767ca62a9bc45e013bd986db9 | [
"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 | 35,743 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import topology.maps
/-!
# Constructions of new topological spaces from old ones
This file constructs products, sums, subtypes and quotients of topological spaces
and sets up their basic theory, such as criteria for maps into or out of these
constructions to be continuous; descriptions of the open sets, neighborhood filters,
and generators of these constructions; and their behavior with respect to embeddings
and other specific classes of maps.
## Implementation note
The constructed topologies are defined using induced and coinduced topologies
along with the complete lattice structure on topologies. Their universal properties
(for example, a map `X → Y × Z` is continuous if and only if both projections
`X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of
continuity. With more work we can also extract descriptions of the open sets,
neighborhood filters and so on.
## Tags
product, sum, disjoint union, subspace, quotient space
-/
noncomputable theory
open topological_space set filter
open_locale classical topological_space filter
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
section constructions
instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) :=
induced coe t
instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) :=
coinduced (quot.mk r) t
instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) :=
coinduced quotient.mk t
instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) :=
induced prod.fst t₁ ⊓ induced prod.snd t₂
instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) :=
coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂
instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) :=
⨆a, coinduced (sigma.mk a) (t₂ a)
instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] :
topological_space (Πa, β a) :=
⨅a, induced (λf, f a) (t₂ a)
instance ulift.topological_space [t : topological_space α] : topological_space (ulift.{v u} α) :=
t.induced ulift.down
/-- The image of a dense set under `quotient.mk` is a dense set. -/
lemma dense.quotient [setoid α] [topological_space α] {s : set α} (H : dense s) :
dense (quotient.mk '' s) :=
(surjective_quotient_mk α).dense_range.dense_image continuous_coinduced_rng H
/-- The composition of `quotient.mk` and a function with dense range has dense range. -/
lemma dense_range.quotient [setoid α] [topological_space α] {f : β → α} (hf : dense_range f) :
dense_range (quotient.mk ∘ f) :=
(surjective_quotient_mk α).dense_range.comp hf continuous_coinduced_rng
instance {p : α → Prop} [topological_space α] [discrete_topology α] :
discrete_topology (subtype p) :=
⟨bot_unique $ assume s hs,
⟨coe '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.coe_injective)⟩⟩
instance sum.discrete_topology [topological_space α] [topological_space β]
[hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) :=
⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩
instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)]
[h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) :=
⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩
section topα
variable [topological_space α]
/-
The 𝓝 filter and the subspace topology.
-/
theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) :
t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 (a : α), coe ⁻¹' u ⊆ t :=
mem_nhds_induced coe a t
theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) :
𝓝 a = comap coe (𝓝 (a : α)) :=
nhds_induced coe a
end topα
end constructions
section prod
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
@[continuity] lemma continuous_fst : continuous (@prod.fst α β) :=
continuous_inf_dom_left continuous_induced_dom
lemma continuous_at_fst {p : α × β} : continuous_at prod.fst p :=
continuous_fst.continuous_at
@[continuity] lemma continuous_snd : continuous (@prod.snd α β) :=
continuous_inf_dom_right continuous_induced_dom
lemma continuous_at_snd {p : α × β} : continuous_at prod.snd p :=
continuous_snd.continuous_at
@[continuity] lemma continuous.prod_mk {f : γ → α} {g : γ → β}
(hf : continuous f) (hg : continuous g) : continuous (λx, (f x, g x)) :=
continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg)
lemma continuous.prod_map {f : γ → α} {g : δ → β} (hf : continuous f) (hg : continuous g) :
continuous (λ x : γ × δ, (f x.1, g x.2)) :=
(hf.comp continuous_fst).prod_mk (hg.comp continuous_snd)
lemma filter.eventually.prod_inl_nhds {p : α → Prop} {a : α} (h : ∀ᶠ x in 𝓝 a, p x) (b : β) :
∀ᶠ x in 𝓝 (a, b), p (x : α × β).1 :=
continuous_at_fst h
lemma filter.eventually.prod_inr_nhds {p : β → Prop} {b : β} (h : ∀ᶠ x in 𝓝 b, p x) (a : α) :
∀ᶠ x in 𝓝 (a, b), p (x : α × β).2 :=
continuous_at_snd h
lemma filter.eventually.prod_mk_nhds {pa : α → Prop} {a} (ha : ∀ᶠ x in 𝓝 a, pa x)
{pb : β → Prop} {b} (hb : ∀ᶠ y in 𝓝 b, pb y) :
∀ᶠ p in 𝓝 (a, b), pa (p : α × β).1 ∧ pb p.2 :=
(ha.prod_inl_nhds b).and (hb.prod_inr_nhds a)
lemma continuous_swap : continuous (prod.swap : α × β → β × α) :=
continuous.prod_mk continuous_snd continuous_fst
lemma continuous_uncurry_left {f : α → β → γ} (a : α)
(h : continuous (function.uncurry f)) : continuous (f a) :=
show continuous (function.uncurry f ∘ (λ b, (a, b))), from h.comp (by continuity)
lemma continuous_uncurry_right {f : α → β → γ} (b : β)
(h : continuous (function.uncurry f)) : continuous (λ a, f a b) :=
show continuous (function.uncurry f ∘ (λ a, (a, b))), from h.comp (by continuity)
lemma continuous_curry {g : α × β → γ} (a : α)
(h : continuous g) : continuous (function.curry g a) :=
show continuous (g ∘ (λ b, (a, b))), from h.comp (by continuity)
lemma is_open.prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) :
is_open (set.prod s t) :=
is_open_inter (hs.preimage continuous_fst) (ht.preimage continuous_snd)
lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = 𝓝 a ×ᶠ 𝓝 b :=
by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced]
lemma mem_nhds_prod_iff {a : α} {b : β} {s : set (α × β)} :
s ∈ 𝓝 (a, b) ↔ ∃ (u ∈ 𝓝 a) (v ∈ 𝓝 b), set.prod u v ⊆ s :=
by rw [nhds_prod_eq, mem_prod_iff]
lemma filter.has_basis.prod_nhds {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop}
{sa : ιa → set α} {sb : ιb → set β} {a : α} {b : β} (ha : (𝓝 a).has_basis pa sa)
(hb : (𝓝 b).has_basis pb sb) :
(𝓝 (a, b)).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) :=
by { rw nhds_prod_eq, exact ha.prod hb }
instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) :=
⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩,
by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩
lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β}
(ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : set.prod s t ∈ 𝓝 (a, b) :=
by rw [nhds_prod_eq]; exact prod_mem_prod ha hb
lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap :=
by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl
lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β}
(ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) :
tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) :=
by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb
lemma filter.eventually.curry_nhds {p : α × β → Prop} {x : α} {y : β} (h : ∀ᶠ x in 𝓝 (x, y), p x) :
∀ᶠ x' in 𝓝 x, ∀ᶠ y' in 𝓝 y, p (x', y') :=
by { rw [nhds_prod_eq] at h, exact h.curry }
lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α}
(hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x :=
hf.prod_mk_nhds hg
lemma continuous_at.prod_map {f : α → γ} {g : β → δ} {p : α × β}
(hf : continuous_at f p.fst) (hg : continuous_at g p.snd) :
continuous_at (λ p : α × β, (f p.1, g p.2)) p :=
(hf.comp continuous_fst.continuous_at).prod (hg.comp continuous_snd.continuous_at)
lemma continuous_at.prod_map' {f : α → γ} {g : β → δ} {x : α} {y : β}
(hf : continuous_at f x) (hg : continuous_at g y) :
continuous_at (λ p : α × β, (f p.1, g p.2)) (x, y) :=
have hf : continuous_at f (x, y).fst, from hf,
have hg : continuous_at g (x, y).snd, from hg,
hf.prod_map hg
lemma prod_generate_from_generate_from_eq {α β : Type*} {s : set (set α)} {t : set (set β)}
(hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) :
@prod.topological_space α β (generate_from s) (generate_from t) =
generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} :=
let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in
le_antisymm
(le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸
@is_open.prod _ _ (generate_from s) (generate_from t) _ _
(generate_open.basic _ hu) (generate_open.basic _ hv))
(le_inf
(coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu,
have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u,
from calc (⋃v∈t, set.prod u v) = set.prod u univ :
set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt}
... = prod.fst ⁻¹' u : by simp [set.prod, preimage],
show G.is_open (prod.fst ⁻¹' u),
from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv,
generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)
(coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv,
have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v,
from calc (⋃u∈s, set.prod u v) = set.prod univ v:
set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt}
... = prod.snd ⁻¹' v : by simp [set.prod, preimage],
show G.is_open (prod.snd ⁻¹' v),
from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu,
generate_open.basic _ ⟨_, hu, _, hv, rfl⟩))
lemma prod_eq_generate_from :
prod.topological_space =
generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} :=
le_antisymm
(le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ hs.prod ht)
(le_inf
(ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩)
(ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩))
lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔
(∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) :=
begin
rw [is_open_iff_nhds],
simp_rw [le_principal_iff, prod.forall,
((nhds_basis_opens _).prod_nhds (nhds_basis_opens _)).mem_iff, prod.exists, exists_prop],
simp only [and_assoc, and.left_comm]
end
lemma continuous_uncurry_of_discrete_topology_left [discrete_topology α]
{f : α → β → γ} (h : ∀ a, continuous (f a)) : continuous (function.uncurry f) :=
continuous_iff_continuous_at.2 $ λ ⟨a, b⟩,
by simp only [continuous_at, nhds_prod_eq, nhds_discrete α, pure_prod, tendsto_map'_iff, (∘),
function.uncurry, (h a).tendsto]
/-- Given a neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood
that is a subset of `s`. -/
lemma exists_nhds_square {s : set (α × α)} {x : α} (hx : s ∈ 𝓝 (x, x)) :
∃U, is_open U ∧ x ∈ U ∧ set.prod U U ⊆ s :=
by simpa [nhds_prod_eq, (nhds_basis_opens x).prod_self.mem_iff, and.assoc, and.left_comm] using hx
/-- The first projection in a product of topological spaces sends open sets to open sets. -/
lemma is_open_map_fst : is_open_map (@prod.fst α β) :=
begin
rw is_open_map_iff_nhds_le,
rintro ⟨x, y⟩ s hs,
rcases mem_nhds_prod_iff.1 hs with ⟨tx, htx, ty, hty, ht⟩,
simp only [subset_def, prod.forall, mem_prod] at ht,
exact mem_sets_of_superset htx (λ x hx, ht x y ⟨hx, mem_of_nhds hty⟩)
end
/-- The second projection in a product of topological spaces sends open sets to open sets. -/
lemma is_open_map_snd : is_open_map (@prod.snd α β) :=
begin
/- This lemma could be proved by composing the fact that the first projection is open, and
exchanging coordinates is a homeomorphism, hence open. As the `prod_comm` homeomorphism is defined
later, we rather go for the direct proof, copy-pasting the proof for the first projection. -/
rw is_open_map_iff_nhds_le,
rintro ⟨x, y⟩ s hs,
rcases mem_nhds_prod_iff.1 hs with ⟨tx, htx, ty, hty, ht⟩,
simp only [subset_def, prod.forall, mem_prod] at ht,
exact mem_sets_of_superset hty (λ y hy, ht x y ⟨mem_of_nhds htx, hy⟩)
end
/-- A product set is open in a product space if and only if each factor is open, or one of them is
empty -/
lemma is_open_prod_iff' {s : set α} {t : set β} :
is_open (set.prod s t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) :=
begin
cases (set.prod s t).eq_empty_or_nonempty with h h,
{ simp [h, prod_eq_empty_iff.1 h] },
{ have st : s.nonempty ∧ t.nonempty, from prod_nonempty_iff.1 h,
split,
{ assume H : is_open (set.prod s t),
refine or.inl ⟨_, _⟩,
show is_open s,
{ rw ← fst_image_prod s st.2,
exact is_open_map_fst _ H },
show is_open t,
{ rw ← snd_image_prod st.1 t,
exact is_open_map_snd _ H } },
{ assume H,
simp only [st.1.ne_empty, st.2.ne_empty, not_false_iff, or_false] at H,
exact H.1.prod H.2 } }
end
lemma closure_prod_eq {s : set α} {t : set β} :
closure (set.prod s t) = set.prod (closure s) (closure t) :=
set.ext $ assume ⟨a, b⟩,
have (𝓝 a ×ᶠ 𝓝 b) ⊓ 𝓟 (set.prod s t) = (𝓝 a ⊓ 𝓟 s) ×ᶠ (𝓝 b ⊓ 𝓟 t),
by rw [←prod_inf_prod, prod_principal_principal],
by simp [closure_eq_cluster_pts, cluster_pt, nhds_prod_eq, this]; exact prod_ne_bot
lemma map_mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β}
(hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t)
(hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) :
f a b ∈ closure u :=
have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩,
show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from
map_mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb
lemma is_closed.prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) :
is_closed (set.prod s₁ s₂) :=
closure_eq_iff_is_closed.mp $ by simp only [h₁.closure_eq, h₂.closure_eq, closure_prod_eq]
/-- The product of two dense sets is a dense set. -/
lemma dense.prod {s : set α} {t : set β} (hs : dense s) (ht : dense t) :
dense (s.prod t) :=
λ x, by { rw closure_prod_eq, exact ⟨hs x.1, ht x.2⟩ }
/-- If `f` and `g` are maps with dense range, then `prod.map f g` has dense range. -/
lemma dense_range.prod_map {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ}
(hf : dense_range f) (hg : dense_range g) : dense_range (prod.map f g) :=
by simpa only [dense_range, prod_range_range_eq] using hf.prod hg
lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) :
inducing (λx:α×γ, (f x.1, g x.2)) :=
⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced,
induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩
lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) :
embedding (λx:α×γ, (f x.1, g x.2)) :=
{ inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩,
..hf.to_inducing.prod_mk hg.to_inducing }
protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) :
is_open_map (λ p : α × γ, (f p.1, g p.2)) :=
begin
rw [is_open_map_iff_nhds_le],
rintros ⟨a, b⟩,
rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq],
exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b)
end
protected lemma open_embedding.prod {f : α → β} {g : γ → δ}
(hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) :=
open_embedding_of_embedding_open (hf.1.prod_mk hg.1)
(hf.is_open_map.prod hg.is_open_map)
lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) :=
embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id
end prod
section sum
open sum
variables [topological_space α] [topological_space β] [topological_space γ]
@[continuity] lemma continuous_inl : continuous (@inl α β) :=
continuous_sup_rng_left continuous_coinduced_rng
@[continuity] lemma continuous_inr : continuous (@inr α β) :=
continuous_sup_rng_right continuous_coinduced_rng
@[continuity] lemma continuous_sum_rec {f : α → γ} {g : β → γ}
(hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) :=
begin
apply continuous_sup_dom;
rw continuous_def at hf hg ⊢;
assumption
end
lemma is_open_sum_iff {s : set (α ⊕ β)} :
is_open s ↔ is_open (inl ⁻¹' s) ∧ is_open (inr ⁻¹' s) :=
iff.rfl
lemma is_open_map_sum {f : α ⊕ β → γ}
(h₁ : is_open_map (λ a, f (inl a))) (h₂ : is_open_map (λ b, f (inr b))) :
is_open_map f :=
begin
intros u hu,
rw is_open_sum_iff at hu,
cases hu with hu₁ hu₂,
have : u = inl '' (inl ⁻¹' u) ∪ inr '' (inr ⁻¹' u),
{ ext (_|_); simp },
rw [this, set.image_union, set.image_image, set.image_image],
exact is_open_union (h₁ _ hu₁) (h₂ _ hu₂)
end
lemma embedding_inl : embedding (@inl α β) :=
{ induced := begin
unfold sum.topological_space,
apply le_antisymm,
{ rw ← coinduced_le_iff_le_induced, exact le_sup_left },
{ intros u hu, existsi (inl '' u),
change
(is_open (inl ⁻¹' (@inl α β '' u)) ∧
is_open (inr ⁻¹' (@inl α β '' u))) ∧
inl ⁻¹' (inl '' u) = u,
have : inl ⁻¹' (@inl α β '' u) = u :=
preimage_image_eq u (λ _ _, inl.inj_iff.mp), rw this,
have : inr ⁻¹' (@inl α β '' u) = ∅ :=
eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, inl_ne_inr h), rw this,
exact ⟨⟨hu, is_open_empty⟩, rfl⟩ }
end,
inj := λ _ _, inl.inj_iff.mp }
lemma embedding_inr : embedding (@inr α β) :=
{ induced := begin
unfold sum.topological_space,
apply le_antisymm,
{ rw ← coinduced_le_iff_le_induced, exact le_sup_right },
{ intros u hu, existsi (inr '' u),
change
(is_open (inl ⁻¹' (@inr α β '' u)) ∧
is_open (inr ⁻¹' (@inr α β '' u))) ∧
inr ⁻¹' (inr '' u) = u,
have : inl ⁻¹' (@inr α β '' u) = ∅ :=
eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, inr_ne_inl h), rw this,
have : inr ⁻¹' (@inr α β '' u) = u :=
preimage_image_eq u (λ _ _, inr.inj_iff.mp), rw this,
exact ⟨⟨is_open_empty, hu⟩, rfl⟩ }
end,
inj := λ _ _, inr.inj_iff.mp }
lemma is_open_range_inl : is_open (range (inl : α → α ⊕ β)) :=
is_open_sum_iff.2 $ by simp
lemma is_open_range_inr : is_open (range (inr : β → α ⊕ β)) :=
is_open_sum_iff.2 $ by simp
lemma open_embedding_inl : open_embedding (inl : α → α ⊕ β) :=
{ open_range := is_open_range_inl,
.. embedding_inl }
lemma open_embedding_inr : open_embedding (inr : β → α ⊕ β) :=
{ open_range := is_open_range_inr,
.. embedding_inr }
end sum
section subtype
variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop}
lemma embedding_subtype_coe : embedding (coe : subtype p → α) :=
⟨⟨rfl⟩, subtype.coe_injective⟩
@[continuity] lemma continuous_subtype_val : continuous (@subtype.val α p) :=
continuous_induced_dom
lemma continuous_subtype_coe : continuous (coe : subtype p → α) :=
continuous_subtype_val
lemma is_open.open_embedding_subtype_coe {s : set α} (hs : is_open s) :
open_embedding (coe : s → α) :=
{ induced := rfl,
inj := subtype.coe_injective,
open_range := (subtype.range_coe : range coe = s).symm ▸ hs }
lemma is_open.is_open_map_subtype_coe {s : set α} (hs : is_open s) :
is_open_map (coe : s → α) :=
hs.open_embedding_subtype_coe.is_open_map
lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) :
is_open_map (s.restrict f) :=
hf.comp hs.is_open_map_subtype_coe
lemma is_closed.closed_embedding_subtype_coe {s : set α} (hs : is_closed s) :
closed_embedding (coe : {x // x ∈ s} → α) :=
{ induced := rfl,
inj := subtype.coe_injective,
closed_range := (subtype.range_coe : range coe = s).symm ▸ hs }
@[continuity] lemma continuous_subtype_mk {f : β → α}
(hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) :=
continuous_induced_rng h
lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) :=
continuous_subtype_mk _ continuous_subtype_coe
lemma continuous_at_subtype_coe {p : α → Prop} {a : subtype p} :
continuous_at (coe : subtype p → α) a :=
continuous_iff_continuous_at.mp continuous_subtype_coe _
lemma map_nhds_subtype_coe_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) :
map (coe : subtype p → α) (𝓝 ⟨a, ha⟩) = 𝓝 a :=
map_nhds_induced_eq $ by simpa only [subtype.coe_mk, subtype.range_coe] using h
lemma nhds_subtype_eq_comap {a : α} {h : p a} :
𝓝 (⟨a, h⟩ : subtype p) = comap coe (𝓝 a) :=
nhds_induced _ _
lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} :
∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, (f x : α)) b (𝓝 (a : α))
| ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff, subtype.coe_mk]
lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop}
(c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x)
(f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) :
continuous f :=
continuous_iff_continuous_at.mpr $ assume x,
let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in
let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in
calc map f (𝓝 x) = map f (map coe (𝓝 x')) :
congr_arg (map f) (map_nhds_subtype_coe_eq _ $ c_sets).symm
... = map (λx:subtype (c i), f x) (𝓝 x') : rfl
... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x'
lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop)
(h_lf : locally_finite (λi, {x | c i x}))
(h_is_closed : ∀i, is_closed {x | c i x})
(h_cover : ∀x, ∃i, c i x)
(f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) :
continuous f :=
continuous_iff_is_closed.mpr $
assume s hs,
have ∀i, is_closed ((coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)),
from assume i,
embedding_is_closed embedding_subtype_coe
(by simp [subtype.range_coe]; exact h_is_closed i)
(continuous_iff_is_closed.mp (f_cont i) _ hs),
have is_closed (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)),
from is_closed_Union_of_locally_finite
(locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx')
this,
have f ⁻¹' s = (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)),
begin
apply set.ext,
have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s :=
λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩,
λ ⟨i, hi, hx⟩, hx⟩,
simpa [and.comm, @and.left_comm (c _ _), ← exists_and_distrib_right],
end,
by rwa [this]
lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}:
x ∈ closure s ↔ (x : α) ∈ closure ((coe : _ → α) '' s) :=
closure_induced $ assume x y, subtype.eq
end subtype
section quotient
variables [topological_space α] [topological_space β] [topological_space γ]
variables {r : α → α → Prop} {s : setoid α}
lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) :=
⟨quot.exists_rep, rfl⟩
@[continuity] lemma continuous_quot_mk : continuous (@quot.mk α r) :=
continuous_coinduced_rng
@[continuity] lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b)
(h : continuous f) : continuous (quot.lift f hr : quot r → β) :=
continuous_coinduced_dom h
lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) :=
quotient_map_quot_mk
lemma continuous_quotient_mk : continuous (@quotient.mk α s) :=
continuous_coinduced_rng
lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b)
(h : continuous f) : continuous (quotient.lift f hs : quotient s → β) :=
continuous_coinduced_dom h
end quotient
section pi
variables {ι : Type*} {π : ι → Type*}
@[continuity]
lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i}
(h : ∀i, continuous (λa, f a i)) : continuous f :=
continuous_infi_rng $ assume i, continuous_induced_rng $ h i
@[continuity]
lemma continuous_apply [∀i, topological_space (π i)] (i : ι) :
continuous (λp:Πi, π i, p i) :=
continuous_infi_dom continuous_induced_dom
/-- Embedding a factor into a product space (by fixing arbitrarily all the other coordinates) is
continuous. -/
@[continuity]
lemma continuous_update [decidable_eq ι] [∀i, topological_space (π i)] {i : ι} {f : Πi:ι, π i} :
continuous (λ x : π i, function.update f i x) :=
begin
refine continuous_pi (λj, _),
by_cases h : j = i,
{ rw h,
simpa using continuous_id },
{ simpa [h] using continuous_const }
end
lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} :
𝓝 a = (⨅i, comap (λx, x i) (𝓝 (a i))) :=
calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi
... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced]
lemma tendsto_pi [t : ∀i, topological_space (π i)] {f : α → Πi, π i} {g : Πi, π i} {u : filter α} :
tendsto f u (𝓝 g) ↔ ∀ x, tendsto (λ i, f i x) u (𝓝 (g x)) :=
by simp [nhds_pi, filter.tendsto_comap_iff]
lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)}
(hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) :=
by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, (hs _ ha).preimage (continuous_apply _))
lemma set_pi_mem_nhds [Π a, topological_space (π a)] {i : set ι} {s : Π a, set (π a)}
{x : Π a, π a} (hi : finite i) (hs : ∀ a ∈ i, s a ∈ 𝓝 (x a)) :
pi i s ∈ 𝓝 x :=
by { rw [pi_def, bInter_mem_sets hi], exact λ a ha, (continuous_apply a).continuous_at (hs a ha) }
lemma pi_eq_generate_from [∀a, topological_space (π a)] :
Pi.topological_space =
generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} :=
le_antisymm
(le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi)
(le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $
⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩)
lemma pi_generate_from_eq {g : Πa, set (set (π a))} :
@Pi.topological_space ι π (λa, generate_from (g a)) =
generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} :=
let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in
begin
rw [pi_eq_generate_from],
refine le_antisymm (generate_from_mono _) (le_generate_from _),
exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩,
{ rintros s ⟨t, i, hi, rfl⟩,
rw [pi_def],
apply is_open_bInter (finset.finite_to_set _),
assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a),
refine le_generate_from _ _ (hi a ha),
exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ }
end
lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) :
@Pi.topological_space ι π (λa, generate_from (g a)) =
generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} :=
begin
rw [pi_generate_from_eq],
refine le_antisymm (generate_from_mono _) (le_generate_from _),
exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩,
{ rintros s ⟨t, i, ht, rfl⟩,
apply is_open_iff_forall_mem_open.2 _,
assume f hf,
choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s,
{ assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa },
refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩,
{ simp [pi_if] },
{ refine generate_open.basic _ ⟨_, assume a, _, rfl⟩,
by_cases a ∈ i; simp [*, pi] at * },
{ have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * },
simpa [pi_if, hf] } }
end
end pi
section sigma
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
@[continuity]
lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) :=
continuous_supr_rng continuous_coinduced_rng
lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) :=
by simp only [is_open_supr_iff, is_open_coinduced]
lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) :=
is_open_sigma_iff
lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) :=
begin
intros s hs,
rw is_open_sigma_iff,
intro j,
classical,
by_cases h : i = j,
{ subst j,
convert hs,
exact set.preimage_image_eq _ sigma_mk_injective },
{ convert is_open_empty,
apply set.eq_empty_of_subset_empty,
rintro x ⟨y, _, hy⟩,
have : i = j, by cc,
contradiction }
end
lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) :=
by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ }
lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) :=
begin
intros s hs,
rw is_closed_sigma_iff,
intro j,
classical,
by_cases h : i = j,
{ subst j,
convert hs,
exact set.preimage_image_eq _ sigma_mk_injective },
{ convert is_closed_empty,
apply set.eq_empty_of_subset_empty,
rintro x ⟨y, _, hy⟩,
have : i = j, by cc,
contradiction }
end
lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) :=
by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ }
lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) :=
open_embedding_of_continuous_injective_open
continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk
lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) :=
closed_embedding_of_continuous_injective_closed
continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk
lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) :=
closed_embedding_sigma_mk.1
/-- A map out of a sum type is continuous if its restriction to each summand is. -/
@[continuity]
lemma continuous_sigma [topological_space β] {f : sigma σ → β}
(h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f :=
continuous_supr_dom (λ i, continuous_coinduced_dom (h i))
@[continuity]
lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)]
{f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) :
continuous (sigma.map f₁ f₂) :=
continuous_sigma $ λ i,
show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)),
from continuous_sigma_mk.comp (hf i)
lemma is_open_map_sigma [topological_space β] {f : sigma σ → β}
(h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f :=
begin
intros s hs,
rw is_open_sigma_iff at hs,
have : s = ⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s),
{ rw Union_image_preimage_sigma_mk_eq_self },
rw this,
rw [image_Union],
apply is_open_Union,
intro i,
rw [image_image],
exact h i _ (hs i)
end
/-- The sum of embeddings is an embedding. -/
lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)]
{f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) :=
begin
refine ⟨⟨_⟩, function.injective_id.sigma_map (λ i, (hf i).inj)⟩,
refine le_antisymm
(continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _,
intros s hs,
replace hs := is_open_sigma_iff.mp hs,
have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s,
{ intro i,
apply is_open_induced_iff.mp,
convert hs i,
exact (hf i).induced.symm },
choose t ht using this,
apply is_open_induced_iff.mpr,
refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩,
ext ⟨i, x⟩,
change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s,
rw [←(ht i).2, mem_Union],
split,
{ rintro ⟨j, hj⟩,
rw mem_image at hj,
rcases hj with ⟨y, hy₁, hy₂⟩,
rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩,
replace hy := eq_of_heq hy,
subst y,
exact hy₁ },
{ intro hx,
use i,
rw mem_image,
exact ⟨f i x, hx, rfl⟩ }
end
end sigma
section ulift
@[continuity] lemma continuous_ulift_down [topological_space α] :
continuous (ulift.down : ulift.{v u} α → α) :=
continuous_induced_dom
@[continuity] lemma continuous_ulift_up [topological_space α] :
continuous (ulift.up : α → ulift.{v u} α) :=
continuous_induced_rng continuous_id
end ulift
lemma mem_closure_of_continuous [topological_space α] [topological_space β]
{f : α → β} {a : α} {s : set α} {t : set β}
(hf : continuous f) (ha : a ∈ closure s) (h : maps_to f s (closure t)) :
f a ∈ closure t :=
calc f a ∈ f '' closure s : mem_image_of_mem _ ha
... ⊆ closure (f '' s) : image_closure_subset_closure_image hf
... ⊆ closure t : closure_minimal h.image_subset is_closed_closure
lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ]
{f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ}
(hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t)
(h : ∀a∈s, ∀b∈t, f a b ∈ closure u) :
f a b ∈ closure u :=
have (a,b) ∈ closure (set.prod s t),
by simp [closure_prod_eq, ha, hb],
show f (a, b).1 (a, b).2 ∈ closure u,
from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $
assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
|
ae861911f5c70945ebc0bd9e763198e7512c10c1 | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2020/problem_sheets/sheet4.lean | eaeb4b64db5edb30dfff9cb88b2a7fc0336f7e9a | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 4,581 | lean | /- Math40001 : Introduction to university mathematics.
Problem Sheet 4, 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 -- the real numbers
/- Question 1.
For each of the sets~$X$ and binary relations~$R$ below, figure out whether~$R$ is (a) reflexive, (b) symmetric, (c) antisymmetric, (d) transitive.
\begin{enumerate}
\item Let $X$ be the set $\{1,2\}$ and define~$R$ like this: $R(1,1)$ is true, $R(1,2)$ is true, $R(2,1)$ is true and $R(2,2)$ is false.
\item Let~$X=\R$ and define $R(a,b)$ to be the proposition $a=-b$.
\item Let~$X=\R$ and define $R(a,b)$ to be false for all real numbers~$a$ and~$b$.
\item Let~$X$ be the empty set and define~$R$ to be the empty binary relation (we don't have to say what its value is on any pair $(a,b)$ because no such pairs exist).
\end{enumerate}
-/
namespace Q1a
inductive X : Type
| one : X
| two : X
namespace X
def R : X → X → Prop
| one one := true
| one two := true
| two one := true
| two two := false
-- insert "¬" if you think it's not reflexive
lemma Q1a_refl : reflexive R :=
begin
sorry
end
-- insert "¬" if you think it's not symmetric
lemma Q1a_symm : symmetric R :=
begin
sorry
end
-- insert "¬" if you think it's not transitive
lemma Q1a_trans : transitive R :=
begin
sorry
end
-- insert "¬" if you think it's not an equiv reln
lemma Q1a_equiv : equivalence R :=
begin
sorry
end
end X
end Q1a
namespace Q1b
def R (a b : ℝ) : Prop := a = -b
-- insert "¬" if you think it's not reflexive
lemma Q1b_refl : reflexive R :=
begin
sorry
end
-- insert "¬" if you think it's not symmetric
lemma Q1b_symm : symmetric R :=
begin
sorry
end
-- insert "¬" if you think it's not transitive
lemma Q1b_trans : transitive R :=
begin
sorry
end
-- insert "¬" if you think it's not an equiv reln
lemma Q1b_equiv : equivalence R :=
begin
sorry
end
end Q1b
namespace Q1c
def R (a b : ℝ) : Prop := false
-- insert "¬" if you think it's not reflexive
lemma Q1c_refl : reflexive R :=
begin
sorry
end
-- insert "¬" if you think it's not symmetric
lemma Q1c_symm : symmetric R :=
begin
sorry
end
-- insert "¬" if you think it's not transitive
lemma Q1c_trans : transitive R :=
begin
sorry
end
-- insert "¬" if you think it's not an equiv reln
lemma Q1c_equiv : equivalence R :=
begin
sorry
end
end Q1c
namespace Q1d
def R (a b : empty) : Prop := by cases a -- i.e. "I'll define it in all cases -- oh look there are no cases"
-- insert "¬" if you think it's not reflexive
lemma Q1d_refl : reflexive R :=
begin
sorry
end
-- insert "¬" if you think it's not symmetric
lemma Q1d_symm : symmetric R :=
begin
sorry
end
-- insert "¬" if you think it's not transitive
lemma Q1d_trans : transitive R :=
begin
sorry
end
-- insert "¬" if you think it's not an equiv reln
lemma Q1d_equiv : equivalence R :=
begin
sorry
end
end Q1d
-- `set ℤ` is the type of subsets of the integers.
def Q2a : partial_order (set ℤ) :=
{ le := λ A B, A ⊆ B,
le_refl := begin sorry end,
le_antisymm := begin sorry end,
le_trans := begin sorry end
}
-- insert ¬ at the beginning if you think it's wrong
lemma Q2b : is_total (set ℤ) (λ A B, A ⊆ B) :=
begin
sorry
end
-- put ¬ in front if you think it's wrong
lemma Q3a : symmetric (λ a b : ℝ, a < b) :=
begin
sorry
end
-- put ¬ in front if you think it's wrong
lemma Q3b : symmetric (λ a b : (∅ : set ℝ), a < b) :=
begin
sorry
end
-- type in the proof in the question. Where do you get stuck?
lemma Q4 (X : Type) (R : X → (X → Prop)) (hs : symmetric R) (ht : transitive R) : reflexive R :=
begin
sorry
end
open function
definition pals {X Y Z : Type} (f : X → Y) (g : X → Z) := ∃ h : Y → Z, bijective h ∧ g = h ∘ f
lemma Q5 (X Y Z: Type) (f : X → Y) (g : X → Z) (hf : surjective f) (hg : surjective g) : pals f g ↔ ∀ a b : X, (f a = f b) ↔ (g a = g b) :=
begin
sorry
end
|
0110b0db1bb622d82b2616cd207117565d605dc4 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /hott/types/fin.hlean | 595cf985cf6fe6b1be3c0f83f158fa6e7dc0ee6d | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 21,033 | hlean | /-
Copyright (c) 2015 Haitao Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Haitao Zhang, Leonardo de Moura, Jakob von Raumer
Finite ordinal types.
-/
import types.list algebra.group function logic types.prod types.sum types.nat.div
open eq nat function list equiv is_trunc algebra sigma sum
structure fin (n : nat) := (val : nat) (is_lt : val < n)
definition less_than [reducible] := fin
namespace fin
attribute fin.val [coercion]
section def_equal
variable {n : nat}
definition sigma_char : fin n ≃ Σ (val : nat), val < n :=
begin
fapply equiv.MK,
intro i, cases i with i ilt, apply dpair i ilt,
intro s, cases s with i ilt, apply fin.mk i ilt,
intro s, cases s with i ilt, reflexivity,
intro i, cases i with i ilt, reflexivity
end
definition is_set_fin [instance] : is_set (fin n) :=
begin
apply is_trunc_equiv_closed, apply equiv.symm, apply sigma_char,
end
definition eq_of_veq : Π {i j : fin n}, (val i) = j → i = j :=
begin
intro i j, cases i with i ilt, cases j with j jlt, esimp,
intro p, induction p, apply ap (mk i), apply !is_prop.elim
end
definition eq_of_veq_refl (i : fin n) : eq_of_veq (refl (val i)) = idp :=
!is_prop.elim
definition veq_of_eq : Π {i j : fin n}, i = j → (val i) = j :=
by intro i j P; apply ap val; exact P
definition eq_iff_veq {i j : fin n} : (val i) = j ↔ i = j :=
pair eq_of_veq veq_of_eq
definition val_inj := @eq_of_veq n
end def_equal
section decidable
open decidable
protected definition has_decidable_eq [instance] (n : nat) :
Π (i j : fin n), decidable (i = j) :=
begin
intros i j, apply decidable_of_decidable_of_iff,
apply nat.has_decidable_eq i j, apply eq_iff_veq,
end
end decidable
/-lemma dinj_lt (n : nat) : dinj (λ i, i < n) fin.mk :=
take a1 a2 Pa1 Pa2 Pmkeq, fin.no_confusion Pmkeq (λ Pe Pqe, Pe)
lemma val_mk (n i : nat) (Plt : i < n) : fin.val (fin.mk i Plt) = i := rfl
definition upto [reducible] (n : nat) : list (fin n) :=
dmap (λ i, i < n) fin.mk (list.upto n)
lemma nodup_upto (n : nat) : nodup (upto n) :=
dmap_nodup_of_dinj (dinj_lt n) (list.nodup_upto n)
lemma mem_upto (n : nat) : Π (i : fin n), i ∈ upto n :=
take i, fin.destruct i
(take ival Piltn,
have ival ∈ list.upto n, from mem_upto_of_lt Piltn,
mem_dmap Piltn this)
lemma upto_zero : upto 0 = [] :=
by rewrite [↑upto, list.upto_nil, dmap_nil]
lemma map_val_upto (n : nat) : map fin.val (upto n) = list.upto n :=
map_dmap_of_inv_of_pos (val_mk n) (@lt_of_mem_upto n)
lemma length_upto (n : nat) : length (upto n) = n :=
calc
length (upto n) = length (list.upto n) : (map_val_upto n ▸ length_map fin.val (upto n))⁻¹
... = n : list.length_upto n
definition is_fintype [instance] (n : nat) : fintype (fin n) :=
fintype.mk (upto n) (nodup_upto n) (mem_upto n)
section pigeonhole
open fintype
lemma card_fin (n : nat) : card (fin n) = n := length_upto n
theorem pigeonhole {n m : nat} (Pmltn : m < n) : ¬Σ f : fin n → fin m, injective f :=
assume Pex, absurd Pmltn (not_lt_of_ge
(calc
n = card (fin n) : card_fin
... ≤ card (fin m) : card_le_of_inj (fin n) (fin m) Pex
... = m : card_fin))
end pigeonhole-/
protected definition zero [constructor] (n : nat) : fin (succ n) :=
mk 0 !zero_lt_succ
definition fin_has_zero [instance] (n : nat) : has_zero (fin (succ n)) :=
has_zero.mk (fin.zero n)
definition val_zero (n : nat) : val (0 : fin (succ n)) = 0 := rfl
definition mk_mod [reducible] (n i : nat) : fin (succ n) :=
mk (i % (succ n)) (mod_lt _ !zero_lt_succ)
theorem mk_mod_zero_eq (n : nat) : mk_mod n 0 = 0 :=
apd011 fin.mk rfl !is_prop.elim
variable {n : nat}
theorem val_lt : Π i : fin n, val i < n
| (mk v h) := h
lemma max_lt (i j : fin n) : max i j < n :=
max_lt (is_lt i) (is_lt j)
definition lift [constructor] : fin n → Π m : nat, fin (n + m)
| (mk v h) m := mk v (lt_add_of_lt_right h m)
definition lift_succ [constructor] (i : fin n) : fin (nat.succ n) :=
have r : fin (n+1), from lift i 1,
r
definition maxi [reducible] : fin (succ n) :=
mk n !lt_succ_self
definition val_lift : Π (i : fin n) (m : nat), val i = val (lift i m)
| (mk v h) m := rfl
lemma mk_succ_ne_zero {i : nat} : Π {P}, mk (succ i) P ≠ (0 : fin (succ n)) :=
assume P Pe, absurd (veq_of_eq Pe) !succ_ne_zero
lemma mk_mod_eq {i : fin (succ n)} : i = mk_mod n i :=
eq_of_veq begin rewrite [↑mk_mod, mod_eq_of_lt !is_lt] end
lemma mk_mod_of_lt {i : nat} (Plt : i < succ n) : mk_mod n i = mk i Plt :=
begin esimp [mk_mod], congruence, exact mod_eq_of_lt Plt end
section lift_lower
lemma lift_zero : lift_succ (0 : fin (succ n)) = (0 : fin (succ (succ n))) :=
by apply eq_of_veq; reflexivity
lemma ne_max_of_lt_max {i : fin (succ n)} : i < n → i ≠ maxi :=
begin
intro hlt he,
have he' : maxi = i, by apply he⁻¹,
induction he', apply nat.lt_irrefl n hlt,
end
lemma lt_max_of_ne_max {i : fin (succ n)} : i ≠ maxi → i < n :=
assume hne : i ≠ maxi,
have vne : val i ≠ n, from
assume he,
have val (@maxi n) = n, from rfl,
have val i = val (@maxi n), from he ⬝ this⁻¹,
absurd (eq_of_veq this) hne,
have val i < nat.succ n, from val_lt i,
lt_of_le_of_ne (le_of_lt_succ this) vne
lemma lift_succ_ne_max {i : fin n} : lift_succ i ≠ maxi :=
begin
cases i with v hlt, esimp [lift_succ, lift, max], intro he,
injection he, substvars,
exact absurd hlt (lt.irrefl v)
end
lemma lift_succ_inj [instance] : is_embedding (@lift_succ n) :=
begin
apply is_embedding_of_is_injective, intro i j,
induction i with iv ilt, induction j with jv jlt, intro Pmkeq,
apply eq_of_veq, apply veq_of_eq Pmkeq
end
definition lt_of_inj_of_max (f : fin (succ n) → fin (succ n)) :
is_embedding f → (f maxi = maxi) → Π i : fin (succ n), i < n → f i < n :=
assume Pinj Peq, take i, assume Pilt,
have P1 : f i = f maxi → i = maxi, from assume Peq, is_injective_of_is_embedding Peq,
have f i ≠ maxi, from
begin rewrite -Peq, intro P2, apply absurd (P1 P2) (ne_max_of_lt_max Pilt) end,
lt_max_of_ne_max this
definition lift_fun : (fin n → fin n) → (fin (succ n) → fin (succ n)) :=
λ f i, dite (i = maxi) (λ Pe, maxi) (λ Pne, lift_succ (f (mk i (lt_max_of_ne_max Pne))))
definition lower_inj (f : fin (succ n) → fin (succ n)) (inj : is_embedding f) :
f maxi = maxi → fin n → fin n :=
assume Peq, take i, mk (f (lift_succ i)) (lt_of_inj_of_max f inj Peq (lift_succ i) (lt_max_of_ne_max lift_succ_ne_max))
lemma lift_fun_max {f : fin n → fin n} : lift_fun f maxi = maxi :=
begin rewrite [↑lift_fun, dif_pos rfl] end
lemma lift_fun_of_ne_max {f : fin n → fin n} {i} (Pne : i ≠ maxi) :
lift_fun f i = lift_succ (f (mk i (lt_max_of_ne_max Pne))) :=
begin rewrite [↑lift_fun, dif_neg Pne] end
lemma lift_fun_eq {f : fin n → fin n} {i : fin n} :
lift_fun f (lift_succ i) = lift_succ (f i) :=
begin
rewrite [lift_fun_of_ne_max lift_succ_ne_max], do 2 congruence,
apply eq_of_veq, esimp, rewrite -val_lift,
end
lemma lift_fun_of_inj {f : fin n → fin n} : is_embedding f → is_embedding (lift_fun f) :=
begin
intro Pemb, apply is_embedding_of_is_injective, intro i j,
have Pdi : decidable (i = maxi), by apply _,
have Pdj : decidable (j = maxi), by apply _,
cases Pdi with Pimax Pinmax,
cases Pdj with Pjmax Pjnmax,
substvars, intros, reflexivity,
substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pjnmax],
intro Plmax, apply absurd Plmax⁻¹ lift_succ_ne_max,
cases Pdj with Pjmax Pjnmax,
substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pinmax],
intro Plmax, apply absurd Plmax lift_succ_ne_max,
rewrite [lift_fun_of_ne_max Pinmax, lift_fun_of_ne_max Pjnmax],
intro Peq, apply eq_of_veq,
cases i with i ilt, cases j with j jlt, esimp at *,
fapply veq_of_eq, apply is_injective_of_is_embedding,
apply @is_injective_of_is_embedding _ _ lift_succ _ _ _ Peq,
end
lemma lift_fun_inj : is_embedding (@lift_fun n) :=
begin
apply is_embedding_of_is_injective, intro f f' Peq, apply eq_of_homotopy, intro i,
have H : lift_fun f (lift_succ i) = lift_fun f' (lift_succ i), by apply congr_fun Peq _,
revert H, rewrite [*lift_fun_eq], apply is_injective_of_is_embedding,
end
lemma lower_inj_apply {f Pinj Pmax} (i : fin n) :
val (lower_inj f Pinj Pmax i) = val (f (lift_succ i)) :=
by rewrite [↑lower_inj]
end lift_lower
section madd
definition madd (i j : fin (succ n)) : fin (succ n) :=
mk ((i + j) % (succ n)) (mod_lt _ !zero_lt_succ)
definition minv : Π i : fin (succ n), fin (succ n)
| (mk iv ilt) := mk ((succ n - iv) % succ n) (mod_lt _ !zero_lt_succ)
lemma val_madd : Π i j : fin (succ n), val (madd i j) = (i + j) % (succ n)
| (mk iv ilt) (mk jv jlt) := by esimp
lemma madd_inj : Π {i : fin (succ n)}, is_embedding (madd i)
| (mk iv ilt) := is_embedding_of_is_injective
(take j₁ j₂, fin.destruct j₁ (fin.destruct j₂ (λ jv₁ jlt₁ jv₂ jlt₂, begin
rewrite [↑madd],
intro Peq', note Peq := ap val Peq', congruence,
rewrite [-(mod_eq_of_lt jlt₁), -(mod_eq_of_lt jlt₂)],
apply mod_eq_mod_of_add_mod_eq_add_mod_left Peq
end)))
lemma madd_mk_mod {i j : nat} : madd (mk_mod n i) (mk_mod n j) = mk_mod n (i+j) :=
eq_of_veq begin esimp [madd, mk_mod], rewrite [ mod_add_mod, add_mod_mod ] end
lemma val_mod : Π i : fin (succ n), (val i) % (succ n) = val i
| (mk iv ilt) := by esimp; rewrite [(mod_eq_of_lt ilt)]
lemma madd_comm (i j : fin (succ n)) : madd i j = madd j i :=
by apply eq_of_veq; rewrite [*val_madd, add.comm (val i)]
lemma zero_madd (i : fin (succ n)) : madd 0 i = i :=
have H : madd (fin.zero n) i = i,
by apply eq_of_veq; rewrite [val_madd, ↑fin.zero, nat.zero_add, mod_eq_of_lt (is_lt i)],
H
lemma madd_zero (i : fin (succ n)) : madd i (fin.zero n) = i :=
!madd_comm ▸ zero_madd i
lemma madd_assoc (i j k : fin (succ n)) : madd (madd i j) k = madd i (madd j k) :=
by apply eq_of_veq; rewrite [*val_madd, mod_add_mod, add_mod_mod, add.assoc (val i)]
lemma madd_left_inv : Π i : fin (succ n), madd (minv i) i = fin.zero n
| (mk iv ilt) := eq_of_veq (by
rewrite [val_madd, ↑minv, mod_add_mod, nat.sub_add_cancel (le_of_lt ilt), mod_self])
definition madd_is_comm_group [instance] : add_comm_group (fin (succ n)) :=
add_comm_group.mk madd _ madd_assoc (fin.zero n) zero_madd madd_zero minv madd_left_inv madd_comm
end madd
definition pred [constructor] : fin n → fin n
| (mk v h) := mk (nat.pred v) (pre_lt_of_lt h)
lemma val_pred : Π (i : fin n), val (pred i) = nat.pred (val i)
| (mk v h) := rfl
lemma pred_zero : pred (fin.zero n) = fin.zero n :=
begin
induction n, reflexivity, apply eq_of_veq, reflexivity,
end
definition mk_pred (i : nat) (h : succ i < succ n) : fin n :=
mk i (lt_of_succ_lt_succ h)
definition succ : fin n → fin (succ n)
| (mk v h) := mk (nat.succ v) (succ_lt_succ h)
lemma val_succ : Π (i : fin n), val (succ i) = nat.succ (val i)
| (mk v h) := rfl
lemma succ_max : fin.succ maxi = (@maxi (nat.succ n)) := rfl
lemma lift_succ.comm : lift_succ ∘ (@succ n) = succ ∘ lift_succ :=
eq_of_homotopy take i,
eq_of_veq (begin rewrite [↑lift_succ, -val_lift, *val_succ, -val_lift] end)
definition elim0 {C : fin 0 → Type} : Π i : fin 0, C i
| (mk v h) := absurd h !not_lt_zero
definition zero_succ_cases {C : fin (nat.succ n) → Type} :
C (fin.zero n) → (Π j : fin n, C (succ j)) → (Π k : fin (nat.succ n), C k) :=
begin
intros CO CS k,
induction k with [vk, pk],
induction (nat.decidable_lt 0 vk) with [HT, HF],
{ show C (mk vk pk), from
let vj := nat.pred vk in
have vk = nat.succ vj, from
inverse (succ_pred_of_pos HT),
have vj < n, from
lt_of_succ_lt_succ (eq.subst `vk = nat.succ vj` pk),
have succ (mk vj `vj < n`) = mk vk pk, by apply val_inj; apply (succ_pred_of_pos HT),
eq.rec_on this (CS (mk vj `vj < n`)) },
{ show C (mk vk pk), from
have vk = 0, from
eq_zero_of_le_zero (le_of_not_gt HF),
have fin.zero n = mk vk pk, from
val_inj (inverse this),
eq.rec_on this CO }
end
definition succ_maxi_cases {C : fin (nat.succ n) → Type} :
(Π j : fin n, C (lift_succ j)) → C maxi → (Π k : fin (nat.succ n), C k) :=
begin
intros CL CM k,
induction k with [vk, pk],
induction (nat.decidable_lt vk n) with [HT, HF],
{ show C (mk vk pk), from
have HL : lift_succ (mk vk HT) = mk vk pk, from
val_inj rfl,
eq.rec_on HL (CL (mk vk HT)) },
{ show C (mk vk pk), from
have HMv : vk = n, from
le.antisymm (le_of_lt_succ pk) (le_of_not_gt HF),
have HM : maxi = mk vk pk, from
val_inj (inverse HMv),
eq.rec_on HM CM }
end
open decidable
-- TODO there has to be a less painful way to do this
definition elim_succ_maxi_cases_lift_succ {C : fin (nat.succ n) → Type}
{Cls : Π j : fin n, C (lift_succ j)} {Cm : C maxi} (i : fin n) :
succ_maxi_cases Cls Cm (lift_succ i) = Cls i :=
begin
esimp[succ_maxi_cases], cases i with i ilt, esimp,
apply decidable.rec,
{ intro ilt', esimp[val_inj], apply concat,
apply ap (λ x, eq.rec_on x _), esimp[eq_of_veq, rfl], reflexivity,
have H : ilt = ilt', by apply is_prop.elim, cases H,
have H' : is_prop.elim (lt_add_of_lt_right ilt 1) (lt_add_of_lt_right ilt 1) = idp,
by apply is_prop.elim,
krewrite H' },
{ intro a, exact absurd ilt a },
end
definition elim_succ_maxi_cases_maxi {C : fin (nat.succ n) → Type}
{Cls : Π j : fin n, C (lift_succ j)} {Cm : C maxi} :
succ_maxi_cases Cls Cm maxi = Cm :=
begin
esimp[succ_maxi_cases, maxi],
apply decidable.rec,
{ intro a, apply absurd a !nat.lt_irrefl },
{ intro a, esimp[val_inj], apply concat,
have H : (le.antisymm (le_of_lt_succ (lt_succ_self n)) (le_of_not_gt a))⁻¹ = idp,
by apply is_prop.elim,
apply ap _ H, krewrite eq_of_veq_refl },
end
definition foldr {A B : Type} (m : A → B → B) (b : B) : Π {n : nat}, (fin n → A) → B :=
nat.rec (λ f, b) (λ n IH f, m (f (fin.zero n)) (IH (λ i : fin n, f (succ i))))
definition foldl {A B : Type} (m : B → A → B) (b : B) : Π {n : nat}, (fin n → A) → B :=
nat.rec (λ f, b) (λ n IH f, m (IH (λ i : fin n, f (lift_succ i))) (f maxi))
theorem choice {C : fin n → Type} :
(Π i : fin n, nonempty (C i)) → nonempty (Π i : fin n, C i) :=
begin
revert C,
induction n with [n, IH],
{ intros C H,
apply nonempty.intro,
exact elim0 },
{ intros C H,
fapply nonempty.elim (H (fin.zero n)),
intro CO,
fapply nonempty.elim (IH (λ i, C (succ i)) (λ i, H (succ i))),
intro CS,
apply nonempty.intro,
exact zero_succ_cases CO CS }
end
/-section
open list
local postfix `+1`:100 := nat.succ
lemma dmap_map_lift {n : nat} : Π l : list nat, (Π i, i ∈ l → i < n) → dmap (λ i, i < n +1) mk l = map lift_succ (dmap (λ i, i < n) mk l)
| [] := assume Plt, rfl
| (i::l) := assume Plt, begin
rewrite [@dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (lt_succ_of_lt (Plt i !mem_cons)), @dmap_cons_of_pos _ _ (λ i, i < n) _ _ _ (Plt i !mem_cons), map_cons],
congruence,
apply dmap_map_lift,
intro j Pjinl, apply Plt, apply mem_cons_of_mem, assumption end
lemma upto_succ (n : nat) : upto (n +1) = maxi :: map lift_succ (upto n) :=
begin
rewrite [↑fin.upto, list.upto_succ, @dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (nat.self_lt_succ n)],
congruence,
apply dmap_map_lift, apply @list.lt_of_mem_upto
end
definition upto_step : Π {n : nat}, fin.upto (n +1) = (map succ (upto n))++[0]
| 0 := rfl
| (i +1) := begin rewrite [upto_succ i, map_cons, append_cons, succ_max, upto_succ, -lift_zero],
congruence, rewrite [map_map, -lift_succ.comm, -map_map, -(map_singleton _ 0), -map_append, -upto_step] end
end-/
open sum equiv decidable
definition fin_zero_equiv_empty : fin 0 ≃ empty :=
begin
fapply equiv.MK, rotate 1, do 2 (intro x; contradiction),
rotate 1, do 2 (intro x; apply elim0 x)
end
definition is_contr_fin_one [instance] : is_contr (fin 1) :=
begin
fapply is_contr.mk, exact 0,
intro x, induction x with v vlt,
apply eq_of_veq, rewrite val_zero,
apply inverse, apply eq_zero_of_le_zero, apply le_of_succ_le_succ, exact vlt,
end
definition fin_sum_equiv (n m : nat) : (fin n + fin m) ≃ fin (n+m) :=
begin
fapply equiv.MK,
{ intro s, induction s with l r,
induction l with v vlt, apply mk v, apply lt_add_of_lt_right, exact vlt,
induction r with v vlt, apply mk (v + n), rewrite {n + m}add.comm,
apply add_lt_add_of_lt_of_le vlt, apply nat.le_refl },
{ intro f, induction f with v vlt,
exact if h : v < n
then sum.inl (mk v h)
else sum.inr (mk (v-n) (nat.sub_lt_of_lt_add vlt (le_of_not_gt h))) },
{ intro f, cases f with v vlt, esimp, apply @by_cases (v < n),
intro vltn, rewrite [dif_pos vltn], apply eq_of_veq, reflexivity,
intro nvltn, rewrite [dif_neg nvltn], apply eq_of_veq, esimp,
apply nat.sub_add_cancel, apply le_of_not_gt, apply nvltn },
{ intro s, cases s with f g,
cases f with v vlt, rewrite [dif_pos vlt],
cases g with v vlt, esimp, have ¬ v + n < n, from
suppose v + n < n,
have v < n - n, from nat.lt_sub_of_add_lt this !le.refl,
have v < 0, by rewrite [nat.sub_self at this]; exact this,
absurd this !not_lt_zero,
apply concat, apply dif_neg this, apply ap inr, apply eq_of_veq, esimp,
apply nat.add_sub_cancel },
end
definition fin_succ_equiv (n : nat) : fin (n + 1) ≃ fin n + unit :=
begin
fapply equiv.MK,
{ apply succ_maxi_cases, esimp, apply inl, apply inr unit.star },
{ intro d, cases d, apply lift_succ a, apply maxi },
{ intro d, cases d,
cases a with a alt, esimp, apply elim_succ_maxi_cases_lift_succ,
cases a, apply elim_succ_maxi_cases_maxi },
{ intro a, apply succ_maxi_cases, esimp,
intro j, krewrite elim_succ_maxi_cases_lift_succ,
krewrite elim_succ_maxi_cases_maxi },
end
open prod
definition fin_prod_equiv (n m : nat) : (fin n × fin m) ≃ fin (n*m) :=
begin
induction n,
{ krewrite nat.zero_mul,
calc fin 0 × fin m ≃ empty × fin m : fin_zero_equiv_empty
... ≃ fin m × empty : prod_comm_equiv
... ≃ empty : prod_empty_equiv
... ≃ fin 0 : fin_zero_equiv_empty },
{ have H : (a + 1) * m = a * m + m, by rewrite [nat.right_distrib, one_mul],
calc fin (a + 1) × fin m
≃ (fin a + unit) × fin m : prod.prod_equiv_prod_right !fin_succ_equiv
... ≃ (fin a × fin m) + (unit × fin m) : sum_prod_right_distrib
... ≃ (fin a × fin m) + (fin m × unit) : prod_comm_equiv
... ≃ fin (a * m) + (fin m × unit) : v_0
... ≃ fin (a * m) + fin m : prod_unit_equiv
... ≃ fin (a * m + m) : fin_sum_equiv
... ≃ fin ((a + 1) * m) : equiv_of_eq (ap fin H⁻¹) },
end
definition fin_two_equiv_bool : fin 2 ≃ bool :=
let H := equiv_unit_of_is_contr (fin 1) in
calc
fin 2 ≃ fin (1 + 1) : equiv.refl
... ≃ fin 1 + fin 1 : fin_sum_equiv
... ≃ unit + unit : H
... ≃ bool : bool_equiv_unit_sum_unit
definition fin_sum_unit_equiv (n : nat) : fin n + unit ≃ fin (nat.succ n) :=
let H := equiv_unit_of_is_contr (fin 1) in
calc
fin n + unit ≃ fin n + fin 1 : H
... ≃ fin (nat.succ n) : fin_sum_equiv
definition fin_sum_equiv_cancel {n : nat} {A B : Type} (H : (fin n) + A ≃ (fin n) + B) :
A ≃ B :=
begin
induction n with n IH,
{ calc A ≃ A + empty : sum_empty_equiv
... ≃ empty + A : sum_comm_equiv
... ≃ fin 0 + A : fin_zero_equiv_empty
... ≃ fin 0 + B : H
... ≃ empty + B : fin_zero_equiv_empty
... ≃ B + empty : sum_comm_equiv
... ≃ B : sum_empty_equiv },
{ apply IH, apply unit_sum_equiv_cancel,
calc unit + (fin n + A) ≃ (unit + fin n) + A : sum_assoc_equiv
... ≃ (fin n + unit) + A : sum_comm_equiv
... ≃ fin (nat.succ n) + A : fin_sum_unit_equiv
... ≃ fin (nat.succ n) + B : H
... ≃ (fin n + unit) + B : fin_sum_unit_equiv
... ≃ (unit + fin n) + B : sum_comm_equiv
... ≃ unit + (fin n + B) : sum_assoc_equiv },
end
definition eq_of_fin_equiv {m n : nat} (H :fin m ≃ fin n) : m = n :=
begin
revert n H, induction m with m IH IH,
{ intro n H, cases n, reflexivity, exfalso,
apply to_fun fin_zero_equiv_empty, apply to_inv H, apply fin.zero },
{ intro n H, cases n with n, exfalso,
apply to_fun fin_zero_equiv_empty, apply to_fun H, apply fin.zero,
have unit + fin m ≃ unit + fin n, from
calc unit + fin m ≃ fin m + unit : sum_comm_equiv
... ≃ fin (nat.succ m) : fin_succ_equiv
... ≃ fin (nat.succ n) : H
... ≃ fin n + unit : fin_succ_equiv
... ≃ unit + fin n : sum_comm_equiv,
have fin m ≃ fin n, from unit_sum_equiv_cancel this,
apply ap nat.succ, apply IH _ this },
end
end fin
|
9eb4207728499d9ce2f0d79c210f381cd2e924c1 | 4727251e0cd73359b15b664c3170e5d754078599 | /archive/miu_language/basic.lean | f4ca4329c312d762cc859cd7561fb7e840588cfd | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 6,035 | lean | /-
Copyright (c) 2020 Gihan Marasingha. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gihan Marasingha
-/
import tactic.linarith
/-!
# An MIU Decision Procedure in Lean
The [MIU formal system](https://en.wikipedia.org/wiki/MU_puzzle) was introduced by Douglas
Hofstadter in the first chapter of his 1979 book,
[Gödel, Escher, Bach](https://en.wikipedia.org/wiki/G%C3%B6del,_Escher,_Bach).
The system is defined by four rules of inference, one axiom, and an alphabet of three symbols:
`M`, `I`, and `U`.
Hofstadter's central question is: can the string `"MU"` be derived?
It transpires that there is a simple decision procedure for this system. A string is derivable if
and only if it starts with `M`, contains no other `M`s, and the number of `I`s in the string is
congruent to 1 or 2 modulo 3.
The principal aim of this project is to give a Lean proof that the derivability of a string is a
decidable predicate.
## The MIU System
In Hofstadter's description, an _atom_ is any one of `M`, `I` or `U`. A _string_ is a finite
sequence of zero or more symbols. To simplify notation, we write a sequence `[I,U,U,M]`,
for example, as `IUUM`.
The four rules of inference are:
1. xI → xIU,
2. Mx → Mxx,
3. xIIIy → xUy,
4. xUUy → xy,
where the notation α → β is to be interpreted as 'if α is derivable, then β is derivable'.
Additionally, he has an axiom:
* `MI` is derivable.
In Lean, it is natural to treat the rules of inference and the axiom on an equal footing via an
inductive data type `derivable` designed so that `derivable x` represents the notion that the string
`x` can be derived from the axiom by the rules of inference. The axiom is represented as a
nonrecursive constructor for `derivable`. This mirrors the translation of Peano's axiom '0 is a
natural number' into the nonrecursive constructor `zero` of the inductive type `nat`.
## References
* [Jeremy Avigad, Leonardo de Moura and Soonho Kong, _Theorem Proving in Lean_]
[avigad_moura_kong-2017]
* [Douglas R Hofstadter, _Gödel, Escher, Bach_][Hofstadter-1979]
## Tags
miu, derivable strings
-/
namespace miu
/-!
### Declarations and instance derivations for `miu_atom` and `miustr`
-/
/--
The atoms of MIU can be represented as an enumerated type in Lean.
-/
@[derive decidable_eq]
inductive miu_atom : Type
| M : miu_atom
| I : miu_atom
| U : miu_atom
/-!
The annotation `@[derive decidable_eq]` above assigns the attribute `derive` to `miu_atom`, through
which Lean automatically derives that `miu_atom` is an instance of `decidable_eq`. The use of
`derive` is crucial in this project and will lead to the automatic derivation of decidability.
-/
open miu_atom
/--
We show that the type `miu_atom` is inhabited, giving `M` (for no particular reason) as the default
element.
-/
instance miu_atom_inhabited : inhabited miu_atom :=
inhabited.mk M
/--
`miu_atom.repr` is the 'natural' function from `miu_atom` to `string`.
-/
def miu_atom.repr : miu_atom → string
| M := "M"
| I := "I"
| U := "U"
/--
Using `miu_atom.repr`, we prove that ``miu_atom` is an instance of `has_repr`.
-/
instance : has_repr miu_atom :=
⟨λ u, u.repr⟩
/--
For simplicity, an `miustr` is just a list of elements of type `miu_atom`.
-/
@[derive [has_append, has_mem miu_atom]]
def miustr := list miu_atom
/--
For display purposes, an `miustr` can be represented as a `string`.
-/
def miustr.mrepr : miustr → string
| [] := ""
| (c::cs) := c.repr ++ (miustr.mrepr cs)
instance miurepr : has_repr miustr :=
⟨λ u, u.mrepr⟩
/--
In the other direction, we set up a coercion from `string` to `miustr`.
-/
def lchar_to_miustr : (list char) → miustr
| [] := []
| (c::cs) :=
let ms := lchar_to_miustr cs in
match c with
| 'M' := M::ms
| 'I' := I::ms
| 'U' := U::ms
| _ := []
end
instance string_coe_miustr : has_coe string miustr :=
⟨λ st, lchar_to_miustr st.data ⟩
/-!
### Derivability
-/
/--
The inductive type `derivable` has five constructors. The nonrecursive constructor `mk` corresponds
to Hofstadter's axiom that `"MI"` is derivable. Each of the constructors `r1`, `r2`, `r3`, `r4`
corresponds to the one of Hofstadter's rules of inference.
-/
inductive derivable : miustr → Prop
| mk : derivable "MI"
| r1 {x} : derivable (x ++ [I]) → derivable (x ++ [I, U])
| r2 {x} : derivable (M :: x) → derivable (M :: x ++ x)
| r3 {x y} : derivable (x ++ [I, I, I] ++ y) → derivable (x ++ U :: y)
| r4 {x y} : derivable (x ++ [U, U] ++ y) → derivable (x ++ y)
/-!
### Rule usage examples
-/
example (h : derivable "UMI") : derivable "UMIU" :=
begin
change ("UMIU" : miustr) with [U,M] ++ [I,U],
exact derivable.r1 h, -- Rule 1
end
example (h : derivable "MIIU") : derivable "MIIUIIU" :=
begin
change ("MIIUIIU" : miustr) with M :: [I,I,U] ++ [I,I,U],
exact derivable.r2 h, -- Rule 2
end
example (h : derivable "UIUMIIIMMM") : derivable "UIUMUMMM" :=
begin
change ("UIUMUMMM" : miustr) with [U,I,U,M] ++ U :: [M,M,M],
exact derivable.r3 h, -- Rule 3
end
example (h : derivable "MIMIMUUIIM") : derivable "MIMIMIIM" :=
begin
change ("MIMIMIIM" : miustr) with [M,I,M,I,M] ++ [I,I,M],
exact derivable.r4 h, -- Rule 4
end
/-!
### Derivability examples
-/
private lemma MIU_der : derivable "MIU":=
begin
change ("MIU" :miustr) with [M] ++ [I,U],
apply derivable.r1, -- reduce to deriving "MI",
constructor, -- which is the base of the inductive construction.
end
example : derivable "MIUIU" :=
begin
change ("MIUIU" : miustr) with M :: [I,U] ++ [I,U],
exact derivable.r2 MIU_der, -- `"MIUIU"` can be derived as `"MIU"` can.
end
example : derivable "MUI" :=
begin
have h₂ : derivable "MII",
{ change ("MII" : miustr) with M :: [I] ++ [I],
exact derivable.r2 derivable.mk, },
have h₃ : derivable "MIIII",
{ change ("MIIII" : miustr) with M :: [I,I] ++ [I,I],
exact derivable.r2 h₂, },
change ("MUI" : miustr) with [M] ++ U :: [I],
exact derivable.r3 h₃, -- We prove our main goal using rule 3
end
end miu
|
abf8e649433dec4be5c0edc202a99f3f9496b3ed | 626e312b5c1cb2d88fca108f5933076012633192 | /src/ring_theory/subring.lean | 984ab2cd5d69105a8d30833c00f40ef999a519e0 | [
"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 | 37,780 | lean | /-
Copyright (c) 2020 Ashvni Narayanan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ashvni Narayanan
-/
import group_theory.subgroup
import ring_theory.subsemiring
/-!
# Subrings
Let `R` be a ring. This file defines the "bundled" subring type `subring R`, a type
whose terms correspond to subrings of `R`. This is the preferred way to talk
about subrings in mathlib. Unbundled subrings (`s : set R` and `is_subring s`)
are not in this file, and they will ultimately be deprecated.
We prove that subrings are a complete lattice, and that you can `map` (pushforward) and
`comap` (pull back) them along ring homomorphisms.
We define the `closure` construction from `set R` to `subring R`, sending a subset of `R`
to the subring it generates, and prove that it is a Galois insertion.
## Main definitions
Notation used here:
`(R : Type u) [ring R] (S : Type u) [ring S] (f g : R →+* S)`
`(A : subring R) (B : subring S) (s : set R)`
* `subring R` : the type of subrings of a ring `R`.
* `instance : complete_lattice (subring R)` : the complete lattice structure on the subrings.
* `subring.center` : the center of a ring `R`.
* `subring.closure` : subring closure of a set, i.e., the smallest subring that includes the set.
* `subring.gi` : `closure : set M → subring M` and coercion `coe : subring M → set M`
form a `galois_insertion`.
* `comap f B : subring A` : the preimage of a subring `B` along the ring homomorphism `f`
* `map f A : subring B` : the image of a subring `A` along the ring homomorphism `f`.
* `prod A B : subring (R × S)` : the product of subrings
* `f.range : subring B` : the range of the ring homomorphism `f`.
* `eq_locus f g : subring R` : given ring homomorphisms `f g : R →+* S`,
the subring of `R` where `f x = g x`
## Implementation notes
A subring is implemented as a subsemiring which is also an additive subgroup.
The initial PR was as a submonoid which is also an additive subgroup.
Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although
`∈` is defined as membership of a subring's underlying set.
## Tags
subring, subrings
-/
open_locale big_operators
universes u v w
variables {R : Type u} {S : Type v} {T : Type w} [ring R] [ring S] [ring T]
set_option old_structure_cmd true
/-- `subring R` is the type of subrings of `R`. A subring of `R` is a subset `s` that is a
multiplicative submonoid and an additive subgroup. Note in particular that it shares the
same 0 and 1 as R. -/
structure subring (R : Type u) [ring R] extends subsemiring R, add_subgroup R
/-- Reinterpret a `subring` as a `subsemiring`. -/
add_decl_doc subring.to_subsemiring
/-- Reinterpret a `subring` as an `add_subgroup`. -/
add_decl_doc subring.to_add_subgroup
namespace subring
/-- The underlying submonoid of a subring. -/
def to_submonoid (s : subring R) : submonoid R :=
{ carrier := s.carrier,
..s.to_subsemiring.to_submonoid }
instance : set_like (subring R) R :=
⟨subring.carrier, λ p q h, by cases p; cases q; congr'⟩
@[simp]
lemma mem_carrier {s : subring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl
/-- Two subrings are equal if they have the same elements. -/
@[ext] theorem ext {S T : subring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h
/-- Copy of a subring with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (S : subring R) (s : set R) (hs : s = ↑S) : subring R :=
{ carrier := s,
neg_mem' := hs.symm ▸ S.neg_mem',
..S.to_subsemiring.copy s hs }
lemma to_subsemiring_injective : function.injective (to_subsemiring : subring R → subsemiring R)
| r s h := ext (set_like.ext_iff.mp h : _)
@[mono]
lemma to_subsemiring_strict_mono : strict_mono (to_subsemiring : subring R → subsemiring R) :=
λ _ _, id
@[mono]
lemma to_subsemiring_mono : monotone (to_subsemiring : subring R → subsemiring R) :=
to_subsemiring_strict_mono.monotone
lemma to_add_subgroup_injective : function.injective (to_add_subgroup : subring R → add_subgroup R)
| r s h := ext (set_like.ext_iff.mp h : _)
@[mono]
lemma to_add_subgroup_strict_mono : strict_mono (to_add_subgroup : subring R → add_subgroup R) :=
λ _ _, id
@[mono]
lemma to_add_subgroup_mono : monotone (to_add_subgroup : subring R → add_subgroup R) :=
to_add_subgroup_strict_mono.monotone
lemma to_submonoid_injective : function.injective (to_submonoid : subring R → submonoid R)
| r s h := ext (set_like.ext_iff.mp h : _)
@[mono]
lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subring R → submonoid R) :=
λ _ _, id
@[mono]
lemma to_submonoid_mono : monotone (to_submonoid : subring R → submonoid R) :=
to_submonoid_strict_mono.monotone
/-- Construct a `subring R` from a set `s`, a submonoid `sm`, and an additive
subgroup `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/
protected def mk' (s : set R) (sm : submonoid R) (sa : add_subgroup R)
(hm : ↑sm = s) (ha : ↑sa = s) :
subring R :=
{ carrier := s,
zero_mem' := ha ▸ sa.zero_mem,
one_mem' := hm ▸ sm.one_mem,
add_mem' := λ x y, by simpa only [← ha] using sa.add_mem,
mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem,
neg_mem' := λ x, by simpa only [← ha] using sa.neg_mem, }
@[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa = s) :
(subring.mk' s sm sa hm ha : set R) = s := rfl
@[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa = s) {x : R} :
x ∈ subring.mk' s sm sa hm ha ↔ x ∈ s :=
iff.rfl
@[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa = s) :
(subring.mk' s sm sa hm ha).to_submonoid = sm :=
set_like.coe_injective hm.symm
@[simp] lemma mk'_to_add_subgroup {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa =s) :
(subring.mk' s sm sa hm ha).to_add_subgroup = sa :=
set_like.coe_injective ha.symm
end subring
/-- A `subsemiring` containing -1 is a `subring`. -/
def subsemiring.to_subring (s : subsemiring R) (hneg : (-1 : R) ∈ s) : subring R :=
{ neg_mem' := by { rintros x, rw <-neg_one_mul, apply subsemiring.mul_mem, exact hneg, }
..s.to_submonoid, ..s.to_add_submonoid }
namespace subring
variables (s : subring R)
/-- A subring contains the ring's 1. -/
theorem one_mem : (1 : R) ∈ s := s.one_mem'
/-- A subring contains the ring's 0. -/
theorem zero_mem : (0 : R) ∈ s := s.zero_mem'
/-- A subring is closed under multiplication. -/
theorem mul_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem'
/-- A subring is closed under addition. -/
theorem add_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x + y ∈ s := s.add_mem'
/-- A subring is closed under negation. -/
theorem neg_mem : ∀ {x : R}, x ∈ s → -x ∈ s := s.neg_mem'
/-- A subring is closed under subtraction -/
theorem sub_mem {x y : R} (hx : x ∈ s) (hy : y ∈ s) : x - y ∈ s :=
by { rw sub_eq_add_neg, exact s.add_mem hx (s.neg_mem hy) }
/-- Product of a list of elements in a subring is in the subring. -/
lemma list_prod_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s :=
s.to_submonoid.list_prod_mem
/-- Sum of a list of elements in a subring is in the subring. -/
lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s :=
s.to_add_subgroup.list_sum_mem
/-- Product of a multiset of elements in a subring of a `comm_ring` is in the subring. -/
lemma multiset_prod_mem {R} [comm_ring R] (s : subring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.prod ∈ s :=
s.to_submonoid.multiset_prod_mem m
/-- Sum of a multiset of elements in an `subring` of a `ring` is
in the `subring`. -/
lemma multiset_sum_mem {R} [ring R] (s : subring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.sum ∈ s :=
s.to_add_subgroup.multiset_sum_mem m
/-- Product of elements of a subring of a `comm_ring` indexed by a `finset` is in the
subring. -/
lemma prod_mem {R : Type*} [comm_ring R] (s : subring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∏ i in t, f i ∈ s :=
s.to_submonoid.prod_mem h
/-- Sum of elements in a `subring` of a `ring` indexed by a `finset`
is in the `subring`. -/
lemma sum_mem {R : Type*} [ring R] (s : subring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∑ i in t, f i ∈ s :=
s.to_add_subgroup.sum_mem h
lemma pow_mem {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := s.to_submonoid.pow_mem hx n
lemma gsmul_mem {x : R} (hx : x ∈ s) (n : ℤ) :
n • x ∈ s := s.to_add_subgroup.gsmul_mem hx n
lemma coe_int_mem (n : ℤ) : (n : R) ∈ s :=
by simp only [← gsmul_one, gsmul_mem, one_mem]
/-- A subring of a ring inherits a ring structure -/
instance to_ring : ring s :=
{ right_distrib := λ x y z, subtype.eq $ right_distrib x y z,
left_distrib := λ x y z, subtype.eq $ left_distrib x y z,
.. s.to_submonoid.to_monoid, .. s.to_add_subgroup.to_add_comm_group }
@[simp, norm_cast] lemma coe_add (x y : s) : (↑(x + y) : R) = ↑x + ↑y := rfl
@[simp, norm_cast] lemma coe_neg (x : s) : (↑(-x) : R) = -↑x := rfl
@[simp, norm_cast] lemma coe_mul (x y : s) : (↑(x * y) : R) = ↑x * ↑y := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : s) : R) = 1 := rfl
@[simp, norm_cast] lemma coe_pow (x : s) (n : ℕ) : (↑(x ^ n) : R) = x ^ n :=
s.to_submonoid.coe_pow x n
@[simp] lemma coe_eq_zero_iff {x : s} : (x : R) = 0 ↔ x = 0 :=
⟨λ h, subtype.ext (trans h s.coe_zero.symm),
λ h, h.symm ▸ s.coe_zero⟩
/-- A subring of a `comm_ring` is a `comm_ring`. -/
instance to_comm_ring {R} [comm_ring R] (s : subring R) : comm_ring s :=
{ mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..subring.to_ring s}
/-- A subring of a non-trivial ring is non-trivial. -/
instance {R} [ring R] [nontrivial R] (s : subring R) : nontrivial s :=
s.to_subsemiring.nontrivial
/-- A subring of a ring with no zero divisors has no zero divisors. -/
instance {R} [ring R] [no_zero_divisors R] (s : subring R) : no_zero_divisors s :=
s.to_subsemiring.no_zero_divisors
/-- A subring of an integral domain is an integral domain. -/
instance {R} [integral_domain R] (s : subring R) : integral_domain s :=
{ .. s.nontrivial, .. s.no_zero_divisors, .. s.to_comm_ring }
/-- A subring of an `ordered_ring` is an `ordered_ring`. -/
instance to_ordered_ring {R} [ordered_ring R] (s : subring R) : ordered_ring s :=
subtype.coe_injective.ordered_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
/-- A subring of an `ordered_comm_ring` is an `ordered_comm_ring`. -/
instance to_ordered_comm_ring {R} [ordered_comm_ring R] (s : subring R) : ordered_comm_ring s :=
subtype.coe_injective.ordered_comm_ring coe rfl rfl
(λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
/-- A subring of a `linear_ordered_ring` is a `linear_ordered_ring`. -/
instance to_linear_ordered_ring {R} [linear_ordered_ring R] (s : subring R) :
linear_ordered_ring s :=
subtype.coe_injective.linear_ordered_ring coe rfl rfl
(λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
/-- A subring of a `linear_ordered_comm_ring` is a `linear_ordered_comm_ring`. -/
instance to_linear_ordered_comm_ring {R} [linear_ordered_comm_ring R] (s : subring R) :
linear_ordered_comm_ring s :=
subtype.coe_injective.linear_ordered_comm_ring coe rfl rfl
(λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
/-- The natural ring hom from a subring of ring `R` to `R`. -/
def subtype (s : subring R) : s →+* R :=
{ to_fun := coe,
.. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype }
@[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl
@[simp, norm_cast] lemma coe_nat_cast (n : ℕ) : ((n : s) : R) = n :=
s.subtype.map_nat_cast n
@[simp, norm_cast] lemma coe_int_cast (n : ℤ) : ((n : s) : R) = n :=
s.subtype.map_int_cast n
/-! ## Partial order -/
@[simp] lemma mem_to_submonoid {s : subring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_submonoid (s : subring R) : (s.to_submonoid : set R) = s := rfl
@[simp] lemma mem_to_add_subgroup {s : subring R} {x : R} :
x ∈ s.to_add_subgroup ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_add_subgroup (s : subring R) : (s.to_add_subgroup : set R) = s := rfl
/-! ## top -/
/-- The subring `R` of the ring `R`. -/
instance : has_top (subring R) :=
⟨{ .. (⊤ : submonoid R), .. (⊤ : add_subgroup R) }⟩
@[simp] lemma mem_top (x : R) : x ∈ (⊤ : subring R) := set.mem_univ x
@[simp] lemma coe_top : ((⊤ : subring R) : set R) = set.univ := rfl
/-! ## comap -/
/-- The preimage of a subring along a ring homomorphism is a subring. -/
def comap {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) (s : subring S) : subring R :=
{ carrier := f ⁻¹' s.carrier,
.. s.to_submonoid.comap (f : R →* S),
.. s.to_add_subgroup.comap (f : R →+ S) }
@[simp] lemma coe_comap (s : subring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl
@[simp]
lemma mem_comap {s : subring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl
lemma comap_comap (s : subring T) (g : S →+* T) (f : R →+* S) :
(s.comap g).comap f = s.comap (g.comp f) :=
rfl
/-! ## map -/
/-- The image of a subring along a ring homomorphism is a subring. -/
def map {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) (s : subring R) : subring S :=
{ carrier := f '' s.carrier,
.. s.to_submonoid.map (f : R →* S),
.. s.to_add_subgroup.map (f : R →+ S) }
@[simp] lemma coe_map (f : R →+* S) (s : subring R) : (s.map f : set S) = f '' s := rfl
@[simp] lemma mem_map {f : R →+* S} {s : subring R} {y : S} :
y ∈ s.map f ↔ ∃ x ∈ s, f x = y :=
set.mem_image_iff_bex
@[simp] lemma map_id : s.map (ring_hom.id R) = s :=
set_like.coe_injective $ set.image_id _
lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) :=
set_like.coe_injective $ set.image_image _ _ _
lemma map_le_iff_le_comap {f : R →+* S} {s : subring R} {t : subring S} :
s.map f ≤ t ↔ s ≤ t.comap f :=
set.image_subset_iff
lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) :=
λ S T, map_le_iff_le_comap
/-- A subring is isomorphic to its image under an injective function -/
noncomputable def equiv_map_of_injective
(f : R →+* S) (hf : function.injective f) : s ≃+* s.map f :=
{ map_mul' := λ _ _, subtype.ext (f.map_mul _ _),
map_add' := λ _ _, subtype.ext (f.map_add _ _),
..equiv.set.image f s hf }
@[simp] lemma coe_equiv_map_of_injective_apply
(f : R →+* S) (hf : function.injective f) (x : s) :
(equiv_map_of_injective s f hf x : S) = f x := rfl
end subring
namespace ring_hom
variables (g : S →+* T) (f : R →+* S)
/-! ## range -/
/-- The range of a ring homomorphism, as a subring of the target. See Note [range copy pattern]. -/
def range {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) : subring S :=
((⊤ : subring R).map f).copy (set.range f) set.image_univ.symm
@[simp] lemma coe_range : (f.range : set S) = set.range f := rfl
@[simp] lemma mem_range {f : R →+* S} {y : S} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl
lemma range_eq_map (f : R →+* S) : f.range = subring.map f ⊤ :=
by { ext, simp }
lemma mem_range_self (f : R →+* S) (x : R) : f x ∈ f.range :=
mem_range.mpr ⟨x, rfl⟩
lemma map_range : f.range.map g = (g.comp f).range :=
by simpa only [range_eq_map] using (⊤ : subring R).map_map g f
-- TODO -- rename to `cod_restrict` when is_ring_hom is deprecated
/-- Restrict the codomain of a ring homomorphism to a subring that includes the range. -/
def cod_restrict' {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S)
(s : subring S) (h : ∀ x, f x ∈ s) : R →+* s :=
{ to_fun := λ x, ⟨f x, h x⟩,
map_add' := λ x y, subtype.eq $ f.map_add x y,
map_zero' := subtype.eq f.map_zero,
map_mul' := λ x y, subtype.eq $ f.map_mul x y,
map_one' := subtype.eq f.map_one }
/-- The range of a ring homomorphism is a fintype, if the domain is a fintype.
Note: this instance can form a diamond with `subtype.fintype` in the
presence of `fintype S`. -/
instance fintype_range [fintype R] [decidable_eq S] (f : R →+* S) : fintype (range f) :=
set.fintype_range f
end ring_hom
namespace subring
/-! ## bot -/
instance : has_bot (subring R) := ⟨(int.cast_ring_hom R).range⟩
instance : inhabited (subring R) := ⟨⊥⟩
lemma coe_bot : ((⊥ : subring R) : set R) = set.range (coe : ℤ → R) :=
ring_hom.coe_range (int.cast_ring_hom R)
lemma mem_bot {x : R} : x ∈ (⊥ : subring R) ↔ ∃ (n : ℤ), ↑n = x :=
ring_hom.mem_range
/-! ## inf -/
/-- The inf of two subrings is their intersection. -/
instance : has_inf (subring R) :=
⟨λ s t,
{ carrier := s ∩ t,
.. s.to_submonoid ⊓ t.to_submonoid,
.. s.to_add_subgroup ⊓ t.to_add_subgroup }⟩
@[simp] lemma coe_inf (p p' : subring R) : ((p ⊓ p' : subring R) : set R) = p ∩ p' := rfl
@[simp] lemma mem_inf {p p' : subring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
instance : has_Inf (subring R) :=
⟨λ s, subring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subring.to_submonoid t )
(⨅ t ∈ s, subring.to_add_subgroup t) (by simp) (by simp)⟩
@[simp, norm_cast] lemma coe_Inf (S : set (subring R)) :
((Inf S : subring R) : set R) = ⋂ s ∈ S, ↑s := rfl
lemma mem_Inf {S : set (subring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff
@[simp] lemma Inf_to_submonoid (s : set (subring R)) :
(Inf s).to_submonoid = ⨅ t ∈ s, subring.to_submonoid t := mk'_to_submonoid _ _
@[simp] lemma Inf_to_add_subgroup (s : set (subring R)) :
(Inf s).to_add_subgroup = ⨅ t ∈ s, subring.to_add_subgroup t := mk'_to_add_subgroup _ _
/-- Subrings of a ring form a complete lattice. -/
instance : complete_lattice (subring R) :=
{ bot := (⊥),
bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ s.coe_int_mem n,
top := (⊤),
le_top := λ s x hx, trivial,
inf := (⊓),
inf_le_left := λ s t x, and.left,
inf_le_right := λ s t x, and.right,
le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩,
.. complete_lattice_of_Inf (subring R)
(λ s, is_glb.of_image (λ s t,
show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)}
lemma eq_top_iff' (A : subring R) : A = ⊤ ↔ ∀ x : R, x ∈ A :=
eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩
/-! ## Center of a ring -/
section
variables (R)
/-- The center of a semiring `R` is the set of elements that commute with everything in `R` -/
def center : subring R :=
{ carrier := set.center R,
neg_mem' := λ a, set.neg_mem_center,
.. subsemiring.center R }
lemma coe_center : ↑(center R) = set.center R := rfl
@[simp] lemma center_to_subsemiring : (center R).to_subsemiring = subsemiring.center R := rfl
variables {R}
lemma mem_center_iff {z : R} : z ∈ center R ↔ ∀ g, g * z = z * g :=
iff.rfl
@[simp] lemma center_eq_top (R) [comm_ring R] : center R = ⊤ :=
set_like.coe_injective (set.center_eq_univ R)
/-- The center is commutative. -/
instance : comm_ring (center R) :=
{ ..subsemiring.center.comm_semiring,
..(center R).to_ring}
end
section division_ring
variables {K : Type u} [division_ring K]
instance : field (center K) :=
{ inv := λ a, ⟨a⁻¹, set.inv_mem_center' a.prop⟩,
mul_inv_cancel := λ ⟨a, ha⟩ h, subtype.ext $ mul_inv_cancel $ subtype.coe_injective.ne h,
div := λ a b, ⟨a / b, set.div_mem_center' a.prop b.prop⟩,
div_eq_mul_inv := λ a b, subtype.ext $ div_eq_mul_inv _ _,
inv_zero := subtype.ext inv_zero,
..(center K).nontrivial,
..center.comm_ring }
@[simp]
lemma center.coe_inv (a : center K) : ((a⁻¹ : center K) : K) = (a : K)⁻¹ := rfl
@[simp]
lemma center.coe_div (a b : center K) : ((a / b : center K) : K) = (a : K) / (b : K) := rfl
end division_ring
/-! ## subring closure of a subset -/
/-- The `subring` generated by a set. -/
def closure (s : set R) : subring R := Inf {S | s ⊆ S}
lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subring R, s ⊆ S → x ∈ S :=
mem_Inf
/-- The subring generated by a set includes the set. -/
@[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx
/-- A subring `t` includes `closure s` if and only if it includes `s`. -/
@[simp]
lemma closure_le {s : set R} {t : subring R} : closure s ≤ t ↔ s ⊆ t :=
⟨set.subset.trans subset_closure, λ h, Inf_le h⟩
/-- Subring closure of a set is monotone in its argument: if `s ⊆ t`,
then `closure s ≤ closure t`. -/
lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t :=
closure_le.2 $ set.subset.trans h subset_closure
lemma closure_eq_of_le {s : set R} {t : subring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) :
closure s = t :=
le_antisymm (closure_le.2 h₁) h₂
/-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements
of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all
elements of the closure of `s`. -/
@[elab_as_eliminator]
lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1)
(Hadd : ∀ x y, p x → p y → p (x + y))
(Hneg : ∀ (x : R), p x → p (-x))
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
(@closure_le _ _ _ ⟨p, H1, Hmul, H0, Hadd, Hneg⟩).2 Hs h
lemma mem_closure_iff {s : set R} {x} :
x ∈ closure s ↔ x ∈ add_subgroup.closure (submonoid.closure s : set R) :=
⟨ λ h, closure_induction h (λ x hx, add_subgroup.subset_closure $ submonoid.subset_closure hx )
(add_subgroup.zero_mem _)
(add_subgroup.subset_closure ( submonoid.one_mem (submonoid.closure s)) )
(λ x y hx hy, add_subgroup.add_mem _ hx hy )
(λ x hx, add_subgroup.neg_mem _ hx )
( λ x y hx hy, add_subgroup.closure_induction hy
(λ q hq, add_subgroup.closure_induction hx
( λ p hp, add_subgroup.subset_closure ((submonoid.closure s).mul_mem hp hq) )
( begin rw zero_mul q, apply add_subgroup.zero_mem _, end )
( λ p₁ p₂ ihp₁ ihp₂, begin rw add_mul p₁ p₂ q, apply add_subgroup.add_mem _ ihp₁ ihp₂, end )
( λ x hx, begin have f : -x * q = -(x*q) :=
by simp, rw f, apply add_subgroup.neg_mem _ hx, end ) )
( begin rw mul_zero x, apply add_subgroup.zero_mem _, end )
( λ q₁ q₂ ihq₁ ihq₂, begin rw mul_add x q₁ q₂, apply add_subgroup.add_mem _ ihq₁ ihq₂ end )
( λ z hz, begin have f : x * -z = -(x*z) := by simp,
rw f, apply add_subgroup.neg_mem _ hz, end ) ),
λ h, add_subgroup.closure_induction h
( λ x hx, submonoid.closure_induction hx
( λ x hx, subset_closure hx )
( one_mem _ )
( λ x y hx hy, mul_mem _ hx hy ) )
( zero_mem _ )
(λ x y hx hy, add_mem _ hx hy)
( λ x hx, neg_mem _ hx ) ⟩
theorem exists_list_of_mem_closure {s : set R} {x : R} (h : x ∈ closure s) :
(∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s ∨ y = (-1:R)) ∧ (L.map list.prod).sum = x) :=
add_subgroup.closure_induction (mem_closure_iff.1 h)
(λ x hx, let ⟨l, hl, h⟩ :=submonoid.exists_list_of_mem_closure hx in ⟨[l], by simp [h];
clear_aux_decl; tauto!⟩)
⟨[], by simp⟩
(λ x y ⟨l, hl1, hl2⟩ ⟨m, hm1, hm2⟩, ⟨l ++ m, λ t ht, (list.mem_append.1 ht).elim (hl1 t) (hm1 t),
by simp [hl2, hm2]⟩)
(λ x ⟨L, hL⟩, ⟨L.map (list.cons (-1)), list.forall_mem_map_iff.2 $ λ j hj, list.forall_mem_cons.2
⟨or.inr rfl, hL.1 j hj⟩, hL.2 ▸ list.rec_on L (by simp)
(by simp [list.map_cons, add_comm] {contextual := tt})⟩)
variable (R)
/-- `closure` forms a Galois insertion with the coercion to set. -/
protected def gi : galois_insertion (@closure R _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, closure_le,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {R}
/-- Closure of a subring `S` equals `S`. -/
lemma closure_eq (s : subring R) : closure (s : set R) = s := (subring.gi R).l_u_eq s
@[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subring.gi R).gc.l_bot
@[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤
lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t :=
(subring.gi R).gc.l_sup
lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(subring.gi R).gc.l_supr
lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t :=
(subring.gi R).gc.l_Sup
lemma map_sup (s t : subring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f :=
(gc_map_comap f).l_sup
lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subring R) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
lemma comap_inf (s t : subring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f :=
(gc_map_comap f).u_inf
lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subring S) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp] lemma map_bot (f : R →+* S) : (⊥ : subring R).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma comap_top (f : R →+* S) : (⊤ : subring S).comap f = ⊤ :=
(gc_map_comap f).u_top
/-- Given `subring`s `s`, `t` of rings `R`, `S` respectively, `s.prod t` is `s × t`
as a subring of `R × S`. -/
def prod (s : subring R) (t : subring S) : subring (R × S) :=
{ carrier := (s : set R).prod t,
.. s.to_submonoid.prod t.to_submonoid, .. s.to_add_subgroup.prod t.to_add_subgroup}
@[norm_cast]
lemma coe_prod (s : subring R) (t : subring S) :
(s.prod t : set (R × S)) = (s : set R).prod (t : set S) :=
rfl
lemma mem_prod {s : subring R} {t : subring S} {p : R × S} :
p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl
@[mono] lemma prod_mono ⦃s₁ s₂ : subring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subring S⦄
(ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ :=
set.prod_mono hs ht
lemma prod_mono_right (s : subring R) : monotone (λ t : subring S, s.prod t) :=
prod_mono (le_refl s)
lemma prod_mono_left (t : subring S) : monotone (λ s : subring R, s.prod t) :=
λ s₁ s₂ hs, prod_mono hs (le_refl t)
lemma prod_top (s : subring R) :
s.prod (⊤ : subring S) = s.comap (ring_hom.fst R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst]
lemma top_prod (s : subring S) :
(⊤ : subring R).prod s = s.comap (ring_hom.snd R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd]
@[simp]
lemma top_prod_top : (⊤ : subring R).prod (⊤ : subring S) = ⊤ :=
(top_prod _).trans $ comap_top _
/-- Product of subrings is isomorphic to their product as rings. -/
def prod_equiv (s : subring R) (t : subring S) : s.prod t ≃+* s × t :=
{ map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t }
/-- The underlying set of a non-empty directed Sup of subrings is just a union of the subrings.
Note that this fails without the directedness assumption (the union of two subrings is
typically not a subring) -/
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S)
{x : R} :
x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩,
let U : subring R := subring.mk' (⋃ i, (S i : set R))
(⨆ i, (S i).to_submonoid) (⨆ i, (S i).to_add_subgroup)
(submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id))
(add_subgroup.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)),
suffices : (⨆ i, S i) ≤ U, by simpa using @this x,
exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩),
end
lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) :
((⨆ i, S i : subring R) : set R) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
lemma mem_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty)
(hS : directed_on (≤) S) {x : R} :
x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s :=
begin
haveI : nonempty S := Sne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk]
end
lemma coe_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) :
(↑(Sup S) : set R) = ⋃ s ∈ S, ↑s :=
set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS]
lemma mem_map_equiv {f : R ≃+* S} {K : subring R} {x : S} :
x ∈ K.map (f : R →+* S) ↔ f.symm x ∈ K :=
@set.mem_image_equiv _ _ ↑K f.to_equiv x
lemma map_equiv_eq_comap_symm (f : R ≃+* S) (K : subring R) :
K.map (f : R →+* S) = K.comap f.symm :=
set_like.coe_injective (f.to_equiv.image_eq_preimage K)
lemma comap_equiv_eq_map_symm (f : R ≃+* S) (K : subring S) :
K.comap (f : R →+* S) = K.map f.symm :=
(map_equiv_eq_comap_symm f.symm K).symm
end subring
namespace ring_hom
variables [ring T] {s : subring R}
open subring
/-- Restriction of a ring homomorphism to a subring of the domain. -/
def restrict (f : R →+* S) (s : subring R) : s →+* S := f.comp s.subtype
@[simp] lemma restrict_apply (f : R →+* S) (x : s) : f.restrict s x = f x := rfl
/-- Restriction of a ring homomorphism to its range interpreted as a subsemiring.
This is the bundled version of `set.range_factorization`. -/
def range_restrict (f : R →+* S) : R →+* f.range :=
f.cod_restrict' f.range $ λ x, ⟨x, rfl⟩
@[simp] lemma coe_range_restrict (f : R →+* S) (x : R) : (f.range_restrict x : S) = f x := rfl
lemma range_restrict_surjective (f : R →+* S) : function.surjective f.range_restrict :=
λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_range.mp hy in ⟨x, subtype.ext hx⟩
lemma range_top_iff_surjective {f : R →+* S} :
f.range = (⊤ : subring S) ↔ function.surjective f :=
set_like.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective
/-- The range of a surjective ring homomorphism is the whole of the codomain. -/
lemma range_top_of_surjective (f : R →+* S) (hf : function.surjective f) :
f.range = (⊤ : subring S) :=
range_top_iff_surjective.2 hf
/-- The subring of elements `x : R` such that `f x = g x`, i.e.,
the equalizer of f and g as a subring of R -/
def eq_locus (f g : R →+* S) : subring R :=
{ carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_locus g }
/-- If two ring homomorphisms are equal on a set, then they are equal on its subring closure. -/
lemma eq_on_set_closure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_locus g, from closure_le.2 h
lemma eq_of_eq_on_set_top {f g : R →+* S} (h : set.eq_on f g (⊤ : subring R)) :
f = g :=
ext $ λ x, h trivial
lemma eq_of_eq_on_set_dense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_set_top $ hs ▸ eq_on_set_closure h
lemma closure_preimage_le (f : R →+* S) (s : set S) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx
/-- The image under a ring homomorphism of the subring generated by a set equals
the subring generated by the image of the set. -/
lemma map_closure (f : R →+* S) (s : set R) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _)
(closure_preimage_le _ _))
(closure_le.2 $ set.image_subset _ subset_closure)
end ring_hom
namespace subring
open ring_hom
/-- The ring homomorphism associated to an inclusion of subrings. -/
def inclusion {S T : subring R} (h : S ≤ T) : S →* T :=
S.subtype.cod_restrict' _ (λ x, h x.2)
@[simp] lemma range_subtype (s : subring R) : s.subtype.range = s :=
set_like.coe_injective $ (coe_srange _).trans subtype.range_coe
@[simp]
lemma range_fst : (fst R S).srange = ⊤ :=
(fst R S).srange_top_of_surjective $ prod.fst_surjective
@[simp]
lemma range_snd : (snd R S).srange = ⊤ :=
(snd R S).srange_top_of_surjective $ prod.snd_surjective
@[simp]
lemma prod_bot_sup_bot_prod (s : subring R) (t : subring S) :
(s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t :=
le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $
assume p hp, prod.fst_mul_snd p ▸ mul_mem _
((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set_like.mem_coe.2 $ one_mem ⊥⟩)
((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set_like.mem_coe.2 $ one_mem ⊥, hp.2⟩)
end subring
namespace ring_equiv
variables {s t : subring R}
/-- Makes the identity isomorphism from a proof two subrings of a multiplicative
monoid are equal. -/
def subring_congr (h : s = t) : s ≃+* t :=
{ map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h }
/-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its
`ring_hom.range`. -/
def of_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) :
R ≃+* f.range :=
{ to_fun := λ x, f.range_restrict x,
inv_fun := λ x, (g ∘ f.range.subtype) x,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := ring_hom.mem_range.mp x.prop in
show f (g x) = x, by rw [←hx', h x'],
..f.range_restrict }
@[simp] lemma of_left_inverse_apply
{g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) :
↑(of_left_inverse h x) = f x := rfl
@[simp] lemma of_left_inverse_symm_apply
{g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.range) :
(of_left_inverse h).symm x = g x := rfl
end ring_equiv
namespace subring
variables {s : set R}
local attribute [reducible] closure
@[elab_as_eliminator]
protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s)
(h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n))
(ha : ∀ {x y}, C x → C y → C (x + y)) : C x :=
begin
have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1,
rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx,
induction L with hd tl ih, { exact h0 },
rw list.forall_mem_cons at HL,
suffices : C (list.prod hd),
{ rw [list.map_cons, list.sum_cons],
exact ha this (ih HL.2) },
replace HL := HL.1, clear ih tl,
suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧
(list.prod hd = list.prod L ∨ list.prod hd = -list.prod L),
{ rcases this with ⟨L, HL', HP | HP⟩,
{ rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 },
rw list.forall_mem_cons at HL',
rw list.prod_cons,
exact hs _ HL'.1 _ (ih HL'.2) },
rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 },
rw [list.prod_cons, neg_mul_eq_mul_neg],
rw list.forall_mem_cons at HL',
exact hs _ HL'.1 _ (ih HL'.2) },
induction hd with hd tl ih,
{ exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ },
rw list.forall_mem_cons at HL,
rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd,
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $
by rw [list.prod_cons, list.prod_cons, HP]⟩ },
{ exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ },
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $
by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ },
{ exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ }
end
lemma closure_preimage_le (f : R →+* S) (s : set S) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx
end subring
lemma add_subgroup.int_mul_mem {G : add_subgroup R} (k : ℤ) {g : R} (h : g ∈ G) :
(k : R) * g ∈ G :=
by { convert add_subgroup.gsmul_mem G h k, simp }
/-! ## Actions by `subring`s
These are just copies of the definitions about `subsemiring` starting from
`subsemiring.mul_action`.
When `R` is commutative, `algebra.of_subring` provides a stronger result than those found in
this file, which uses the same scalar action.
-/
section actions
namespace subring
variables {α β : Type*}
/-- The action by a subring is the action by the underlying ring. -/
instance [mul_action R α] (S : subring R) : mul_action S α :=
S.to_subsemiring.mul_action
lemma smul_def [mul_action R α] {S : subring R} (g : S) (m : α) : g • m = (g : R) • m := rfl
instance smul_comm_class_left
[mul_action R β] [has_scalar α β] [smul_comm_class R α β] (S : subring R) :
smul_comm_class S α β :=
S.to_subsemiring.smul_comm_class_left
instance smul_comm_class_right
[has_scalar α β] [mul_action R β] [smul_comm_class α R β] (S : subring R) :
smul_comm_class α S β :=
S.to_subsemiring.smul_comm_class_right
/-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/
instance
[has_scalar α β] [mul_action R α] [mul_action R β] [is_scalar_tower R α β] (S : subring R) :
is_scalar_tower S α β :=
S.to_subsemiring.is_scalar_tower
instance [mul_action R α] [has_faithful_scalar R α] (S : subring R) :
has_faithful_scalar S α :=
S.to_subsemiring.has_faithful_scalar
/-- The action by a subring is the action by the underlying ring. -/
instance [add_monoid α] [distrib_mul_action R α] (S : subring R) : distrib_mul_action S α :=
S.to_subsemiring.distrib_mul_action
/-- The action by a subring is the action by the underlying ring. -/
instance [add_comm_monoid α] [module R α] (S : subring R) : module S α :=
S.to_subsemiring.module
end subring
end actions
|
0820e6b66a418abdfaa7f51d3749742841a79d3f | 89793396560dbc54fe665669485dab75e31828d3 | /classes/ua_classes.lean | 06306fcd1c30fe8e70686d503b27169013d4ff82 | [
"Apache-2.0"
] | permissive | jipsen/lean-prover-universal-algebra | 78cb22e8f9008e4692117e18820be07c54350822 | 5decd84053f30f175ebb86c39df4fd6b6d72400e | refs/heads/master | 1,621,084,439,950 | 1,531,936,337,000 | 1,531,936,337,000 | 107,141,703 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,999 | lean | /-
Released under Apache 2.0 license as described in the file LICENSE.
Author: Peter Jipsen
Names based on http://math.chapman.edu/~jipsen/structures/doku.php
-/
import init.logic .identities
universes u
class Mag {α:Type u}(o:α→α → α) --Magmas (=Binars)
class Sgrp{α:Type u}(o:α→α → α) := --Semigroups
(asso: associative o)
lemma asso_sgrp {α : Type}{o:α→α → α}{e:α} [Sgrp o]: --sgrps are associative
∀a b c:α, o(o a b)c = o a(o b c) := Sgrp.asso o
class CSgrp{α:Type u}(o:α→α → α) extends Sgrp o := --Commutative semigroups
(comm: commutative o)
class Band {α:Type u}(m:α→α → α) extends Sgrp m := --Bands
(idem: idempotent m)
class Slat {α:Type u}(m:α→α → α) extends Band m := --Semiattices
(comm: commutative m)
-- use coersion to tell Lean that every Slat is an idempotent CSgrp
class Lat {α:Type u}(j:α→α → α)(m:α→α → α) := --Lattices
(asso_j: associative j)(asso_m: associative m)
(comm_j: commutative j)(comm_m: commutative m)
(abs_jm: absorption j m)(abs_mj: absorption m j)
class Mon {α:Type u}(o:α→α → α)(e:α) extends Sgrp o := --Monoids
(id_l: identity_l o e)
(id_r: identity_r o e)
lemma asso {α : Type}{o:α→α → α}{e:α} [Mon o e]: -- monoids are associative
∀a b c:α, o(o a b)c = o a(o b c) := Sgrp.asso o
class CMon {α:Type u}(o:α→α → α)(e:α) extends Mon o e :=--Commutative monoids
(comm: commutative o)
--class MValg {α:Type u}(o:α→α → α)(i:α → α)(e:α) extends Sgrp o := --MV-algebras
class Grp {α:Type u}(o:α→α → α)(i:α → α)(e:α) extends Sgrp o := --Groups
(id_l : identity_l o e)
(inv_l: inverse_r o i e)
-- Some small models
inductive M₂: Type | e:M₂ | a:M₂
export M₂ (e a)
namespace M₂ -- 2-elt idempotent monoid
def cdot: M₂→M₂ → M₂ | e x := x | x e := x | a a := a
lemma cdot_id: identity_r cdot e := assume x, by cases x; refl
lemma id_cdot: identity_l cdot e := assume x, by cases x; refl
lemma cdot_asso: associative cdot :=
assume x y z, by cases x; cases y; cases z; refl
lemma cdot_idem: idempotent cdot := assume x, by cases x; refl
instance: Sgrp cdot := ⟨cdot_asso⟩
instance: Band cdot := ⟨cdot_idem⟩ -- removed 1st component ⟨cdot_asso⟩,
instance: Mon cdot e := ⟨id_cdot, cdot_id⟩ -- removed 1st component ⟨cdot_asso⟩,
end M₂
inductive Z₂: Type | e:Z₂ | a:Z₂
export Z₂ (e a)
namespace Z₂ -- 2-elt group
def add: Z₂→Z₂ → Z₂ | e x := x | x e := x | a a := e
lemma add_zero: right_identity add e := assume x, by cases x; refl
lemma zero_add: left_identity add e := assume x, by cases x; refl
lemma add_assoc: associative add :=
assume x y z, by cases x; cases y; cases z; refl
instance: Sgrp add := ⟨add_assoc⟩
instance: Mon add e := ⟨zero_add, add_zero⟩ -- removed 1st component ⟨add_asso⟩,
end Z₂ |
20586dc8935858fcf2172a2c98fe481f056ad9c3 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /library/init/data/array/lemmas.lean | f36494f82de4b6b6b94bc59dcbd287f2766370c9 | [
"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 | 4,042 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
-/
prelude
import .basic init.data.nat init.data.list.lemmas
universes u w
namespace array
variables {α : Type u} {β : Type w} {n : nat}
lemma read_eq_read' [inhabited α] (a : array α n) (i : nat) (h : i < n) : read a ⟨i, h⟩ = read' a i :=
by unfold read'; rw [dif_pos h]
lemma write_eq_write' (a : array α n) (i : nat) (h : i < n) (v : α) : write a ⟨i, h⟩ v = write' a i v :=
by unfold write'; rw [dif_pos h]
theorem rev_list_reverse_core (a : array α n) : Π i (h : i ≤ n) (t : list α),
(a.iterate_aux (λ _ v l, v :: l) i h []).reverse_core t = a.rev_iterate_aux (λ _ v l, v :: l) i h t
| 0 h t := rfl
| (i+1) h t := rev_list_reverse_core i _ _
theorem rev_list_reverse (a : array α n) : a.rev_list.reverse = a.to_list :=
rev_list_reverse_core a _ _ _
theorem to_list_reverse (a : array α n) : a.to_list.reverse = a.rev_list :=
by rw [-rev_list_reverse, list.reverse_reverse]
theorem rev_list_length_aux (a : array α n) (i h) : (a.iterate_aux (λ _ v l, v :: l) i h []).length = i :=
by induction i; simph[iterate_aux]
theorem rev_list_length (a : array α n) : a.rev_list.length = n :=
rev_list_length_aux a _ _
theorem to_list_length (a : array α n) : a.to_list.length = n :=
by rw[-rev_list_reverse, list.length_reverse, rev_list_length]
theorem to_list_nth_core (a : array α n) (i : ℕ) (ih : i < n) : Π (j) {jh t h'},
(∀k tl, j + k = i → list.nth_le t k tl = a.read ⟨i, ih⟩) → (a.rev_iterate_aux (λ _ v l, v :: l) j jh t).nth_le i h' = a.read ⟨i, ih⟩
| 0 _ _ _ al := al i _ $ zero_add _
| (j+1) jh t h' al := to_list_nth_core j $ λk tl hjk,
show list.nth_le (a.read ⟨j, jh⟩ :: t) k tl = a.read ⟨i, ih⟩, from
match k, hjk, tl with
| 0, e, tl := match i, e, ih with ._, rfl, _ := rfl end
| k'+1, _, tl := by simp[list.nth_le]; exact al _ _ (by simph)
end
theorem to_list_nth (a : array α n) (i : ℕ) (h h') : list.nth_le a.to_list i h' = a.read ⟨i, h⟩ :=
to_list_nth_core _ _ _ _ (λk tl, absurd tl $ nat.not_lt_zero _)
theorem mem_iff_rev_list_mem_core (a : array α n) (v : α) : Π i (h : i ≤ n),
(∃ (j : fin n), j.1 < i ∧ read a j = v) ↔ v ∈ a.iterate_aux (λ _ v l, v :: l) i h []
| 0 _ := ⟨λ⟨_, n, _⟩, absurd n $ nat.not_lt_zero _, false.elim⟩
| (i+1) h := let IH := mem_iff_rev_list_mem_core i (le_of_lt h) in
⟨λ⟨j, ji1, e⟩, or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ ji1)
(λji, list.mem_cons_of_mem _ $ IH.1 ⟨j, ji, e⟩)
(λje, by simp[iterate_aux]; apply or.inl; note H : j = ⟨i, h⟩ := fin.eq_of_veq je; rwa [-H, e]),
λm, begin
simp[iterate_aux, list.mem] at m,
cases m with e m',
exact ⟨⟨i, h⟩, nat.lt_succ_self _, eq.symm e⟩,
exact let ⟨j, ji, e⟩ := IH.2 m' in
⟨j, nat.le_succ_of_le ji, e⟩
end⟩
theorem mem_iff_rev_list_mem (a : array α n) (v : α) : v ∈ a ↔ v ∈ a.rev_list :=
iff.trans
(exists_congr $ λj, iff.symm $ show j.1 < n ∧ read a j = v ↔ read a j = v, from and_iff_right j.2)
(mem_iff_rev_list_mem_core a v _ _)
theorem mem_iff_list_mem (a : array α n) (v : α) : v ∈ a ↔ v ∈ a.to_list :=
by rw -rev_list_reverse; simp[mem_iff_rev_list_mem]
@[simp] def to_list_to_array (a : array α n) : a.to_list.to_array == a :=
have array.mk (λ (v : fin n), list.nth_le (to_list a) (v.val) (eq.rec_on (eq.symm (to_list_length a)) (v.is_lt))) = a, from
match a with ⟨f⟩ := congr_arg array.mk $ funext $ λ⟨i, h⟩, to_list_nth ⟨f⟩ i h _ end,
heq_of_heq_of_eq
(@eq.drec_on _ _ (λm (e : a.to_list.length = m), (array.mk (λv, a.to_list.nth_le v.1 v.2)) ==
(@array.mk α m $ λv, a.to_list.nth_le v.1 (eq.rec_on (eq.symm e) v.2))) _ a.to_list_length (heq.refl _)) this
@[simp] def to_array_to_list (l : list α) : l.to_array.to_list = l :=
list.ext_le (to_list_length _) $ λn h1 h2, to_list_nth _ _ _ _
end array
|
896d98c5fb04662b2ed9a83f5676fe2d826fe416 | e91b0bc0bcf14cf6e1bfc20ad1f00ad7cfa5fa76 | /src/sheaves/sheaf_of_types_on_basis.lean | d33b85b17ae9b6f7e34e6467a57338ec94404323 | [] | no_license | kckennylau/lean-scheme | b2de50025289a0339d97798466ef777e1899b0f8 | 8dc513ef9606d2988227490e915b7c7e173a2791 | refs/heads/master | 1,587,165,137,978 | 1,548,172,249,000 | 1,548,172,249,000 | 167,025,881 | 0 | 0 | null | 1,548,173,930,000 | 1,548,173,924,000 | Lean | UTF-8 | Lean | false | false | 18,335 | lean | import sheaves.presheaf_of_types
import sheaves.presheaf_of_types_on_basis
import sheaves.sheaf_of_types
import sheaves.stalk_on_basis
universes u v w
-- Kevin and Kenny
open topological_space
-- TODO: Rename this. helper1 will be useful for presheaves as well.
-- If ⋃ Ui = U then for all i U_i ⊆ U
def helper1 {α : Type u} {γ : Type u} {U : set α} {Ui : γ → set α} {i : γ} :
(⋃ (i' : γ), (Ui i')) = U → Ui i ⊆ U :=
λ Hcov z HzUi, Hcov ▸ ⟨_, ⟨_, rfl⟩, HzUi⟩
-- union of a bunch of sets U_{ijk} = U_i intersect U_j implies U_{ijk} sub U_i
def helper2 {X : Type u} {γ : Type u} {Ui : γ → set X}
{β : γ → γ → Type*} {Uijk : Π (i j : γ), β i j → set X} {i j : γ} {k : β i j}
: (⋃ (k' : β i j), Uijk i j k') = Ui i ∩ Ui j → Uijk i j k ⊆ Ui i :=
λ H, have H1 : Uijk i j k ⊆ Ui i ∩ Ui j,
from λ z hz, H ▸ ⟨_, ⟨_, rfl⟩, hz⟩,
set.subset.trans H1 (set.inter_subset_left _ _)
-- union of a bunch of sets U_{ijk} = U_i intersect U_j implies U_{ijk} sub U_j
def helper3 {X : Type u} {γ : Type u} {Ui : γ → set X}
{β : γ → γ → Type*} {Uijk : Π (i j : γ), β i j → set X} {i j : γ} {k : β i j}
: (⋃ (k' : β i j), Uijk i j k') = Ui i ∩ Ui j → Uijk i j k ⊆ Ui j :=
λ H, have H1 : Uijk i j k ⊆ Ui i ∩ Ui j,
from λ z hz, H ▸ ⟨_, ⟨_, rfl⟩, hz⟩,
set.subset.trans H1 (set.inter_subset_right _ _)
section preliminaries
-- Sheaf condition.
parameters {α : Type u} [T : topological_space α]
parameters {B : set (set α)} [HB : is_topological_basis B]
structure covering (U : set α) :=
{γ : Type u} -- TODO: should this be v?
(Ui : γ → set α)
(BUi : ∀ i, (Ui i) ∈ B)
(Hcov : (⋃ i : γ, Ui i) = U)
structure covering_inter {U : set α} (CU : covering U) :=
(Iij : CU.γ → CU.γ → Type u) -- TODO: should this be w?
(Uijk : ∀ i j, Iij i j → set α)
(BUijk : ∀ i j, ∀ (k : Iij i j), (Uijk i j k) ∈ B)
(Hintercov : ∀ i j, (⋃ (k : Iij i j), Uijk i j k) = CU.Ui i ∩ CU.Ui j)
definition is_sheaf_of_types_on_basis (F : presheaf_of_types_on_basis α HB) :=
∀ {U} (BU : U ∈ B) (OC : covering U) (OCI : covering_inter OC),
∀ (s : Π (i : OC.γ), F (OC.BUi i)) (i j : OC.γ) (k : OCI.Iij i j),
F.res (OC.BUi i) (OCI.BUijk i j k) (helper2 (OCI.Hintercov i j)) (s i) =
F.res (OC.BUi j) (OCI.BUijk i j k) (helper3 (OCI.Hintercov i j)) (s j) →
∃! (S : F BU), ∀ (i : OC.γ),
F.res BU (OC.BUi i) (helper1 OC.Hcov) S = s i
-- -- This is the correct definition of sheaf of types on a basis, with no assumption that
-- -- intersection of two basis elements is a basis element. I prove it for O_X
-- -- in tag01HR
-- definition is_sheaf_of_types_on_basis
-- (F : presheaf_of_types_on_basis α HB) : Prop :=
-- ∀ {U} (BU : U ∈ B) {γ : Type u} (Ui : γ → set α) (BUi : ∀ i, (Ui i) ∈ B)
-- (Hcov : (⋃ (x : γ), (Ui x)) = U)
-- {β : γ → γ → Type u} (Uijk : Π (i j : γ), β i j → set X)
-- (BUijk : ∀ i j : γ, ∀ k : β i j, B (Uijk i j k) )
-- (Hcov2 : ∀ i j : γ, (⋃ (k : β i j), Uijk i j k )= Ui i ∩ Ui j)
-- (si : Π (i : γ), F (BUi i))-- sections on the cover
-- -- if they agree on overlaps
-- (Hagree : ∀ i j : γ, ∀ k : β i j,
-- FPTB.res (BUi i) (BUijk i j k) (helper2 (Hcov2 i j): Uijk i j k ⊆ Ui i) (si i)
-- = FPTB.res (BUi j) (BUijk i j k) (helper3 (Hcov2 i j) : Uijk i j k ⊆ Ui j) (si j)),
-- -- then there's a unique global section which agrees with all of them.
-- ∃! s : FPTB.F BU, ∀ i : γ, FPTB.res BU (BUi i) ((helper1 Hcov) : Ui i ⊆ U) s = si i
-- tag 009N
include HB -- TODO: why is this not included?
lemma open_basis_elem {U : set α} (BU : U ∈ B) : T.is_open U :=
HB.2.2.symm ▸ generate_open.basic U BU
definition presheaf_of_types_to_presheaf_of_types_on_basis
(F : presheaf_of_types α) : presheaf_of_types_on_basis α HB :=
{ F := λ U BU, F (open_basis_elem BU),
res := λ U V BU BV HVU, F.res (open_basis_elem BU) (open_basis_elem BV) HVU,
Hid := λ U BU, F.Hid (open_basis_elem BU),
Hcomp := λ U V W BU BV BW, F.Hcomp (open_basis_elem BU) (open_basis_elem BV) (open_basis_elem BW) }
definition presheaf_of_types_on_basis_to_presheaf_of_types
(F : presheaf_of_types_on_basis α HB) : presheaf_of_types α :=
{ F := λ U OU, {s : Π (x ∈ U), presheaf_on_basis_stalk F x //
∀ (x ∈ U), ∃ (V) (BV : V ∈ B) (Hx : x ∈ V) (σ : F BV),
∀ (y ∈ U ∩ V), s y = λ _, ⟦{U := V, BU := BV, Hx := H.2, s := σ}⟧},
res := λ U W OU OW HWU FU,
{ val := λ x HxW, (FU.val x $ HWU HxW),
property := λ x HxW,
begin
rcases (FU.property x (HWU HxW)) with ⟨V, ⟨BV, ⟨HxV, ⟨σ, HFV⟩⟩⟩⟩,
use [V, BV, HxV, σ],
rintros y ⟨HyW, HyV⟩,
rw (HFV y ⟨HWU HyW, HyV⟩),
end },
Hid := λ U OU, funext $ λ x, subtype.eq rfl,
Hcomp := λ U V W OU OV OW HWV HVU, funext $ λ x, subtype.eq rfl}
#check has_coe
instance coe1 : has_coe (presheaf_of_types_on_basis α HB) (presheaf_of_types α) :=
⟨presheaf_of_types_on_basis_to_presheaf_of_types⟩
-- end preliminaries
-- -- #print subtype.mk_eq_mk -- this is a simp lemma so why can't
-- -- I use simp?
-- --variables {X : Type*} [T : topological_space X] {B : set (set X)}
-- -- {HB : topological_space.is_topological_basis B} (FB : presheaf_of_types_on_basis HB)
-- -- (HF : is_sheaf_of_types_on_basis FB)
-- --set_option pp.notation false
-- -- set_option pp.proofs true
-- section extension
-- parameters {α : Type u} [T : topological_space α]
-- parameters {B : set (set α)} [HB : is_topological_basis B]
-- include HB
/-
def locality (F : presheaf_of_types α) :=
∀ {U} (OU : T.is_open U) (OC : covering) (OCU : covers OC U) (s t : F OU),
(∀ (i : OC.γ),
F.res OU (OC.OUi i) (OCU ▸ set.subset_Union OC.Ui i) s =
F.res OU (OC.OUi i) (OCU ▸ set.subset_Union OC.Ui i) t) →
s = t
def gluing (F : presheaf_of_types α) :=
∀ {U} (OU : T.is_open U) (OC : covering) (OCU : covers OC U),
∀ (s : Π (i : OC.γ), F (OC.OUi i)) (i j : OC.γ),
res_to_inter_left F (OC.OUi i) (OC.OUi j) (s i) =
res_to_inter_right F (OC.OUi i) (OC.OUi j) (s j) →
∃ (S : F OU), ∀ (i : OC.γ),
F.res OU (OC.OUi i) (OCU ▸ set.subset_Union OC.Ui i) S = s i
-/
theorem extension_is_sheaf
(F : presheaf_of_types_on_basis α HB)
(HF : is_sheaf_of_types_on_basis F)
: is_sheaf_of_types (presheaf_of_types_on_basis_to_presheaf_of_types F) :=
begin
split,
-- Locality.
{ intros U OU OC OCU s t Hst,
rcases OC with ⟨γ, Ui, OUi⟩,
},
-- Gluing.
{}
end
end preliminaries
#exit
theorem extension_is_sheaf {X : Type u} [T : topological_space X] {B : set (set X)}
{HB : topological_space.is_topological_basis B} (FB : presheaf_of_types_on_basis HB)
(HF : is_sheaf_of_types_on_basis FB)
: is_sheaf_of_types (extend_off_basis FB HF) := begin
intros U OU γ Ui UiO Hcov,
split,
{ intros b c Hbc,
apply subtype.eq,
apply funext,
intro x,
apply funext,
intro HxU,
rw ←Hcov at HxU,
cases HxU with Uig HUig,
cases HUig with H2 HUigx,
cases H2 with g Hg,
rw Hg at HUigx,
-- Hbc is the assumption that b and c are locally equal.
have Hig := congr_fun (subtype.mk_eq_mk.1 Hbc) g,
have H := congr_fun (subtype.mk_eq_mk.1 Hig) x,
--exact (congr_fun H HUigx),
have H2 := congr_fun H HUigx,
exact H2,
},
{ intro s,
existsi _,swap,
{ refine ⟨_,_⟩,
{ intros x HxU,
rw ←Hcov at HxU,
cases (classical.indefinite_description _ HxU) with Uig HUig,
cases (classical.indefinite_description _ HUig) with H2 HUigx,
cases (classical.indefinite_description _ H2) with g Hg,
rw Hg at HUigx,
have t := (s.val g),
exact t.val x HUigx,
},
intros x HxU,
rw ←Hcov at HxU,
cases HxU with Uig HUig,
cases HUig with H2 HUigx,
cases H2 with g Hg,
rw Hg at HUigx,
cases (s.val g).property x HUigx with V HV,
cases HV with BV H2,
cases H2 with HxV H3,
-- now replace V by W, in B, contained in V and in Uig, and containing x
have OUig := UiO g,
have H := ((topological_space.mem_nhds_of_is_topological_basis HB).1 _ :
∃ (W : set X) (H : W ∈ B), x ∈ W ∧ W ⊆ (V ∩ Ui g)),
swap,
have UVUig : T.is_open (V ∩ Ui g) := T.is_open_inter V (Ui g) _ OUig,
have HxVUig : x ∈ V ∩ Ui g := ⟨_,HUigx⟩,
exact mem_nhds_sets UVUig HxVUig,
exact HxV,
rw HB.2.2,
exact topological_space.generate_open.basic V BV,
cases H with W HW,
cases HW with HWB HW,
existsi W,
existsi HWB,
existsi HW.1,
cases H3 with sigma Hsigma,
have HWV := (set.subset.trans HW.2 $ set.inter_subset_left _ _),
existsi FB.res BV HWB HWV sigma,
intros y Hy,
-- now apply Hsigma
have Hy2 : y ∈ V ∩ Ui g := HW.2 Hy.2,
have Hy3 : y ∈ (Ui g) ∩ V := ⟨Hy2.2,Hy2.1⟩,
have H := Hsigma y Hy3,
apply funext,
intro Hyu,
dsimp,
/- goal now
subtype.rec
(λ (Uig : set X) (HUig : ∃ (H : ∃ (i : γ), Uig = Ui i), y ∈ Uig),
subtype.rec
(λ (H2 : ∃ (i : γ), Uig = Ui i) (HUigx : y ∈ Uig),
subtype.rec (λ (g : γ) (Hg : Uig = Ui g), (s.val g).val y _)
(classical.indefinite_description (λ (i : γ), Uig = Ui i) H2))
(classical.indefinite_description (λ (H : ∃ (i : γ), Uig = Ui i), y ∈ Uig) HUig))
(classical.indefinite_description (λ (t : set X), ∃ (H : ∃ (i : γ), t = Ui i), y ∈ t) _) =
⟦{U := W, BU := HWB, Hx := _, s := FB.res BV HWB _ sigma}⟧
-/
cases (classical.indefinite_description (λ (t : set X), ∃ (H : ∃ (i : γ), t = Ui i), y ∈ t) _) with S HS,
dsimp,
/- goal now
subtype.rec
(λ (H2 : ∃ (i : γ), T = Ui i) (HUigx : y ∈ T),
subtype.rec (λ (g : γ) (Hg : T = Ui g), (s.val g).val y _)
(classical.indefinite_description (λ (i : γ), T = Ui i) H2))
(classical.indefinite_description (λ (H : ∃ (i : γ), T = Ui i), y ∈ T) HT) =
⟦{U := W, BU := HWB, Hx := _, s := FB.res BV HWB _ sigma}⟧
-/
cases (classical.indefinite_description (λ (H : ∃ (i : γ), S = Ui i), y ∈ S) HS) with Hh HyS2,
dsimp,
/-
subtype.rec (λ (g : γ) (Hg : T = Ui g), (s.val g).val y _)
(classical.indefinite_description (λ (i : γ), T = Ui i) Hh) =
⟦{U := W, BU := HWB, Hx := _, s := FB.res BV HWB _ sigma}⟧-/
cases (classical.indefinite_description (λ (i : γ), S = Ui i) Hh) with h HSUih,
dsimp,
/-
(s.val h).val y _ = ⟦{U := W, BU := HWB, Hx := _, s := FB.res BV HWB _ sigma}⟧
-/
rw HSUih at HyS2,
revert HyS2,
intro HyS,
suffices : (s.val h).val y HyS = (s.val g).val y Hy2.2,
rw this,
rw Hsigma y Hy3,
apply quotient.sound,
existsi W,
existsi Hy.2,
existsi HWB,
existsi HWV,
existsi set.subset.refl _,
suffices this2 : FB.res _ HWB HWV sigma = FB.res _ HWB _ (FB.res BV HWB HWV sigma),
simpa using this2,
rw FB.Hid,refl,
-- what's left here is (s.val h).val y HyT = (s.val g).val y _
have Hy4 : y ∈ Ui g := Hy3.1,
show (s.val h).val y HyS = (s.val g).val y Hy4, -- both of type presheaf_on_basis_stalk FB x
have H2 := s.property g h,
unfold res_to_inter_left at H2,
unfold res_to_inter_right at H2,
have OUigh : T.is_open (Ui g ∩ Ui h) := T.is_open_inter _ _ (UiO g) (UiO h),
have H3 : (s.val g).val y Hy4 =
((extend_off_basis FB HF).res (Ui g) (Ui g ∩ Ui h) (UiO g) OUigh (set.inter_subset_left _ _) (s.val g)).val y ⟨Hy4,HyS⟩ := rfl,
have H4 : (s.val h).val y HyS =
((extend_off_basis FB HF).res (Ui h) (Ui g ∩ Ui h) (UiO h) OUigh (set.inter_subset_right _ _) (s.val h)).val y ⟨Hy4,HyS⟩ := rfl,
rw H3,
rw H4,
rw H2,
},
{
dsimp,
/- goal now
gluing (extend_off_basis FB HF) U Ui Hcov
⟨λ (x : X) (HxU : x ∈ U),
subtype.rec
(λ (Uig : set X) (HUig : ∃ (H : ∃ (i : γ), Uig = Ui i), x ∈ Uig),
subtype.rec
(λ (H2 : ∃ (i : γ), Uig = Ui i) (HUigx : x ∈ Uig),
subtype.rec (λ (g : γ) (Hg : Uig = Ui g), (s.val g).val x _)
(classical.indefinite_description (λ (i : γ), Uig = Ui i) H2))
(classical.indefinite_description (λ (H : ∃ (i : γ), Uig = Ui i), x ∈ Uig) HUig))
(classical.indefinite_description (λ (t : set X), ∃ (H : ∃ (i : γ), t = Ui i), x ∈ t) _),
_⟩ =
s
-/
unfold gluing,
apply subtype.eq,
dsimp,
apply funext,
intro i,
apply subtype.eq,
/- goal now
((extend_off_basis FB HF).res U (Ui i) OU _ _
⟨λ (x : X) (HxU : x ∈ U),
subtype.rec
(λ (Uig : set X) (HUig : ∃ (H : ∃ (i : γ), Uig = Ui i), x ∈ Uig),
subtype.rec
(λ (H2 : ∃ (i : γ), Uig = Ui i) (HUigx : x ∈ Uig),
subtype.rec (λ (g : γ) (Hg : Uig = Ui g), (s.val g).val x _)
(classical.indefinite_description (λ (i : γ), Uig = Ui i) H2))
(classical.indefinite_description (λ (H : ∃ (i : γ), Uig = Ui i), x ∈ Uig) HUig))
(classical.indefinite_description (λ (t : set X), ∃ (H : ∃ (i : γ), t = Ui i), x ∈ t) _),
_⟩).val =
(s.val i).val
-/
apply funext,
intro x,
apply funext,
intro HxUi,
/- goal now
((extend_off_basis FB HF).res U (Ui i) OU _ _
⟨λ (x : X) (HxU : x ∈ U),
subtype.rec
(λ (Uig : set X) (HUig : ∃ (H : ∃ (i : γ), Uig = Ui i), x ∈ Uig),
subtype.rec
(λ (H2 : ∃ (i : γ), Uig = Ui i) (HUigx : x ∈ Uig),
subtype.rec (λ (g : γ) (Hg : Uig = Ui g), (s.val g).val x _)
(classical.indefinite_description (λ (i : γ), Uig = Ui i) H2))
(classical.indefinite_description (λ (H : ∃ (i : γ), Uig = Ui i), x ∈ Uig) HUig))
(classical.indefinite_description (λ (t : set X), ∃ (H : ∃ (i : γ), t = Ui i), x ∈ t) _),
_⟩).val
x
HxUi =
(s.val i).val x HxUi
-/
have HxU : x ∈ U := Hcov ▸ (set.subset_Union Ui i) (HxUi),
let HHH : presheaf_on_basis_stalk FB x := subtype.rec
(λ (Uig : set X) (HUig : ∃ (H : ∃ (i : γ), Uig = Ui i), x ∈ Uig),
subtype.rec
(λ (H2 : ∃ (i : γ), Uig = Ui i) (HUigx : x ∈ Uig),
subtype.rec (λ (g : γ) (Hg : Uig = Ui g), (s.val g).val x (Hg ▸ HUigx))
(classical.indefinite_description (λ (i : γ), Uig = Ui i) H2))
(classical.indefinite_description (λ (H : ∃ (i : γ), Uig = Ui i), x ∈ Uig) HUig))
(classical.indefinite_description (λ (t : set X), ∃ (H : ∃ (i : γ), t = Ui i), x ∈ t) ⟨Ui i,⟨i,rfl⟩,HxUi⟩),
suffices : (subtype.rec
(λ (Uig : set X) (HUig : ∃ (H : ∃ (i : γ), Uig = Ui i), x ∈ Uig),
subtype.rec
(λ (H2 : ∃ (i : γ), Uig = Ui i) (HUigx : x ∈ Uig),
subtype.rec (λ (g : γ) (Hg : Uig = Ui g), (s.val g).val x (Hg ▸ HUigx))
(classical.indefinite_description (λ (i : γ), Uig = Ui i) H2))
(classical.indefinite_description (λ (H : ∃ (i : γ), Uig = Ui i), x ∈ Uig) HUig))
(classical.indefinite_description (λ (t : set X), ∃ (H : ∃ (i : γ), t = Ui i), x ∈ t) ⟨Ui i,⟨i,rfl⟩,HxUi⟩)
: presheaf_on_basis_stalk FB x)
= (s.val i).val x HxUi,
rw ←this,
refl,
cases (classical.indefinite_description (λ (t : set X), ∃ (H : ∃ (i : γ), t = Ui i), x ∈ t) ⟨Ui i,⟨i,rfl⟩,HxUi⟩) with Uij HUij,
dsimp,
cases (classical.indefinite_description (λ (H : ∃ (i : γ), Uij = Ui i), x ∈ Uij) HUij) with H2 HxUij,
dsimp,
cases (classical.indefinite_description (λ (i : γ), Uij = Ui i) H2) with j Hj,
dsimp,
rw Hj at HxUij,
-- HxUi : x in Ui i
-- HxUij : x in Ui j
show (s.val j).val x HxUij = (s.val i).val x HxUi,
have HxUiUj : x ∈ Ui i ∩ Ui j := ⟨HxUi,HxUij⟩,
have Hs := s.property i j,
have H3 : (s.val j).val x HxUij = (@res_to_inter_right _ _ (extend_off_basis FB HF) (Ui i) (Ui j) (UiO i) (UiO j) (s.val j)).val x HxUiUj := rfl,
rw H3,
rw ←Hs,
refl,
}
}
end
#exit
definition extend_off_basis_map {X : Type*} [T : topological_space X] {B : set (set X)}
{HB : topological_space.is_topological_basis B} (FB : presheaf_of_types_on_basis HB)
(HF : is_sheaf_of_types_on_basis FB) :
morphism_of_presheaves_of_types_on_basis FB (restriction_of_presheaf_to_basis (extend_off_basis FB HF)) := sorry
theorem extension_extends {X : Type*} [T : topological_space X] {B : set (set X)}
{HB : topological_space.is_topological_basis B} (FB : presheaf_of_types_on_basis HB)
(HF : is_sheaf_of_types_on_basis FB) :
is_isomorphism_of_presheaves_of_types_on_basis (extend_off_basis_map FB HF) := sorry
theorem extension_unique {X : Type*} [T : topological_space X] {B : set (set X)}
{HB : topological_space.is_topological_basis B} (FB : presheaf_of_types_on_basis HB)
(HF : is_sheaf_of_types_on_basis FB) (G : presheaf_of_types X)
(HG : is_sheaf_of_types G) (psi : morphism_of_presheaves_of_types_on_basis FB (restriction_of_presheaf_to_basis G))
(HI : is_isomorphism_of_presheaves_of_types_on_basis psi) -- we have an extension which agrees with FB on B
: ∃ rho : morphism_of_presheaves_of_types (extend_off_basis FB HF) G, -- I would happily change the direction of the iso rho
is_isomorphism_of_presheaves_of_types rho ∧
∀ (U : set X) (BU : B U),
(rho.morphism U (basis_element_is_open HB BU)) ∘ ((extend_off_basis_map FB HF).morphism BU) = (psi.morphism BU) := sorry
|
36bf95a0ce97a3a056d877dc9f8179a03e16d99c | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/list/forall2.lean | ad1040cbe08a9ce0a88ff10c8e478ed504173a52 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 14,210 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl
-/
import data.list.infix
/-!
# Double universal quantification on a list
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file provides an API for `list.forall₂` (definition in `data.list.defs`).
`forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length, and whenever `a` is the nth element
of `l₁`, and `b` is the nth element of `l₂`, then `R a b` is satisfied.
-/
open nat function
namespace list
variables {α β γ δ : Type*} {R S : α → β → Prop} {P : γ → δ → Prop} {Rₐ : α → α → Prop}
open relator
mk_iff_of_inductive_prop list.forall₂ list.forall₂_iff
@[simp] theorem forall₂_cons {a b l₁ l₂} :
forall₂ R (a :: l₁) (b :: l₂) ↔ R a b ∧ forall₂ R l₁ l₂ :=
⟨λ h, by cases h with h₁ h₂; split; assumption, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩
theorem forall₂.imp
(H : ∀ a b, R a b → S a b) {l₁ l₂}
(h : forall₂ R l₁ l₂) : forall₂ S l₁ l₂ :=
by induction h; constructor; solve_by_elim
lemma forall₂.mp {Q : α → β → Prop} (h : ∀ a b, Q a b → R a b → S a b) :
∀ {l₁ l₂}, forall₂ Q l₁ l₂ → forall₂ R l₁ l₂ → forall₂ S l₁ l₂
| [] [] forall₂.nil forall₂.nil := forall₂.nil
| (a :: l₁) (b :: l₂) (forall₂.cons hr hrs) (forall₂.cons hq hqs) :=
forall₂.cons (h a b hr hq) (forall₂.mp hrs hqs)
lemma forall₂.flip : ∀ {a b}, forall₂ (flip R) b a → forall₂ R a b
| _ _ forall₂.nil := forall₂.nil
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ h₂.flip
@[simp] lemma forall₂_same : ∀ {l : list α}, forall₂ Rₐ l l ↔ ∀ x ∈ l, Rₐ x x
| [] := by simp
| (a :: l) := by simp [@forall₂_same l]
lemma forall₂_refl [is_refl α Rₐ] (l : list α) : forall₂ Rₐ l l :=
forall₂_same.2 $ λ a h, refl _
@[simp] lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) :=
begin
funext a b, apply propext,
split,
{ intro h, induction h, {refl}, simp only [*]; split; refl },
{ rintro rfl, exact forall₂_refl _ }
end
@[simp, priority 900] lemma forall₂_nil_left_iff {l} : forall₂ R nil l ↔ l = nil :=
⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩
@[simp, priority 900] lemma forall₂_nil_right_iff {l} : forall₂ R l nil ↔ l = nil :=
⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩
lemma forall₂_cons_left_iff {a l u} :
forall₂ R (a :: l) u ↔ (∃b u', R a b ∧ forall₂ R l u' ∧ u = b :: u') :=
iff.intro
(λ h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end)
(λ h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end)
lemma forall₂_cons_right_iff {b l u} :
forall₂ R u (b :: l) ↔ (∃a u', R a b ∧ forall₂ R u' l ∧ u = a :: u') :=
iff.intro
(λ h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end)
(λ h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end)
lemma forall₂_and_left {p : α → Prop} :
∀ l u, forall₂ (λa b, p a ∧ R a b) l u ↔ (∀ a∈l, p a) ∧ forall₂ R l u
| [] u := by simp only [forall₂_nil_left_iff, forall_prop_of_false (not_mem_nil _),
imp_true_iff, true_and]
| (a :: l) u := by simp only [forall₂_and_left l, forall₂_cons_left_iff, forall_mem_cons,
and_assoc, and_comm, and.left_comm, exists_and_distrib_left.symm]
@[simp] lemma forall₂_map_left_iff {f : γ → α} :
∀ {l u}, forall₂ R (map f l) u ↔ forall₂ (λc b, R (f c) b) l u
| [] _ := by simp only [map, forall₂_nil_left_iff]
| (a :: l) _ := by simp only [map, forall₂_cons_left_iff, forall₂_map_left_iff]
@[simp] lemma forall₂_map_right_iff {f : γ → β} :
∀ {l u}, forall₂ R l (map f u) ↔ forall₂ (λa c, R a (f c)) l u
| _ [] := by simp only [map, forall₂_nil_right_iff]
| _ (b :: u) := by simp only [map, forall₂_cons_right_iff, forall₂_map_right_iff]
lemma left_unique_forall₂' (hr : left_unique R) :
∀ {a b c}, forall₂ R a c → forall₂ R b c → a = b
| a₀ nil a₁ forall₂.nil forall₂.nil := rfl
| (a₀ :: l₀) (b :: l) (a₁ :: l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) :=
hr ha₀ ha₁ ▸ left_unique_forall₂' h₀ h₁ ▸ rfl
lemma _root_.relator.left_unique.forall₂ (hr : left_unique R) : left_unique (forall₂ R) :=
@left_unique_forall₂' _ _ _ hr
lemma right_unique_forall₂' (hr : right_unique R) : ∀ {a b c}, forall₂ R a b → forall₂ R a c → b = c
| nil a₀ a₁ forall₂.nil forall₂.nil := rfl
| (b :: l) (a₀ :: l₀) (a₁ :: l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) :=
hr ha₀ ha₁ ▸ right_unique_forall₂' h₀ h₁ ▸ rfl
lemma _root_.relator.right_unique.forall₂ (hr : right_unique R) : right_unique (forall₂ R) :=
@right_unique_forall₂' _ _ _ hr
lemma _root_.relator.bi_unique.forall₂ (hr : bi_unique R) : bi_unique (forall₂ R) :=
⟨hr.left.forall₂, hr.right.forall₂⟩
theorem forall₂.length_eq :
∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂
| _ _ forall₂.nil := rfl
| _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂.length_eq h₂)
theorem forall₂.nth_le :
∀ {x : list α} {y : list β} (h : forall₂ R x y) ⦃i : ℕ⦄ (hx : i < x.length) (hy : i < y.length),
R (x.nth_le i hx) (y.nth_le i hy)
| (a₁ :: l₁) (a₂ :: l₂) (forall₂.cons ha hl) 0 hx hy := ha
| (a₁ :: l₁) (a₂ :: l₂) (forall₂.cons ha hl) (succ i) hx hy := hl.nth_le _ _
lemma forall₂_of_length_eq_of_nth_le : ∀ {x : list α} {y : list β},
x.length = y.length → (∀ i h₁ h₂, R (x.nth_le i h₁) (y.nth_le i h₂)) → forall₂ R x y
| [] [] hl h := forall₂.nil
| (a₁ :: l₁) (a₂ :: l₂) hl h := forall₂.cons
(h 0 (nat.zero_lt_succ _) (nat.zero_lt_succ _))
(forall₂_of_length_eq_of_nth_le (succ.inj hl) (
λ i h₁ h₂, h i.succ (succ_lt_succ h₁) (succ_lt_succ h₂)))
theorem forall₂_iff_nth_le {l₁ : list α} {l₂ : list β} :
forall₂ R l₁ l₂ ↔ l₁.length = l₂.length ∧ ∀ i h₁ h₂, R (l₁.nth_le i h₁) (l₂.nth_le i h₂) :=
⟨λ h, ⟨h.length_eq, h.nth_le⟩, and.rec forall₂_of_length_eq_of_nth_le⟩
theorem forall₂_zip :
∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b
| _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁
| _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃
theorem forall₂_iff_zip {l₁ l₂} : forall₂ R l₁ l₂ ↔
length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b :=
⟨λ h, ⟨forall₂.length_eq h, @forall₂_zip _ _ _ _ _ h⟩,
λ h, begin
cases h with h₁ h₂,
induction l₁ with a l₁ IH generalizing l₂,
{ cases length_eq_zero.1 h₁.symm, constructor },
{ cases l₂ with b l₂; injection h₁ with h₁,
exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) }
end⟩
theorem forall₂_take :
∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (take n l₁) (take n l₂)
| 0 _ _ _ := by simp only [forall₂.nil, take]
| (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, take]
| (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_take n]
theorem forall₂_drop :
∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (drop n l₁) (drop n l₂)
| 0 _ _ h := by simp only [drop, h]
| (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, drop]
| (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_drop n]
theorem forall₂_take_append (l : list α) (l₁ : list β) (l₂ : list β)
(h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.take (length l₁) l) l₁ :=
have h': forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)),
from forall₂_take (length l₁) h,
by rwa [take_left] at h'
theorem forall₂_drop_append (l : list α) (l₁ : list β) (l₂ : list β)
(h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.drop (length l₁) l) l₂ :=
have h': forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)),
from forall₂_drop (length l₁) h,
by rwa [drop_left] at h'
lemma rel_mem (hr : bi_unique R) : (R ⇒ forall₂ R ⇒ iff) (∈) (∈)
| a b h [] [] forall₂.nil := by simp only [not_mem_nil]
| a b h (a' :: as) (b' :: bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂)
lemma rel_map : ((R ⇒ P) ⇒ forall₂ R ⇒ forall₂ P) map map
| f g h [] [] forall₂.nil := forall₂.nil
| f g h (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂)
lemma rel_append : (forall₂ R ⇒ forall₂ R ⇒ forall₂ R) append append
| [] [] h l₁ l₂ hl := hl
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl)
lemma rel_reverse : (forall₂ R ⇒ forall₂ R) reverse reverse
| [] [] forall₂.nil := forall₂.nil
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := begin
simp only [reverse_cons],
exact rel_append (rel_reverse h₂) (forall₂.cons h₁ forall₂.nil)
end
@[simp]
lemma forall₂_reverse_iff {l₁ l₂} : forall₂ R (reverse l₁) (reverse l₂) ↔ forall₂ R l₁ l₂ :=
iff.intro
(λ h, by { rw [← reverse_reverse l₁, ← reverse_reverse l₂], exact rel_reverse h })
(λ h, rel_reverse h)
lemma rel_join : (forall₂ (forall₂ R) ⇒ forall₂ R) join join
| [] [] forall₂.nil := forall₂.nil
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂)
lemma rel_bind : (forall₂ R ⇒ (R ⇒ forall₂ P) ⇒ forall₂ P) list.bind list.bind :=
λ a b h₁ f g h₂, rel_join (rel_map @h₂ h₁)
lemma rel_foldl : ((P ⇒ R ⇒ P) ⇒ P ⇒ forall₂ R ⇒ P) foldl foldl
| f g hfg _ _ h _ _ forall₂.nil := h
| f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs
lemma rel_foldr : ((R ⇒ P ⇒ P) ⇒ P ⇒ forall₂ R ⇒ P) foldr foldr
| f g hfg _ _ h _ _ forall₂.nil := h
| f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs)
lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q]
(hpq : (R ⇒ (↔)) p q) :
(forall₂ R ⇒ forall₂ R) (filter p) (filter q)
| _ _ forall₂.nil := forall₂.nil
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) :=
begin
by_cases p a,
{ have : q b, { rwa [← hpq h₁] },
simp only [filter_cons_of_pos _ h, filter_cons_of_pos _ this, forall₂_cons, h₁, rel_filter h₂,
and_true], },
{ have : ¬ q b, { rwa [← hpq h₁] },
simp only [filter_cons_of_neg _ h, filter_cons_of_neg _ this, rel_filter h₂], },
end
lemma rel_filter_map : ((R ⇒ option.rel P) ⇒ forall₂ R ⇒ forall₂ P) filter_map filter_map
| f g hfg _ _ forall₂.nil := forall₂.nil
| f g hfg (a :: as) (b :: bs) (forall₂.cons h₁ h₂) :=
by rw [filter_map_cons, filter_map_cons];
from match f a, g b, hfg h₁ with
| _, _, option.rel.none := rel_filter_map @hfg h₂
| _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂)
end
@[to_additive]
lemma rel_prod [monoid α] [monoid β]
(h : R 1 1) (hf : (R ⇒ R ⇒ R) (*) (*)) : (forall₂ R ⇒ R) prod prod :=
rel_foldl hf h
/-- Given a relation `R`, `sublist_forall₂ r l₁ l₂` indicates that there is a sublist of `l₂` such
that `forall₂ r l₁ l₂`. -/
inductive sublist_forall₂ (R : α → β → Prop) : list α → list β → Prop
| nil {l} : sublist_forall₂ [] l
| cons {a₁ a₂ l₁ l₂} : R a₁ a₂ → sublist_forall₂ l₁ l₂ →
sublist_forall₂ (a₁ :: l₁) (a₂ :: l₂)
| cons_right {a l₁ l₂} : sublist_forall₂ l₁ l₂ → sublist_forall₂ l₁ (a :: l₂)
lemma sublist_forall₂_iff {l₁ : list α} {l₂ : list β} :
sublist_forall₂ R l₁ l₂ ↔ ∃ l, forall₂ R l₁ l ∧ l <+ l₂ :=
begin
split; intro h,
{ induction h with _ a b l1 l2 rab rll ih b l1 l2 hl ih,
{ exact ⟨nil, forall₂.nil, nil_sublist _⟩ },
{ obtain ⟨l, hl1, hl2⟩ := ih,
refine ⟨b :: l, forall₂.cons rab hl1, hl2.cons_cons b⟩ },
{ obtain ⟨l, hl1, hl2⟩ := ih,
exact ⟨l, hl1, hl2.trans (sublist.cons _ _ _ (sublist.refl _))⟩ } },
{ obtain ⟨l, hl1, hl2⟩ := h,
revert l₁,
induction hl2 with _ _ _ _ ih _ _ _ _ ih; intros l₁ hl1,
{ rw [forall₂_nil_right_iff.1 hl1],
exact sublist_forall₂.nil },
{ exact sublist_forall₂.cons_right (ih hl1) },
{ cases hl1 with _ _ _ _ hr hl _,
exact sublist_forall₂.cons hr (ih hl) } }
end
instance sublist_forall₂.is_refl [is_refl α Rₐ] :
is_refl (list α) (sublist_forall₂ Rₐ) :=
⟨λ l, sublist_forall₂_iff.2 ⟨l, forall₂_refl l, sublist.refl l⟩⟩
instance sublist_forall₂.is_trans [is_trans α Rₐ] :
is_trans (list α) (sublist_forall₂ Rₐ) :=
⟨λ a b c, begin
revert a b,
induction c with _ _ ih,
{ rintros _ _ h1 (_ | _ | _),
exact h1 },
{ rintros a b h1 h2,
cases h2 with _ _ _ _ _ hbc tbc _ _ y1 btc,
{ cases h1,
exact sublist_forall₂.nil },
{ cases h1 with _ _ _ _ _ hab tab _ _ _ atb,
{ exact sublist_forall₂.nil },
{ exact sublist_forall₂.cons (trans hab hbc) (ih _ _ tab tbc) },
{ exact sublist_forall₂.cons_right (ih _ _ atb tbc) } },
{ exact sublist_forall₂.cons_right (ih _ _ h1 btc), } }
end⟩
lemma sublist.sublist_forall₂ {l₁ l₂ : list α} (h : l₁ <+ l₂) [is_refl α Rₐ] :
sublist_forall₂ Rₐ l₁ l₂ :=
sublist_forall₂_iff.2 ⟨l₁, forall₂_refl l₁, h⟩
lemma tail_sublist_forall₂_self [is_refl α Rₐ] (l : list α) :
sublist_forall₂ Rₐ l.tail l :=
l.tail_sublist.sublist_forall₂
end list
|
11036646933fadeac3fcb56160a81391b8fa69e7 | fecda8e6b848337561d6467a1e30cf23176d6ad0 | /src/ring_theory/subring.lean | 0b2722a7511232455b3c827bfc8beded856c18ca | [
"Apache-2.0"
] | permissive | spolu/mathlib | bacf18c3d2a561d00ecdc9413187729dd1f705ed | 480c92cdfe1cf3c2d083abded87e82162e8814f4 | refs/heads/master | 1,671,684,094,325 | 1,600,736,045,000 | 1,600,736,045,000 | 297,564,749 | 1 | 0 | null | 1,600,758,368,000 | 1,600,758,367,000 | null | UTF-8 | Lean | false | false | 29,875 | lean | /-
Copyright (c) 2020 Ashvni Narayanan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors : Ashvni Narayanan
-/
import group_theory.subgroup
import ring_theory.subsemiring
/-!
# Subrings
Let `R` be a ring. This file defines the "bundled" subring type `subring R`, a type
whose terms correspond to subrings of `R`. This is the preferred way to talk
about subrings in mathlib. Unbundled subrings (`s : set R` and `is_subring s`)
are not in this file, and they will ultimately be deprecated.
We prove that subrings are a complete lattice, and that you can `map` (pushforward) and
`comap` (pull back) them along ring homomorphisms.
We define the `closure` construction from `set R` to `subring R`, sending a subset of `R`
to the subring it generates, and prove that it is a Galois insertion.
## Main definitions
Notation used here:
`(R : Type u) [ring R] (S : Type u) [ring S] (f g : R →+* S)`
`(A : subring R) (B : subring S) (s : set R)`
* `subring R` : the type of subrings of a ring `R`.
* `instance : complete_lattice (subring R)` : the complete lattice structure on the subrings.
* `subring.closure` : subring closure of a set, i.e., the smallest subring that includes the set.
* `subring.gi` : `closure : set M → subring M` and coercion `coe : subring M → set M`
form a `galois_insertion`.
* `comap f B : subring A` : the preimage of a subring `B` along the ring homomorphism `f`
* `map f A : subring B` : the image of a subring `A` along the ring homomorphism `f`.
* `prod A B : subring (R × S)` : the product of subrings
* `f.range : subring B` : the range of the ring homomorphism `f`.
* `eq_locus f g : subring R` : given ring homomorphisms `f g : R →+* S`,
the subring of `R` where `f x = g x`
## Implementation notes
A subring is implemented as a subsemiring which is also an additive subgroup.
The initial PR was as a submonoid which is also an additive subgroup.
Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although
`∈` is defined as membership of a subring's underlying set.
## Tags
subring, subrings
-/
open_locale big_operators
universes u v w
open group
variables {R : Type u} {S : Type v} {T : Type w} [ring R] [ring S] [ring T]
set_option old_structure_cmd true
/-- `subring R` is the type of subrings of `R`. A subring of `R` is a subset `s` that is a
multiplicative submonoid and an additive subgroup. Note in particular that it shares the
same 0 and 1 as R. -/
structure subring (R : Type u) [ring R] extends subsemiring R, add_subgroup R
/-- Reinterpret a `subring` as a `subsemiring`. -/
add_decl_doc subring.to_subsemiring
/-- Reinterpret a `subring` as an `add_subgroup`. -/
add_decl_doc subring.to_add_subgroup
namespace subring
/-- The underlying submonoid of a subring. -/
def to_submonoid (s : subring R) : submonoid R :=
{ carrier := s.carrier,
..s.to_subsemiring.to_submonoid }
instance : has_coe (subring R) (set R) := ⟨subring.carrier⟩
instance : has_coe_to_sort (subring R) := ⟨Type*, λ S, S.carrier⟩
instance : has_mem R (subring R) := ⟨λ m S, m ∈ (S:set R)⟩
/-- Construct a `subring R` from a set `s`, a submonoid `sm`, and an additive
subgroup `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/
protected def mk' (s : set R) (sm : submonoid R) (sa : add_subgroup R)
(hm : ↑sm = s) (ha : ↑sa = s) :
subring R :=
{ carrier := s,
zero_mem' := ha ▸ sa.zero_mem,
one_mem' := hm ▸ sm.one_mem,
add_mem' := λ x y, by simpa only [← ha] using sa.add_mem,
mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem,
neg_mem' := λ x, by simpa only [← ha] using sa.neg_mem, }
@[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa = s) :
(subring.mk' s sm sa hm ha : set R) = s := rfl
@[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa = s) {x : R} :
x ∈ subring.mk' s sm sa hm ha ↔ x ∈ s :=
iff.rfl
@[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa = s) :
(subring.mk' s sm sa hm ha).to_submonoid = sm :=
submonoid.ext' hm.symm
@[simp] lemma mk'_to_add_subgroup {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa =s) :
(subring.mk' s sm sa hm ha).to_add_subgroup = sa :=
add_subgroup.ext' ha.symm
end subring
protected lemma subring.exists {s : subring R} {p : s → Prop} :
(∃ x : s, p x) ↔ ∃ x ∈ s, p ⟨x, ‹x ∈ s›⟩ :=
set_coe.exists
protected lemma subring.forall {s : subring R} {p : s → Prop} :
(∀ x : s, p x) ↔ ∀ x ∈ s, p ⟨x, ‹x ∈ s›⟩ :=
set_coe.forall
/-- A `subsemiring` containing -1 is a `subring`. -/
def subsemiring.to_subring (s : subsemiring R) (hneg : (-1 : R) ∈ s) : subring R :=
{ neg_mem' := by { rintros x, rw <-neg_one_mul, apply subsemiring.mul_mem, exact hneg, }
..s.to_submonoid, ..s.to_add_submonoid }
namespace subring
variables (s : subring R)
/-- Two subrings are equal if the underlying subsets are equal. -/
theorem ext' ⦃s t : subring R⦄ (h : (s : set R) = t) : s = t :=
by { cases s, cases t, congr' }
/-- Two subrings are equal if and only if the underlying subsets are equal. -/
protected theorem ext'_iff {s t : subring R} : s = t ↔ (s : set R) = t :=
⟨λ h, h ▸ rfl, λ h, ext' h⟩
/-- Two subrings are equal if they have the same elements. -/
@[ext] theorem ext {S T : subring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h
/-- A subring contains the ring's 1. -/
theorem one_mem : (1 : R) ∈ s := s.one_mem'
/-- A subring contains the ring's 0. -/
theorem zero_mem : (0 : R) ∈ s := s.zero_mem'
/-- A subring is closed under multiplication. -/
theorem mul_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem'
/-- A subring is closed under addition. -/
theorem add_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x + y ∈ s := s.add_mem'
/-- A subring is closed under negation. -/
theorem neg_mem : ∀ {x : R}, x ∈ s → -x ∈ s := s.neg_mem'
/-- Product of a list of elements in a subring is in the subring. -/
lemma list_prod_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s :=
s.to_submonoid.list_prod_mem
/-- Sum of a list of elements in a subring is in the subring. -/
lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s :=
s.to_add_subgroup.list_sum_mem
/-- Product of a multiset of elements in a subring of a `comm_ring` is in the subring. -/
lemma multiset_prod_mem {R} [comm_ring R] (s : subring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.prod ∈ s :=
s.to_submonoid.multiset_prod_mem m
/-- Sum of a multiset of elements in an `subring` of a `ring` is
in the `subring`. -/
lemma multiset_sum_mem {R} [ring R] (s : subring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.sum ∈ s :=
s.to_add_subgroup.multiset_sum_mem m
/-- Product of elements of a subring of a `comm_ring` indexed by a `finset` is in the
subring. -/
lemma prod_mem {R : Type*} [comm_ring R] (s : subring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∏ i in t, f i ∈ s :=
s.to_submonoid.prod_mem h
/-- Sum of elements in a `subring` of a `ring` indexed by a `finset`
is in the `subring`. -/
lemma sum_mem {R : Type*} [ring R] (s : subring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∑ i in t, f i ∈ s :=
s.to_add_subgroup.sum_mem h
lemma pow_mem {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := s.to_submonoid.pow_mem hx n
lemma gsmul_mem {x : R} (hx : x ∈ s) (n : ℤ) :
n •ℤ x ∈ s := s.to_add_subgroup.gsmul_mem hx n
lemma coe_int_mem (n : ℤ) : (n : R) ∈ s :=
by simp only [← gsmul_one, gsmul_mem, one_mem]
/-- A subring of a ring inherits a ring structure -/
instance to_ring : ring s :=
{ right_distrib := λ x y z, subtype.eq $ right_distrib x y z,
left_distrib := λ x y z, subtype.eq $ left_distrib x y z,
.. s.to_submonoid.to_monoid, .. s.to_add_subgroup.to_add_comm_group }
@[simp, norm_cast] lemma coe_add (x y : s) : (↑(x + y) : R) = ↑x + ↑y := rfl
@[simp, norm_cast] lemma coe_neg (x : s) : (↑(-x) : R) = -↑x := rfl
@[simp, norm_cast] lemma coe_mul (x y : s) : (↑(x * y) : R) = ↑x * ↑y := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : s) : R) = 1 := rfl
@[simp] lemma coe_eq_zero_iff {x : s} : (x : R) = 0 ↔ x = 0 :=
⟨λ h, subtype.ext (trans h s.coe_zero.symm),
λ h, h.symm ▸ s.coe_zero⟩
/-- A subring of a `comm_ring` is a `comm_ring`. -/
def to_comm_ring {R} [comm_ring R] (s : subring R) : comm_ring s :=
{ mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..subring.to_ring s}
/-- The natural ring hom from a subring of ring `R` to `R`. -/
def subtype (s : subring R) : s →+* R :=
{ to_fun := coe,
.. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype }
@[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl
/-! # Partial order -/
instance : partial_order (subring R) :=
{ le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t,
.. partial_order.lift (coe : subring R → set R) ext' }
lemma le_def {s t : subring R} : s ≤ t ↔ ∀ ⦃x : R⦄, x ∈ s → x ∈ t := iff.rfl
@[simp, norm_cast] lemma coe_subset_coe {s t : subring R} : (s : set R) ⊆ t ↔ s ≤ t := iff.rfl
@[simp, norm_cast] lemma coe_ssubset_coe {s t : subring R} : (s : set R) ⊂ t ↔ s < t := iff.rfl
@[simp, norm_cast]
lemma mem_coe {S : subring R} {m : R} : m ∈ (S : set R) ↔ m ∈ S := iff.rfl
@[simp, norm_cast]
lemma coe_coe (s : subring R) : ↥(s : set R) = s := rfl
@[simp] lemma mem_to_submonoid {s : subring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_submonoid (s : subring R) : (s.to_submonoid : set R) = s := rfl
@[simp] lemma mem_to_add_subgroup {s : subring R} {x : R} :
x ∈ s.to_add_subgroup ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_add_subgroup (s : subring R) : (s.to_add_subgroup : set R) = s := rfl
/-! # top -/
/-- The subring `R` of the ring `R`. -/
instance : has_top (subring R) :=
⟨{ .. (⊤ : submonoid R), .. (⊤ : add_subgroup R) }⟩
@[simp] lemma mem_top (x : R) : x ∈ (⊤ : subring R) := set.mem_univ x
@[simp] lemma coe_top : ((⊤ : subring R) : set R) = set.univ := rfl
/-! # comap -/
/-- The preimage of a subring along a ring homomorphism is a subring. -/
def comap {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) (s : subring S) : subring R :=
{ carrier := f ⁻¹' s.carrier,
.. s.to_submonoid.comap (f : R →* S),
.. s.to_add_subgroup.comap (f : R →+ S) }
@[simp] lemma coe_comap (s : subring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl
@[simp]
lemma mem_comap {s : subring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl
lemma comap_comap (s : subring T) (g : S →+* T) (f : R →+* S) :
(s.comap g).comap f = s.comap (g.comp f) :=
rfl
/-! # map -/
/-- The image of a subring along a ring homomorphism is a subring. -/
def map {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) (s : subring R) : subring S :=
{ carrier := f '' s.carrier,
.. s.to_submonoid.map (f : R →* S),
.. s.to_add_subgroup.map (f : R →+ S) }
@[simp] lemma coe_map (f : R →+* S) (s : subring R) : (s.map f : set S) = f '' s := rfl
@[simp] lemma mem_map {f : R →+* S} {s : subring R} {y : S} :
y ∈ s.map f ↔ ∃ x ∈ s, f x = y :=
set.mem_image_iff_bex
lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) :=
ext' $ set.image_image _ _ _
lemma map_le_iff_le_comap {f : R →+* S} {s : subring R} {t : subring S} :
s.map f ≤ t ↔ s ≤ t.comap f :=
set.image_subset_iff
lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) :=
λ S T, map_le_iff_le_comap
end subring
namespace ring_hom
variables (g : S →+* T) (f : R →+* S)
/-! # range -/
/-- The range of a ring homomorphism, as a subring of the target. -/
def range {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) : subring S := (⊤ : subring R).map f
@[simp] lemma coe_range : (f.range : set S) = set.range f := set.image_univ
@[simp] lemma mem_range {f : R →+* S} {y : S} : y ∈ f.range ↔ ∃ x, f x = y :=
by simp [range]
lemma map_range : f.range.map g = (g.comp f).range :=
(⊤ : subring R).map_map g f
-- TODO -- rename to `cod_restrict` when is_ring_hom is deprecated
/-- Restrict the codomain of a ring homomorphism to a subring that includes the range. -/
def cod_restrict' {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S)
(s : subring S) (h : ∀ x, f x ∈ s) : R →+* s :=
{ to_fun := λ x, ⟨f x, h x⟩,
map_add' := λ x y, subtype.eq $ f.map_add x y,
map_zero' := subtype.eq f.map_zero,
map_mul' := λ x y, subtype.eq $ f.map_mul x y,
map_one' := subtype.eq f.map_one }
end ring_hom
namespace subring
variables {cR : Type u} [comm_ring cR]
/-- A subring of a commutative ring is a commutative ring. -/
def subset_comm_ring (S : subring cR) : comm_ring S :=
{mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..subring.to_ring S}
/-- A subring of an integral domain is an integral domain. -/
instance subring.domain {D : Type*} [integral_domain D] (S : subring D) : integral_domain S :=
{ exists_pair_ne := ⟨0, 1, mt subtype.ext_iff_val.1 zero_ne_one⟩,
eq_zero_or_eq_zero_of_mul_eq_zero := λ ⟨x, hx⟩ ⟨y, hy⟩,
by { simp only [subtype.ext_iff_val, subtype.coe_mk], exact eq_zero_or_eq_zero_of_mul_eq_zero },
.. S.subset_comm_ring, }
/-! # bot -/
instance : has_bot (subring R) := ⟨(int.cast_ring_hom R).range⟩
instance : inhabited (subring R) := ⟨⊥⟩
lemma coe_bot : ((⊥ : subring R) : set R) = set.range (coe : ℤ → R) :=
ring_hom.coe_range (int.cast_ring_hom R)
lemma mem_bot {x : R} : x ∈ (⊥ : subring R) ↔ ∃ (n : ℤ), ↑n = x :=
ring_hom.mem_range
/-! # inf -/
/-- The inf of two subrings is their intersection. -/
instance : has_inf (subring R) :=
⟨λ s t,
{ carrier := s ∩ t,
.. s.to_submonoid ⊓ t.to_submonoid,
.. s.to_add_subgroup ⊓ t.to_add_subgroup }⟩
@[simp] lemma coe_inf (p p' : subring R) : ((p ⊓ p' : subring R) : set R) = p ∩ p' := rfl
@[simp] lemma mem_inf {p p' : subring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
instance : has_Inf (subring R) :=
⟨λ s, subring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subring.to_submonoid t ) (⨅ t ∈ s, subring.to_add_subgroup t) (by simp) (by simp)⟩
@[simp, norm_cast] lemma coe_Inf (S : set (subring R)) :
((Inf S : subring R) : set R) = ⋂ s ∈ S, ↑s := rfl
lemma mem_Inf {S : set (subring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff
@[simp] lemma Inf_to_submonoid (s : set (subring R)) : (Inf s).to_submonoid = ⨅ t ∈ s, subring.to_submonoid t := mk'_to_submonoid _ _
@[simp] lemma Inf_to_add_subgroup (s : set (subring R)) :
(Inf s).to_add_subgroup = ⨅ t ∈ s, subring.to_add_subgroup t := mk'_to_add_subgroup _ _
/-- Subrings of a ring form a complete lattice. -/
instance : complete_lattice (subring R) :=
{ bot := (⊥),
bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ s.coe_int_mem n,
top := (⊤),
le_top := λ s x hx, trivial,
inf := (⊓),
inf_le_left := λ s t x, and.left,
inf_le_right := λ s t x, and.right,
le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩,
.. complete_lattice_of_Inf (subring R)
(λ s, is_glb.of_image (λ s t, show (s : set R) ≤ t ↔ s ≤ t, from coe_subset_coe) is_glb_binfi)}
/-! # subring closure of a subset -/
/-- The `subring` generated by a set. -/
def closure (s : set R) : subring R := Inf {S | s ⊆ S}
lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subring R, s ⊆ S → x ∈ S :=
mem_Inf
/-- The subring generated by a set includes the set. -/
@[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx
/-- A subring `t` includes `closure s` if and only if it includes `s`. -/
@[simp]
lemma closure_le {s : set R} {t : subring R} : closure s ≤ t ↔ s ⊆ t :=
⟨set.subset.trans subset_closure, λ h, Inf_le h⟩
/-- Subring closure of a set is monotone in its argument: if `s ⊆ t`,
then `closure s ≤ closure t`. -/
lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t :=
closure_le.2 $ set.subset.trans h subset_closure
lemma closure_eq_of_le {s : set R} {t : subring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) :
closure s = t :=
le_antisymm (closure_le.2 h₁) h₂
/-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements
of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all elements
of the closure of `s`. -/
@[elab_as_eliminator]
lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1)
(Hadd : ∀ x y, p x → p y → p (x + y))
(Hneg : ∀ (x : R), p x → p (-x))
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
(@closure_le _ _ _ ⟨p, H1, Hmul, H0, Hadd, Hneg⟩).2 Hs h
lemma mem_closure_iff {s : set R} {x} :
x ∈ closure s ↔ x ∈ add_subgroup.closure (submonoid.closure s : set R) :=
⟨ λ h, closure_induction h (λ x hx, add_subgroup.subset_closure $ submonoid.subset_closure hx )
(add_subgroup.zero_mem _)
(add_subgroup.subset_closure ( submonoid.one_mem (submonoid.closure s)) )
(λ x y hx hy, add_subgroup.add_mem _ hx hy )
(λ x hx, add_subgroup.neg_mem _ hx )
( λ x y hx hy, add_subgroup.closure_induction hy
(λ q hq, add_subgroup.closure_induction hx
( λ p hp, add_subgroup.subset_closure ((submonoid.closure s).mul_mem hp hq) )
( begin rw zero_mul q, apply add_subgroup.zero_mem _, end )
( λ p₁ p₂ ihp₁ ihp₂, begin rw add_mul p₁ p₂ q, apply add_subgroup.add_mem _ ihp₁ ihp₂, end )
( λ x hx, begin have f : -x * q = -(x*q) := by simp, rw f, apply add_subgroup.neg_mem _ hx, end ) )
( begin rw mul_zero x, apply add_subgroup.zero_mem _, end )
( λ q₁ q₂ ihq₁ ihq₂, begin rw mul_add x q₁ q₂, apply add_subgroup.add_mem _ ihq₁ ihq₂ end )
( λ z hz, begin have f : x * -z = -(x*z) := by simp, rw f, apply add_subgroup.neg_mem _ hz, end ) ),
λ h, add_subgroup.closure_induction h
( λ x hx, submonoid.closure_induction hx
( λ x hx, subset_closure hx )
( one_mem _ )
( λ x y hx hy, mul_mem _ hx hy ) )
( zero_mem _ )
(λ x y hx hy, add_mem _ hx hy)
( λ x hx, neg_mem _ hx ) ⟩
theorem exists_list_of_mem_closure {s : set R} {x : R} (h : x ∈ closure s) :
(∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s ∨ y = (-1:R)) ∧ (L.map list.prod).sum = x) :=
add_subgroup.closure_induction (mem_closure_iff.1 h)
(λ x hx, let ⟨l, hl, h⟩ :=submonoid.exists_list_of_mem_closure hx in ⟨[l], by simp [h];
clear_aux_decl; tauto!⟩)
⟨[], by simp⟩
(λ x y ⟨l, hl1, hl2⟩ ⟨m, hm1, hm2⟩, ⟨l ++ m, λ t ht, (list.mem_append.1 ht).elim (hl1 t) (hm1 t),
by simp [hl2, hm2]⟩)
(λ x ⟨L, hL⟩, ⟨L.map (list.cons (-1)), list.forall_mem_map_iff.2 $ λ j hj, list.forall_mem_cons.2
⟨or.inr rfl, hL.1 j hj⟩, hL.2 ▸ list.rec_on L (by simp)
(by simp [list.map_cons, add_comm] {contextual := tt})⟩)
variable (R)
/-- `closure` forms a Galois insertion with the coercion to set. -/
protected def gi : galois_insertion (@closure R _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, closure_le,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {R}
/-- Closure of a subring `S` equals `S`. -/
lemma closure_eq (s : subring R) : closure (s : set R) = s := (subring.gi R).l_u_eq s
@[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subring.gi R).gc.l_bot
@[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤
lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t :=
(subring.gi R).gc.l_sup
lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(subring.gi R).gc.l_supr
lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t :=
(subring.gi R).gc.l_Sup
lemma map_sup (s t : subring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f :=
(gc_map_comap f).l_sup
lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subring R) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
lemma comap_inf (s t : subring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f :=
(gc_map_comap f).u_inf
lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subring S) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp] lemma map_bot (f : R →+* S) : (⊥ : subring R).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma comap_top (f : R →+* S) : (⊤ : subring S).comap f = ⊤ :=
(gc_map_comap f).u_top
/-- Given `subring`s `s`, `t` of rings `R`, `S` respectively, `s.prod t` is `s × t`
as a subring of `R × S`. -/
def prod (s : subring R) (t : subring S) : subring (R × S) :=
{ carrier := (s : set R).prod t,
.. s.to_submonoid.prod t.to_submonoid, .. s.to_add_subgroup.prod t.to_add_subgroup}
@[norm_cast]
lemma coe_prod (s : subring R) (t : subring S) :
(s.prod t : set (R × S)) = (s : set R).prod (t : set S) :=
rfl
lemma mem_prod {s : subring R} {t : subring S} {p : R × S} :
p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl
@[mono] lemma prod_mono ⦃s₁ s₂ : subring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subring S⦄
(ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ :=
set.prod_mono hs ht
lemma prod_mono_right (s : subring R) : monotone (λ t : subring S, s.prod t) :=
prod_mono (le_refl s)
lemma prod_mono_left (t : subring S) : monotone (λ s : subring R, s.prod t) :=
λ s₁ s₂ hs, prod_mono hs (le_refl t)
lemma prod_top (s : subring R) :
s.prod (⊤ : subring S) = s.comap (ring_hom.fst R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst]
lemma top_prod (s : subring S) :
(⊤ : subring R).prod s = s.comap (ring_hom.snd R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd]
@[simp]
lemma top_prod_top : (⊤ : subring R).prod (⊤ : subring S) = ⊤ :=
(top_prod _).trans $ comap_top _
/-- Product of subrings is isomorphic to their product as rings. -/
def prod_equiv (s : subring R) (t : subring S) : s.prod t ≃+* s × t :=
{ map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t }
/-- The underlying set of a non-empty directed Sup of subrings is just a union of the subrings.
Note that this fails without the directedness assumption (the union of two subrings is
typically not a subring) -/
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S)
{x : R} :
x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr S i) hi⟩,
let U : subring R := subring.mk' (⋃ i, (S i : set R))
(⨆ i, (S i).to_submonoid) (⨆ i, (S i).to_add_subgroup)
(submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id))
(add_subgroup.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)),
suffices : (⨆ i, S i) ≤ U, by simpa using @this x,
exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩),
end
lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) :
((⨆ i, S i : subring R) : set R) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
lemma mem_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty)
(hS : directed_on (≤) S) {x : R} :
x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s :=
begin
haveI : nonempty S := Sne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk]
end
lemma coe_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) :
(↑(Sup S) : set R) = ⋃ s ∈ S, ↑s :=
set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS]
end subring
namespace ring_hom
variables [ring T] {s : subring R}
open subring
/-- Restriction of a ring homomorphism to a subring of the domain. -/
def restrict (f : R →+* S) (s : subring R) : s →+* S := f.comp s.subtype
@[simp] lemma restrict_apply (f : R →+* S) (x : s) : f.restrict s x = f x := rfl
/-- Restriction of a ring homomorphism to its range interpreted as a subsemiring. -/
def range_restrict (f : R →+* S) : R →+* f.range :=
f.cod_restrict' f.range $ λ x, ⟨x, subring.mem_top x, rfl⟩
@[simp] lemma coe_range_restrict (f : R →+* S) (x : R) : (f.range_restrict x : S) = f x := rfl
lemma range_top_iff_surjective {f : R →+* S} :
f.range = (⊤ : subring S) ↔ function.surjective f :=
subring.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective
/-- The range of a surjective ring homomorphism is the whole of the codomain. -/
lemma range_top_of_surjective (f : R →+* S) (hf : function.surjective f) :
f.range = (⊤ : subring S) :=
range_top_iff_surjective.2 hf
/-- The subring of elements `x : R` such that `f x = g x`, i.e.,
the equalizer of f and g as a subring of R -/
def eq_locus (f g : R →+* S) : subring R :=
{ carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_locus g }
/-- If two ring homomorphisms are equal on a set, then they are equal on its subring closure. -/
lemma eq_on_set_closure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_locus g, from closure_le.2 h
lemma eq_of_eq_on_set_top {f g : R →+* S} (h : set.eq_on f g (⊤ : subring R)) :
f = g :=
ext $ λ x, h trivial
lemma eq_of_eq_on_set_dense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_set_top $ hs ▸ eq_on_set_closure h
lemma closure_preimage_le (f : R →+* S) (s : set S) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx
/-- The image under a ring homomorphism of the subring generated by a set equals
the subring generated by the image of the set. -/
lemma map_closure (f : R →+* S) (s : set R) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _)
(closure_preimage_le _ _))
(closure_le.2 $ set.image_subset _ subset_closure)
end ring_hom
namespace subring
open ring_hom
/-- The ring homomorphism associated to an inclusion of subrings. -/
def inclusion {S T : subring R} (h : S ≤ T) : S →* T :=
S.subtype.cod_restrict' _ (λ x, h x.2)
@[simp] lemma range_subtype (s : subring R) : s.subtype.range = s :=
ext' $ (coe_srange _).trans subtype.range_coe
@[simp]
lemma range_fst : (fst R S).srange = ⊤ :=
(fst R S).srange_top_of_surjective $ prod.fst_surjective
@[simp]
lemma range_snd : (snd R S).srange = ⊤ :=
(snd R S).srange_top_of_surjective $ prod.snd_surjective
@[simp]
lemma prod_bot_sup_bot_prod (s : subring R) (t : subring S) :
(s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t :=
le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $
assume p hp, prod.fst_mul_snd p ▸ mul_mem _
((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, mem_coe.2 $ one_mem ⊥⟩)
((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨mem_coe.2 $ one_mem ⊥, hp.2⟩)
end subring
namespace ring_equiv
variables {s t : subring R}
/-- Makes the identity isomorphism from a proof two subrings of a multiplicative
monoid are equal. -/
def subring_congr (h : s = t) : s ≃+* t :=
{ map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ subring.ext'_iff.1 h }
end ring_equiv
namespace subring
variables {s : set R}
local attribute [reducible] closure
@[elab_as_eliminator]
protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s)
(h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n))
(ha : ∀ {x y}, C x → C y → C (x + y)) : C x :=
begin
have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1,
rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx,
induction L with hd tl ih, { exact h0 },
rw list.forall_mem_cons at HL,
suffices : C (list.prod hd),
{ rw [list.map_cons, list.sum_cons],
exact ha this (ih HL.2) },
replace HL := HL.1, clear ih tl,
suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L),
{ rcases this with ⟨L, HL', HP | HP⟩,
{ rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 },
rw list.forall_mem_cons at HL',
rw list.prod_cons,
exact hs _ HL'.1 _ (ih HL'.2) },
rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 },
rw [list.prod_cons, neg_mul_eq_mul_neg],
rw list.forall_mem_cons at HL',
exact hs _ HL'.1 _ (ih HL'.2) },
induction hd with hd tl ih,
{ exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ },
rw list.forall_mem_cons at HL,
rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd,
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $
by rw [list.prod_cons, list.prod_cons, HP]⟩ },
{ exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ },
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $
by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ },
{ exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ }
end
lemma closure_preimage_le (f : R →+* S) (s : set S) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx
end subring
|
49a3ac91bdbd50686536d27ee9612501585cbcde | 137c667471a40116a7afd7261f030b30180468c2 | /src/ring_theory/localization.lean | d7fcc414e1c039c2617eb8fa1e04bfaceb93d086 | [
"Apache-2.0"
] | permissive | bragadeesh153/mathlib | 46bf814cfb1eecb34b5d1549b9117dc60f657792 | b577bb2cd1f96eb47031878256856020b76f73cd | refs/heads/master | 1,687,435,188,334 | 1,626,384,207,000 | 1,626,384,207,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 72,831 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston
-/
import data.equiv.ring
import group_theory.monoid_localization
import ring_theory.ideal.operations
import ring_theory.algebraic
import ring_theory.integral_closure
import ring_theory.non_zero_divisors
/-!
# Localizations of commutative rings
We characterize the localization of a commutative ring `R` at a submonoid `M` up to
isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a
ring homomorphism `f : R →+* S` satisfying 3 properties:
1. For all `y ∈ M`, `f y` is a unit;
2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`;
3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`.
In the following, let `R, P` be commutative rings, `S, Q` be `R`- and `P`-algebras
and `M, T` be submonoids of `R` and `P` respectively, e.g.:
```
variables (R S P Q : Type*) [comm_ring R] [comm_ring S] [comm_ring P] [comm_ring Q]
variables [algebra R S] [algebra P Q] (M : submonoid R) (T : submonoid P)
```
## Main definitions
* `is_localization (M : submonoid R) (S : Type*)` is a typeclass expressing that `S` is a
localization of `R` at `M`, i.e. the canonical map `algebra_map R S : R →+* S` is a
localization map (satisfying the above properties).
* `is_localization.mk' S` is a surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`
* `is_localization.lift` is the ring homomorphism from `S` induced by a homomorphism from `R`
which maps elements of `M` to invertible elements of the codomain.
* `is_localization.map S Q` is the ring homomorphism from `S` to `Q` which maps elements
of `M` to elements of `T`
* `is_localization.ring_equiv_of_ring_equiv`: if `R` and `P` are isomorphic by an isomorphism
sending `M` to `T`, then `S` and `Q` are isomorphic
* `is_localization.alg_equiv`: if `Q` is another localization of `R` at `M`, then `S` and `Q`
are isomorphic as `R`-algebras
* `is_localization.is_integer` is a predicate stating that `x : S` is in the image of `R`
* `is_localization.away (x : R) S` expresses that `S` is a localization away from `x`, as an
abbreviation of `is_localization (submonoid.powers x) S`
* `is_localization.at_prime (I : ideal R) [is_prime I] (S : Type*)` expresses that `S` is a
localization at (the complement of) a prime ideal `I`, as an abbreviation of
`is_localization I.prime_compl S`
* `is_fraction_ring R K` expresses that `K` is a field of fractions of `R`, as an abbreviation of
`is_localization (non_zero_divisors R) K`
## Main results
* `localization M S`, a construction of the localization as a quotient type, defined in
`group_theory.monoid_localization`, has `comm_ring`, `algebra R` and `is_localization M`
instances if `R` is a ring. `localization.away`, `localization.at_prime` and `fraction_ring`
are abbreviations for `localization`s and have their corresponding `is_localization` instances
* `is_localization.at_prime.local_ring`: a theorem (not an instance) stating a localization at the
complement of a prime ideal is a local ring
* `is_fraction_ring.field`: a definition (not an instance) stating the localization of an integral
domain `R` at `R \ {0}` is a field
* `rat.is_fraction_ring_int` is an instance stating `ℚ` is the field of fractions of `ℤ`
## Implementation notes
In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one
structure with an isomorphic one; one way around this is to isolate a predicate characterizing
a structure up to isomorphism, and reason about things that satisfy the predicate.
A previous version of this file used a fully bundled type of ring localization maps,
then used a type synonym `f.codomain` for `f : localization_map M S` to instantiate the
`R`-algebra structure on `S`. This results in defining ad-hoc copies for everything already
defined on `S`. By making `is_localization` a predicate on the `algebra_map R S`,
we can ensure the localization map commutes nicely with other `algebra_map`s.
To prove most lemmas about a localization map `algebra_map R S` in this file we invoke the
corresponding proof for the underlying `comm_monoid` localization map
`is_localization.to_localization_map M S`, which can be found in `group_theory.monoid_localization`
and the namespace `submonoid.localization_map`.
To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas.
These show the quotient map `mk : R → M → localization M` equals the surjection
`localization_map.mk'` induced by the map `algebra_map : R →+* localization M`.
The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file,
which are about the `localization_map.mk'` induced by any localization map.
The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}`
is a field" is a `def` rather than an `instance`, so if you want to reason about a field of
fractions `K`, assume `[field K]` instead of just `[comm_ring K]`.
## Tags
localization, ring localization, commutative ring localization, characteristic predicate,
commutative ring, field of fractions
-/
variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S]
variables [algebra R S] {P : Type*} [comm_ring P]
open function
open_locale big_operators
/-- The typeclass `is_localization (M : submodule R) S` where `S` is an `R`-algebra
expresses that `S` is isomorphic to the localization of `R` at `M`. -/
class is_localization : Prop :=
(map_units [] : ∀ y : M, is_unit (algebra_map R S y))
(surj [] : ∀ z : S, ∃ x : R × M, z * algebra_map R S x.2 = algebra_map R S x.1)
(eq_iff_exists [] : ∀ {x y}, algebra_map R S x = algebra_map R S y ↔ ∃ c : M, x * c = y * c)
variables {M S}
namespace is_localization
section is_localization
variables [is_localization M S]
section
variables (M S)
/-- `is_localization.to_localization_map M S` shows `S` is the monoid localization of `R` at `M`. -/
@[simps]
def to_localization_map : submonoid.localization_map M S :=
{ to_fun := algebra_map R S,
map_units' := is_localization.map_units _,
surj' := is_localization.surj _,
eq_iff_exists' := λ _ _, is_localization.eq_iff_exists _ _,
.. algebra_map R S }
@[simp]
lemma to_localization_map_to_map :
(to_localization_map M S).to_map = (algebra_map R S : R →* S) := rfl
lemma to_localization_map_to_map_apply (x) :
(to_localization_map M S).to_map x = algebra_map R S x := rfl
end
section
variables (R)
-- TODO: define a subalgebra of `is_integer`s
/-- Given `a : S`, `S` a localization of `R`, `is_integer R a` iff `a` is in the image of
the localization map from `R` to `S`. -/
def is_integer (a : S) : Prop := a ∈ (algebra_map R S).range
end
lemma is_integer_zero : is_integer R (0 : S) := subring.zero_mem _
lemma is_integer_one : is_integer R (1 : S) := subring.one_mem _
lemma is_integer_add {a b : S} (ha : is_integer R a) (hb : is_integer R b) :
is_integer R (a + b) :=
subring.add_mem _ ha hb
lemma is_integer_mul {a b : S} (ha : is_integer R a) (hb : is_integer R b) :
is_integer R (a * b) :=
subring.mul_mem _ ha hb
lemma is_integer_smul {a : R} {b : S} (hb : is_integer R b) :
is_integer R (a • b) :=
begin
rcases hb with ⟨b', hb⟩,
use a * b',
rw [←hb, (algebra_map R S).map_mul, algebra.smul_def]
end
variables (M)
/-- Each element `a : S` has an `M`-multiple which is an integer.
This version multiplies `a` on the right, matching the argument order in `localization_map.surj`.
-/
lemma exists_integer_multiple' (a : S) :
∃ (b : M), is_integer R (a * algebra_map R S b) :=
let ⟨⟨num, denom⟩, h⟩ := is_localization.surj _ a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩
/-- Each element `a : S` has an `M`-multiple which is an integer.
This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance.
-/
lemma exists_integer_multiple (a : S) :
∃ (b : M), is_integer R ((b : R) • a) :=
by { simp_rw [algebra.smul_def, mul_comm _ a], apply exists_integer_multiple' }
/-- Given a localization map `f : M →* N`, a section function sending `z : N` to some
`(x, y) : M × S` such that `f x * (f y)⁻¹ = z`. -/
noncomputable def sec (z : S) : R × M :=
classical.some $ is_localization.surj _ z
@[simp] lemma to_localization_map_sec : (to_localization_map M S).sec = sec M := rfl
/-- Given `z : S`, `is_localization.sec M z` is defined to be a pair `(x, y) : R × M` such
that `z * f y = f x` (so this lemma is true by definition). -/
lemma sec_spec (z : S) :
z * algebra_map R S (is_localization.sec M z).2 =
algebra_map R S (is_localization.sec M z).1 :=
classical.some_spec $ is_localization.surj _ z
/-- Given `z : S`, `is_localization.sec M z` is defined to be a pair `(x, y) : R × M` such
that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/
lemma sec_spec' (z : S) :
algebra_map R S (is_localization.sec M z).1 =
algebra_map R S (is_localization.sec M z).2 * z :=
by rw [mul_comm, sec_spec]
open_locale big_operators
/-- We can clear the denominators of a finite set of fractions. -/
lemma exist_integer_multiples_of_finset (s : finset S) :
∃ (b : M), ∀ a ∈ s, is_integer R ((b : R) • a) :=
begin
haveI := classical.prop_decidable,
use ∏ a in s, (is_localization.sec M a).2,
intros a ha,
use (∏ x in s.erase a, (is_localization.sec M x).2) * (is_localization.sec M a).1,
rw [ring_hom.map_mul, sec_spec', ←mul_assoc, ←(algebra_map R S).map_mul, ← algebra.smul_def],
congr' 2,
refine trans _ ((submonoid.subtype M).map_prod _ _).symm,
rw [mul_comm, ←finset.prod_insert (s.not_mem_erase a), finset.insert_erase ha],
refl,
end
variables {R M}
lemma map_right_cancel {x y} {c : M} (h : algebra_map R S (c * x) = algebra_map R S (c * y)) :
algebra_map R S x = algebra_map R S y :=
(to_localization_map M S).map_right_cancel h
lemma map_left_cancel {x y} {c : M} (h : algebra_map R S (x * c) = algebra_map R S (y * c)) :
algebra_map R S x = algebra_map R S y :=
(to_localization_map M S).map_left_cancel h
lemma eq_zero_of_fst_eq_zero {z x} {y : M}
(h : z * algebra_map R S y = algebra_map R S x) (hx : x = 0) : z = 0 :=
by { rw [hx, (algebra_map R S).map_zero] at h,
exact (is_unit.mul_left_eq_zero (is_localization.map_units S y)).1 h}
variables (S)
/-- `is_localization.mk' S` is the surjection sending `(x, y) : R × M` to
`f x * (f y)⁻¹`. -/
noncomputable def mk' (x : R) (y : M) : S :=
(to_localization_map M S).mk' x y
@[simp] lemma mk'_sec (z : S) :
mk' S (is_localization.sec M z).1 (is_localization.sec M z).2 = z :=
(to_localization_map M S).mk'_sec _
lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) :
mk' S (x₁ * x₂) (y₁ * y₂) = mk' S x₁ y₁ * mk' S x₂ y₂ :=
(to_localization_map M S).mk'_mul _ _ _ _
lemma mk'_one (x) : mk' S x (1 : M) = algebra_map R S x :=
(to_localization_map M S).mk'_one _
@[simp]
lemma mk'_spec (x) (y : M) :
mk' S x y * algebra_map R S y = algebra_map R S x :=
(to_localization_map M S).mk'_spec _ _
@[simp]
lemma mk'_spec' (x) (y : M) :
algebra_map R S y * mk' S x y = algebra_map R S x :=
(to_localization_map M S).mk'_spec' _ _
variables {S}
theorem eq_mk'_iff_mul_eq {x} {y : M} {z} :
z = mk' S x y ↔ z * algebra_map R S y = algebra_map R S x :=
(to_localization_map M S).eq_mk'_iff_mul_eq
theorem mk'_eq_iff_eq_mul {x} {y : M} {z} :
mk' S x y = z ↔ algebra_map R S x = z * algebra_map R S y :=
(to_localization_map M S).mk'_eq_iff_eq_mul
variables (M)
lemma mk'_surjective (z : S) : ∃ x (y : M), mk' S x y = z :=
let ⟨r, hr⟩ := is_localization.surj _ z in ⟨r.1, r.2, (eq_mk'_iff_mul_eq.2 hr).symm⟩
variables {M}
lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} :
mk' S x₁ y₁ = mk' S x₂ y₂ ↔ algebra_map R S (x₁ * y₂) = algebra_map R S (x₂ * y₁) :=
(to_localization_map M S).mk'_eq_iff_eq
lemma mk'_mem_iff {x} {y : M} {I : ideal S} : mk' S x y ∈ I ↔ algebra_map R S x ∈ I :=
begin
split;
intro h,
{ rw [← mk'_spec S x y, mul_comm],
exact I.mul_mem_left ((algebra_map R S) y) h },
{ rw ← mk'_spec S x y at h,
obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (map_units S y),
have := I.mul_mem_left b h,
rwa [mul_comm, mul_assoc, hb, mul_one] at this }
end
protected lemma eq {a₁ b₁} {a₂ b₂ : M} :
mk' S a₁ a₂ = mk' S b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c :=
(to_localization_map M S).eq
section ext
variables [algebra R P] [is_localization M P]
lemma eq_iff_eq {x y} :
algebra_map R S x = algebra_map R S y ↔ algebra_map R P x = algebra_map R P y :=
(to_localization_map M S).eq_iff_eq (to_localization_map M P)
lemma mk'_eq_iff_mk'_eq {x₁ x₂}
{y₁ y₂ : M} : mk' S x₁ y₁ = mk' S x₂ y₂ ↔ mk' P x₁ y₁ = mk' P x₂ y₂ :=
(to_localization_map M S).mk'_eq_iff_mk'_eq (to_localization_map M P)
lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) :
mk' S a₁ a₂ = mk' S b₁ b₂ :=
(to_localization_map M S).mk'_eq_of_eq H
variables (S)
@[simp] lemma mk'_self {x : R} (hx : x ∈ M) : mk' S x ⟨x, hx⟩ = 1 :=
(to_localization_map M S).mk'_self _ hx
@[simp] lemma mk'_self' {x : M} : mk' S (x : R) x = 1 :=
(to_localization_map M S).mk'_self' _
lemma mk'_self'' {x : M} : mk' S x.1 x = 1 :=
mk'_self' _
end ext
lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) :
(algebra_map R S) x * mk' S y z = mk' S (x * y) z :=
(to_localization_map M S).mul_mk'_eq_mk'_of_mul _ _ _
lemma mk'_eq_mul_mk'_one (x : R) (y : M) :
mk' S x y = (algebra_map R S) x * mk' S 1 y :=
((to_localization_map M S).mul_mk'_one_eq_mk' _ _).symm
@[simp] lemma mk'_mul_cancel_left (x : R) (y : M) :
mk' S (y * x : R) y = (algebra_map R S) x :=
(to_localization_map M S).mk'_mul_cancel_left _ _
lemma mk'_mul_cancel_right (x : R) (y : M) :
mk' S (x * y) y = (algebra_map R S) x :=
(to_localization_map M S).mk'_mul_cancel_right _ _
@[simp] lemma mk'_mul_mk'_eq_one (x y : M) :
mk' S (x : R) y * mk' S (y : R) x = 1 :=
by rw [←mk'_mul, mul_comm]; exact mk'_self _ _
lemma mk'_mul_mk'_eq_one' (x : R) (y : M) (h : x ∈ M) :
mk' S x y * mk' S (y : R) ⟨x, h⟩ = 1 :=
mk'_mul_mk'_eq_one ⟨x, h⟩ _
section
variables (M)
lemma is_unit_comp (j : S →+* P) (y : M) :
is_unit (j.comp (algebra_map R S) y) :=
(to_localization_map M S).is_unit_comp j.to_monoid_hom _
end
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/
lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y}
(h : (algebra_map R S) x = (algebra_map R S) y) :
g x = g y :=
@submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _
(to_localization_map M S) g.to_monoid_hom hg _ _ h
lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) :
mk' S (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = mk' S x₁ y₁ + mk' S x₂ y₂ :=
mk'_eq_iff_eq_mul.2 $ eq.symm
begin
rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul,
mul_comm _ ((algebra_map R S) _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc,
←(algebra_map R S).map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul],
simp only [(algebra_map R S).map_add, submonoid.coe_mul, (algebra_map R S).map_mul],
ring_exp,
end
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from
`S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that
`z = f x * (f y)⁻¹`. -/
noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P :=
ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _
(to_localization_map M S) g.to_monoid_hom hg) $
begin
intros x y,
rw [(to_localization_map M S).lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm,
(to_localization_map M S).lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq',
←eq_sub_iff_add_eq, mul_assoc, (to_localization_map M S).lift_spec_mul],
show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _),
simp only [← g.map_sub, ← g.map_mul, to_localization_map_sec],
apply eq_of_eq hg,
rw [(algebra_map R S).map_mul, sec_spec', mul_sub, (algebra_map R S).map_sub],
simp only [ring_hom.map_mul, sec_spec'],
ring,
assumption
end
variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y))
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from
`S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/
lemma lift_mk' (x y) :
lift hg (mk' S x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.mrestrict M) hg y)⁻¹ :=
(to_localization_map M S).lift_mk' _ _ _
lemma lift_mk'_spec (x v) (y : M) :
lift hg (mk' S x y) = v ↔ g x = g y * v :=
(to_localization_map M S).lift_mk'_spec _ _ _ _
@[simp] lemma lift_eq (x : R) :
lift hg ((algebra_map R S) x) = g x :=
(to_localization_map M S).lift_eq _ _
lemma lift_eq_iff {x y : R × M} :
lift hg (mk' S x.1 x.2) = lift hg (mk' S y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) :=
(to_localization_map M S).lift_eq_iff _
@[simp] lemma lift_comp : (lift hg).comp (algebra_map R S) = g :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ (to_localization_map M S).lift_comp _
@[simp] lemma lift_of_comp (j : S →+* P) :
lift (is_unit_comp M j) = j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ (to_localization_map M S).lift_of_comp j.to_monoid_hom
variables (M)
lemma epic_of_localization_map (j k : S →+* P)
(h : ∀ a, j.comp (algebra_map R S) a = k.comp (algebra_map R S) a) : j = k :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map
_ _ _ _ _ _ _ (to_localization_map M S) j.to_monoid_hom k.to_monoid_hom h
variables {M}
lemma lift_unique {j : S →+* P}
(hj : ∀ x, j ((algebra_map R S) x) = g x) : lift hg = j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique
_ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom hg j.to_monoid_hom hj
@[simp] lemma lift_id (x) : lift (map_units S : ∀ y : M, is_unit _) x = x :=
(to_localization_map M S).lift_id _
lemma lift_surjective_iff :
surjective (lift hg : S → P) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 :=
(to_localization_map M S).lift_surjective_iff hg
lemma lift_injective_iff :
injective (lift hg : S → P) ↔ ∀ x y, algebra_map R S x = algebra_map R S y ↔ g x = g y :=
(to_localization_map M S).lift_injective_iff hg
section map
variables {T : submonoid P} {Q : Type*} [comm_ring Q] (hy : M ≤ T.comap g)
variables [algebra P Q] [is_localization T Q]
section
variables (Q)
/-- Map a homomorphism `g : R →+* P` to `S →+* Q`, where `S` and `Q` are
localizations of `R` and `P` at `M` and `T` respectively,
such that `g(M) ⊆ T`.
We send `z : S` to `algebra_map P Q (g x) * (algebra_map P Q (g y))⁻¹`, where
`(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/
noncomputable def map (g : R →+* P) (hy : M ≤ T.comap g) : S →+* Q :=
@lift R _ M _ _ _ _ _ _ ((algebra_map P Q).comp g) (λ y, map_units _ ⟨g y, hy y.2⟩)
end
lemma map_eq (x) :
map Q g hy ((algebra_map R S) x) = algebra_map P Q (g x) :=
lift_eq (λ y, map_units _ ⟨g y, hy y.2⟩) x
@[simp] lemma map_comp :
(map Q g hy).comp (algebra_map R S) = (algebra_map P Q).comp g :=
lift_comp $ λ y, map_units _ ⟨g y, hy y.2⟩
lemma map_mk' (x) (y : M) :
map Q g hy (mk' S x y) = mk' Q (g x) ⟨g y, hy y.2⟩ :=
@submonoid.localization_map.map_mk' _ _ _ _ _ _ _ (to_localization_map M S)
g.to_monoid_hom _ (λ y, hy y.2) _ _ (to_localization_map T Q) _ _
@[simp] lemma map_id (z : S) (h : M ≤ M.comap (ring_hom.id R) := le_refl M) :
map S (ring_hom.id _) h z = z :=
lift_id _
lemma map_unique (j : S →+* Q)
(hj : ∀ x : R, j (algebra_map R S x) = algebra_map P Q (g x)) : map Q g hy = j :=
lift_unique (λ y, map_units _ ⟨g y, hy y.2⟩) hj
/-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition
of the induced maps equals the map of localizations induced by `l ∘ g`. -/
lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W]
[algebra A W] [is_localization U W] {l : P →+* A} (hl : T ≤ U.comap l) :
(map W l hl).comp (map Q g hy : S →+* _) = map W (l.comp g) (λ x hx, hl (hy hx)) :=
ring_hom.ext $ λ x, @submonoid.localization_map.map_map _ _ _ _ _ P _ (to_localization_map M S) g _
_ _ _ _ _ _ _ _ _ (to_localization_map U W) l _ x
/-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition
of the induced maps equals the map of localizations induced by `l ∘ g`. -/
lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W]
[algebra A W] [is_localization U W] {l : P →+* A} (hl : T ≤ U.comap l) (x : S) :
map W l hl (map Q g hy x) = map W (l.comp g) (λ x hx, hl (hy hx)) x :=
by rw ←map_comp_map hy hl; refl
section
variables (S Q)
/-- If `S`, `Q` are localizations of `R` and `P` at submonoids `M, T` respectively, an
isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations
`S ≃+* Q`. -/
@[simps]
noncomputable def ring_equiv_of_ring_equiv (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) :
S ≃+* Q :=
have H' : T.map h.symm.to_monoid_hom = M,
by { rw [← M.map_id, ← H, submonoid.map_map], congr, ext, apply h.symm_apply_apply },
{ to_fun := map Q (h : R →+* P) (M.le_comap_of_map_le (le_of_eq H)),
inv_fun := map S (h.symm : P →+* R) (T.le_comap_of_map_le (le_of_eq H')),
left_inv := λ x, by { rw [map_map, map_unique _ (ring_hom.id _), ring_hom.id_apply],
intro x, convert congr_arg (algebra_map R S) (h.symm_apply_apply x).symm },
right_inv := λ x, by { rw [map_map, map_unique _ (ring_hom.id _), ring_hom.id_apply],
intro x, convert congr_arg (algebra_map P Q) (h.apply_symm_apply x).symm },
.. map Q (h : R →+* P) _ }
end
lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) :
(ring_equiv_of_ring_equiv S Q j H : S →+* Q) =
map Q (j : R →+* P) (M.le_comap_of_map_le (le_of_eq H)) := rfl
@[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) :
ring_equiv_of_ring_equiv S Q j H ((algebra_map R S) x) = algebra_map P Q (j x) :=
map_eq _ _
lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x : R) (y : M) :
ring_equiv_of_ring_equiv S Q j H (mk' S x y) =
mk' Q (j x) ⟨j y, show j y ∈ T, from H ▸ set.mem_image_of_mem j y.2⟩ :=
map_mk' _ _ _
end map
section alg_equiv
variables {Q : Type*} [comm_ring Q] [algebra R Q] [is_localization M Q]
section
variables (M S Q)
/-- If `S`, `Q` are localizations of `R` at the submonoid `M` respectively,
there is an isomorphism of localizations `S ≃ₐ[R] Q`. -/
@[simps]
noncomputable def alg_equiv : S ≃ₐ[R] Q :=
{ commutes' := ring_equiv_of_ring_equiv_eq _,
.. ring_equiv_of_ring_equiv S Q (ring_equiv.refl R) M.map_id }
end
@[simp]
lemma alg_equiv_mk' (x : R) (y : M) : alg_equiv M S Q (mk' S x y) = mk' Q x y:=
map_mk' _ _ _
@[simp]
lemma alg_equiv_symm_mk' (x : R) (y : M) : (alg_equiv M S Q).symm (mk' Q x y) = mk' S x y:=
map_mk' _ _ _
end alg_equiv
end is_localization
section away
variables (x : R)
/-- Given `x : R`, the typeclass `is_localization.away x S` states that `S` is
isomorphic to the localization of `R` at the submonoid generated by `x`. -/
abbreviation away (S : Type*) [comm_ring S] [algebra R S] :=
is_localization (submonoid.powers x) S
namespace away
variables [is_localization.away x S]
/-- Given `x : R` and a localization map `F : R →+* S` away from `x`, `inv_self` is `(F x)⁻¹`. -/
noncomputable def inv_self : S :=
mk' S 1 ⟨x, submonoid.mem_powers _⟩
variables {g : R →+* P}
/-- Given `x : R`, a localization map `F : R →+* S` away from `x`, and a map of `comm_ring`s
`g : R →+* P` such that `g x` is invertible, the homomorphism induced from `S` to `P` sending
`z : S` to `g y * (g x)⁻ⁿ`, where `y : R, n : ℕ` are such that `z = F y * (F x)⁻ⁿ`. -/
noncomputable def lift (hg : is_unit (g x)) : S →+* P :=
is_localization.lift $ λ (y : submonoid.powers x), show is_unit (g y.1),
begin
obtain ⟨n, hn⟩ := y.2,
rw [←hn, g.map_pow],
exact is_unit.map (monoid_hom.of $ ((^ n) : P → P)) hg,
end
@[simp] lemma away_map.lift_eq (hg : is_unit (g x)) (a : R) :
lift x hg ((algebra_map R S) a) = g a := lift_eq _ _
@[simp] lemma away_map.lift_comp (hg : is_unit (g x)) :
(lift x hg).comp (algebra_map R S) = g := lift_comp _
/-- Given `x y : R` and localizations `S`, `P` away from `x` and `x * y`
respectively, the homomorphism induced from `S` to `P`. -/
noncomputable def away_to_away_right (y : R) [algebra R P] [is_localization.away (x * y) P] :
S →+* P :=
lift x $ show is_unit ((algebra_map R P) x), from
is_unit_of_mul_eq_one ((algebra_map R P) x) (mk' P y ⟨x * y, submonoid.mem_powers _⟩) $
by rw [mul_mk'_eq_mk'_of_mul, mk'_self]
end away
end away
end is_localization
namespace localization
open is_localization
/-! ### Constructing a localization at a given submonoid -/
variables {M}
instance : has_add (localization M) :=
⟨λ z w, con.lift_on₂ z w
(λ x y : R × M, mk ((x.2 : R) * y.1 + y.2 * x.1) (x.2 * y.2)) $
λ r1 r2 r3 r4 h1 h2, (con.eq _).2
begin
rw r_eq_r' at h1 h2 ⊢,
cases h1 with t₅ ht₅,
cases h2 with t₆ ht₆,
use t₆ * t₅,
calc ((r1.2 : R) * r2.1 + r2.2 * r1.1) * (r3.2 * r4.2) * (t₆ * t₅) =
(r2.1 * r4.2 * t₆) * (r1.2 * r3.2 * t₅) + (r1.1 * r3.2 * t₅) * (r2.2 * r4.2 * t₆) : by ring
... = (r3.2 * r4.1 + r4.2 * r3.1) * (r1.2 * r2.2) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring
end⟩
instance : has_neg (localization M) :=
⟨λ z, con.lift_on z (λ x : R × M, mk (-x.1) x.2) $
λ r1 r2 h, (con.eq _).2
begin
rw r_eq_r' at h ⊢,
cases h with t ht,
use t,
rw [neg_mul_eq_neg_mul_symm, neg_mul_eq_neg_mul_symm, ht],
ring_nf,
end⟩
instance : has_zero (localization M) :=
⟨mk 0 1⟩
private meta def tac := `[{
intros,
refine quotient.sound' (r_of_eq _),
simp only [prod.snd_mul, prod.fst_mul, submonoid.coe_mul],
ring }]
instance : comm_ring (localization M) :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
add_assoc := λ m n k, quotient.induction_on₃' m n k (by tac),
zero_add := λ y, quotient.induction_on' y (by tac),
add_zero := λ y, quotient.induction_on' y (by tac),
neg := has_neg.neg,
sub := λ x y, x + -y,
sub_eq_add_neg := λ x y, rfl,
add_left_neg := λ y, by exact quotient.induction_on' y (by tac),
add_comm := λ y z, quotient.induction_on₂' z y (by tac),
left_distrib := λ m n k, quotient.induction_on₃' m n k (by tac),
right_distrib := λ m n k, quotient.induction_on₃' m n k (by tac),
..localization.comm_monoid M }
instance : algebra R (localization M) :=
ring_hom.to_algebra $
{ map_zero' := rfl,
map_add' := λ x y, (con.eq _).2 $ r_of_eq $ by simp [add_comm],
.. localization.monoid_of M }
instance : is_localization M (localization M) :=
{ map_units := (localization.monoid_of M).map_units,
surj := (localization.monoid_of M).surj,
eq_iff_exists := λ _ _, (localization.monoid_of M).eq_iff_exists }
lemma monoid_of_eq_algebra_map (x) :
(monoid_of M).to_map x = algebra_map R (localization M) x :=
rfl
lemma mk_one_eq_algebra_map (x) : mk x 1 = algebra_map R (localization M) x := rfl
lemma mk_eq_mk'_apply (x y) : mk x y = is_localization.mk' (localization M) x y :=
mk_eq_monoid_of_mk'_apply _ _
@[simp] lemma mk_eq_mk' : (mk : R → M → (localization M)) = is_localization.mk' (localization M) :=
mk_eq_monoid_of_mk'
variables [is_localization M S]
section
variables (M S)
/-- The localization of `R` at `M` as a quotient type is isomorphic to any other localization. -/
@[simps]
noncomputable def alg_equiv : localization M ≃ₐ[R] S :=
is_localization.alg_equiv M _ _
end
@[simp] lemma alg_equiv_mk' (x : R) (y : M) :
alg_equiv M S (mk' (localization M) x y) = mk' S x y :=
alg_equiv_mk' _ _
@[simp] lemma alg_equiv_symm_mk' (x : R) (y : M) :
(alg_equiv M S).symm (mk' S x y) = mk' (localization M) x y :=
alg_equiv_symm_mk' _ _
lemma alg_equiv_mk (x y) :
alg_equiv M S (mk x y) = mk' S x y :=
by rw [mk_eq_mk', alg_equiv_mk']
lemma alg_equiv_symm_mk (x : R) (y : M) :
(alg_equiv M S).symm (mk' S x y) = mk x y :=
by rw [mk_eq_mk', alg_equiv_symm_mk']
end localization
variables {M}
section at_prime
variables (I : ideal R) [hp : I.is_prime]
include hp
namespace ideal
/-- The complement of a prime ideal `I ⊆ R` is a submonoid of `R`. -/
def prime_compl :
submonoid R :=
{ carrier := (Iᶜ : set R),
one_mem' := by convert I.ne_top_iff_one.1 hp.1; refl,
mul_mem' := λ x y hnx hny hxy, or.cases_on (hp.mem_or_mem hxy) hnx hny }
end ideal
variables (S)
/-- Given a prime ideal `P`, the typeclass `is_localization.at_prime S P` states that `S` is
isomorphic to the localization of `R` at the complement of `P`. -/
protected abbreviation is_localization.at_prime := is_localization I.prime_compl S
/-- Given a prime ideal `P`, `localization.at_prime S P` is a localization of
`R` at the complement of `P`, as a quotient type. -/
protected abbreviation localization.at_prime := localization I.prime_compl
namespace is_localization
theorem at_prime.local_ring [is_localization.at_prime S I] : local_ring S :=
local_of_nonunits_ideal
(λ hze, begin
rw [←(algebra_map R S).map_one, ←(algebra_map R S).map_zero] at hze,
obtain ⟨t, ht⟩ := (eq_iff_exists I.prime_compl S).1 hze,
exact ((show (t : R) ∉ I, from t.2) (have htz : (t : R) = 0, by simpa using ht.symm,
htz.symm ▸ I.zero_mem))
end)
(begin
intros x y hx hy hu,
cases is_unit_iff_exists_inv.1 hu with z hxyz,
have : ∀ {r : R} {s : I.prime_compl}, mk' S r s ∈ nonunits S → r ∈ I, from
λ (r : R) (s : I.prime_compl), not_imp_comm.1
(λ nr, is_unit_iff_exists_inv.2 ⟨mk' S ↑s (⟨r, nr⟩ : I.prime_compl),
mk'_mul_mk'_eq_one' _ _ nr⟩),
rcases mk'_surjective I.prime_compl x with ⟨rx, sx, hrx⟩,
rcases mk'_surjective I.prime_compl y with ⟨ry, sy, hry⟩,
rcases mk'_surjective I.prime_compl z with ⟨rz, sz, hrz⟩,
rw [←hrx, ←hry, ←hrz, ←mk'_add, ←mk'_mul,
←mk'_self S I.prime_compl.one_mem] at hxyz,
rw ←hrx at hx, rw ←hry at hy,
obtain ⟨t, ht⟩ := is_localization.eq.1 hxyz,
simp only [mul_one, one_mul, submonoid.coe_mul, subtype.coe_mk] at ht,
rw [←sub_eq_zero, ←sub_mul] at ht,
have hr := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right t.2,
rw sub_eq_add_neg at hr,
have := I.neg_mem_iff.1 ((ideal.add_mem_iff_right _ _).1 hr),
{ exact not_or (mt hp.mem_or_mem (not_or sx.2 sy.2)) sz.2 (hp.mem_or_mem this)},
{ exact I.mul_mem_right _ (I.add_mem (I.mul_mem_right _ (this hx))
(I.mul_mem_right _ (this hy)))}
end)
end is_localization
namespace localization
/-- The localization of `R` at the complement of a prime ideal is a local ring. -/
instance at_prime.local_ring : local_ring (localization I.prime_compl) :=
is_localization.at_prime.local_ring (localization I.prime_compl) I
end localization
end at_prime
namespace is_localization
variables [is_localization M S]
section ideals
variables (M) (S)
include M
/-- Explicit characterization of the ideal given by `ideal.map (algebra_map R S) I`.
In practice, this ideal differs only in that the carrier set is defined explicitly.
This definition is only meant to be used in proving `mem_map_to_map_iff`,
and any proof that needs to refer to the explicit carrier set should use that theorem. -/
private def map_ideal (I : ideal R) : ideal S :=
{ carrier := { z : S | ∃ x : I × M, z * algebra_map R S x.2 = algebra_map R S x.1},
zero_mem' := ⟨⟨0, 1⟩, by simp⟩,
add_mem' := begin
rintros a b ⟨a', ha⟩ ⟨b', hb⟩,
use ⟨a'.2 * b'.1 + b'.2 * a'.1, I.add_mem (I.mul_mem_left _ b'.1.2) (I.mul_mem_left _ a'.1.2)⟩,
use a'.2 * b'.2,
simp only [ring_hom.map_add, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul],
rw [add_mul, ← mul_assoc a, ha, mul_comm (algebra_map R S a'.2) (algebra_map R S b'.2),
← mul_assoc b, hb],
ring
end,
smul_mem' := begin
rintros c x ⟨x', hx⟩,
obtain ⟨c', hc⟩ := is_localization.surj M c,
use ⟨c'.1 * x'.1, I.mul_mem_left c'.1 x'.1.2⟩,
use c'.2 * x'.2,
simp only [←hx, ←hc, smul_eq_mul, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul],
ring
end }
theorem mem_map_algebra_map_iff {I : ideal R} {z} :
z ∈ ideal.map (algebra_map R S) I ↔ ∃ x : I × M, z * algebra_map R S x.2 = algebra_map R S x.1 :=
begin
split,
{ change _ → z ∈ map_ideal M S I,
refine λ h, ideal.mem_Inf.1 h (λ z hz, _),
obtain ⟨y, hy⟩ := hz,
use ⟨⟨⟨y, hy.left⟩, 1⟩, by simp [hy.right]⟩ },
{ rintros ⟨⟨a, s⟩, h⟩,
rw [← ideal.unit_mul_mem_iff_mem _ (map_units S s), mul_comm],
exact h.symm ▸ ideal.mem_map_of_mem _ a.2 }
end
theorem map_comap (J : ideal S) :
ideal.map (algebra_map R S) (ideal.comap (algebra_map R S) J) = J :=
le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x hJ,
begin
obtain ⟨r, s, hx⟩ := mk'_surjective M x,
rw ←hx at ⊢ hJ,
exact ideal.mul_mem_right _ _ (ideal.mem_map_of_mem _ (show (algebra_map R S) r ∈ J, from
mk'_spec S r s ▸ J.mul_mem_right ((algebra_map R S) s) hJ)),
end
theorem comap_map_of_is_prime_disjoint (I : ideal R) (hI : I.is_prime)
(hM : disjoint (M : set R) I) :
ideal.comap (algebra_map R S) (ideal.map (algebra_map R S) I) = I :=
begin
refine le_antisymm (λ a ha, _) ideal.le_comap_map,
rw [ideal.mem_comap, mem_map_algebra_map_iff M S] at ha,
obtain ⟨⟨b, s⟩, h⟩ := ha,
have : (algebra_map R S) (a * ↑s - b) = 0 := by simpa [sub_eq_zero] using h,
rw [← (algebra_map R S).map_zero, eq_iff_exists M S] at this,
obtain ⟨c, hc⟩ := this,
have : a * s ∈ I,
{ rw zero_mul at hc,
let this : (a * ↑s - ↑b) * ↑c ∈ I := hc.symm ▸ I.zero_mem,
cases hI.mem_or_mem this with h1 h2,
{ simpa using I.add_mem h1 b.2 },
{ exfalso,
refine hM ⟨c.2, h2⟩ } },
cases hI.mem_or_mem this with h1 h2,
{ exact h1 },
{ exfalso,
refine hM ⟨s.2, h2⟩ }
end
/-- If `S` is the localization of `R` at a submonoid, the ordering of ideals of `S` is
embedded in the ordering of ideals of `R`. -/
def order_embedding : ideal S ↪o ideal R :=
{ to_fun := λ J, ideal.comap (algebra_map R S) J,
inj' := function.left_inverse.injective (map_comap M S),
map_rel_iff' := λ J₁ J₂, ⟨λ hJ, (map_comap M S) J₁ ▸ (map_comap M S) J₂ ▸ ideal.map_mono hJ,
ideal.comap_mono⟩ }
/-- If `R` is a ring, then prime ideals in the localization at `M`
correspond to prime ideals in the original ring `R` that are disjoint from `M`.
This lemma gives the particular case for an ideal and its comap,
see `le_rel_iso_of_prime` for the more general relation isomorphism -/
lemma is_prime_iff_is_prime_disjoint (J : ideal S) :
J.is_prime ↔ (ideal.comap (algebra_map R S) J).is_prime ∧
disjoint (M : set R) ↑(ideal.comap (algebra_map R S) J) :=
begin
split,
{ refine λ h, ⟨⟨_, _⟩, λ m hm,
h.ne_top (ideal.eq_top_of_is_unit_mem _ hm.2 (map_units S ⟨m, hm.left⟩))⟩,
{ refine λ hJ, h.ne_top _,
rw [eq_top_iff, ← (order_embedding M S).le_iff_le],
exact le_of_eq hJ.symm },
{ intros x y hxy,
rw [ideal.mem_comap, ring_hom.map_mul] at hxy,
exact h.mem_or_mem hxy } },
{ refine λ h, ⟨λ hJ, h.left.ne_top (eq_top_iff.2 _), _⟩,
{ rwa [eq_top_iff, ← (order_embedding M S).le_iff_le] at hJ },
{ intros x y hxy,
obtain ⟨a, s, ha⟩ := mk'_surjective M x,
obtain ⟨b, t, hb⟩ := mk'_surjective M y,
have : mk' S (a * b) (s * t) ∈ J := by rwa [mk'_mul, ha, hb],
rw [mk'_mem_iff, ← ideal.mem_comap] at this,
replace this := h.left.mem_or_mem this,
rw [ideal.mem_comap, ideal.mem_comap] at this,
rwa [← ha, ← hb, mk'_mem_iff, mk'_mem_iff] } }
end
/-- If `R` is a ring, then prime ideals in the localization at `M`
correspond to prime ideals in the original ring `R` that are disjoint from `M`.
This lemma gives the particular case for an ideal and its map,
see `le_rel_iso_of_prime` for the more general relation isomorphism, and the reverse implication -/
lemma is_prime_of_is_prime_disjoint (I : ideal R) (hp : I.is_prime)
(hd : disjoint (M : set R) ↑I) : (ideal.map (algebra_map R S) I).is_prime :=
begin
rw [is_prime_iff_is_prime_disjoint M S, comap_map_of_is_prime_disjoint M S I hp hd],
exact ⟨hp, hd⟩
end
/-- If `R` is a ring, then prime ideals in the localization at `M`
correspond to prime ideals in the original ring `R` that are disjoint from `M` -/
def order_iso_of_prime :
{p : ideal S // p.is_prime} ≃o {p : ideal R // p.is_prime ∧ disjoint (M : set R) ↑p} :=
{ to_fun := λ p, ⟨ideal.comap (algebra_map R S) p.1,
(is_prime_iff_is_prime_disjoint M S p.1).1 p.2⟩,
inv_fun := λ p, ⟨ideal.map (algebra_map R S) p.1,
is_prime_of_is_prime_disjoint M S p.1 p.2.1 p.2.2⟩,
left_inv := λ J, subtype.eq (map_comap M S J),
right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint M S I.1 I.2.1 I.2.2),
map_rel_iff' := λ I I', ⟨λ h, (show I.val ≤ I'.val,
from (map_comap M S I.val) ▸ (map_comap M S I'.val) ▸ (ideal.map_mono h)), λ h x hx, h hx⟩ }
/-- `quotient_map` applied to maximal ideals of a localization is `surjective`.
The quotient by a maximal ideal is a field, so inverses to elements already exist,
and the localization necessarily maps the equivalence class of the inverse in the localization -/
lemma surjective_quotient_map_of_maximal_of_localization {I : ideal S} [I.is_prime] {J : ideal R}
{H : J ≤ I.comap (algebra_map R S)} (hI : (I.comap (algebra_map R S)).is_maximal) :
function.surjective (I.quotient_map (algebra_map R S) H) :=
begin
intro s,
obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective s,
obtain ⟨r, ⟨m, hm⟩, rfl⟩ := mk'_surjective M s,
by_cases hM : (ideal.quotient.mk (I.comap (algebra_map R S))) m = 0,
{ have : I = ⊤,
{ rw ideal.eq_top_iff_one,
rw [ideal.quotient.eq_zero_iff_mem, ideal.mem_comap] at hM,
convert I.mul_mem_right (mk' S 1 ⟨m, hm⟩) hM,
rw [← mk'_eq_mul_mk'_one, mk'_self] },
exact ⟨0, eq_comm.1 (by simp [ideal.quotient.eq_zero_iff_mem, this])⟩ },
{ rw ideal.quotient.maximal_ideal_iff_is_field_quotient at hI,
obtain ⟨n, hn⟩ := hI.3 hM,
obtain ⟨rn, rfl⟩ := ideal.quotient.mk_surjective n,
refine ⟨(ideal.quotient.mk J) (r * rn), _⟩,
-- The rest of the proof is essentially just algebraic manipulations to prove the equality
rw ← ring_hom.map_mul at hn,
replace hn := congr_arg (ideal.quotient_map I (algebra_map R S) le_rfl) hn,
simp only [ring_hom.map_one, ideal.quotient_map_mk, ring_hom.map_mul] at hn,
rw [ideal.quotient_map_mk, ← sub_eq_zero, ← ring_hom.map_sub,
ideal.quotient.eq_zero_iff_mem, ← ideal.quotient.eq_zero_iff_mem, ring_hom.map_sub,
sub_eq_zero, mk'_eq_mul_mk'_one],
simp only [mul_eq_mul_left_iff, ring_hom.map_mul],
exact or.inl (mul_left_cancel' (λ hn, hM (ideal.quotient.eq_zero_iff_mem.2
(ideal.mem_comap.2 (ideal.quotient.eq_zero_iff_mem.1 hn)))) (trans hn
(by rw [← ring_hom.map_mul, ← mk'_eq_mul_mk'_one, mk'_self, ring_hom.map_one]))) }
end
end ideals
variables (S)
/-- Map from ideals of `R` to submodules of `S` induced by `f`. -/
-- This was previously a `has_coe` instance, but if `S = R` then this will loop.
-- It could be a `has_coe_t` instance, but we keep it explicit here to avoid slowing down
-- the rest of the library.
def coe_submodule (I : ideal R) : submodule R S := submodule.map (algebra.linear_map R S) I
lemma mem_coe_submodule (I : ideal R) {x : S} :
x ∈ coe_submodule S I ↔ ∃ y : R, y ∈ I ∧ algebra_map R S y = x :=
iff.rfl
lemma coe_submodule_mono {I J : ideal R} (h : I ≤ J) :
coe_submodule S I ≤ coe_submodule S J :=
submodule.map_mono h
@[simp] lemma coe_submodule_top : coe_submodule S (⊤ : ideal R) = 1 :=
by rw [coe_submodule, submodule.map_top, submodule.one_eq_range]
variables {g : R →+* P}
variables {T : submonoid P} (hy : M ≤ T.comap g) {Q : Type*} [comm_ring Q]
variables [algebra P Q] [is_localization T Q]
lemma map_smul (x : S) (z : R) :
map Q g hy (z • x : S) = g z • map Q g hy x :=
by rw [algebra.smul_def, algebra.smul_def, ring_hom.map_mul, map_eq]
section
include M
lemma is_noetherian_ring (h : is_noetherian_ring R) : is_noetherian_ring S :=
begin
rw [is_noetherian_ring_iff, is_noetherian_iff_well_founded] at h ⊢,
exact order_embedding.well_founded ((is_localization.order_embedding M S).dual) h
end
end
section integer_normalization
open polynomial
open_locale classical
variables (M) {S}
/-- `coeff_integer_normalization p` gives the coefficients of the polynomial
`integer_normalization p` -/
noncomputable def coeff_integer_normalization (p : polynomial S) (i : ℕ) : R :=
if hi : i ∈ p.support
then classical.some (classical.some_spec
(exist_integer_multiples_of_finset M (p.support.image p.coeff))
(p.coeff i)
(finset.mem_image.mpr ⟨i, hi, rfl⟩))
else 0
lemma coeff_integer_normalization_of_not_mem_support (p : polynomial S) (i : ℕ)
(h : coeff p i = 0) : coeff_integer_normalization M p i = 0 :=
by simp only [coeff_integer_normalization, h, mem_support_iff, eq_self_iff_true, not_true,
ne.def, dif_neg, not_false_iff]
lemma coeff_integer_normalization_mem_support (p : polynomial S) (i : ℕ)
(h : coeff_integer_normalization M p i ≠ 0) : i ∈ p.support :=
begin
contrapose h,
rw [ne.def, not_not, coeff_integer_normalization, dif_neg h]
end
/-- `integer_normalization g` normalizes `g` to have integer coefficients
by clearing the denominators -/
noncomputable def integer_normalization (p : polynomial S) :
polynomial R :=
∑ i in p.support, monomial i (coeff_integer_normalization M p i)
@[simp]
lemma integer_normalization_coeff (p : polynomial S) (i : ℕ) :
(integer_normalization M p).coeff i = coeff_integer_normalization M p i :=
by simp [integer_normalization, coeff_monomial, coeff_integer_normalization_of_not_mem_support]
{contextual := tt}
lemma integer_normalization_spec (p : polynomial S) :
∃ (b : M), ∀ i,
algebra_map R S ((integer_normalization M p).coeff i) = (b : R) • p.coeff i :=
begin
use classical.some (exist_integer_multiples_of_finset M (p.support.image p.coeff)),
intro i,
rw [integer_normalization_coeff, coeff_integer_normalization],
split_ifs with hi,
{ exact classical.some_spec (classical.some_spec
(exist_integer_multiples_of_finset M (p.support.image p.coeff))
(p.coeff i)
(finset.mem_image.mpr ⟨i, hi, rfl⟩)) },
{ convert (smul_zero _).symm,
{ apply ring_hom.map_zero },
{ exact not_mem_support_iff.mp hi } }
end
lemma integer_normalization_map_to_map (p : polynomial S) :
∃ (b : M), (integer_normalization M p).map (algebra_map R S) = (b : R) • p :=
let ⟨b, hb⟩ := integer_normalization_spec M p in
⟨b, polynomial.ext (λ i, by { rw [coeff_map, coeff_smul], exact hb i })⟩
variables {R' : Type*} [comm_ring R']
lemma integer_normalization_eval₂_eq_zero (g : S →+* R') (p : polynomial S)
{x : R'} (hx : eval₂ g x p = 0) :
eval₂ (g.comp (algebra_map R S)) x (integer_normalization M p) = 0 :=
let ⟨b, hb⟩ := integer_normalization_map_to_map M p in
trans (eval₂_map (algebra_map R S) g x).symm
(by rw [hb, ← is_scalar_tower.algebra_map_smul S (b : R) p, eval₂_smul, hx, mul_zero])
lemma integer_normalization_aeval_eq_zero [algebra R R'] [algebra S R'] [is_scalar_tower R S R']
(p : polynomial S) {x : R'} (hx : aeval x p = 0) :
aeval x (integer_normalization M p) = 0 :=
by rw [aeval_def, is_scalar_tower.algebra_map_eq R S R',
integer_normalization_eval₂_eq_zero _ _ _ hx]
end integer_normalization
variables {R M} (S) {A K : Type*} [integral_domain A]
lemma to_map_eq_zero_iff {x : R} (hM : M ≤ non_zero_divisors R) :
algebra_map R S x = 0 ↔ x = 0 :=
begin
rw ← (algebra_map R S).map_zero,
split; intro h,
{ cases (eq_iff_exists M S).mp h with c hc,
rw zero_mul at hc,
exact hM c.2 x hc },
{ rw h },
end
protected lemma injective (hM : M ≤ non_zero_divisors R) :
injective (algebra_map R S) :=
begin
rw ring_hom.injective_iff (algebra_map R S),
intros a ha,
rwa to_map_eq_zero_iff S hM at ha
end
protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R]
(hM : M ≤ non_zero_divisors R) {x : R} (hx : x ∈ non_zero_divisors R) : algebra_map R S x ≠ 0 :=
map_ne_zero_of_mem_non_zero_divisors (is_localization.injective S hM) hx
variables (S Q M)
/-- Injectivity of a map descends to the map induced on localizations. -/
lemma map_injective_of_injective
(hg : function.injective g) [is_localization (M.map g : submonoid P) Q]
(hM : (M.map g : submonoid P) ≤ non_zero_divisors P) :
function.injective (map Q g M.le_comap_map : S → Q) :=
begin
rintros x y hxy,
obtain ⟨a, b, rfl⟩ := mk'_surjective M x,
obtain ⟨c, d, rfl⟩ := mk'_surjective M y,
rw [map_mk' _ a b, map_mk' _ c d, mk'_eq_iff_eq] at hxy,
refine mk'_eq_iff_eq.2 (congr_arg (algebra_map _ _) (hg _)),
convert is_localization.injective _ hM hxy; simp,
end
variables {S Q M}
@[mono]
lemma coe_submodule_le_coe_submodule (h : M ≤ non_zero_divisors R)
{I J : ideal R} :
coe_submodule S I ≤ coe_submodule S J ↔ I ≤ J :=
submodule.map_le_map_iff_of_injective (is_localization.injective _ h) _ _
@[mono]
lemma coe_submodule_strict_mono (h : M ≤ non_zero_divisors R) :
strict_mono (coe_submodule S : ideal R → submodule R S) :=
strict_mono_of_le_iff_le (λ _ _, (coe_submodule_le_coe_submodule h).symm)
variables (S) {Q M}
/-- A `comm_ring` `S` which is the localization of an integral domain `R` at a subset of
non-zero elements is an integral domain. -/
def integral_domain_of_le_non_zero_divisors [algebra A S] {M : submonoid A} [is_localization M S]
(hM : M ≤ non_zero_divisors A) : integral_domain S :=
{ eq_zero_or_eq_zero_of_mul_eq_zero :=
begin
intros z w h,
cases surj M z with x hx,
cases surj M w with y hy,
have : z * w * algebra_map A S y.2 * algebra_map A S x.2 =
algebra_map A S x.1 * algebra_map A S y.1,
by rw [mul_assoc z, hy, ←hx]; ac_refl,
rw [h, zero_mul, zero_mul, ← (algebra_map A S).map_mul] at this,
cases eq_zero_or_eq_zero_of_mul_eq_zero ((to_map_eq_zero_iff S hM).mp this.symm) with H H,
{ exact or.inl (eq_zero_of_fst_eq_zero hx H) },
{ exact or.inr (eq_zero_of_fst_eq_zero hy H) },
end,
exists_pair_ne := ⟨(algebra_map A S) 0, (algebra_map A S) 1,
λ h, zero_ne_one (is_localization.injective S hM h)⟩,
.. ‹comm_ring S› }
/-- The localization at of an integral domain to a set of non-zero elements is an integral domain -/
def integral_domain_localization {M : submonoid A} (hM : M ≤ non_zero_divisors A) :
integral_domain (localization M) :=
integral_domain_of_le_non_zero_divisors _ hM
/--
The localization of an integral domain at the complement of a prime ideal is an integral domain.
-/
instance integral_domain_of_local_at_prime {P : ideal A} (hp : P.is_prime) :
integral_domain (localization.at_prime P) :=
integral_domain_localization (le_non_zero_divisors_of_domain (by simpa only [] using P.zero_mem))
namespace at_prime
variables (I : ideal R) [hI : I.is_prime] [is_localization.at_prime S I]
include hI
lemma is_unit_to_map_iff (x : R) :
is_unit ((algebra_map R S) x) ↔ x ∈ I.prime_compl :=
⟨λ h hx, (is_prime_of_is_prime_disjoint I.prime_compl S I hI disjoint_compl_left).ne_top $
(ideal.map (algebra_map R S) I).eq_top_of_is_unit_mem (ideal.mem_map_of_mem _ hx) h,
λ h, map_units S ⟨x, h⟩⟩
-- Can't use typeclasses to infer the `local_ring` instance, so use an `opt_param` instead
-- (since `local_ring` is a `Prop`, there should be no unification issues.)
lemma to_map_mem_maximal_iff (x : R) (h : _root_.local_ring S := local_ring S I) :
algebra_map R S x ∈ local_ring.maximal_ideal S ↔ x ∈ I :=
not_iff_not.mp $ by
simpa only [@local_ring.mem_maximal_ideal S, mem_nonunits_iff, not_not]
using is_unit_to_map_iff S I x
lemma is_unit_mk'_iff (x : R) (y : I.prime_compl) :
is_unit (mk' S x y) ↔ x ∈ I.prime_compl :=
⟨λ h hx, mk'_mem_iff.mpr ((to_map_mem_maximal_iff S I x).mpr hx) h,
λ h, is_unit_iff_exists_inv.mpr ⟨mk' S ↑y ⟨x, h⟩, mk'_mul_mk'_eq_one ⟨x, h⟩ y⟩⟩
lemma mk'_mem_maximal_iff (x : R) (y : I.prime_compl) (h : _root_.local_ring S := local_ring S I) :
mk' S x y ∈ local_ring.maximal_ideal S ↔ x ∈ I :=
not_iff_not.mp $ by
simpa only [@local_ring.mem_maximal_ideal S, mem_nonunits_iff, not_not]
using is_unit_mk'_iff S I x y
end at_prime
end is_localization
namespace localization
open is_localization
local attribute [instance] classical.prop_decidable
variables (I : ideal R) [hI : I.is_prime]
include hI
variables {I}
/-- The unique maximal ideal of the localization at `I.prime_compl` lies over the ideal `I`. -/
lemma at_prime.comap_maximal_ideal :
ideal.comap (algebra_map R (localization.at_prime I))
(local_ring.maximal_ideal (localization I.prime_compl)) = I :=
ideal.ext $ λ x, by
simpa only [ideal.mem_comap] using at_prime.to_map_mem_maximal_iff _ I x
/-- The image of `I` in the localization at `I.prime_compl` is a maximal ideal, and in particular
it is the unique maximal ideal given by the local ring structure `at_prime.local_ring` -/
lemma at_prime.map_eq_maximal_ideal :
ideal.map (algebra_map R (localization.at_prime I)) I =
(local_ring.maximal_ideal (localization I.prime_compl)) :=
begin
convert congr_arg (ideal.map _) at_prime.comap_maximal_ideal.symm,
rw map_comap I.prime_compl
end
lemma le_comap_prime_compl_iff {J : ideal P} [hJ : J.is_prime] {f : R →+* P} :
I.prime_compl ≤ J.prime_compl.comap f ↔ J.comap f ≤ I :=
⟨λ h x hx, by { contrapose! hx, exact h hx },
λ h x hx hfxJ, hx (h hfxJ)⟩
variables (I)
/--
For a ring hom `f : R →+* S` and a prime ideal `J` in `S`, the induced ring hom from the
localization of `R` at `J.comap f` to the localization of `S` at `J`.
To make this definition more flexible, we allow any ideal `I` of `R` as input, together with a proof
that `I = J.comap f`. This can be useful when `I` is not definitionally equal to `J.comap f`.
-/
noncomputable def local_ring_hom (J : ideal P) [hJ : J.is_prime] (f : R →+* P)
(hIJ : I = J.comap f) :
localization.at_prime I →+* localization.at_prime J :=
is_localization.map (localization.at_prime J) f (le_comap_prime_compl_iff.mpr (ge_of_eq hIJ))
lemma local_ring_hom_to_map (J : ideal P) [hJ : J.is_prime] (f : R →+* P)
(hIJ : I = J.comap f) (x : R) :
local_ring_hom I J f hIJ (algebra_map _ _ x) = algebra_map _ _ (f x) :=
map_eq _ _
lemma local_ring_hom_mk' (J : ideal P) [hJ : J.is_prime] (f : R →+* P)
(hIJ : I = J.comap f) (x : R) (y : I.prime_compl) :
local_ring_hom I J f hIJ (is_localization.mk' _ x y) =
is_localization.mk' (localization.at_prime J) (f x)
(⟨f y, le_comap_prime_compl_iff.mpr (ge_of_eq hIJ) y.2⟩ : J.prime_compl) :=
map_mk' _ _ _
instance is_local_ring_hom_local_ring_hom (J : ideal P) [hJ : J.is_prime] (f : R →+* P)
(hIJ : I = J.comap f) :
is_local_ring_hom (local_ring_hom I J f hIJ) :=
is_local_ring_hom.mk $ λ x hx,
begin
rcases is_localization.mk'_surjective I.prime_compl x with ⟨r, s, rfl⟩,
rw local_ring_hom_mk' at hx,
rw at_prime.is_unit_mk'_iff at hx ⊢,
exact λ hr, hx ((set_like.ext_iff.mp hIJ r).mp hr),
end
lemma local_ring_hom_unique (J : ideal P) [hJ : J.is_prime] (f : R →+* P)
(hIJ : I = J.comap f) {j : localization.at_prime I →+* localization.at_prime J}
(hj : ∀ x : R, j (algebra_map _ _ x) = algebra_map _ _ (f x)) :
local_ring_hom I J f hIJ = j :=
map_unique _ _ hj
@[simp] lemma local_ring_hom_id :
local_ring_hom I I (ring_hom.id R) (ideal.comap_id I).symm = ring_hom.id _ :=
local_ring_hom_unique _ _ _ _ (λ x, rfl)
@[simp] lemma local_ring_hom_comp {S : Type*} [comm_ring S]
(J : ideal S) [hJ : J.is_prime] (K : ideal P) [hK : K.is_prime]
(f : R →+* S) (hIJ : I = J.comap f) (g : S →+* P) (hJK : J = K.comap g) :
local_ring_hom I K (g.comp f) (by rw [hIJ, hJK, ideal.comap_comap f g]) =
(local_ring_hom J K g hJK).comp (local_ring_hom I J f hIJ) :=
local_ring_hom_unique _ _ _ _
(λ r, by simp only [function.comp_app, ring_hom.coe_comp, local_ring_hom_to_map])
end localization
open is_localization
/-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/
lemma localization_map_bijective_of_field {R Rₘ : Type*} [integral_domain R] [comm_ring Rₘ]
{M : submonoid R} (hM : (0 : R) ∉ M) (hR : is_field R)
[algebra R Rₘ] [is_localization M Rₘ] : function.bijective (algebra_map R Rₘ) :=
begin
refine ⟨is_localization.injective _ (le_non_zero_divisors_of_domain hM), λ x, _⟩,
obtain ⟨r, ⟨m, hm⟩, rfl⟩ := mk'_surjective M x,
obtain ⟨n, hn⟩ := hR.mul_inv_cancel (λ hm0, hM (hm0 ▸ hm) : m ≠ 0),
exact ⟨r * n,
by erw [eq_mk'_iff_mul_eq, ← ring_hom.map_mul, mul_assoc, mul_comm n, hn, mul_one]⟩
end
variables (R) {A : Type*} [integral_domain A]
variables (K : Type*)
/-- `is_fraction_ring R K` states `K` is the field of fractions of an integral domain `R`. -/
-- TODO: should this extend `algebra` instead of assuming it?
abbreviation is_fraction_ring [comm_ring K] [algebra R K] := is_localization (non_zero_divisors R) K
/-- The cast from `int` to `rat` as a `fraction_ring`. -/
instance rat.is_fraction_ring : is_fraction_ring ℤ ℚ :=
{ map_units :=
begin
rintro ⟨x, hx⟩,
rw mem_non_zero_divisors_iff_ne_zero at hx,
simpa only [ring_hom.eq_int_cast, is_unit_iff_ne_zero, int.cast_eq_zero,
ne.def, subtype.coe_mk] using hx,
end,
surj :=
begin
rintro ⟨n, d, hd, h⟩,
refine ⟨⟨n, ⟨d, _⟩⟩, rat.mul_denom_eq_num⟩,
rwa [mem_non_zero_divisors_iff_ne_zero, int.coe_nat_ne_zero_iff_pos]
end,
eq_iff_exists :=
begin
intros x y,
rw [ring_hom.eq_int_cast, ring_hom.eq_int_cast, int.cast_inj],
refine ⟨by { rintro rfl, use 1 }, _⟩,
rintro ⟨⟨c, hc⟩, h⟩,
apply int.eq_of_mul_eq_mul_right _ h,
rwa mem_non_zero_divisors_iff_ne_zero at hc,
end }
namespace is_fraction_ring
variables {R K}
section comm_ring
variables [comm_ring K] [algebra R K] [is_fraction_ring R K] [algebra A K] [is_fraction_ring A K]
lemma to_map_eq_zero_iff {x : R} :
algebra_map R K x = 0 ↔ x = 0 :=
to_map_eq_zero_iff _ (le_of_eq rfl)
variables (R K)
protected theorem injective : function.injective (algebra_map R K) :=
is_localization.injective _ (le_of_eq rfl)
variables {R K}
@[simp, mono]
lemma coe_submodule_le_coe_submodule
{I J : ideal R} : coe_submodule K I ≤ coe_submodule K J ↔ I ≤ J :=
is_localization.coe_submodule_le_coe_submodule (le_refl _)
@[mono]
lemma coe_submodule_strict_mono :
strict_mono (coe_submodule K : ideal R → submodule R K) :=
strict_mono_of_le_iff_le (λ _ _, coe_submodule_le_coe_submodule.symm)
protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R]
{x : R} (hx : x ∈ non_zero_divisors R) : algebra_map R K x ≠ 0 :=
is_localization.to_map_ne_zero_of_mem_non_zero_divisors _ (le_refl _) hx
variables (A)
/-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an
integral domain. -/
def to_integral_domain : integral_domain K :=
integral_domain_of_le_non_zero_divisors K (le_refl (non_zero_divisors A))
local attribute [instance] classical.dec_eq
/-- The inverse of an element in the field of fractions of an integral domain. -/
protected noncomputable def inv (z : K) : K :=
if h : z = 0 then 0 else
mk' K ↑(sec (non_zero_divisors A) z).2
⟨(sec _ z).1,
mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $
eq_zero_of_fst_eq_zero (sec_spec (non_zero_divisors A) z) h0⟩
protected lemma mul_inv_cancel (x : K) (hx : x ≠ 0) :
x * is_fraction_ring.inv A x = 1 :=
show x * dite _ _ _ = 1, by rw [dif_neg hx,
←is_unit.mul_left_inj (map_units K ⟨(sec _ x).1, mem_non_zero_divisors_iff_ne_zero.2 $
λ h0, hx $ eq_zero_of_fst_eq_zero (sec_spec (non_zero_divisors A) x) h0⟩),
one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (mk'_sec _ x).symm
/-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a
field. -/
noncomputable def to_field : field K :=
{ inv := is_fraction_ring.inv A,
mul_inv_cancel := is_fraction_ring.mul_inv_cancel A,
inv_zero := dif_pos rfl,
.. to_integral_domain A }
end comm_ring
variables {B : Type*} [integral_domain B] [field K] {L : Type*} [field L]
[algebra A K] [is_fraction_ring A K] {g : A →+* L}
lemma mk'_mk_eq_div {r s} (hs : s ∈ non_zero_divisors A) :
mk' K r ⟨s, hs⟩ = algebra_map A K r / algebra_map A K s :=
mk'_eq_iff_eq_mul.2 $ (div_mul_cancel (algebra_map A K r)
(is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hs)).symm
lemma mk'_eq_div {r} (s : non_zero_divisors A) :
mk' K r s = algebra_map A K r / algebra_map A K s :=
mk'_mk_eq_div s.2
lemma is_unit_map_of_injective (hg : function.injective g)
(y : non_zero_divisors A) : is_unit (g y) :=
is_unit.mk0 (g y) $ map_ne_zero_of_mem_non_zero_divisors hg y.2
/-- Given an integral domain `A` with field of fractions `K`,
and an injective ring hom `g : A →+* L` where `L` is a field, we get a
field hom sending `z : K` to `g x * (g y)⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are
such that `z = f x * (f y)⁻¹`. -/
noncomputable def lift (hg : injective g) : K →+* L :=
lift $ λ (y : non_zero_divisors A), is_unit_map_of_injective hg y
/-- Given an integral domain `A` with field of fractions `K`,
and an injective ring hom `g : A →+* L` where `L` is a field,
field hom induced from `K` to `L` maps `f x / f y` to `g x / g y` for all
`x : A, y ∈ non_zero_divisors A`. -/
@[simp] lemma lift_mk' (hg : injective g) (x) (y : non_zero_divisors A) :
lift hg (mk' K x y) = g x / g y :=
begin
erw lift_mk' (is_unit_map_of_injective hg),
erw submonoid.localization_map.mul_inv_left
(λ y : non_zero_divisors A, show is_unit (g.to_monoid_hom y), from
is_unit_map_of_injective hg y),
exact (mul_div_cancel' _ (map_ne_zero_of_mem_non_zero_divisors hg y.2)).symm,
end
/-- Given integral domains `A, B` with fields of fractions `K`, `L`
and an injective ring hom `j : A →+* B`, we get a field hom
sending `z : K` to `g (j x) * (g (j y))⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are
such that `z = f x * (f y)⁻¹`. -/
noncomputable def map [algebra B L] [is_fraction_ring B L] {j : A →+* B} (hj : injective j) :
K →+* L :=
map L j (show non_zero_divisors A ≤ (non_zero_divisors B).comap j,
from λ y hy, map_mem_non_zero_divisors hj hy)
/-- Given integral domains `A, B` and localization maps to their fields of fractions
`f : A →+* K, g : B →+* L`, an isomorphism `j : A ≃+* B` induces an isomorphism of
fields of fractions `K ≃+* L`. -/
noncomputable def field_equiv_of_ring_equiv [algebra B L] [is_fraction_ring B L] (h : A ≃+* B) :
K ≃+* L :=
ring_equiv_of_ring_equiv K L h
begin
ext b,
show b ∈ h.to_equiv '' _ ↔ _,
erw [h.to_equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq,
mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero],
exact h.symm.map_ne_zero_iff
end
lemma integer_normalization_eq_zero_iff {p : polynomial K} :
integer_normalization (non_zero_divisors A) p = 0 ↔ p = 0 :=
begin
refine (polynomial.ext_iff.trans (polynomial.ext_iff.trans _).symm),
obtain ⟨⟨b, nonzero⟩, hb⟩ := integer_normalization_spec _ p,
split; intros h i,
{ apply to_map_eq_zero_iff.mp,
rw [hb i, h i],
apply smul_zero,
assumption },
{ have hi := h i,
rw [polynomial.coeff_zero, ← @to_map_eq_zero_iff A _ K, hb i, algebra.smul_def] at hi,
apply or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hi),
intro h,
apply mem_non_zero_divisors_iff_ne_zero.mp nonzero,
exact to_map_eq_zero_iff.mp h }
end
/-- A field is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`.
-/
lemma comap_is_algebraic_iff [algebra A L] [algebra K L] [is_scalar_tower A K L] :
algebra.is_algebraic A L ↔ algebra.is_algebraic K L :=
begin
split; intros h x; obtain ⟨p, hp, px⟩ := h x,
{ refine ⟨p.map (algebra_map A K), λ h, hp (polynomial.ext (λ i, _)), _⟩,
{ have : algebra_map A K (p.coeff i) = 0 := trans (polynomial.coeff_map _ _).symm (by simp [h]),
exact to_map_eq_zero_iff.mp this },
{ rwa is_scalar_tower.aeval_apply _ K at px } },
{ exact ⟨integer_normalization _ p,
mt integer_normalization_eq_zero_iff.mp hp,
integer_normalization_aeval_eq_zero _ p px⟩ },
end
section num_denom
variables (A) [unique_factorization_monoid A]
lemma exists_reduced_fraction (x : K) :
∃ (a : A) (b : non_zero_divisors A),
(∀ {d}, d ∣ a → d ∣ b → is_unit d) ∧ mk' K a b = x :=
begin
obtain ⟨⟨b, b_nonzero⟩, a, hab⟩ := exists_integer_multiple (non_zero_divisors A) x,
obtain ⟨a', b', c', no_factor, rfl, rfl⟩ :=
unique_factorization_monoid.exists_reduced_factors' a b
(mem_non_zero_divisors_iff_ne_zero.mp b_nonzero),
obtain ⟨c'_nonzero, b'_nonzero⟩ := mul_mem_non_zero_divisors.mp b_nonzero,
refine ⟨a', ⟨b', b'_nonzero⟩, @no_factor, _⟩,
refine mul_left_cancel'
(is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors b_nonzero) _,
simp only [subtype.coe_mk, ring_hom.map_mul, algebra.smul_def] at *,
erw [←hab, mul_assoc, mk'_spec' _ a' ⟨b', b'_nonzero⟩],
end
/-- `f.num x` is the numerator of `x : f.codomain` as a reduced fraction. -/
noncomputable def num (x : K) : A :=
classical.some (exists_reduced_fraction A x)
/-- `f.num x` is the denominator of `x : f.codomain` as a reduced fraction. -/
noncomputable def denom (x : K) : non_zero_divisors A :=
classical.some (classical.some_spec (exists_reduced_fraction A x))
lemma num_denom_reduced (x : K) :
∀ {d}, d ∣ num A x → d ∣ denom A x → is_unit d :=
(classical.some_spec (classical.some_spec (exists_reduced_fraction A x))).1
@[simp] lemma mk'_num_denom (x : K) : mk' K (num A x) (denom A x) = x :=
(classical.some_spec (classical.some_spec (exists_reduced_fraction A x))).2
variables {A}
lemma num_mul_denom_eq_num_iff_eq {x y : K} :
x * algebra_map A K (denom A y) = algebra_map A K (num A y) ↔ x = y :=
⟨λ h, by simpa only [mk'_num_denom] using eq_mk'_iff_mul_eq.mpr h,
λ h, eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom])⟩
lemma num_mul_denom_eq_num_iff_eq' {x y : K} :
y * algebra_map A K (denom A x) = algebra_map A K (num A x) ↔ x = y :=
⟨λ h, by simpa only [eq_comm, mk'_num_denom] using eq_mk'_iff_mul_eq.mpr h,
λ h, eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom])⟩
lemma num_mul_denom_eq_num_mul_denom_iff_eq {x y : K} :
num A y * denom A x = num A x * denom A y ↔ x = y :=
⟨λ h, by simpa only [mk'_num_denom] using mk'_eq_of_eq h,
λ h, by rw h⟩
lemma eq_zero_of_num_eq_zero {x : K} (h : num A x = 0) : x = 0 :=
num_mul_denom_eq_num_iff_eq'.mp (by rw [zero_mul, h, ring_hom.map_zero])
lemma is_integer_of_is_unit_denom {x : K} (h : is_unit (denom A x : A)) : is_integer A x :=
begin
cases h with d hd,
have d_ne_zero : algebra_map A K (denom A x) ≠ 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors (denom A x).2,
use ↑d⁻¹ * num A x,
refine trans _ (mk'_num_denom A x),
rw [ring_hom.map_mul, ring_hom.map_units_inv, hd],
apply mul_left_cancel' d_ne_zero,
rw [←mul_assoc, mul_inv_cancel d_ne_zero, one_mul, mk'_spec']
end
lemma is_unit_denom_of_num_eq_zero {x : K} (h : num A x = 0) : is_unit (denom A x : A) :=
num_denom_reduced A x (h.symm ▸ dvd_zero _) (dvd_refl _)
end num_denom
end is_fraction_ring
section algebra
section is_integral
variables {R S} {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ]
variables [algebra R Rₘ] [is_localization M Rₘ]
variables [algebra S Sₘ] [is_localization (algebra.algebra_map_submonoid S M) Sₘ]
section
variables (S M)
/-- Definition of the natural algebra induced by the localization of an algebra.
Given an algebra `R → S`, a submonoid `R` of `M`, and a localization `Rₘ` for `M`,
let `Sₘ` be the localization of `S` to the image of `M` under `algebra_map R S`.
Then this is the natural algebra structure on `Rₘ → Sₘ`, such that the entire square commutes,
where `localization_map.map_comp` gives the commutativity of the underlying maps -/
noncomputable def localization_algebra : algebra Rₘ Sₘ :=
(map Sₘ (algebra_map R S)
(show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map)
: Rₘ →+* Sₘ).to_algebra
end
lemma algebra_map_mk' (r : R) (m : M) :
(@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) (mk' Rₘ r m) =
mk' Sₘ (algebra_map R S r) ⟨algebra_map R S m, algebra.mem_algebra_map_submonoid_of_mem m⟩ :=
map_mk' _ _ _
variables (Rₘ Sₘ)
/-- Injectivity of the underlying `algebra_map` descends to the algebra induced by localization. -/
lemma localization_algebra_injective (hRS : function.injective (algebra_map R S))
(hM : algebra.algebra_map_submonoid S M ≤ non_zero_divisors S) :
function.injective (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) :=
is_localization.map_injective_of_injective M Rₘ Sₘ hRS hM
variables {Rₘ Sₘ}
open polynomial
lemma ring_hom.is_integral_elem_localization_at_leading_coeff
{R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S)
(x : S) (p : polynomial R) (hf : p.eval₂ f x = 0) (M : submonoid R)
(hM : p.leading_coeff ∈ M) {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ]
[algebra R Rₘ] [is_localization M Rₘ]
[algebra S Sₘ] [is_localization (M.map f : submonoid S) Sₘ] :
(map Sₘ f M.le_comap_map : Rₘ →+* _).is_integral_elem (algebra_map S Sₘ x) :=
begin
by_cases triv : (1 : Rₘ) = 0,
{ exact ⟨0, ⟨trans leading_coeff_zero triv.symm, eval₂_zero _ _⟩⟩ },
haveI : nontrivial Rₘ := nontrivial_of_ne 1 0 triv,
obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.mp
(map_units Rₘ ⟨p.leading_coeff, hM⟩),
refine ⟨(p.map (algebra_map R Rₘ)) * C b, ⟨_, _⟩⟩,
{ refine monic_mul_C_of_leading_coeff_mul_eq_one _,
rwa leading_coeff_map_of_leading_coeff_ne_zero (algebra_map R Rₘ),
refine λ hfp, zero_ne_one (trans (zero_mul b).symm (hfp ▸ hb) : (0 : Rₘ) = 1) },
{ refine eval₂_mul_eq_zero_of_left _ _ _ _,
erw [eval₂_map, is_localization.map_comp, ← hom_eval₂ _ f (algebra_map S Sₘ) x],
exact trans (congr_arg (algebra_map S Sₘ) hf) (ring_hom.map_zero _) }
end
/-- Given a particular witness to an element being algebraic over an algebra `R → S`,
We can localize to a submonoid containing the leading coefficient to make it integral.
Explicitly, the map between the localizations will be an integral ring morphism -/
theorem is_integral_localization_at_leading_coeff {x : S} (p : polynomial R)
(hp : aeval x p = 0) (hM : p.leading_coeff ∈ M) :
(map Sₘ (algebra_map R S)
(show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map)
: Rₘ →+* _).is_integral_elem (algebra_map S Sₘ x) :=
(algebra_map R S).is_integral_elem_localization_at_leading_coeff x p hp M hM
/-- If `R → S` is an integral extension, `M` is a submonoid of `R`,
`Rₘ` is the localization of `R` at `M`,
and `Sₘ` is the localization of `S` at the image of `M` under the extension map,
then the induced map `Rₘ → Sₘ` is also an integral extension -/
theorem is_integral_localization (H : algebra.is_integral R S) :
(map Sₘ (algebra_map R S)
(show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map)
: Rₘ →+* _).is_integral :=
begin
intro x,
by_cases triv : (1 : R) = 0,
{ have : (1 : Rₘ) = 0 := by convert congr_arg (algebra_map R Rₘ) triv; simp,
exact ⟨0, ⟨trans leading_coeff_zero this.symm, eval₂_zero _ _⟩⟩ },
{ haveI : nontrivial R := nontrivial_of_ne 1 0 triv,
obtain ⟨⟨s, ⟨u, hu⟩⟩, hx⟩ := surj (algebra.algebra_map_submonoid S M) x,
obtain ⟨v, hv⟩ := hu,
obtain ⟨v', hv'⟩ := is_unit_iff_exists_inv'.1 (map_units Rₘ ⟨v, hv.1⟩),
refine @is_integral_of_is_integral_mul_unit Rₘ _ _ _
(localization_algebra M S) x (algebra_map S Sₘ u) v' _ _,
{ replace hv' := congr_arg (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) hv',
rw [ring_hom.map_mul, ring_hom.map_one, ← ring_hom.comp_apply _ (algebra_map R Rₘ)] at hv',
erw is_localization.map_comp at hv',
exact hv.2 ▸ hv' },
{ obtain ⟨p, hp⟩ := H s,
exact hx.symm ▸ is_integral_localization_at_leading_coeff p hp.2 (hp.1.symm ▸ M.one_mem) } }
end
lemma is_integral_localization' {R S : Type*} [comm_ring R] [comm_ring S]
{f : R →+* S} (hf : f.is_integral) (M : submonoid R) :
(map (localization (M.map (f : R →* S))) f M.le_comap_map : localization M →+* _).is_integral :=
@is_integral_localization R _ M S _ f.to_algebra _ _ _ _ _ _ _ _ hf
end is_integral
namespace integral_closure
variables {L : Type*} [field K] [field L] [algebra A K] [is_fraction_ring A K]
open algebra
/-- If the field `L` is an algebraic extension of the integral domain `A`,
the integral closure of `A` in `L` has fraction field `L`. -/
lemma is_fraction_ring_of_algebraic [algebra A L] (alg : is_algebraic A L)
(inj : ∀ x, algebra_map A L x = 0 → x = 0) :
is_fraction_ring (integral_closure A L) L :=
⟨(λ ⟨⟨y, integral⟩, nonzero⟩,
have y ≠ 0 := λ h, mem_non_zero_divisors_iff_ne_zero.mp nonzero (subtype.ext_iff_val.mpr h),
show is_unit y, from ⟨⟨y, y⁻¹, mul_inv_cancel this, inv_mul_cancel this⟩, rfl⟩),
(λ z, let ⟨x, y, hy, hxy⟩ := exists_integral_multiple (alg z) inj in
⟨⟨x, ⟨y, mem_non_zero_divisors_iff_ne_zero.mpr hy⟩⟩, hxy⟩),
(λ x y, ⟨λ (h : x.1 = y.1), ⟨1, by simpa using subtype.ext_iff_val.mpr h⟩,
λ ⟨c, hc⟩, congr_arg (algebra_map _ L)
(mul_right_cancel' (mem_non_zero_divisors_iff_ne_zero.mp c.2) hc)⟩)⟩
variables (K L)
/-- If the field `L` is a finite extension of the fraction field of the integral domain `A`,
the integral closure of `A` in `L` has fraction field `L`. -/
lemma is_fraction_ring_of_finite_extension [algebra A L] [algebra K L]
[is_scalar_tower A K L] [finite_dimensional K L] :
is_fraction_ring (integral_closure A L) L :=
is_fraction_ring_of_algebraic
(is_fraction_ring.comap_is_algebraic_iff.mpr (is_algebraic_of_finite : is_algebraic K L))
(λ x hx, is_fraction_ring.to_map_eq_zero_iff.mp ((algebra_map K L).map_eq_zero.mp $
(is_scalar_tower.algebra_map_apply _ _ _ _).symm.trans hx))
end integral_closure
end algebra
variables (A)
/-- The fraction field of an integral domain as a quotient type. -/
@[reducible] def fraction_ring := localization (non_zero_divisors A)
namespace fraction_ring
variables {A}
noncomputable instance : field (fraction_ring A) :=
is_fraction_ring.to_field A
@[simp] lemma mk_eq_div {r s} : (localization.mk r s : fraction_ring A) =
(algebra_map _ _ r / algebra_map A _ s : fraction_ring A) :=
by rw [localization.mk_eq_mk', is_fraction_ring.mk'_eq_div]
variables (A)
/-- Given an integral domain `A` and a localization map to a field of fractions
`f : A →+* K`, we get an `A`-isomorphism between the field of fractions of `A` as a quotient
type and `K`. -/
noncomputable def alg_equiv (K : Type*) [field K] [algebra A K] [is_fraction_ring A K] :
fraction_ring A ≃ₐ[A] K :=
localization.alg_equiv (non_zero_divisors A) K
end fraction_ring
|
7ad41cd3ba1c843279a2b17e974300b035a75969 | a4673261e60b025e2c8c825dfa4ab9108246c32e | /tests/lean/run/struct3.lean | 28ccf3ef8524b8eb0db1b35776a47d39e5af77ca | [
"Apache-2.0"
] | permissive | jcommelin/lean4 | c02dec0cc32c4bccab009285475f265f17d73228 | 2909313475588cc20ac0436e55548a4502050d0a | refs/heads/master | 1,674,129,550,893 | 1,606,415,348,000 | 1,606,415,348,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 531 | lean |
universes u v
class Bind2 (m : Type u → Type v) :=
(bind : ∀ {α β : Type u}, m α → (α → m β) → m β)
set_option pp.all true
class Monad2 (m : Type u → Type v) extends Applicative m, Bind2 m : Type (max (u+1) v) :=
(map := fun f x => Bind2.bind x (pure ∘ f))
(seq := fun f x => Bind2.bind f fun y => Functor.map y x)
(seqLeft := fun x y => Bind2.bind x fun a => Bind2.bind y fun _ => pure a)
(seqRight := @fun β x y => Bind2.bind x fun _ => y) -- Recall that `@` disables implicit lambda support
|
a66c1626a73a33bccd956af571459b4cebf57217 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/algebra/continued_fractions/convergents_equiv.lean | 93f87fe36087c0b419f644b62fb7c956efaff253 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 20,597 | lean | /-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import algebra.continued_fractions.continuants_recurrence
import algebra.continued_fractions.terminated_stable
import tactic.linarith
/-!
# Equivalence of Recursive and Direct Computations of `gcf` Convergents
## Summary
We show the equivalence of two computations of convergents (recurrence relation (`convergents`) vs.
direct evaluation (`convergents'`)) for `gcf`s on linear ordered fields. We follow the proof from
[hardy2008introduction], Chapter 10. Here's a sketch:
Let `c` be a continued fraction `[h; (a₀, b₀), (a₁, b₁), (a₂, b₂),...]`, visually:
a₀
h + ---------------------------
a₁
b₀ + --------------------
a₂
b₁ + --------------
a₃
b₂ + --------
b₃ + ...
One can compute the convergents of `c` in two ways:
1. Directly evaluating the fraction described by `c` up to a given `n` (`convergents'`)
2. Using the recurrence (`convergents`):
- `A₋₁ = 1, A₀ = h, Aₙ = bₙ₋₁ * Aₙ₋₁ + aₙ₋₁ * Aₙ₋₂`, and
- `B₋₁ = 0, B₀ = 1, Bₙ = bₙ₋₁ * Bₙ₋₁ + aₙ₋₁ * Bₙ₋₂`.
To show the equivalence of the computations in the main theorem of this file
`convergents_eq_convergents'`, we proceed by induction. The case `n = 0` is trivial.
For `n + 1`, we first "squash" the `n + 1`th position of `c` into the `n`th position to obtain
another continued fraction
`c' := [h; (a₀, b₀),..., (aₙ-₁, bₙ-₁), (aₙ, bₙ + aₙ₊₁ / bₙ₊₁), (aₙ₊₁, bₙ₊₁),...]`.
This squashing process is formalised in section `squash`. Note that directly evaluating `c` up to
position `n + 1` is equal to evaluating `c'` up to `n`. This is shown in lemma
`succ_nth_convergent'_eq_squash_gcf_nth_convergent'`.
By the inductive hypothesis, the two computations for the `n`th convergent of `c` coincide.
So all that is left to show is that the recurrence relation for `c` at `n + 1` and and `c'` at
`n` coincide. This can be shown by another induction.
The corresponding lemma in this file is `succ_nth_convergent_eq_squash_gcf_nth_convergent`.
## Main Theorems
- `generalized_continued_fraction.convergents_eq_convergents'` shows the equivalence under a strict
positivity restriction on the sequence.
- `continued_fractions.convergents_eq_convergents'` shows the equivalence for (regular) continued
fractions.
## References
- https://en.wikipedia.org/wiki/Generalized_continued_fraction
- [*Hardy, GH and Wright, EM and Heath-Brown, Roger and Silverman, Joseph*][hardy2008introduction]
## Tags
fractions, recurrence, equivalence
-/
variables {K : Type*} {n : ℕ}
namespace generalized_continued_fraction
open generalized_continued_fraction as gcf
variables {g : gcf K} {s : seq $ gcf.pair K}
section squash
/-!
We will show the equivalence of the computations by induction. To make the induction work, we need
to be able to *squash* the nth and (n + 1)th value of a sequence. This squashing itself and the
lemmas about it are not very interesting. As a reader, you hence might want to skip this section.
-/
section with_division_ring
variable [division_ring K]
/--
Given a sequence of gcf.pairs `s = [(a₀, bₒ), (a₁, b₁), ...]`, `squash_seq s n`
combines `⟨aₙ, bₙ⟩` and `⟨aₙ₊₁, bₙ₊₁⟩` at position `n` to `⟨aₙ, bₙ + aₙ₊₁ / bₙ₊₁⟩`. For example,
`squash_seq s 0 = [(a₀, bₒ + a₁ / b₁), (a₁, b₁),...]`.
If `s.terminated_at (n + 1)`, then `squash_seq s n = s`.
-/
def squash_seq (s : seq $ gcf.pair K) (n : ℕ) : seq (gcf.pair K) :=
match prod.mk (s.nth n) (s.nth (n + 1)) with
| ⟨some gp_n, some gp_succ_n⟩ := seq.nats.zip_with
-- return the squashed value at position `n`; otherwise, do nothing.
(λ n' gp, if n' = n then ⟨gp_n.a, gp_n.b + gp_succ_n.a / gp_succ_n.b⟩ else gp) s
| _ := s
end
/-! We now prove some simple lemmas about the squashed sequence -/
/-- If the sequence already terminated at position `n + 1`, nothing gets squashed. -/
lemma squash_seq_eq_self_of_terminated (terminated_at_succ_n : s.terminated_at (n + 1)) :
squash_seq s n = s :=
begin
change s.nth (n + 1) = none at terminated_at_succ_n,
cases s_nth_eq : (s.nth n);
simp only [*, squash_seq]
end
/-- If the sequence has not terminated before position `n + 1`, the value at `n + 1` gets
squashed into position `n`. -/
lemma squash_seq_nth_of_not_terminated {gp_n gp_succ_n : gcf.pair K}
(s_nth_eq : s.nth n = some gp_n) (s_succ_nth_eq : s.nth (n + 1) = some gp_succ_n) :
(squash_seq s n).nth n = some ⟨gp_n.a, gp_n.b + gp_succ_n.a / gp_succ_n.b⟩ :=
by simp [*, squash_seq, (seq.zip_with_nth_some (seq.nats_nth n) s_nth_eq _)]
/-- The values before the squashed position stay the same. -/
lemma squash_seq_nth_of_lt {m : ℕ} (m_lt_n : m < n) : (squash_seq s n).nth m = s.nth m :=
begin
cases s_succ_nth_eq : s.nth (n + 1),
case option.none { rw (squash_seq_eq_self_of_terminated s_succ_nth_eq) },
case option.some
{ obtain ⟨gp_n, s_nth_eq⟩ : ∃ gp_n, s.nth n = some gp_n, from
s.ge_stable n.le_succ s_succ_nth_eq,
obtain ⟨gp_m, s_mth_eq⟩ : ∃ gp_m, s.nth m = some gp_m, from
s.ge_stable (le_of_lt m_lt_n) s_nth_eq,
simp [*, squash_seq, (seq.zip_with_nth_some (seq.nats_nth m) s_mth_eq _),
(ne_of_lt m_lt_n)] }
end
/-- Squashing at position `n + 1` and taking the tail is the same as squashing the tail of the
sequence at position `n`. -/
lemma squash_seq_succ_n_tail_eq_squash_seq_tail_n :
(squash_seq s (n + 1)).tail = squash_seq s.tail n :=
begin
cases s_succ_succ_nth_eq : s.nth (n + 2) with gp_succ_succ_n,
case option.none
{ have : squash_seq s (n + 1) = s, from squash_seq_eq_self_of_terminated s_succ_succ_nth_eq,
cases s_succ_nth_eq : (s.nth (n + 1));
simp only [squash_seq, seq.nth_tail, s_succ_nth_eq, s_succ_succ_nth_eq] },
case option.some
{ obtain ⟨gp_succ_n, s_succ_nth_eq⟩ : ∃ gp_succ_n, s.nth (n + 1) = some gp_succ_n, from
s.ge_stable (n + 1).le_succ s_succ_succ_nth_eq,
-- apply extensionality with `m` and continue by cases `m = n`.
ext m,
cases decidable.em (m = n) with m_eq_n m_ne_n,
{ have : s.tail.nth n = some gp_succ_n, from (s.nth_tail n).trans s_succ_nth_eq,
simp [*, squash_seq, seq.nth_tail, (seq.zip_with_nth_some (seq.nats_nth n) this),
(seq.zip_with_nth_some (seq.nats_nth (n + 1)) s_succ_nth_eq)] },
{ have : s.tail.nth m = s.nth (m + 1), from s.nth_tail m,
cases s_succ_mth_eq : s.nth (m + 1),
all_goals { have s_tail_mth_eq, from this.trans s_succ_mth_eq },
{ simp only [*, squash_seq, seq.nth_tail, (seq.zip_with_nth_none' s_succ_mth_eq),
(seq.zip_with_nth_none' s_tail_mth_eq)] },
{ simp [*, squash_seq, seq.nth_tail,
(seq.zip_with_nth_some (seq.nats_nth (m + 1)) s_succ_mth_eq),
(seq.zip_with_nth_some (seq.nats_nth m) s_tail_mth_eq)] } } }
end
/-- The auxiliary function `convergents'_aux` returns the same value for a sequence and the
corresponding squashed sequence at the squashed position. -/
lemma succ_succ_nth_convergent'_aux_eq_succ_nth_convergent'_aux_squash_seq :
convergents'_aux s (n + 2) = convergents'_aux (squash_seq s n) (n + 1) :=
begin
cases s_succ_nth_eq : (s.nth $ n + 1) with gp_succ_n,
case option.none
{ rw [(squash_seq_eq_self_of_terminated s_succ_nth_eq),
(convergents'_aux_stable_step_of_terminated s_succ_nth_eq)] },
case option.some
{ induction n with m IH generalizing s gp_succ_n,
case nat.zero
{ obtain ⟨gp_head, s_head_eq⟩ : ∃ gp_head, s.head = some gp_head, from
s.ge_stable zero_le_one s_succ_nth_eq,
have : (squash_seq s 0).head = some ⟨gp_head.a, gp_head.b + gp_succ_n.a / gp_succ_n.b⟩,
from squash_seq_nth_of_not_terminated s_head_eq s_succ_nth_eq,
simp [*, convergents'_aux, seq.head, seq.nth_tail] },
case nat.succ
{ obtain ⟨gp_head, s_head_eq⟩ : ∃ gp_head, s.head = some gp_head, from
s.ge_stable (m + 2).zero_le s_succ_nth_eq,
suffices : gp_head.a / (gp_head.b + convergents'_aux s.tail (m + 2))
= convergents'_aux (squash_seq s (m + 1)) (m + 2), by
simpa only [convergents'_aux, s_head_eq],
have : convergents'_aux s.tail (m + 2) = convergents'_aux (squash_seq s.tail m) (m + 1), by
{ have : s.tail.nth (m + 1) = some gp_succ_n, by simpa [seq.nth_tail] using s_succ_nth_eq,
exact (IH _ this) },
have : (squash_seq s (m + 1)).head = some gp_head, from
(squash_seq_nth_of_lt m.succ_pos).trans s_head_eq,
simp only [*, convergents'_aux, squash_seq_succ_n_tail_eq_squash_seq_tail_n] } }
end
/-! Let us now lift the squashing operation to gcfs. -/
/--
Given a gcf `g = [h; (a₀, bₒ), (a₁, b₁), ...]`, we have
- `squash_nth.gcf g 0 = [h + a₀ / b₀); (a₀, bₒ), ...]`,
- `squash_nth.gcf g (n + 1) = ⟨g.h, squash_seq g.s n⟩`
-/
def squash_gcf (g : gcf K) : ℕ → gcf K
| 0 := match g.s.nth 0 with
| none := g
| some gp := ⟨g.h + gp.a / gp.b, g.s⟩
end
| (n + 1) := ⟨g.h, squash_seq g.s n⟩
/-! Again, we derive some simple lemmas that are not really of interest. This time for the
squashed gcf. -/
/-- If the gcf already terminated at position `n`, nothing gets squashed. -/
lemma squash_gcf_eq_self_of_terminated (terminated_at_n : terminated_at g n) :
squash_gcf g n = g :=
begin
cases n,
case nat.zero
{ change g.s.nth 0 = none at terminated_at_n,
simp only [convergents', squash_gcf, convergents'_aux, terminated_at_n] },
case nat.succ
{ cases g, simp [(squash_seq_eq_self_of_terminated terminated_at_n), squash_gcf] }
end
/-- The values before the squashed position stay the same. -/
lemma squash_gcf_nth_of_lt {m : ℕ} (m_lt_n : m < n) :
(squash_gcf g (n + 1)).s.nth m = g.s.nth m :=
by simp only [squash_gcf, (squash_seq_nth_of_lt m_lt_n)]
/-- `convergents'` returns the same value for a gcf and the corresponding squashed gcf at the
squashed position. -/
lemma succ_nth_convergent'_eq_squash_gcf_nth_convergent' :
g.convergents' (n + 1) = (squash_gcf g n).convergents' n :=
begin
cases n,
case nat.zero
{ cases g_s_head_eq : (g.s.nth 0);
simp [g_s_head_eq, squash_gcf, convergents', convergents'_aux, seq.head] },
case nat.succ
{ simp only [succ_succ_nth_convergent'_aux_eq_succ_nth_convergent'_aux_squash_seq,
convergents', squash_gcf] }
end
/-- The auxiliary continuants before the squashed position stay the same. -/
lemma continuants_aux_eq_continuants_aux_squash_gcf_of_le {m : ℕ} :
m ≤ n → continuants_aux g m = (squash_gcf g n).continuants_aux m :=
nat.strong_induction_on m
(begin
clear m,
assume m IH m_le_n,
cases m with m',
{ refl },
{ cases n with n',
{ have : false, from m'.not_succ_le_zero m_le_n, contradiction }, -- 1 ≰ 0
{ cases m' with m'',
{ refl },
{ -- get some inequalities to instantiate the IH for m'' and m'' + 1
have m'_lt_n : m'' + 1 < n' + 1, from m_le_n,
have : m'' + 1 < m'' + 2, by linarith,
have succ_m''th_conts_aux_eq := IH (m'' + 1) this (le_of_lt m'_lt_n),
have : m'' < m'' + 2, by linarith,
have m''th_conts_aux_eq := IH m'' this (le_of_lt $ lt_of_lt_of_le (by linarith) n'.le_succ),
have : (squash_gcf g (n' + 1)).s.nth m'' = g.s.nth m'', from
squash_gcf_nth_of_lt (by linarith),
simp [continuants_aux, succ_m''th_conts_aux_eq, m''th_conts_aux_eq, this] } } }
end)
end with_division_ring
/-- The convergents coincide in the expected way at the squashed position if the partial denominator
at the squashed position is not zero. -/
lemma succ_nth_convergent_eq_squash_gcf_nth_convergent [field K]
(nth_part_denom_ne_zero : ∀ {b : K}, g.partial_denominators.nth n = some b → b ≠ 0) :
g.convergents (n + 1) = (squash_gcf g n).convergents n :=
begin
cases decidable.em (g.terminated_at n) with terminated_at_n not_terminated_at_n,
{ have : squash_gcf g n = g, from squash_gcf_eq_self_of_terminated terminated_at_n,
simp only [this, (convergents_stable_of_terminated n.le_succ terminated_at_n)] },
{ obtain ⟨⟨a, b⟩, s_nth_eq⟩ : ∃ gp_n, g.s.nth n = some gp_n, from
with_one.ne_one_iff_exists.elim_left not_terminated_at_n,
have b_ne_zero : b ≠ 0, from nth_part_denom_ne_zero (part_denom_eq_s_b s_nth_eq),
cases n with n',
case nat.zero
{ suffices : (b * g.h + a) / b = g.h + a / b, by
simpa [squash_gcf, s_nth_eq, convergent_eq_conts_a_div_conts_b,
(continuants_recurrence_aux s_nth_eq zeroth_continuant_aux_eq_one_zero
first_continuant_aux_eq_h_one)],
calc
(b * g.h + a) / b = b * g.h / b + a / b : by ring -- requires `field` rather than `division_ring`
... = g.h + a / b : by rw (mul_div_cancel_left _ b_ne_zero) },
case nat.succ
{ obtain ⟨⟨pa, pb⟩, s_n'th_eq⟩ : ∃ gp_n', g.s.nth n' = some gp_n' :=
g.s.ge_stable n'.le_succ s_nth_eq,
-- Notations
let g' := squash_gcf g (n' + 1),
set pred_conts := g.continuants_aux (n' + 1) with succ_n'th_conts_aux_eq,
set ppred_conts := g.continuants_aux n' with n'th_conts_aux_eq,
let pA := pred_conts.a, let pB := pred_conts.b,
let ppA := ppred_conts.a, let ppB := ppred_conts.b,
set pred_conts' := g'.continuants_aux (n' + 1) with succ_n'th_conts_aux_eq',
set ppred_conts' := g'.continuants_aux n' with n'th_conts_aux_eq',
let pA' := pred_conts'.a, let pB' := pred_conts'.b, let ppA' := ppred_conts'.a,
let ppB' := ppred_conts'.b,
-- first compute the convergent of the squashed gcf
have : g'.convergents (n' + 1)
= ((pb + a / b) * pA' + pa * ppA') / ((pb + a / b) * pB' + pa * ppB'),
{ have : g'.s.nth n' = some ⟨pa, pb + a / b⟩,
{ simpa only [squash_nth_gcf] using
(squash_seq_nth_of_not_terminated s_n'th_eq s_nth_eq) },
rw [convergent_eq_conts_a_div_conts_b,
(continuants_recurrence_aux this n'th_conts_aux_eq'.symm succ_n'th_conts_aux_eq'.symm)], },
rw this,
-- then compute the convergent of the original gcf by recursively unfolding the continuants
-- computation twice
have : g.convergents (n' + 2)
= (b * (pb * pA + pa * ppA) + a * pA) / (b * (pb * pB + pa * ppB) + a * pB),
{ -- use the recurrence once
have : g.continuants_aux (n' + 2) = ⟨pb * pA + pa * ppA, pb * pB + pa * ppB⟩ :=
continuants_aux_recurrence s_n'th_eq n'th_conts_aux_eq.symm succ_n'th_conts_aux_eq.symm,
-- and a second time
rw [convergent_eq_conts_a_div_conts_b,
(continuants_recurrence_aux s_nth_eq succ_n'th_conts_aux_eq.symm this)] },
rw this,
suffices : ((pb + a / b) * pA + pa * ppA) / ((pb + a / b) * pB + pa * ppB)
= (b * (pb * pA + pa * ppA) + a * pA) / (b * (pb * pB + pa * ppB) + a * pB),
{ obtain ⟨eq1, eq2, eq3, eq4⟩ : pA' = pA ∧ pB' = pB ∧ ppA' = ppA ∧ ppB' = ppB,
{ simp [*, (continuants_aux_eq_continuants_aux_squash_gcf_of_le $ le_refl $ n' + 1).symm,
(continuants_aux_eq_continuants_aux_squash_gcf_of_le n'.le_succ).symm] },
symmetry,
simpa only [eq1, eq2, eq3, eq4, mul_div_cancel _ b_ne_zero] },
field_simp [b_ne_zero],
congr' 1; ring } }
end
end squash
/-- Shows that the recurrence relation (`convergents`) and direct evaluation (`convergents'`) of the
gcf coincide at position `n` if the sequence of fractions contains strictly positive values only.
Requiring positivity of all values is just one possible condition to obtain this result.
For example, the dual - sequences with strictly negative values only - would also work.
In practice, one most commonly deals with (regular) continued fractions, which satisfy the
positivity criterion required here. The analogous result for them
(see `continued_fractions.convergents_eq_convergents`) hence follows directly from this theorem.
-/
theorem convergents_eq_convergents' [linear_ordered_field K]
(s_pos : ∀ {gp : gcf.pair K} {m : ℕ}, m < n → g.s.nth m = some gp → 0 < gp.a ∧ 0 < gp.b) :
g.convergents n = g.convergents' n :=
begin
induction n with n IH generalizing g,
case nat.zero { simp },
case nat.succ
{ let g' := squash_gcf g n, -- first replace the rhs with the squashed computation
suffices : g.convergents (n + 1) = g'.convergents' n, by
rwa [succ_nth_convergent'_eq_squash_gcf_nth_convergent'],
cases decidable.em (terminated_at g n) with terminated_at_n not_terminated_at_n,
{ have g'_eq_g : g' = g, from squash_gcf_eq_self_of_terminated terminated_at_n,
have : ∀ ⦃gp m⦄, m < n → g.s.nth m = some gp → 0 < gp.a ∧ 0 < gp.b, by
{ assume _ _ m_lt_n s_mth_eq, exact (s_pos (nat.lt.step m_lt_n) s_mth_eq) },
rw [(convergents_stable_of_terminated n.le_succ terminated_at_n), g'_eq_g, (IH this)] },
{ suffices : g.convergents (n + 1) = g'.convergents n, by -- invoke the IH for the squashed gcf
{ have : ∀ ⦃gp' m⦄, m < n → g'.s.nth m = some gp' → 0 < gp'.a ∧ 0 < gp'.b, by
{ assume gp' m m_lt_n s_mth_eq',
-- case distinction on m + 1 = n or m + 1 < n
cases m_lt_n with n succ_m_lt_n,
{ -- the difficult case at the squashed position: we first obtain the values from
-- the sequence
obtain ⟨gp_succ_m, s_succ_mth_eq⟩ : ∃ gp_succ_m, g.s.nth (m + 1) = some gp_succ_m, from
with_one.ne_one_iff_exists.elim_left not_terminated_at_n,
obtain ⟨gp_m, mth_s_eq⟩ : ∃ gp_m, g.s.nth m = some gp_m, from
g.s.ge_stable m.le_succ s_succ_mth_eq,
-- we then plug them into the recurrence
suffices : 0 < gp_m.a ∧ 0 < gp_m.b + gp_succ_m.a / gp_succ_m.b, by {
have : g'.s.nth m = some ⟨gp_m.a, gp_m.b + gp_succ_m.a / gp_succ_m.b⟩, from
squash_seq_nth_of_not_terminated mth_s_eq s_succ_mth_eq,
have : gp' = ⟨gp_m.a, gp_m.b + gp_succ_m.a / gp_succ_m.b⟩, by cc,
rwa this },
split,
{ exact (s_pos (nat.lt.step m_lt_n) mth_s_eq).left },
{ have : 0 < gp_m.b, from (s_pos (nat.lt.step m_lt_n) mth_s_eq).right,
have : 0 < gp_succ_m.a / gp_succ_m.b, by
{ have : 0 < gp_succ_m.a ∧ 0 < gp_succ_m.b, from
s_pos (lt_add_one $ m + 1) s_succ_mth_eq,
exact (div_pos this.left this.right) },
linarith } },
{ -- the easy case: before the squashed position, nothing changes
have : g.s.nth m = some gp', by {
have : g'.s.nth m = g.s.nth m, from squash_gcf_nth_of_lt succ_m_lt_n,
rwa this at s_mth_eq' },
exact s_pos (nat.lt.step $ nat.lt.step succ_m_lt_n) this } },
rwa [(IH this).symm] },
-- now the result follows from the fact that the convergents coincide at the squashed position
-- as established in `succ_nth_convergent_eq_squash_gcf_nth_convergent`.
have : ∀ ⦃b⦄, g.partial_denominators.nth n = some b → b ≠ 0, by
{ assume b nth_part_denom_eq,
obtain ⟨gp, s_nth_eq, ⟨refl⟩⟩ : ∃ gp, g.s.nth n = some gp ∧ gp.b = b, from
exists_s_b_of_part_denom nth_part_denom_eq,
exact (ne_of_lt (s_pos (lt_add_one n) s_nth_eq).right).symm },
exact succ_nth_convergent_eq_squash_gcf_nth_convergent this } }
end
end generalized_continued_fraction
namespace continued_fraction
open generalized_continued_fraction as gcf
open simple_continued_fraction as scf
open continued_fraction as cf
/-- Shows that the recurrence relation (`convergents`) and direct evaluation (`convergents'`) of a
(regular) continued fraction coincide. -/
theorem convergents_eq_convergents' [linear_ordered_field K] {c : cf K} :
(↑c : gcf K).convergents = (↑c : gcf K).convergents' :=
begin
ext n,
apply gcf.convergents_eq_convergents',
assume gp m m_lt_n s_nth_eq,
split,
{ have : gp.a = 1, from (c : scf K).property m gp.a (gcf.part_num_eq_s_a s_nth_eq),
simp only [zero_lt_one, this] },
{ exact (c.property m gp.b $ gcf.part_denom_eq_s_b s_nth_eq) }
end
end continued_fraction
|
56eb8edc8749c6eb1a224470662a52d51b03fffa | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/1302.lean | 1d1a8ef0f97a5624001ef0c334d2a4bda7209e7b | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 159 | lean | open list fin
vm_eval map (λ i, true) [1]
vm_eval map (λ i, true) [1, 2, 3]
vm_eval map (λ (i : fin 2), true) [fin.mk 0 dec_trivial, fin.mk 1 dec_trivial]
|
b951e9f113438e1536295a7b25995835d276452f | 1d265c7dd8cb3d0e1d645a19fd6157a2084c3921 | /src/other/real_vector3d_cross.lean | bc1116854dea4fbd17c52b67ee952b353478db3f | [
"MIT"
] | permissive | hanzhi713/lean-proofs | de432372f220d302be09b5ca4227f8986567e4fd | 4d8356a878645b9ba7cb036f87737f3f1e68ede5 | refs/heads/master | 1,585,580,245,658 | 1,553,646,623,000 | 1,553,646,623,000 | 151,342,188 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 1,871 | lean | import data.real.basic
-- this is a proof that ∀ vectors a, b ∈ ℝ³,
-- (a × b) ⬝ a = 0 ∧ (a × b) ⬝ b = 0
def dot: ℝ × ℝ × ℝ → ℝ × ℝ × ℝ → ℝ := λ ⟨a, b, c⟩ ⟨d, e, f⟩, a*d + b*e + c*f
def cross: ℝ × ℝ × ℝ → ℝ × ℝ × ℝ → ℝ × ℝ × ℝ := λ ⟨a, b, c⟩ ⟨d, e, f⟩, ⟨b*f - c*e, c*d - a*f, a*e - b*d⟩
variables m n p j k l : ℝ
#check dot (cross (m, n, p) (j, k, l)) (j, k, l)
theorem cross' (a b c d e f: ℝ) : cross (a, b, c) (d, e, f) = (b*f - c*e, c*d - a*f, a*e - b*d) := rfl
theorem dot' (a b c d e f: ℝ) : dot (a, b, c) (d, e, f) = a*d + b*e + c*f := rfl
local attribute [simp] mul_comm mul_assoc mul_right_comm
theorem proof1 : ∀ {a b c d e f: ℝ}, dot (cross (a, b, c) (d, e, f)) (a, b, c) = 0 :=
assume a b c d e f,
calc
dot (cross (a, b, c) (d, e, f)) (a, b, c) = dot (b*f - c*e, c*d - a*f, a*e - b*d) (a, b, c) : by rw cross'
... = (b*f - c*e)*a + (c*d - a*f)*b + (a*e - b*d)*c : by rw dot'
... = b*f*a - c*e*a + (c*d*b - a*f*b) + (a*e*c - b*d*c) : by repeat {rw sub_mul}
... = 0 : by simp
#check proof1
theorem proof2 : ∀ {a b c d e f: ℝ}, dot (cross (a, b, c) (d, e, f)) (d, e, f) = 0 :=
assume a b c d e f,
calc
dot (cross (a, b, c) (d, e, f)) (d, e, f) = dot (b*f - c*e, c*d - a*f, a*e - b*d) (d, e, f) : by rw cross'
... = (b*f - c*e)*d + (c*d - a*f)*e + (a*e - b*d)*f : by rw dot'
... = b*f*d - c*e*d + (c*d*e - a*f*e) + (a*e*f - b*d*f) : by repeat {rw sub_mul}
... = a * (e * f) + (c * (d * e) + (-(a * (e * f)) + -(c * (d * e)))) : by simp
... = a * (e * f) + (c * (d * e) + -(a * (e * f)) + -(c * (d * e))) : by rw add_assoc
... = 0 : by simp
#check proof2
example (a b c d e f: ℝ) :
dot (cross (a, b, c) (d, e, f)) (a, b, c) = 0 ∧ dot (cross (a, b, c) (d, e, f)) (d, e, f) = 0 :=
and.intro proof1 proof2 |
a428742f06ed483c584c90df1f21e5aeb7960210 | a721fe7446524f18ba361625fc01033d9c8b7a78 | /elaborate/strong_induction.lean | 363bba8aad72d69c1e8faff97128c53240e022b3 | [] | 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 | 76,178 | lean | λ (statement : mynat → Prop) (base_case : statement zero)
(inductive_step :
∀ (n : mynat), (∀ (m : mynat), (∃ (k : mynat), n = add m k) → statement m) → statement (succ n))
(k : mynat),
mynat.rec
(λ (M : mynat) (hMl0 : ∃ (k : mynat), zero = add M k),
eq.rec base_case
(eq.rec (eq.refl (statement M))
(eq.rec (eq.refl (statement M))
(Exists.rec
(λ (w : mynat) (h : zero = add M w) («_» : ∃ (k : mynat), zero = add M k),
mynat.rec
(eq.rec true.intro
(eq.rec (eq.refl (add zero w = zero → zero = zero))
(eq.rec
(propext
{mp := λ (hab : add zero w = zero → zero = zero) (hc : w = zero),
(eq.rec {mp := λ (h : zero = zero), h, mpr := λ (h : zero = zero), h}
(eq.rec (eq.refl (zero = zero))
(propext
{mp := λ (hl : zero = zero), true.intro,
mpr := λ (hr : true), eq.refl zero}))).mp
(hab
((eq.rec
{mp := λ (h : add zero w = zero), h,
mpr := λ (h : add zero w = zero), h}
(eq.rec (eq.refl (add zero w = zero))
(eq.rec (eq.refl (eq (add zero w)))
(eq.rec (eq.refl (add zero w))
(mynat.rec
(eq.rec true.intro
(eq.rec (eq.refl (zero = zero))
(eq.rec (eq.refl (zero = zero))
(propext
{mp := λ (hl : zero = zero), true.intro,
mpr := λ (hr : true), eq.refl zero}))))
(λ (n_n : mynat) (n_ih : add zero n_n = n_n),
eq.rec n_ih
(eq.rec (eq.refl (succ (add zero n_n) = succ n_n))
(eq.rec
(eq.refl (succ (add zero n_n) = succ n_n))
(propext
{mp := λ
(h :
succ (add zero n_n) = succ n_n),
eq.rec
(λ
(h11 :
succ (add zero n_n) =
succ (add zero n_n))
(a :
add zero n_n =
add zero n_n →
add zero n_n = n_n),
a (eq.refl (add zero n_n)))
h
h
(λ
(n_eq : add zero n_n = n_n),
n_eq),
mpr := λ (a : add zero n_n = n_n),
eq.rec
(eq.refl
(succ (add zero n_n)))
a}))))
w))))).mpr
hc)),
mpr := λ (hcd : w = zero → true) (ha : add zero w = zero),
(eq.rec {mp := λ (h : zero = zero), h, mpr := λ (h : zero = zero), h}
(eq.rec (eq.refl (zero = zero))
(propext
{mp := λ (hl : zero = zero), true.intro,
mpr := λ (hr : true), eq.refl zero}))).mpr
(hcd
((eq.rec
{mp := λ (h : add zero w = zero), h,
mpr := λ (h : add zero w = zero), h}
(eq.rec (eq.refl (add zero w = zero))
(eq.rec (eq.refl (eq (add zero w)))
(eq.rec (eq.refl (add zero w))
(mynat.rec
(eq.rec true.intro
(eq.rec (eq.refl (zero = zero))
(eq.rec (eq.refl (zero = zero))
(propext
{mp := λ (hl : zero = zero), true.intro,
mpr := λ (hr : true), eq.refl zero}))))
(λ (n_n : mynat) (n_ih : add zero n_n = n_n),
eq.rec n_ih
(eq.rec
(eq.refl (succ (add zero n_n) = succ n_n))
(eq.rec
(eq.refl (succ (add zero n_n) = succ n_n))
(propext
{mp := λ
(h :
succ (add zero n_n) =
succ n_n),
eq.rec
(λ
(h11 :
succ (add zero n_n) =
succ (add zero n_n))
(a :
add zero n_n =
add zero n_n →
add zero n_n = n_n),
a
(eq.refl
(add zero n_n)))
h
h
(λ
(n_eq : add zero n_n = n_n),
n_eq),
mpr := λ (a : add zero n_n = n_n),
eq.rec
(eq.refl
(succ (add zero n_n)))
a}))))
w))))).mp
ha))})
(propext
{mp := λ (h : w = zero → true), true.intro,
mpr := λ (ha : true) (h : w = zero), true.intro}))))
(λ (n : mynat) (ih : add n w = zero → n = zero),
eq.rec
(λ (hsmnz : succ (add w n) = zero),
false.rec (succ n = zero)
(eq.rec
(λ («_» : succ (add w n) = succ (add w n)) (a : zero = succ (add w n)),
eq.rec
(λ (h11 : zero = zero) (a : hsmnz == eq.refl (succ (add w n)) → false), a)
a
a)
hsmnz
hsmnz
(eq.refl zero)
(heq.refl hsmnz)))
(eq.rec (eq.refl (add (succ n) w = zero → succ n = zero))
(propext
{mp := λ (hab : add (succ n) w = zero → succ n = zero)
(hc : succ (add w n) = zero),
hab
((eq.rec
{mp := λ (h : add (succ n) w = zero), h,
mpr := λ (h : add (succ n) w = zero), h}
(eq.rec (eq.refl (add (succ n) w = zero))
(eq.rec (eq.refl (eq (add (succ n) w)))
(mynat.rec
(eq.rec true.intro
(eq.rec (eq.refl (succ n = succ (add zero n)))
(eq.rec
(eq.rec (eq.refl (succ n = succ (add zero n)))
(eq.rec (eq.refl (succ (add zero n)))
(eq.rec
(mynat.rec (eq.refl zero)
(λ (m_n : mynat)
(m_ih : add zero m_n = m_n),
eq.rec m_ih
(eq.rec
(eq.refl
(succ (add zero m_n) =
succ m_n))
(eq.rec
(eq.refl
(succ (add zero m_n) =
succ m_n))
(propext
{mp := λ
(h :
succ
(add zero
m_n) =
succ m_n),
eq.rec
(λ
(h11 :
succ
(add zero
m_n) =
succ
(add zero
m_n))
(a :
add zero
m_n =
add zero
m_n →
add zero
m_n =
m_n),
a
(eq.refl
(add
zero
m_n)))
h
h
(λ
(n_eq :
add zero
m_n =
m_n),
n_eq),
mpr := λ
(a :
add zero m_n =
m_n),
eq.rec
(eq.refl
(succ
(add zero
m_n)))
a}))))
n)
(eq.rec
(eq.refl (succ (add zero n) = succ n))
(eq.rec
(eq.refl (succ (add zero n) = succ n))
(propext
{mp := λ
(h :
succ (add zero n) =
succ n),
eq.rec
(λ
(h11 :
succ (add zero n) =
succ (add zero n))
(a :
add zero n =
add zero n →
add zero n = n),
a
(eq.refl
(add zero n)))
h
h
(λ
(n_eq :
add zero n = n),
n_eq),
mpr := λ (a : add zero n = n),
eq.rec
(eq.refl
(succ (add zero n)))
a}))))))
(propext
{mp := λ (hl : succ n = succ n), true.intro,
mpr := λ (hr : true), eq.refl (succ n)}))))
(λ (n_n : mynat)
(n_ih : add (succ n) n_n = succ (add n_n n)),
eq.rec n_ih
(eq.rec
(eq.refl
(succ (add (succ n) n_n) =
succ (add (succ n_n) n)))
(eq.rec
(eq.rec
(eq.refl
(succ (add (succ n) n_n) =
succ (add (succ n_n) n)))
(eq.rec
(mynat.rec (eq.refl (succ n_n))
(λ (n_n_1 : mynat)
(n_ih :
add (succ n_n) n_n_1 =
succ (add n_n n_n_1)),
eq.rec n_ih
(eq.rec
(eq.refl
(succ (add (succ n_n) n_n_1) =
succ
(succ (add n_n n_n_1))))
(eq.rec
(eq.refl
(succ
(add (succ n_n)
n_n_1) =
succ
(succ
(add n_n n_n_1))))
(propext
{mp := λ
(h :
succ
(add (succ n_n)
n_n_1) =
succ
(succ
(add n_n
n_n_1))),
eq.rec
(λ
(h11 :
succ
(add
(succ
n_n)
n_n_1) =
succ
(add
(succ
n_n)
n_n_1))
(a :
add (succ n_n)
n_n_1 =
add
(succ n_n)
n_n_1 →
add (succ n_n)
n_n_1 =
succ
(add n_n
n_n_1)),
a
(eq.refl
(add
(succ
n_n)
n_n_1)))
h
h
(λ
(n_eq :
add (succ n_n)
n_n_1 =
succ
(add n_n
n_n_1)),
n_eq),
mpr := λ
(a :
add (succ n_n)
n_n_1 =
succ
(add n_n
n_n_1)),
eq.rec
(eq.refl
(succ
(add
(succ
n_n)
n_n_1)))
a}))))
n)
(eq.rec
(eq.refl
(succ (add (succ n_n) n) =
succ (succ (add n_n n))))
(eq.rec
(eq.refl
(succ (add (succ n_n) n) =
succ (succ (add n_n n))))
(propext
{mp := λ
(h :
succ (add (succ n_n) n) =
succ (succ (add n_n n))),
eq.rec
(λ
(h11 :
succ
(add (succ n_n)
n) =
succ
(add (succ n_n)
n))
(a :
add (succ n_n) n =
add (succ n_n) n →
add (succ n_n) n =
succ (add n_n n)),
a
(eq.refl
(add (succ n_n)
n)))
h
h
(λ
(n_eq :
add (succ n_n) n =
succ (add n_n n)),
n_eq),
mpr := λ
(a :
add (succ n_n) n =
succ (add n_n n)),
eq.rec
(eq.refl
(succ
(add (succ n_n)
n)))
a})))))
(propext
{mp := λ
(h :
succ (add (succ n) n_n) =
succ (succ (add n_n n))),
eq.rec
(λ
(h11 :
succ (add (succ n) n_n) =
succ (add (succ n) n_n))
(a :
add (succ n) n_n =
add (succ n) n_n →
add (succ n) n_n =
succ (add n_n n)),
a (eq.refl (add (succ n) n_n)))
h
h
(λ
(n_eq :
add (succ n) n_n =
succ (add n_n n)), n_eq),
mpr := λ
(a :
add (succ n) n_n = succ (add n_n n)),
eq.rec
(eq.refl (succ (add (succ n) n_n)))
a}))))
w)))).mpr
hc),
mpr := λ (hcd : succ (add w n) = zero → succ n = zero)
(ha : add (succ n) w = zero),
hcd
((eq.rec
{mp := λ (h : add (succ n) w = zero), h,
mpr := λ (h : add (succ n) w = zero), h}
(eq.rec (eq.refl (add (succ n) w = zero))
(eq.rec (eq.refl (eq (add (succ n) w)))
(mynat.rec
(eq.rec true.intro
(eq.rec (eq.refl (succ n = succ (add zero n)))
(eq.rec
(eq.rec (eq.refl (succ n = succ (add zero n)))
(eq.rec (eq.refl (succ (add zero n)))
(eq.rec
(mynat.rec (eq.refl zero)
(λ (m_n : mynat)
(m_ih : add zero m_n = m_n),
eq.rec m_ih
(eq.rec
(eq.refl
(succ (add zero m_n) =
succ m_n))
(eq.rec
(eq.refl
(succ (add zero m_n) =
succ m_n))
(propext
{mp := λ
(h :
succ
(add zero
m_n) =
succ m_n),
eq.rec
(λ
(h11 :
succ
(add
zero
m_n) =
succ
(add
zero
m_n))
(a :
add zero
m_n =
add zero
m_n →
add zero
m_n =
m_n),
a
(eq.refl
(add
zero
m_n)))
h
h
(λ
(n_eq :
add zero
m_n =
m_n),
n_eq),
mpr := λ
(a :
add zero m_n =
m_n),
eq.rec
(eq.refl
(succ
(add
zero
m_n)))
a}))))
n)
(eq.rec
(eq.refl (succ (add zero n) = succ n))
(eq.rec
(eq.refl
(succ (add zero n) = succ n))
(propext
{mp := λ
(h :
succ (add zero n) =
succ n),
eq.rec
(λ
(h11 :
succ (add zero n) =
succ (add zero n))
(a :
add zero n =
add zero n →
add zero n = n),
a
(eq.refl
(add zero n)))
h
h
(λ
(n_eq :
add zero n = n),
n_eq),
mpr := λ (a : add zero n = n),
eq.rec
(eq.refl
(succ
(add zero n)))
a}))))))
(propext
{mp := λ (hl : succ n = succ n), true.intro,
mpr := λ (hr : true), eq.refl (succ n)}))))
(λ (n_n : mynat)
(n_ih : add (succ n) n_n = succ (add n_n n)),
eq.rec n_ih
(eq.rec
(eq.refl
(succ (add (succ n) n_n) =
succ (add (succ n_n) n)))
(eq.rec
(eq.rec
(eq.refl
(succ (add (succ n) n_n) =
succ (add (succ n_n) n)))
(eq.rec
(mynat.rec (eq.refl (succ n_n))
(λ (n_n_1 : mynat)
(n_ih :
add (succ n_n) n_n_1 =
succ (add n_n n_n_1)),
eq.rec n_ih
(eq.rec
(eq.refl
(succ (add (succ n_n) n_n_1) =
succ
(succ (add n_n n_n_1))))
(eq.rec
(eq.refl
(succ
(add (succ n_n)
n_n_1) =
succ
(succ
(add n_n n_n_1))))
(propext
{mp := λ
(h :
succ
(add
(succ n_n)
n_n_1) =
succ
(succ
(add n_n
n_n_1))),
eq.rec
(λ
(h11 :
succ
(add
(succ
n_n)
n_n_1) =
succ
(add
(succ
n_n)
n_n_1))
(a :
add
(succ
n_n)
n_n_1 =
add
(succ
n_n)
n_n_1 →
add
(succ
n_n)
n_n_1 =
succ
(add n_n
n_n_1)),
a
(eq.refl
(add
(succ
n_n)
n_n_1)))
h
h
(λ
(n_eq :
add
(succ
n_n)
n_n_1 =
succ
(add n_n
n_n_1)),
n_eq),
mpr := λ
(a :
add (succ n_n)
n_n_1 =
succ
(add n_n
n_n_1)),
eq.rec
(eq.refl
(succ
(add
(succ
n_n)
n_n_1)))
a}))))
n)
(eq.rec
(eq.refl
(succ (add (succ n_n) n) =
succ (succ (add n_n n))))
(eq.rec
(eq.refl
(succ (add (succ n_n) n) =
succ (succ (add n_n n))))
(propext
{mp := λ
(h :
succ (add (succ n_n) n) =
succ
(succ (add n_n n))),
eq.rec
(λ
(h11 :
succ
(add (succ n_n)
n) =
succ
(add (succ n_n)
n))
(a :
add (succ n_n) n =
add (succ n_n)
n →
add (succ n_n) n =
succ (add n_n n)),
a
(eq.refl
(add (succ n_n)
n)))
h
h
(λ
(n_eq :
add (succ n_n) n =
succ (add n_n n)),
n_eq),
mpr := λ
(a :
add (succ n_n) n =
succ (add n_n n)),
eq.rec
(eq.refl
(succ
(add (succ n_n)
n)))
a})))))
(propext
{mp := λ
(h :
succ (add (succ n) n_n) =
succ (succ (add n_n n))),
eq.rec
(λ
(h11 :
succ (add (succ n) n_n) =
succ (add (succ n) n_n))
(a :
add (succ n) n_n =
add (succ n) n_n →
add (succ n) n_n =
succ (add n_n n)),
a (eq.refl (add (succ n) n_n)))
h
h
(λ
(n_eq :
add (succ n) n_n =
succ (add n_n n)), n_eq),
mpr := λ
(a :
add (succ n) n_n = succ (add n_n n)),
eq.rec
(eq.refl (succ (add (succ n) n_n)))
a}))))
w)))).mp
ha)})))
M
(eq.rec (eq.refl zero) h))
hMl0
hMl0))))
(λ (N_n : mynat) (N_ih : ∀ (M : mynat), (∃ (k : mynat), N_n = add M k) → statement M) (M : mynat)
(hMlesN : ∃ (k : mynat), succ N_n = add M k),
Exists.rec
(λ (w : mynat) (h : succ N_n = add M w) («_» : ∃ (k : mynat), succ N_n = add M k),
mynat.rec
(λ (hd : succ N_n = M),
eq.rec (inductive_step N_n N_ih)
(eq.rec (eq.refl (statement M)) (eq.rec (eq.refl (statement M)) (eq.rec (eq.refl (succ N_n)) hd))))
(λ (n : mynat) (ih : succ N_n = add M n → statement M) (hd : succ N_n = succ (add M n)),
N_ih M
(Exists.intro n
(eq.rec hd
(eq.rec (eq.refl (succ N_n = succ (add M n)))
(propext
{mp := λ (h : succ N_n = succ (add M n)),
eq.rec
(λ (h11 : succ N_n = succ N_n) (a : N_n = N_n → N_n = add M n),
a (eq.refl N_n))
h
h
(λ (n_eq : N_n = add M n), n_eq),
mpr := λ (a : N_n = add M n), eq.rec (eq.refl (succ N_n)) a})))))
w
h)
hMlesN
hMlesN)
k
k
(Exists.intro zero
(eq.rec (eq.refl (succ k))
(eq.rec (eq.refl (succ k = succ k))
(propext {mp := λ (h : succ k = succ k), eq.refl k, mpr := λ (a : k = k), eq.refl (succ k)}))))
|
8676b6b43629f2f7c885e0c984ab05c29c13a8fc | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/polynomial/derivative.lean | 81c756e087a40e426d6f2d3c931bf86f404c486c | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 13,964 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import data.polynomial.eval
import algebra.iterate_hom
/-!
# The derivative map on polynomials
## Main definitions
* `polynomial.derivative`: The formal derivative of polynomials, expressed as a linear map.
-/
noncomputable theory
open finset
open_locale big_operators classical
namespace polynomial
universes u v w y z
variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {A : Type z} {a b : R} {n : ℕ}
section derivative
section semiring
variables [semiring R]
/-- `derivative p` is the formal derivative of the polynomial `p` -/
def derivative : polynomial R →ₗ[R] polynomial R :=
{ to_fun := λ p, p.sum (λ n a, C (a * n) * X^(n-1)),
map_add' := λ p q, by rw sum_add_index;
simp only [add_mul, forall_const, ring_hom.map_add,
eq_self_iff_true, zero_mul, ring_hom.map_zero],
map_smul' := λ a p, by rw sum_smul_index;
simp only [mul_sum, ← C_mul', mul_assoc, coeff_C_mul, ring_hom.map_mul, forall_const,
zero_mul, ring_hom.map_zero, sum] }
lemma derivative_apply (p : polynomial R) :
derivative p = p.sum (λn a, C (a * n) * X^(n - 1)) := rfl
lemma coeff_derivative (p : polynomial R) (n : ℕ) :
coeff (derivative p) n = coeff p (n + 1) * (n + 1) :=
begin
rw [derivative_apply],
simp only [coeff_X_pow, coeff_sum, coeff_C_mul],
rw [sum, finset.sum_eq_single (n + 1)],
simp only [nat.add_succ_sub_one, add_zero, mul_one, if_true, eq_self_iff_true], norm_cast,
{ assume b, cases b,
{ intros, rw [nat.cast_zero, mul_zero, zero_mul], },
{ intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } },
{ rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one, mem_support_iff],
intro h, push_neg at h, simp [h], },
end
@[simp]
lemma derivative_zero : derivative (0 : polynomial R) = 0 :=
derivative.map_zero
@[simp]
lemma iterate_derivative_zero {k : ℕ} : derivative^[k] (0 : polynomial R) = 0 :=
begin
induction k with k ih,
{ simp, },
{ simp [ih], },
end
@[simp]
lemma derivative_monomial (a : R) (n : ℕ) : derivative (monomial n a) = monomial (n - 1) (a * n) :=
by { rw [derivative_apply, sum_monomial_index, C_mul_X_pow_eq_monomial], simp }
lemma derivative_C_mul_X_pow (a : R) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) :=
by rw [C_mul_X_pow_eq_monomial, C_mul_X_pow_eq_monomial, derivative_monomial]
@[simp] lemma derivative_X_pow (n : ℕ) :
derivative (X ^ n : polynomial R) = (n : polynomial R) * X ^ (n - 1) :=
by convert derivative_C_mul_X_pow (1 : R) n; simp
@[simp] lemma derivative_C {a : R} : derivative (C a) = 0 :=
by simp [derivative_apply]
@[simp] lemma derivative_X : derivative (X : polynomial R) = 1 :=
(derivative_monomial _ _).trans $ by simp
@[simp] lemma derivative_one : derivative (1 : polynomial R) = 0 :=
derivative_C
@[simp] lemma derivative_bit0 {a : polynomial R} : derivative (bit0 a) = bit0 (derivative a) :=
by simp [bit0]
@[simp] lemma derivative_bit1 {a : polynomial R} : derivative (bit1 a) = bit0 (derivative a) :=
by simp [bit1]
@[simp] lemma derivative_add {f g : polynomial R} :
derivative (f + g) = derivative f + derivative g :=
derivative.map_add f g
@[simp] lemma iterate_derivative_add {f g : polynomial R} {k : ℕ} :
derivative^[k] (f + g) = (derivative^[k] f) + (derivative^[k] g) :=
derivative.to_add_monoid_hom.iterate_map_add _ _ _
@[simp] lemma derivative_neg {R : Type*} [ring R] (f : polynomial R) :
derivative (-f) = - derivative f :=
linear_map.map_neg derivative f
@[simp] lemma iterate_derivative_neg {R : Type*} [ring R] {f : polynomial R} {k : ℕ} :
derivative^[k] (-f) = - (derivative^[k] f) :=
(@derivative R _).to_add_monoid_hom.iterate_map_neg _ _
@[simp] lemma derivative_sub {R : Type*} [ring R] {f g : polynomial R} :
derivative (f - g) = derivative f - derivative g :=
linear_map.map_sub derivative f g
@[simp] lemma iterate_derivative_sub {R : Type*} [ring R] {k : ℕ} {f g : polynomial R} :
derivative^[k] (f - g) = (derivative^[k] f) - (derivative^[k] g) :=
begin
induction k with k ih generalizing f g,
{ simp [nat.iterate], },
{ simp [nat.iterate, ih], }
end
@[simp] lemma derivative_sum {s : finset ι} {f : ι → polynomial R} :
derivative (∑ b in s, f b) = ∑ b in s, derivative (f b) :=
derivative.map_sum
@[simp] lemma derivative_smul (r : R) (p : polynomial R) : derivative (r • p) = r • derivative p :=
derivative.map_smul _ _
@[simp] lemma iterate_derivative_smul (r : R) (p : polynomial R) (k : ℕ) :
derivative^[k] (r • p) = r • (derivative^[k] p) :=
begin
induction k with k ih generalizing p,
{ simp, },
{ simp [ih], },
end
/-- We can't use `derivative_mul` here because
we want to prove this statement also for noncommutative rings.-/
@[simp]
lemma derivative_C_mul (a : R) (p : polynomial R) : derivative (C a * p) = C a * derivative p :=
by convert derivative_smul a p; apply C_mul'
@[simp]
lemma iterate_derivative_C_mul (a : R) (p : polynomial R) (k : ℕ) :
derivative^[k] (C a * p) = C a * (derivative^[k] p) :=
by convert iterate_derivative_smul a p k; apply C_mul'
end semiring
section comm_semiring
variables [comm_semiring R]
lemma derivative_eval (p : polynomial R) (x : R) :
p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) :=
by simp only [derivative_apply, eval_sum, eval_pow, eval_C, eval_X, eval_nat_cast, eval_mul]
@[simp] lemma derivative_mul {f g : polynomial R} :
derivative (f * g) = derivative f * g + f * derivative g :=
calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) :
begin
rw mul_eq_sum_sum,
transitivity, exact derivative_sum,
transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum },
apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm,
transitivity,
{ apply congr_arg, exact monomial_eq_C_mul_X },
exact derivative_C_mul_X_pow _ _
end
... = f.sum (λn a, g.sum (λm b,
(C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) :
sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm,
by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul];
cases n; simp only [nat.succ_sub_succ, pow_zero];
cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero,
nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm]
... = derivative f * g + f * derivative g :
begin
conv { to_rhs, congr,
{ rw [← sum_C_mul_X_eq g] },
{ rw [← sum_C_mul_X_eq f] } },
simp only [sum, sum_add_distrib, finset.mul_sum, finset.sum_mul, derivative_apply]
end
theorem derivative_pow_succ (p : polynomial R) (n : ℕ) :
(p ^ (n + 1)).derivative = (n + 1) * (p ^ n) * p.derivative :=
nat.rec_on n (by rw [pow_one, nat.cast_zero, zero_add, one_mul, pow_zero, one_mul]) $ λ n ih,
by rw [pow_succ', derivative_mul, ih, mul_right_comm, ← add_mul,
add_mul (n.succ : polynomial R), one_mul, pow_succ', mul_assoc, n.cast_succ]
theorem derivative_pow (p : polynomial R) (n : ℕ) :
(p ^ n).derivative = n * (p ^ (n - 1)) * p.derivative :=
nat.cases_on n (by rw [pow_zero, derivative_one, nat.cast_zero, zero_mul, zero_mul]) $ λ n,
by rw [p.derivative_pow_succ n, n.succ_sub_one, n.cast_succ]
lemma derivative_comp (p q : polynomial R) :
(p.comp q).derivative = q.derivative * p.derivative.comp q :=
begin
apply polynomial.induction_on' p,
{ intros p₁ p₂ h₁ h₂, simp [h₁, h₂, mul_add], },
{ intros n r,
simp only [derivative_pow, derivative_mul, monomial_comp, derivative_monomial, derivative_C,
zero_mul, C_eq_nat_cast, zero_add, ring_hom.map_mul],
-- is there a tactic for this? (a multiplicative `abel`):
rw [mul_comm (derivative q)],
simp only [mul_assoc], }
end
@[simp]
theorem derivative_map [comm_semiring S] (p : polynomial R) (f : R →+* S) :
(p.map f).derivative = p.derivative.map f :=
polynomial.induction_on p
(λ r, by rw [map_C, derivative_C, derivative_C, map_zero])
(λ p q ihp ihq, by rw [map_add, derivative_add, ihp, ihq, derivative_add, map_add])
(λ n r ih, by rw [map_mul, map_C, map_pow, map_X,
derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one,
derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one,
map_mul, map_C, map_mul, map_pow, map_add, map_nat_cast, map_one, map_X])
@[simp]
theorem iterate_derivative_map [comm_semiring S] (p : polynomial R) (f : R →+* S) (k : ℕ):
polynomial.derivative^[k] (p.map f) = (polynomial.derivative^[k] p).map f :=
begin
induction k with k ih generalizing p,
{ simp, },
{ simp [ih], },
end
/-- Chain rule for formal derivative of polynomials. -/
theorem derivative_eval₂_C (p q : polynomial R) :
(p.eval₂ C q).derivative = p.derivative.eval₂ C q * q.derivative :=
polynomial.induction_on p
(λ r, by rw [eval₂_C, derivative_C, eval₂_zero, zero_mul])
(λ p₁ p₂ ih₁ ih₂, by rw [eval₂_add, derivative_add, ih₁, ih₂, derivative_add, eval₂_add, add_mul])
(λ n r ih, by rw [pow_succ', ← mul_assoc, eval₂_mul, eval₂_X, derivative_mul, ih,
@derivative_mul _ _ _ X, derivative_X, mul_one, eval₂_add, @eval₂_mul _ _ _ _ X, eval₂_X,
add_mul, mul_right_comm])
theorem of_mem_support_derivative {p : polynomial R} {n : ℕ} (h : n ∈ p.derivative.support) :
n + 1 ∈ p.support :=
mem_support_iff.2 $ λ (h1 : p.coeff (n+1) = 0), mem_support_iff.1 h $
show p.derivative.coeff n = 0, by rw [coeff_derivative, h1, zero_mul]
theorem degree_derivative_lt {p : polynomial R} (hp : p ≠ 0) : p.derivative.degree < p.degree :=
(finset.sup_lt_iff $ bot_lt_iff_ne_bot.2 $ mt degree_eq_bot.1 hp).2 $ λ n hp, lt_of_lt_of_le
(with_bot.some_lt_some.2 n.lt_succ_self) $ finset.le_sup $ of_mem_support_derivative hp
theorem nat_degree_derivative_lt {p : polynomial R} (hp : p.derivative ≠ 0) :
p.derivative.nat_degree < p.nat_degree :=
have hp1 : p ≠ 0, from λ h, hp $ by rw [h, derivative_zero],
with_bot.some_lt_some.1 $
begin
rw [nat_degree, option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp, nat_degree,
option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp1],
exact degree_derivative_lt hp1
end
theorem degree_derivative_le {p : polynomial R} : p.derivative.degree ≤ p.degree :=
if H : p = 0 then le_of_eq $ by rw [H, derivative_zero] else le_of_lt $ degree_derivative_lt H
/-- The formal derivative of polynomials, as linear homomorphism. -/
def derivative_lhom (R : Type*) [comm_ring R] : polynomial R →ₗ[R] polynomial R :=
{ to_fun := derivative,
map_add' := λ p q, derivative_add,
map_smul' := λ r p, derivative_smul r p }
@[simp] lemma derivative_lhom_coe {R : Type*} [comm_ring R] :
(polynomial.derivative_lhom R : polynomial R → polynomial R) = polynomial.derivative :=
rfl
@[simp] lemma derivative_cast_nat {n : ℕ} : derivative (n : polynomial R) = 0 :=
begin
rw ← C.map_nat_cast n,
exact derivative_C,
end
@[simp] lemma iterate_derivative_cast_nat_mul {n k : ℕ} {f : polynomial R} :
derivative^[k] (n * f) = n * (derivative^[k] f) :=
begin
induction k with k ih generalizing f,
{ simp [nat.iterate], },
{ simp [nat.iterate, ih], }
end
end comm_semiring
section comm_ring
variables [comm_ring R]
lemma derivative_comp_one_sub_X (p : polynomial R) :
(p.comp (1-X)).derivative = -p.derivative.comp (1-X) :=
by simp [derivative_comp]
@[simp]
lemma iterate_derivative_comp_one_sub_X (p : polynomial R) (k : ℕ) :
derivative^[k] (p.comp (1-X)) = (-1)^k * (derivative^[k] p).comp (1-X) :=
begin
induction k with k ih generalizing p,
{ simp, },
{ simp [ih p.derivative, iterate_derivative_neg, derivative_comp, pow_succ], },
end
end comm_ring
section domain
variables [integral_domain R]
lemma mem_support_derivative [char_zero R] (p : polynomial R) (n : ℕ) :
n ∈ (derivative p).support ↔ n + 1 ∈ p.support :=
suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : R) = 0)) ↔ coeff p (n + 1) ≠ 0,
by simpa only [mem_support_iff, coeff_derivative, ne.def, mul_eq_zero],
by { rw [nat.cast_eq_zero], simp only [nat.succ_ne_zero, or_false] }
@[simp] lemma degree_derivative_eq [char_zero R] (p : polynomial R) (hp : 0 < nat_degree p) :
degree (derivative p) = (nat_degree p - 1 : ℕ) :=
begin
have h0 : p ≠ 0,
{ contrapose! hp,
simp [hp] },
apply le_antisymm,
{ rw derivative_apply,
apply le_trans (degree_sum_le _ _) (sup_le (λ n hn, _)),
apply le_trans (degree_C_mul_X_pow_le _ _) (with_bot.coe_le_coe.2 (nat.sub_le_sub_right _ _)),
apply le_nat_degree_of_mem_supp _ hn },
{ refine le_sup _,
rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff],
{ show ¬ leading_coeff p = 0,
rw [leading_coeff_eq_zero],
assume h, rw [h, nat_degree_zero] at hp,
exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), },
exact hp }
end
theorem nat_degree_eq_zero_of_derivative_eq_zero
[char_zero R] {f : polynomial R} (h : f.derivative = 0) :
f.nat_degree = 0 :=
begin
by_cases hf : f = 0,
{ exact (congr_arg polynomial.nat_degree hf).trans rfl },
{ rw nat_degree_eq_zero_iff_degree_le_zero,
by_contra absurd,
have f_nat_degree_pos : 0 < f.nat_degree,
{ rwa [not_le, ←nat_degree_pos_iff_degree_pos] at absurd },
let m := f.nat_degree - 1,
have hm : m + 1 = f.nat_degree := nat.sub_add_cancel f_nat_degree_pos,
have h2 := coeff_derivative f m,
rw polynomial.ext_iff at h,
rw [h m, coeff_zero, zero_eq_mul] at h2,
cases h2,
{ rw [hm, ←leading_coeff, leading_coeff_eq_zero] at h2,
exact hf h2, },
{ norm_cast at h2 } }
end
end domain
end derivative
end polynomial
|
9be2407961ba4fa9a8e4a3f7607101ebba5678a4 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/normed/order/basic.lean | 79e3daec9d62afa430e7cd7d28feb820374d18dd | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 4,239 | lean | /-
Copyright (c) 2020 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker, Yaël Dillies
-/
import algebra.order.group.type_tags
import analysis.normed_space.basic
/-!
# Ordered normed spaces
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file, we define classes for fields and groups that are both normed and ordered.
These are mostly useful to avoid diamonds during type class inference.
-/
open filter set
open_locale topology
variables {α : Type*}
/-- A `normed_ordered_add_group` is an additive group that is both a `normed_add_comm_group` and an
`ordered_add_comm_group`. This class is necessary to avoid diamonds caused by both classes
carrying their own group structure. -/
class normed_ordered_add_group (α : Type*)
extends ordered_add_comm_group α, has_norm α, metric_space α :=
(dist_eq : ∀ x y, dist x y = ‖x - y‖ . obviously)
/-- A `normed_ordered_group` is a group that is both a `normed_comm_group` and an
`ordered_comm_group`. This class is necessary to avoid diamonds caused by both classes
carrying their own group structure. -/
@[to_additive]
class normed_ordered_group (α : Type*) extends ordered_comm_group α, has_norm α, metric_space α :=
(dist_eq : ∀ x y, dist x y = ‖x / y‖ . obviously)
/-- A `normed_linear_ordered_add_group` is an additive group that is both a `normed_add_comm_group`
and a `linear_ordered_add_comm_group`. This class is necessary to avoid diamonds caused by both
classes carrying their own group structure. -/
class normed_linear_ordered_add_group (α : Type*)
extends linear_ordered_add_comm_group α, has_norm α, metric_space α :=
(dist_eq : ∀ x y, dist x y = ‖x - y‖ . obviously)
/-- A `normed_linear_ordered_group` is a group that is both a `normed_comm_group` and a
`linear_ordered_comm_group`. This class is necessary to avoid diamonds caused by both classes
carrying their own group structure. -/
@[to_additive]
class normed_linear_ordered_group (α : Type*)
extends linear_ordered_comm_group α, has_norm α, metric_space α :=
(dist_eq : ∀ x y, dist x y = ‖x / y‖ . obviously)
/-- A `normed_linear_ordered_field` is a field that is both a `normed_field` and a
`linear_ordered_field`. This class is necessary to avoid diamonds. -/
class normed_linear_ordered_field (α : Type*)
extends linear_ordered_field α, has_norm α, metric_space α :=
(dist_eq : ∀ x y, dist x y = ‖x - y‖ . obviously)
(norm_mul' : ∀ x y : α, ‖x * y‖ = ‖x‖ * ‖y‖)
@[to_additive, priority 100]
instance normed_ordered_group.to_normed_comm_group [normed_ordered_group α] : normed_comm_group α :=
⟨normed_ordered_group.dist_eq⟩
@[to_additive, priority 100]
instance normed_linear_ordered_group.to_normed_ordered_group [normed_linear_ordered_group α] :
normed_ordered_group α :=
⟨normed_linear_ordered_group.dist_eq⟩
@[priority 100] instance normed_linear_ordered_field.to_normed_field (α : Type*)
[normed_linear_ordered_field α] : normed_field α :=
{ dist_eq := normed_linear_ordered_field.dist_eq,
norm_mul' := normed_linear_ordered_field.norm_mul' }
instance : normed_linear_ordered_field ℚ :=
⟨dist_eq_norm, norm_mul⟩
noncomputable
instance : normed_linear_ordered_field ℝ :=
⟨dist_eq_norm, norm_mul⟩
@[to_additive] instance [normed_ordered_group α] : normed_ordered_group αᵒᵈ :=
{ ..normed_ordered_group.to_normed_comm_group, ..order_dual.ordered_comm_group }
@[to_additive] instance [normed_linear_ordered_group α] : normed_linear_ordered_group αᵒᵈ :=
{ ..order_dual.normed_ordered_group, ..order_dual.linear_order _ }
instance [normed_ordered_group α] : normed_ordered_add_group (additive α) :=
{ ..additive.normed_add_comm_group }
instance [normed_ordered_add_group α] : normed_ordered_group (multiplicative α) :=
{ ..multiplicative.normed_comm_group }
instance [normed_linear_ordered_group α] : normed_linear_ordered_add_group (additive α) :=
{ ..additive.normed_add_comm_group }
instance [normed_linear_ordered_add_group α] : normed_linear_ordered_group (multiplicative α) :=
{ ..multiplicative.normed_comm_group }
|
0e0345ba1d584764ee45dba5cf14f57eee7367bf | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/field_theory/intermediate_field.lean | d722bf870780df7d2ed2c19188d4f837a80d7b0b | [
"Apache-2.0"
] | permissive | mcncm/mathlib | 8d25099344d9d2bee62822cb9ed43aa3e09fa05e | fde3d78cadeec5ef827b16ae55664ef115e66f57 | refs/heads/master | 1,672,743,316,277 | 1,602,618,514,000 | 1,602,618,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,410 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import field_theory.subfield
import ring_theory.algebra_tower
/-!
# Intermediate fields
Let `L / K` be a field extension, given as an instance `algebra K L`.
This file defines the type of fields in between `K` and `L`, `intermediate_field K L`.
An `intermediate_field K L` is a subfield of `L` which contains (the image of) `K`,
i.e. it is a `subfield L` and a `subalgebra K L`.
## Main definitions
* `intermediate_field K L` : the type of intermediate fields between `K` and `L`.
* `subalgebra.to_intermediate_field`: turns a subalgebra closed under `⁻¹`
into an intermediate field
* `subfield.to_intermediate_field`: turns a subfield containing the image of `K`
into an intermediate field
* `intermediate_field.map`: map an intermediate field along an `alg_hom`
## Implementation notes
Intermediate fields are defined with a structure extending `subfield` and `subalgebra`.
A `subalgebra` is closed under all operations except `⁻¹`,
## TODO
* `field.adjoin` currently returns a `subalgebra`, this should become an
`intermediate_field`. The lattice structure on `intermediate_field` will
follow from the adjunction given by `field.adjoin`.
## Tags
intermediate field, field extension
-/
open_locale big_operators
variables (K L : Type*) [field K] [field L] [algebra K L]
section
set_option old_structure_cmd true
/-- `S : intermediate_field K L` is a subset of `L` such that there is a field
tower `L / S / K`. -/
structure intermediate_field extends subalgebra K L, subfield L
/-- Reinterpret an `intermediate_field` as a `subalgebra`. -/
add_decl_doc intermediate_field.to_subalgebra
/-- Reinterpret an `intermediate_field` as a `subfield`. -/
add_decl_doc intermediate_field.to_subfield
end
variables {K L} (S : intermediate_field K L)
namespace intermediate_field
instance : has_coe (intermediate_field K L) (set L) :=
⟨intermediate_field.carrier⟩
@[simp] lemma coe_to_subalgebra : (S.to_subalgebra : set L) = S := rfl
@[simp] lemma coe_to_subfield : (S.to_subfield : set L) = S := rfl
instance : has_coe_to_sort (intermediate_field K L) := ⟨Type*, λ S, S.carrier⟩
instance : has_mem L (intermediate_field K L) := ⟨λ m S, m ∈ (S : set L)⟩
@[simp] lemma mem_mk (s : set L) (hK : ∀ x, algebra_map K L x ∈ s)
(ho hm hz ha hn hi) (x : L) :
x ∈ intermediate_field.mk s ho hm hz ha hK hn hi ↔ x ∈ s := iff.rfl
@[simp] lemma mem_coe (x : L) : x ∈ (S : set L) ↔ x ∈ S := iff.rfl
@[simp] lemma mem_to_subalgebra (s : intermediate_field K L) (x : L) :
x ∈ s.to_subalgebra ↔ x ∈ s := iff.rfl
@[simp] lemma mem_to_subfield (s : intermediate_field K L) (x : L) :
x ∈ s.to_subfield ↔ x ∈ s := iff.rfl
/-- Two intermediate fields are equal if the underlying subsets are equal. -/
theorem ext' ⦃s t : intermediate_field K L⦄ (h : (s : set L) = t) : s = t :=
by { cases s, cases t, congr' }
/-- Two intermediate fields are equal if and only if the underlying subsets are equal. -/
protected theorem ext'_iff {s t : intermediate_field K L} : s = t ↔ (s : set L) = t :=
⟨λ h, h ▸ rfl, λ h, ext' h⟩
/-- Two intermediate fields are equal if they have the same elements. -/
@[ext] theorem ext {S T : intermediate_field K L} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T :=
ext' $ set.ext h
/-- An intermediate field contains the image of the smaller field. -/
theorem algebra_map_mem (x : K) : algebra_map K L x ∈ S :=
S.algebra_map_mem' x
/-- An intermediate field contains the ring's 1. -/
theorem one_mem : (1 : L) ∈ S := S.one_mem'
/-- An intermediate field contains the ring's 0. -/
theorem zero_mem : (0 : L) ∈ S := S.zero_mem'
/-- An intermediate field is closed under multiplication. -/
theorem mul_mem : ∀ {x y : L}, x ∈ S → y ∈ S → x * y ∈ S := S.mul_mem'
/-- An intermediate field is closed under scalar multiplication. -/
theorem smul_mem {y : L} : y ∈ S → ∀ {x : K}, x • y ∈ S := S.to_subalgebra.smul_mem
/-- An intermediate field is closed under addition. -/
theorem add_mem : ∀ {x y : L}, x ∈ S → y ∈ S → x + y ∈ S := S.add_mem'
/-- An intermediate field is closed under subtraction -/
theorem sub_mem {x y : L} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S :=
S.to_subfield.sub_mem hx hy
/-- An intermediate field is closed under negation. -/
theorem neg_mem : ∀ {x : L}, x ∈ S → -x ∈ S := S.neg_mem'
/-- An intermediate field is closed under inverses. -/
theorem inv_mem : ∀ {x : L}, x ∈ S → x⁻¹ ∈ S := S.inv_mem'
/-- An intermediate field is closed under division. -/
theorem div_mem {x y : L} (hx : x ∈ S) (hy : y ∈ S) : x / y ∈ S :=
S.to_subfield.div_mem hx hy
/-- Product of a list of elements in an intermediate_field is in the intermediate_field. -/
lemma list_prod_mem {l : list L} : (∀ x ∈ l, x ∈ S) → l.prod ∈ S :=
S.to_subfield.list_prod_mem
/-- Sum of a list of elements in an intermediate field is in the intermediate_field. -/
lemma list_sum_mem {l : list L} : (∀ x ∈ l, x ∈ S) → l.sum ∈ S :=
S.to_subfield.list_sum_mem
/-- Product of a multiset of elements in an intermediate field is in the intermediate_field. -/
lemma multiset_prod_mem (m : multiset L) :
(∀ a ∈ m, a ∈ S) → m.prod ∈ S :=
S.to_subfield.multiset_prod_mem m
/-- Sum of a multiset of elements in a `intermediate_field` is in the `intermediate_field`. -/
lemma multiset_sum_mem (m : multiset L) :
(∀ a ∈ m, a ∈ S) → m.sum ∈ S :=
S.to_subfield.multiset_sum_mem m
/-- Product of elements of an intermediate field indexed by a `finset` is in the intermediate_field. -/
lemma prod_mem {ι : Type*} {t : finset ι} {f : ι → L} (h : ∀ c ∈ t, f c ∈ S) :
∏ i in t, f i ∈ S :=
S.to_subfield.prod_mem h
/-- Sum of elements in a `intermediate_field` indexed by a `finset` is in the `intermediate_field`. -/
lemma sum_mem {ι : Type*} {t : finset ι} {f : ι → L} (h : ∀ c ∈ t, f c ∈ S) :
∑ i in t, f i ∈ S :=
S.to_subfield.sum_mem h
lemma pow_mem {x : L} (hx : x ∈ S) (n : ℤ) : x^n ∈ S :=
begin
cases n,
{ exact @is_submonoid.pow_mem L _ S.to_subfield.to_submonoid x _ hx n, },
{ have h := @is_submonoid.pow_mem L _ S.to_subfield.to_submonoid x _ hx _,
exact subfield.inv_mem S.to_subfield h, },
end
lemma gsmul_mem {x : L} (hx : x ∈ S) (n : ℤ) :
n •ℤ x ∈ S := S.to_subfield.gsmul_mem hx n
lemma coe_int_mem (n : ℤ) : (n : L) ∈ S :=
by simp only [← gsmul_one, gsmul_mem, one_mem]
end intermediate_field
/-- Turn a subalgebra closed under inverses into an intermediate field -/
def subalgebra.to_intermediate_field (S : subalgebra K L) (inv_mem : ∀ x ∈ S, x⁻¹ ∈ S) :
intermediate_field K L :=
{ neg_mem' := λ x, S.neg_mem,
inv_mem' := inv_mem,
.. S }
/-- Turn a subfield of `L` containing the image of `K` into an intermediate field -/
def subfield.to_intermediate_field (S : subfield L)
(algebra_map_mem : ∀ x, algebra_map K L x ∈ S) :
intermediate_field K L :=
{ algebra_map_mem' := algebra_map_mem,
.. S }
namespace intermediate_field
/-- An intermediate field inherits a field structure -/
instance to_field : field S :=
S.to_subfield.to_field
@[simp, norm_cast] lemma coe_add (x y : S) : (↑(x + y) : L) = ↑x + ↑y := rfl
@[simp, norm_cast] lemma coe_neg (x : S) : (↑(-x) : L) = -↑x := rfl
@[simp, norm_cast] lemma coe_mul (x y : S) : (↑(x * y) : L) = ↑x * ↑y := rfl
@[simp, norm_cast] lemma coe_inv (x : S) : (↑(x⁻¹) : L) = (↑x)⁻¹ := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : S) : L) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : S) : L) = 1 := rfl
instance algebra : algebra K S :=
S.to_subalgebra.algebra
instance to_algebra : algebra S L :=
S.to_subalgebra.to_algebra
instance : is_scalar_tower K S L :=
is_scalar_tower.subalgebra' _ _ _ S.to_subalgebra
variables {L' : Type*} [field L'] [algebra K L']
/-- If `f : L →+* L'` fixes `K`, `S.map f` is the intermediate field between `L'` and `K`
such that `x ∈ S ↔ f x ∈ S.map f`. -/
def map (f : L →ₐ[K] L') : intermediate_field K L' :=
{ inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, S.inv_mem hx, f.map_inv x⟩ },
neg_mem' := λ x hx, (S.to_subalgebra.map f).neg_mem hx,
.. S.to_subalgebra.map f}
/-- The embedding from an intermediate field of `L / K` to `L`. -/
def val : S →ₐ[K] L :=
S.to_subalgebra.val
@[simp] theorem coe_val : ⇑S.val = coe := rfl
@[simp] lemma val_mk {x : L} (hx : x ∈ S) : S.val ⟨x, hx⟩ = x := rfl
variables {S}
lemma to_subalgebra_injective {S S' : intermediate_field K L}
(h : S.to_subalgebra = S'.to_subalgebra) : S = S' :=
by { ext, rw [← mem_to_subalgebra, ← mem_to_subalgebra, h] }
instance : partial_order (intermediate_field K L) :=
{ le := λ S T, (S : set L) ⊆ T,
le_refl := λ S, set.subset.refl S,
le_trans := λ _ _ _, set.subset.trans,
le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ }
variables (S)
lemma set_range_subset : set.range (algebra_map K L) ⊆ S :=
S.to_subalgebra.range_subset
lemma field_range_le : (algebra_map K L).field_range ≤ S.to_subfield :=
λ x hx, S.to_subalgebra.range_subset (by rwa [set.mem_range, ← ring_hom.mem_field_range])
variables {S}
section tower
/-- Lift an intermediate_field of an intermediate_field -/
def lift1 {F : intermediate_field K L} (E : intermediate_field K F) : intermediate_field K L :=
map E (val F)
/-- Lift an intermediate_field of an intermediate_field -/
def lift2 {F : intermediate_field K L} (E : intermediate_field F L) : intermediate_field K L :=
{ carrier := E.carrier,
zero_mem' := zero_mem E,
add_mem' := λ x y, add_mem E,
neg_mem' := λ x, neg_mem E,
one_mem' := one_mem E,
mul_mem' := λ x y, mul_mem E,
inv_mem' := λ x, inv_mem E,
algebra_map_mem' := λ x, algebra_map_mem E (algebra_map K F x) }
instance has_lift1 {F : intermediate_field K L} :
has_lift_t (intermediate_field K F) (intermediate_field K L) := ⟨lift1⟩
instance has_lift2 {F : intermediate_field K L} :
has_lift_t (intermediate_field F L) (intermediate_field K L) := ⟨lift2⟩
@[simp] lemma mem_lift2 {F : intermediate_field K L} {E : intermediate_field F L} {x : L} :
x ∈ (↑E : intermediate_field K L) ↔ x ∈ E := iff.rfl
end tower
end intermediate_field
|
e0619c4e8985178bb03189aa891ff23ea5849428 | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/ring_theory/algebraic.lean | 257874be742ecfc31de5641340918cff58eff3c0 | [
"Apache-2.0"
] | permissive | molodiuc/mathlib | cae2ba3ef1601c1f42ca0b625c79b061b63fef5b | 98ebe5a6739fbe254f9ee9d401882d4388f91035 | refs/heads/master | 1,674,237,127,059 | 1,606,353,533,000 | 1,606,353,533,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,486 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import linear_algebra.finite_dimensional
import ring_theory.integral_closure
import data.polynomial.integral_normalization
/-!
# Algebraic elements and algebraic extensions
An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial.
An R-algebra is algebraic over R if and only if all its elements are algebraic over R.
The main result in this file proves transitivity of algebraicity:
a tower of algebraic field extensions is algebraic.
-/
universe variables u v
open_locale classical
open polynomial
section
variables (R : Type u) {A : Type v} [comm_ring R] [comm_ring A] [algebra R A]
/-- An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. -/
def is_algebraic (x : A) : Prop :=
∃ p : polynomial R, p ≠ 0 ∧ aeval x p = 0
variables {R}
/-- A subalgebra is algebraic if all its elements are algebraic. -/
def subalgebra.is_algebraic (S : subalgebra R A) : Prop := ∀ x ∈ S, is_algebraic R x
variables (R A)
/-- An algebra is algebraic if all its elements are algebraic. -/
def algebra.is_algebraic : Prop := ∀ x : A, is_algebraic R x
variables {R A}
/-- A subalgebra is algebraic if and only if it is algebraic an algebra. -/
lemma subalgebra.is_algebraic_iff (S : subalgebra R A) :
S.is_algebraic ↔ @algebra.is_algebraic R S _ _ (S.algebra) :=
begin
delta algebra.is_algebraic subalgebra.is_algebraic,
rw [subtype.forall'],
apply forall_congr, rintro ⟨x, hx⟩,
apply exists_congr, intro p,
apply and_congr iff.rfl,
have h : function.injective (S.val) := subtype.val_injective,
conv_rhs { rw [← h.eq_iff, alg_hom.map_zero], },
rw [← aeval_alg_hom_apply, S.val_apply]
end
/-- An algebra is algebraic if and only if it is algebraic as a subalgebra. -/
lemma algebra.is_algebraic_iff : algebra.is_algebraic R A ↔ (⊤ : subalgebra R A).is_algebraic :=
begin
delta algebra.is_algebraic subalgebra.is_algebraic,
simp only [algebra.mem_top, forall_prop_of_true, iff_self],
end
end
section zero_ne_one
variables (R : Type u) {A : Type v} [comm_ring R] [nontrivial R] [comm_ring A] [algebra R A]
/-- An integral element of an algebra is algebraic.-/
lemma is_integral.is_algebraic {x : A} (h : is_integral R x) : is_algebraic R x :=
by { rcases h with ⟨p, hp, hpx⟩, exact ⟨p, hp.ne_zero, hpx⟩ }
end zero_ne_one
section field
variables (K : Type u) {A : Type v} [field K] [comm_ring A] [algebra K A]
/-- An element of an algebra over a field is algebraic if and only if it is integral.-/
lemma is_algebraic_iff_is_integral {x : A} :
is_algebraic K x ↔ is_integral K x :=
begin
refine ⟨_, is_integral.is_algebraic K⟩,
rintro ⟨p, hp, hpx⟩,
refine ⟨_, monic_mul_leading_coeff_inv hp, _⟩,
rw [← aeval_def, alg_hom.map_mul, hpx, zero_mul],
end
end field
namespace algebra
variables {K : Type*} {L : Type*} {A : Type*}
variables [field K] [field L] [comm_ring A]
variables [algebra K L] [algebra L A] [algebra K A] [is_scalar_tower K L A]
/-- If L is an algebraic field extension of K and A is an algebraic algebra over L,
then A is algebraic over K. -/
lemma is_algebraic_trans (L_alg : is_algebraic K L) (A_alg : is_algebraic L A) :
is_algebraic K A :=
begin
simp only [is_algebraic, is_algebraic_iff_is_integral] at L_alg A_alg ⊢,
exact is_integral_trans L_alg A_alg,
end
/-- A field extension is algebraic if it is finite. -/
lemma is_algebraic_of_finite [finite : finite_dimensional K L] : is_algebraic K L :=
λ x, (is_algebraic_iff_is_integral _).mpr (is_integral_of_submodule_noetherian ⊤
(is_noetherian_of_submodule_of_noetherian _ _ _ finite) x algebra.mem_top)
end algebra
variables {R S : Type*} [integral_domain R] [comm_ring S]
lemma exists_integral_multiple [algebra R S] {z : S} (hz : is_algebraic R z)
(inj : ∀ x, algebra_map R S x = 0 → x = 0) :
∃ (x : integral_closure R S) (y ≠ (0 : integral_closure R S)),
z * y = x :=
begin
rcases hz with ⟨p, p_ne_zero, px⟩,
set n := p.nat_degree with n_def,
set a := p.leading_coeff with a_def,
have a_ne_zero : a ≠ 0 := mt polynomial.leading_coeff_eq_zero.mp p_ne_zero,
have y_integral : is_integral R (algebra_map R S a) := is_integral_algebra_map,
have x_integral : is_integral R (z * algebra_map R S a) :=
⟨ p.integral_normalization,
monic_integral_normalization p_ne_zero,
integral_normalization_aeval_eq_zero p_ne_zero px inj ⟩,
refine ⟨⟨_, x_integral⟩, ⟨_, y_integral⟩, _, rfl⟩,
exact λ h, a_ne_zero (inj _ (subtype.ext_iff_val.mp h))
end
section field
variables {K L : Type*} [field K] [field L] [algebra K L] (A : subalgebra K L)
lemma inv_eq_of_aeval_div_X_ne_zero {x : L} {p : polynomial K}
(aeval_ne : aeval x (div_X p) ≠ 0) :
x⁻¹ = aeval x (div_X p) / (aeval x p - algebra_map _ _ (p.coeff 0)) :=
begin
rw [inv_eq_iff, inv_div, div_eq_iff, sub_eq_iff_eq_add, mul_comm],
conv_lhs { rw ← div_X_mul_X_add p },
rw [alg_hom.map_add, alg_hom.map_mul, aeval_X, aeval_C],
exact aeval_ne
end
lemma inv_eq_of_root_of_coeff_zero_ne_zero {x : L} {p : polynomial K}
(aeval_eq : aeval x p = 0) (coeff_zero_ne : p.coeff 0 ≠ 0) :
x⁻¹ = - (aeval x (div_X p) / algebra_map _ _ (p.coeff 0)) :=
begin
convert inv_eq_of_aeval_div_X_ne_zero (mt (λ h, (algebra_map K L).injective _) coeff_zero_ne),
{ rw [aeval_eq, zero_sub, div_neg] },
rw ring_hom.map_zero,
convert aeval_eq,
conv_rhs { rw ← div_X_mul_X_add p },
rw [alg_hom.map_add, alg_hom.map_mul, h, zero_mul, zero_add, aeval_C]
end
lemma subalgebra.inv_mem_of_root_of_coeff_zero_ne_zero {x : A} {p : polynomial K}
(aeval_eq : aeval x p = 0) (coeff_zero_ne : p.coeff 0 ≠ 0) : (x⁻¹ : L) ∈ A :=
begin
have : (x⁻¹ : L) = aeval x (div_X p) / (aeval x p - algebra_map _ _ (p.coeff 0)),
{ rw [aeval_eq, submodule.coe_zero, zero_sub, div_neg],
convert inv_eq_of_root_of_coeff_zero_ne_zero _ coeff_zero_ne,
{ rw subalgebra.aeval_coe },
{ simpa using aeval_eq } },
rw [this, div_eq_mul_inv, aeval_eq, submodule.coe_zero, zero_sub, ← ring_hom.map_neg,
← ring_hom.map_inv],
exact A.mul_mem (aeval x p.div_X).2 (A.algebra_map_mem _),
end
lemma subalgebra.inv_mem_of_algebraic {x : A} (hx : is_algebraic K (x : L)) : (x⁻¹ : L) ∈ A :=
begin
obtain ⟨p, ne_zero, aeval_eq⟩ := hx,
replace aeval_eq : aeval x p = 0,
{ rw ← submodule.coe_eq_zero,
convert aeval_eq,
exact is_scalar_tower.algebra_map_aeval K A L _ _ },
revert ne_zero aeval_eq,
refine p.rec_on_horner _ _ _,
{ intro h,
contradiction },
{ intros p a hp ha ih ne_zero aeval_eq,
refine A.inv_mem_of_root_of_coeff_zero_ne_zero aeval_eq _,
rwa [coeff_add, hp, zero_add, coeff_C, if_pos rfl] },
{ intros p hp ih ne_zero aeval_eq,
rw [alg_hom.map_mul, aeval_X, mul_eq_zero] at aeval_eq,
cases aeval_eq with aeval_eq x_eq,
{ exact ih hp aeval_eq },
{ rw [x_eq, submodule.coe_zero, inv_zero],
exact A.zero_mem } }
end
/-- In an algebraic extension L/K, an intermediate subalgebra is a field. -/
lemma subalgebra.is_field_of_algebraic (hKL : algebra.is_algebraic K L) : is_field A :=
{ mul_inv_cancel := λ a ha, ⟨
⟨a⁻¹, A.inv_mem_of_algebraic (hKL a)⟩,
subtype.ext (mul_inv_cancel (mt submodule.coe_eq_zero.mp ha))⟩,
.. subalgebra.integral_domain A }
end field
|
ee84cbac019ac0a86c9cd232b3de466c365891ad | cc060cf567f81c404a13ee79bf21f2e720fa6db0 | /lean/cpdt.lean | ac1c2a68850550a4699fe9fae00651af05779a37 | [
"Apache-2.0"
] | permissive | semorrison/proof | cf0a8c6957153bdb206fd5d5a762a75958a82bca | 5ee398aa239a379a431190edbb6022b1a0aa2c70 | refs/heads/master | 1,610,414,502,842 | 1,518,696,851,000 | 1,518,696,851,000 | 78,375,937 | 2 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 208 | lean | namespace tactic
open tactic
meta def appHyps (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
match gs with
| [] := fail "appHyps failed, no goals work"
| (g::rs) := tac
end tactic
|
8e34b3c670eb041bf3ef7f71f8e1ba3adc804a8c | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/category_theory/concrete_category/basic.lean | 976da2fece4f04aa06a518a9586c0db01c51a436 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,451 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather, Yury Kudryashov
-/
import category_theory.types
import category_theory.epi_mono
/-!
# Concrete categories
A concrete category is a category `C` with a fixed faithful functor
`forget : C ⥤ Type*`. We define concrete categories using `class
concrete_category`. In particular, we impose no restrictions on the
carrier type `C`, so `Type` is a concrete category with the identity
forgetful functor.
Each concrete category `C` comes with a canonical faithful functor
`forget C : C ⥤ Type*`. We say that a concrete category `C` admits a
*forgetful functor* to a concrete category `D`, if it has a functor
`forget₂ C D : C ⥤ D` such that `(forget₂ C D) ⋙ (forget D) = forget C`,
see `class has_forget₂`. Due to `faithful.div_comp`, it suffices
to verify that `forget₂.obj` and `forget₂.map` agree with the equality
above; then `forget₂` will satisfy the functor laws automatically, see
`has_forget₂.mk'`.
Two classes helping construct concrete categories in the two most
common cases are provided in the files `bundled_hom` and
`unbundled_hom`, see their documentation for details.
## References
See [Ahrens and Lumsdaine, *Displayed Categories*][ahrens2017] for
related work.
-/
universes w v v' u
namespace category_theory
/--
A concrete category is a category `C` with a fixed faithful functor `forget : C ⥤ Type`.
Note that `concrete_category` potentially depends on three independent universe levels,
* the universe level `w` appearing in `forget : C ⥤ Type w`
* the universe level `v` of the morphisms (i.e. we have a `category.{v} C`)
* the universe level `u` of the objects (i.e `C : Type u`)
They are specified that order, to avoid unnecessary universe annotations.
-/
class concrete_category (C : Type u) [category.{v} C] :=
(forget [] : C ⥤ Type w)
[forget_faithful : faithful forget]
attribute [instance] concrete_category.forget_faithful
/-- The forgetful functor from a concrete category to `Type u`. -/
@[reducible] def forget (C : Type v) [category C] [concrete_category.{u} C] : C ⥤ Type u :=
concrete_category.forget C
/--
Provide a coercion to `Type u` for a concrete category. This is not marked as an instance
as it could potentially apply to every type, and so is too expensive in typeclass search.
You can use it on particular examples as:
```
instance : has_coe_to_sort X := concrete_category.has_coe_to_sort X
```
-/
def concrete_category.has_coe_to_sort (C : Type v) [category C] [concrete_category C] :
has_coe_to_sort C :=
{ S := Type u, coe := (concrete_category.forget C).obj }
section
local attribute [instance] concrete_category.has_coe_to_sort
variables {C : Type v} [category C] [concrete_category C]
@[simp] lemma forget_obj_eq_coe {X : C} : (forget C).obj X = X := rfl
/-- Usually a bundled hom structure already has a coercion to function
that works with different universes. So we don't use this as a global instance. -/
def concrete_category.has_coe_to_fun {X Y : C} : has_coe_to_fun (X ⟶ Y) :=
{ F := λ f, X → Y,
coe := λ f, (forget _).map f }
local attribute [instance] concrete_category.has_coe_to_fun
/-- In any concrete category, we can test equality of morphisms by pointwise evaluations.-/
lemma concrete_category.hom_ext {X Y : C} (f g : X ⟶ Y) (w : ∀ x : X, f x = g x) : f = g :=
begin
apply faithful.map_injective (forget C),
ext,
exact w x,
end
@[simp] lemma forget_map_eq_coe {X Y : C} (f : X ⟶ Y) : (forget C).map f = f := rfl
/--
Analogue of `congr_fun h x`,
when `h : f = g` is an equality between morphisms in a concrete category.
-/
lemma congr_hom {X Y : C} {f g : X ⟶ Y} (h : f = g) (x : X) : f x = g x :=
congr_fun (congr_arg (λ k : X ⟶ Y, (k : X → Y)) h) x
@[simp] lemma coe_id {X : C} (x : X) : ((𝟙 X) : X → X) x = x :=
congr_fun ((forget _).map_id X) x
@[simp] lemma coe_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) :
(f ≫ g) x = g (f x) :=
congr_fun ((forget _).map_comp _ _) x
@[simp] lemma coe_hom_inv_id {X Y : C} (f : X ≅ Y) (x : X) :
f.inv (f.hom x) = x :=
congr_fun ((forget C).map_iso f).hom_inv_id x
@[simp] lemma coe_inv_hom_id {X Y : C} (f : X ≅ Y) (y : Y) :
f.hom (f.inv y) = y :=
congr_fun ((forget C).map_iso f).inv_hom_id y
lemma concrete_category.congr_hom {X Y : C} {f g : X ⟶ Y} (h : f = g) (x : X) : f x = g x :=
congr_fun (congr_arg (λ f : X ⟶ Y, (f : X → Y)) h) x
lemma concrete_category.congr_arg {X Y : C} (f : X ⟶ Y) {x x' : X} (h : x = x') : f x = f x' :=
congr_arg (f : X → Y) h
/-- In any concrete category, injective morphisms are monomorphisms. -/
lemma concrete_category.mono_of_injective {X Y : C} (f : X ⟶ Y) (i : function.injective f) :
mono f :=
faithful_reflects_mono (forget C) ((mono_iff_injective f).2 i)
/-- In any concrete category, surjective morphisms are epimorphisms. -/
lemma concrete_category.epi_of_surjective {X Y : C} (f : X ⟶ Y) (s : function.surjective f) :
epi f :=
faithful_reflects_epi (forget C) ((epi_iff_surjective f).2 s)
end
instance concrete_category.types : concrete_category (Type u) :=
{ forget := 𝟭 _ }
/--
`has_forget₂ C D`, where `C` and `D` are both concrete categories, provides a functor
`forget₂ C D : C ⥤ D` and a proof that `forget₂ ⋙ (forget D) = forget C`.
-/
class has_forget₂ (C : Type v) (D : Type v') [category C] [concrete_category.{u} C] [category D]
[concrete_category.{u} D] :=
(forget₂ : C ⥤ D)
(forget_comp : forget₂ ⋙ (forget D) = forget C . obviously)
/-- The forgetful functor `C ⥤ D` between concrete categories for which we have an instance
`has_forget₂ C `. -/
@[reducible] def forget₂ (C : Type v) (D : Type v') [category C] [concrete_category C] [category D]
[concrete_category D] [has_forget₂ C D] : C ⥤ D :=
has_forget₂.forget₂
instance forget_faithful (C : Type v) (D : Type v') [category C] [concrete_category C] [category D]
[concrete_category D] [has_forget₂ C D] : faithful (forget₂ C D) :=
has_forget₂.forget_comp.faithful_of_comp
instance induced_category.concrete_category {C : Type v} {D : Type v'} [category D]
[concrete_category D] (f : C → D) :
concrete_category (induced_category D f) :=
{ forget := induced_functor f ⋙ forget D }
instance induced_category.has_forget₂ {C : Type v} {D : Type v'} [category D] [concrete_category D]
(f : C → D) :
has_forget₂ (induced_category D f) D :=
{ forget₂ := induced_functor f,
forget_comp := rfl }
/--
In order to construct a “partially forgetting” functor, we do not need to verify functor laws;
it suffices to ensure that compositions agree with `forget₂ C D ⋙ forget D = forget C`.
-/
def has_forget₂.mk' {C : Type v} {D : Type v'} [category C] [concrete_category C] [category D]
[concrete_category D] (obj : C → D) (h_obj : ∀ X, (forget D).obj (obj X) = (forget C).obj X)
(map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y))
(h_map : ∀ {X Y} {f : X ⟶ Y}, (forget D).map (map f) == (forget C).map f) :
has_forget₂ C D :=
{ forget₂ := faithful.div _ _ _ @h_obj _ @h_map,
forget_comp := by apply faithful.div_comp }
instance has_forget_to_Type (C : Type v) [category C] [concrete_category C] :
has_forget₂ C (Type u) :=
{ forget₂ := forget C,
forget_comp := functor.comp_id _ }
end category_theory
|
05e55c347b7f321719939b96675f24643328c532 | 6ae186a0c6ab366b39397ec9250541c9d5aeb023 | /src/category_theory/adjunctions/hom_adjunction.lean | 4a83aade57fa5e45a3ad91549f9493cbf111bcac | [] | no_license | ThanhPhamPhuong/lean-category-theory | 0d5c4fe1137866b4fe29ec2753d99aa0d0667881 | 968a29fe7c0b20e10d8a27e120aca8ddc184e1ea | refs/heads/master | 1,587,206,682,489 | 1,544,045,056,000 | 1,544,045,056,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,380 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.products
import category_theory.opposites
import category_theory.isomorphism
import category_theory.tactics.obviously
open category_theory
namespace category_theory.adjunctions
universes u₁ v₁
-- TODO should we allow different universe levels, at the expense of some lifts?
variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₁} [𝒟 : category.{u₁ v₁} D]
include 𝒞 𝒟
def hom_adjunction (L : C ⥤ D) (R : D ⥤ C) :=
((functor.prod L.op (functor.id D)) ⋙ (functor.hom D))
≅
(functor.prod (functor.id (Cᵒᵖ)) R) ⋙ (functor.hom C)
def mate {L : C ⥤ D} {R : D ⥤ C} (A : hom_adjunction L R) {X : C} {Y : D} (f : (L.obj X) ⟶ Y) :
X ⟶ (R.obj Y) :=
((A.hom).app (X, Y)) f
-- PROJECT lemmas about mates.
-- PROJECT -- to do this, we need to first define whiskering of NaturalIsomorphisms
-- See Remark 2.1.11 of Leinster
-- def composition_of_HomAdjunctions
-- {C D E : Category} {L : Functor C D} {L' : Functor D E} {R : Functor D C} {R' : Functor E D}
-- (A : HomAdjunction L R) (B : HomAdjunction L' R')
-- : HomAdjunction (FunctorComposition L L') (FunctorComposition R' R) := sorry
end category_theory.adjunctions |
5bab07982e3c2009e084fd88a93fdf60eeba3521 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/tactic/cache.lean | 1ef055b95646fb30f1eb52daece10032408644c1 | [
"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 | 2,315 | 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.doc_commands
/-!
# Instance cache tactics
For performance reasons, Lean does not automatically update its database
of class instances during a proof. The group of tactics in this file
helps to force such updates.
-/
open tactic.interactive
/--
For performance reasons, Lean does not automatically update its database
of class instances during a proof. The group of tactics described below
helps to force such updates. For a simple (but very artificial) example,
consider the function `default` from the core library. It has type
`Π (α : Sort u) [inhabited α], α`, so one can use `default` only if Lean
can find a registered instance of `inhabited α`. Because the database of
such instance is not automatically updated during a proof, the following
attempt won't work (Lean will not pick up the instance from the local
context):
```lean
def my_id (α : Type) : α → α :=
begin
intro x,
have : inhabited α := ⟨x⟩,
exact default, -- Won't work!
end
```
However, it will work, producing the identity function, if one replaces `have`
by its variant `haveI` described below.
* `resetI`: Reset the instance cache. This allows any instances
currently in the context to be used in typeclass inference.
* `unfreezingI { tac }`: Unfreeze local instances while executing the tactic `tac`.
* `introI`/`introsI`: `intro`/`intros` followed by `resetI`. Like
`intro`/`intros`, but uses the introduced variable in typeclass inference.
* `casesI`: like `cases`, but can also be used with instance arguments.
* `substI`: like `subst`, but can also substitute in type-class arguments
* `haveI`/`letI`: `have`/`let` followed by `resetI`. Used to add typeclasses
to the context so that they can be used in typeclass inference.
* `exactI`: `resetI` followed by `exact`. Like `exact`, but uses all
variables in the context for typeclass inference.
-/
add_tactic_doc
{ name := "Instance cache tactics",
category := doc_category.tactic,
decl_names := [``resetI, ``unfreezingI, ``casesI, ``substI, ``introI, ``introsI, ``haveI, ``letI,
``exactI],
tags := ["type class", "context management"] }
|
eb48b8ee17e08712488af0461952472891428579 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/binderNotation.lean | 77b76aa2cb93d701842fbf8fa25b7e9a426a5e92 | [
"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 | 573 | lean | #check ∃ x, x > 1
#check ∃ (x y : Nat), x > y
#check ∃ x y : Nat, x > y
#check ∃ (x : Nat) (y : Nat), x > y
theorem ex1 : (∃ x y : Nat, x > y) = (∃ (x : Nat) (y : Nat), x > y) := rfl
abbrev Vector α n := { a : Array α // a.size = n }
#check Σ α n, Vector α n
#check Σ (α : Type) (n : Nat), Vector α n
#check (α : Type) × (n : Nat) × Vector α n
#check Σ' α n, Vector α n
#check Σ' (α : Type) (n : Nat), Vector α n
#check (α : Type) ×' (n : Nat) ×' Vector α n
#check @Vector
#check fun (α : Type) => Sigma fun (n : Nat) => Vector α n
|
82bf62558c19779a73b175ffbcd8adf96e414b57 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/sum/order.lean | f6f26e9e4637e16643826225e4236f47f2e35abd | [
"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 | 22,829 | 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 order.hom.basic
import order.lexicographic
/-!
# Orders on a sum type
This file defines the disjoint sum and the linear (aka lexicographic) sum of two orders and provides
relation instances for `sum.lift_rel` and `sum.lex`.
We declare the disjoint sum of orders as the default set of instances. The linear order goes on a
type synonym.
## Main declarations
* `sum.has_le`, `sum.has_lt`: Disjoint sum of orders.
* `sum.lex.has_le`, `sum.lex.has_lt`: Lexicographic/linear sum of orders.
## Notation
* `α ⊕ₗ β`: The linear sum of `α` and `β`.
-/
namespace sum
variables {α β γ δ : Type*}
/-! ### Unbundled relation classes -/
section lift_rel
variables (r : α → α → Prop) (s : β → β → Prop)
@[refl] lemma lift_rel.refl [is_refl α r] [is_refl β s] : ∀ x, lift_rel r s x x
| (inl a) := lift_rel.inl (refl _)
| (inr a) := lift_rel.inr (refl _)
instance [is_refl α r] [is_refl β s] : is_refl (α ⊕ β) (lift_rel r s) := ⟨lift_rel.refl _ _⟩
instance [is_irrefl α r] [is_irrefl β s] : is_irrefl (α ⊕ β) (lift_rel r s) :=
⟨by { rintro _ (⟨a, _, h⟩ | ⟨a, _, h⟩); exact irrefl _ h }⟩
@[trans] lemma lift_rel.trans [is_trans α r] [is_trans β s] :
∀ {a b c}, lift_rel r s a b → lift_rel r s b c → lift_rel r s a c
| _ _ _ (lift_rel.inl hab) (lift_rel.inl hbc) := lift_rel.inl $ trans hab hbc
| _ _ _ (lift_rel.inr hab) (lift_rel.inr hbc) := lift_rel.inr $ trans hab hbc
instance [is_trans α r] [is_trans β s] : is_trans (α ⊕ β) (lift_rel r s) :=
⟨λ _ _ _, lift_rel.trans _ _⟩
instance [is_antisymm α r] [is_antisymm β s] : is_antisymm (α ⊕ β) (lift_rel r s) :=
⟨by { rintro _ _ (⟨a, b, hab⟩ | ⟨a, b, hab⟩) (⟨_, _, hba⟩ | ⟨_, _, hba⟩); rw antisymm hab hba }⟩
end lift_rel
section lex
variables (r : α → α → Prop) (s : β → β → Prop)
instance [is_refl α r] [is_refl β s] : is_refl (α ⊕ β) (lex r s) :=
⟨by { rintro (a | a), exacts [lex.inl (refl _), lex.inr (refl _)] }⟩
instance [is_irrefl α r] [is_irrefl β s] : is_irrefl (α ⊕ β) (lex r s) :=
⟨by { rintro _ (⟨a, _, h⟩ | ⟨a, _, h⟩); exact irrefl _ h }⟩
instance [is_trans α r] [is_trans β s] : is_trans (α ⊕ β) (lex r s) :=
⟨by { rintro _ _ _ (⟨a, b, hab⟩ | ⟨a, b, hab⟩) (⟨_, c, hbc⟩ | ⟨_, c, hbc⟩),
exacts [lex.inl (trans hab hbc), lex.sep _ _, lex.inr (trans hab hbc), lex.sep _ _] }⟩
instance [is_antisymm α r] [is_antisymm β s] : is_antisymm (α ⊕ β) (lex r s) :=
⟨by { rintro _ _ (⟨a, b, hab⟩ | ⟨a, b, hab⟩) (⟨_, _, hba⟩ | ⟨_, _, hba⟩); rw antisymm hab hba }⟩
instance [is_total α r] [is_total β s] : is_total (α ⊕ β) (lex r s) :=
⟨λ a b, match a, b with
| inl a, inl b := (total_of r a b).imp lex.inl lex.inl
| inl a, inr b := or.inl (lex.sep _ _)
| inr a, inl b := or.inr (lex.sep _ _)
| inr a, inr b := (total_of s a b).imp lex.inr lex.inr
end⟩
instance [is_trichotomous α r] [is_trichotomous β s] : is_trichotomous (α ⊕ β) (lex r s) :=
⟨λ a b, match a, b with
| inl a, inl b := (trichotomous_of r a b).imp3 lex.inl (congr_arg _) lex.inl
| inl a, inr b := or.inl (lex.sep _ _)
| inr a, inl b := or.inr (or.inr $ lex.sep _ _)
| inr a, inr b := (trichotomous_of s a b).imp3 lex.inr (congr_arg _) lex.inr
end⟩
instance [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) :=
{ wf := sum.lex_wf is_well_order.wf is_well_order.wf }
end lex
/-! ### Disjoint sum of two orders -/
section disjoint
instance [has_le α] [has_le β] : has_le (α ⊕ β) := ⟨lift_rel (≤) (≤)⟩
instance [has_lt α] [has_lt β] : has_lt (α ⊕ β) := ⟨lift_rel (<) (<)⟩
lemma le_def [has_le α] [has_le β] {a b : α ⊕ β} : a ≤ b ↔ lift_rel (≤) (≤) a b := iff.rfl
lemma lt_def [has_lt α] [has_lt β] {a b : α ⊕ β} : a < b ↔ lift_rel (<) (<) a b := iff.rfl
@[simp] lemma inl_le_inl_iff [has_le α] [has_le β] {a b : α} : (inl a : α ⊕ β) ≤ inl b ↔ a ≤ b :=
lift_rel_inl_inl
@[simp] lemma inr_le_inr_iff [has_le α] [has_le β] {a b : β} : (inr a : α ⊕ β) ≤ inr b ↔ a ≤ b :=
lift_rel_inr_inr
@[simp] lemma inl_lt_inl_iff [has_lt α] [has_lt β] {a b : α} : (inl a : α ⊕ β) < inl b ↔ a < b :=
lift_rel_inl_inl
@[simp] lemma inr_lt_inr_iff [has_lt α] [has_lt β] {a b : β} : (inr a : α ⊕ β) < inr b ↔ a < b :=
lift_rel_inr_inr
@[simp] lemma not_inl_le_inr [has_le α] [has_le β] {a : α} {b : β} : ¬ inl b ≤ inr a :=
not_lift_rel_inl_inr
@[simp] lemma not_inl_lt_inr [has_lt α] [has_lt β] {a : α} {b : β} : ¬ inl b < inr a :=
not_lift_rel_inl_inr
@[simp] lemma not_inr_le_inl [has_le α] [has_le β] {a : α} {b : β} : ¬ inr b ≤ inl a :=
not_lift_rel_inr_inl
@[simp] lemma not_inr_lt_inl [has_lt α] [has_lt β] {a : α} {b : β} : ¬ inr b < inl a :=
not_lift_rel_inr_inl
section preorder
variables [preorder α] [preorder β]
instance : preorder (α ⊕ β) :=
{ le_refl := λ _, refl _,
le_trans := λ _ _ _, trans,
lt_iff_le_not_le := λ a b, begin
refine ⟨λ hab, ⟨hab.mono (λ _ _, le_of_lt) (λ _ _, le_of_lt), _⟩, _⟩,
{ rintro (⟨b, a, hba⟩ | ⟨b, a, hba⟩),
{ exact hba.not_lt (inl_lt_inl_iff.1 hab) },
{ exact hba.not_lt (inr_lt_inr_iff.1 hab) } },
{ rintro ⟨⟨a, b, hab⟩ | ⟨a, b, hab⟩, hba⟩,
{ exact lift_rel.inl (hab.lt_of_not_le $ λ h, hba $ lift_rel.inl h) },
{ exact lift_rel.inr (hab.lt_of_not_le $ λ h, hba $ lift_rel.inr h) } }
end,
.. sum.has_le, .. sum.has_lt }
lemma inl_mono : monotone (inl : α → α ⊕ β) := λ a b, lift_rel.inl
lemma inr_mono : monotone (inr : β → α ⊕ β) := λ a b, lift_rel.inr
lemma inl_strict_mono : strict_mono (inl : α → α ⊕ β) := λ a b, lift_rel.inl
lemma inr_strict_mono : strict_mono (inr : β → α ⊕ β) := λ a b, lift_rel.inr
end preorder
instance [partial_order α] [partial_order β] : partial_order (α ⊕ β) :=
{ le_antisymm := λ _ _, antisymm,
.. sum.preorder }
instance no_min_order [has_lt α] [has_lt β] [no_min_order α] [no_min_order β] :
no_min_order (α ⊕ β) :=
⟨λ a, match a with
| inl a := let ⟨b, h⟩ := exists_lt a in ⟨inl b, inl_lt_inl_iff.2 h⟩
| inr a := let ⟨b, h⟩ := exists_lt a in ⟨inr b, inr_lt_inr_iff.2 h⟩
end⟩
instance no_max_order [has_lt α] [has_lt β] [no_max_order α] [no_max_order β] :
no_max_order (α ⊕ β) :=
⟨λ a, match a with
| inl a := let ⟨b, h⟩ := exists_gt a in ⟨inl b, inl_lt_inl_iff.2 h⟩
| inr a := let ⟨b, h⟩ := exists_gt a in ⟨inr b, inr_lt_inr_iff.2 h⟩
end⟩
@[simp] lemma no_min_order_iff [has_lt α] [has_lt β] :
no_min_order (α ⊕ β) ↔ no_min_order α ∧ no_min_order β :=
⟨λ _, by exactI ⟨⟨λ a, begin
obtain ⟨b | b, h⟩ := exists_lt (inl a : α ⊕ β),
{ exact ⟨b, inl_lt_inl_iff.1 h⟩ },
{ exact (not_inr_lt_inl h).elim }
end⟩, ⟨λ a, begin
obtain ⟨b | b, h⟩ := exists_lt (inr a : α ⊕ β),
{ exact (not_inl_lt_inr h).elim },
{ exact ⟨b, inr_lt_inr_iff.1 h⟩ }
end⟩⟩, λ h, @sum.no_min_order _ _ _ _ h.1 h.2⟩
@[simp] lemma no_max_order_iff [has_lt α] [has_lt β] :
no_max_order (α ⊕ β) ↔ no_max_order α ∧ no_max_order β :=
⟨λ _, by exactI ⟨⟨λ a, begin
obtain ⟨b | b, h⟩ := exists_gt (inl a : α ⊕ β),
{ exact ⟨b, inl_lt_inl_iff.1 h⟩ },
{ exact (not_inl_lt_inr h).elim }
end⟩, ⟨λ a, begin
obtain ⟨b | b, h⟩ := exists_gt (inr a : α ⊕ β),
{ exact (not_inr_lt_inl h).elim },
{ exact ⟨b, inr_lt_inr_iff.1 h⟩ }
end⟩⟩, λ h, @sum.no_max_order _ _ _ _ h.1 h.2⟩
instance densely_ordered [has_lt α] [has_lt β] [densely_ordered α] [densely_ordered β] :
densely_ordered (α ⊕ β) :=
⟨λ a b h, match a, b, h with
| inl a, inl b, lift_rel.inl h := let ⟨c, ha, hb⟩ := exists_between h in
⟨to_lex (inl c), lift_rel.inl ha, lift_rel.inl hb⟩
| inr a, inr b, lift_rel.inr h := let ⟨c, ha, hb⟩ := exists_between h in
⟨to_lex (inr c), lift_rel.inr ha, lift_rel.inr hb⟩
end⟩
@[simp] lemma densely_ordered_iff [has_lt α] [has_lt β] :
densely_ordered (α ⊕ β) ↔ densely_ordered α ∧ densely_ordered β :=
⟨λ _, by exactI ⟨⟨λ a b h, begin
obtain ⟨c | c, ha, hb⟩ := @exists_between (α ⊕ β) _ _ _ _ (inl_lt_inl_iff.2 h),
{ exact ⟨c, inl_lt_inl_iff.1 ha, inl_lt_inl_iff.1 hb⟩ },
{ exact (not_inl_lt_inr ha).elim }
end⟩, ⟨λ a b h, begin
obtain ⟨c | c, ha, hb⟩ := @exists_between (α ⊕ β) _ _ _ _ (inr_lt_inr_iff.2 h),
{ exact (not_inl_lt_inr hb).elim },
{ exact ⟨c, inr_lt_inr_iff.1 ha, inr_lt_inr_iff.1 hb⟩ }
end⟩⟩, λ h, @sum.densely_ordered _ _ _ _ h.1 h.2⟩
@[simp] lemma swap_le_swap_iff [has_le α] [has_le β] {a b : α ⊕ β} : a.swap ≤ b.swap ↔ a ≤ b :=
by cases a; cases b;
simp only [swap, inr_le_inr_iff, inl_le_inl_iff, not_inl_le_inr, not_inr_le_inl]
@[simp] lemma swap_lt_swap_iff [has_lt α] [has_lt β] {a b : α ⊕ β} : a.swap < b.swap ↔ a < b :=
by cases a; cases b;
simp only [swap, inr_lt_inr_iff, inl_lt_inl_iff, not_inl_lt_inr, not_inr_lt_inl]
end disjoint
/-! ### Linear sum of two orders -/
namespace lex
notation α ` ⊕ₗ `:30 β:29 := _root_.lex (α ⊕ β)
--TODO: Can we make `inlₗ`, `inrₗ` `local notation`?
/-- Lexicographical `sum.inl`. Only used for pattern matching. -/
@[pattern] abbreviation _root_.sum.inlₗ (x : α) : α ⊕ₗ β := to_lex (sum.inl x)
/-- Lexicographical `sum.inr`. Only used for pattern matching. -/
@[pattern] abbreviation _root_.sum.inrₗ (x : β) : α ⊕ₗ β := to_lex (sum.inr x)
/-- The linear/lexicographical `≤` on a sum. -/
instance has_le [has_le α] [has_le β] : has_le (α ⊕ₗ β) := ⟨lex (≤) (≤)⟩
/-- The linear/lexicographical `<` on a sum. -/
instance has_lt [has_lt α] [has_lt β] : has_lt (α ⊕ₗ β) := ⟨lex (<) (<)⟩
@[simp] lemma to_lex_le_to_lex [has_le α] [has_le β] {a b : α ⊕ β} :
to_lex a ≤ to_lex b ↔ lex (≤) (≤) a b := iff.rfl
@[simp] lemma to_lex_lt_to_lex [has_lt α] [has_lt β] {a b : α ⊕ β} :
to_lex a < to_lex b ↔ lex (<) (<) a b := iff.rfl
lemma le_def [has_le α] [has_le β] {a b : α ⊕ₗ β} : a ≤ b ↔ lex (≤) (≤) (of_lex a) (of_lex b) :=
iff.rfl
lemma lt_def [has_lt α] [has_lt β] {a b : α ⊕ₗ β} : a < b ↔ lex (<) (<) (of_lex a) (of_lex b) :=
iff.rfl
@[simp] lemma inl_le_inl_iff [has_le α] [has_le β] {a b : α} :
to_lex (inl a : α ⊕ β) ≤ to_lex (inl b) ↔ a ≤ b :=
lex_inl_inl
@[simp] lemma inr_le_inr_iff [has_le α] [has_le β] {a b : β} :
to_lex (inr a : α ⊕ β) ≤ to_lex (inr b) ↔ a ≤ b :=
lex_inr_inr
@[simp] lemma inl_lt_inl_iff [has_lt α] [has_lt β] {a b : α} :
to_lex (inl a : α ⊕ β) < to_lex (inl b) ↔ a < b :=
lex_inl_inl
@[simp] lemma inr_lt_inr_iff [has_lt α] [has_lt β] {a b : β} :
to_lex (inr a : α ⊕ₗ β) < to_lex (inr b) ↔ a < b :=
lex_inr_inr
@[simp] lemma inl_le_inr [has_le α] [has_le β] (a : α) (b : β) : to_lex (inl a) ≤ to_lex (inr b) :=
lex.sep _ _
@[simp] lemma inl_lt_inr [has_lt α] [has_lt β] (a : α) (b : β) : to_lex (inl a) < to_lex (inr b) :=
lex.sep _ _
@[simp] lemma not_inr_le_inl [has_le α] [has_le β] {a : α} {b : β} :
¬ to_lex (inr b) ≤ to_lex (inl a) :=
lex_inr_inl
@[simp] lemma not_inr_lt_inl [has_lt α] [has_lt β] {a : α} {b : β} :
¬ to_lex (inr b) < to_lex (inl a) :=
lex_inr_inl
section preorder
variables [preorder α] [preorder β]
instance preorder : preorder (α ⊕ₗ β) :=
{ le_refl := refl_of (lex (≤) (≤)),
le_trans := λ _ _ _, trans_of (lex (≤) (≤)),
lt_iff_le_not_le := λ a b, begin
refine ⟨λ hab, ⟨hab.mono (λ _ _, le_of_lt) (λ _ _, le_of_lt), _⟩, _⟩,
{ rintro (⟨b, a, hba⟩ | ⟨b, a, hba⟩ | ⟨b, a⟩),
{ exact hba.not_lt (inl_lt_inl_iff.1 hab) },
{ exact hba.not_lt (inr_lt_inr_iff.1 hab) },
{ exact not_inr_lt_inl hab } },
{ rintro ⟨⟨a, b, hab⟩ | ⟨a, b, hab⟩ | ⟨a, b⟩, hba⟩,
{ exact lex.inl (hab.lt_of_not_le $ λ h, hba $ lex.inl h) },
{ exact lex.inr (hab.lt_of_not_le $ λ h, hba $ lex.inr h) },
{ exact lex.sep _ _} }
end,
.. lex.has_le, .. lex.has_lt }
lemma to_lex_mono : monotone (@to_lex (α ⊕ β)) := λ a b h, h.lex
lemma to_lex_strict_mono : strict_mono (@to_lex (α ⊕ β)) := λ a b h, h.lex
lemma inl_mono : monotone (to_lex ∘ inl : α → α ⊕ₗ β) := to_lex_mono.comp inl_mono
lemma inr_mono : monotone (to_lex ∘ inr : β → α ⊕ₗ β) := to_lex_mono.comp inr_mono
lemma inl_strict_mono : strict_mono (to_lex ∘ inl : α → α ⊕ₗ β) :=
to_lex_strict_mono.comp inl_strict_mono
lemma inr_strict_mono : strict_mono (to_lex ∘ inr : β → α ⊕ₗ β) :=
to_lex_strict_mono.comp inr_strict_mono
end preorder
instance partial_order [partial_order α] [partial_order β] : partial_order (α ⊕ₗ β) :=
{ le_antisymm := λ _ _, antisymm_of (lex (≤) (≤)),
.. lex.preorder }
instance linear_order [linear_order α] [linear_order β] : linear_order (α ⊕ₗ β) :=
{ le_total := total_of (lex (≤) (≤)),
decidable_le := lex.decidable_rel,
decidable_eq := sum.decidable_eq _ _,
.. lex.partial_order }
/-- The lexicographical bottom of a sum is the bottom of the left component. -/
instance order_bot [has_le α] [order_bot α] [has_le β] : order_bot (α ⊕ₗ β) :=
{ bot := inl ⊥,
bot_le := begin
rintro (a | b),
{ exact lex.inl bot_le },
{ exact lex.sep _ _ }
end }
@[simp] lemma inl_bot [has_le α] [order_bot α] [has_le β]: to_lex (inl ⊥ : α ⊕ β) = ⊥ := rfl
/-- The lexicographical top of a sum is the top of the right component. -/
instance order_top [has_le α] [has_le β] [order_top β] : order_top (α ⊕ₗ β) :=
{ top := inr ⊤,
le_top := begin
rintro (a | b),
{ exact lex.sep _ _ },
{ exact lex.inr le_top }
end }
@[simp] lemma inr_top [has_le α] [has_le β] [order_top β] : to_lex (inr ⊤ : α ⊕ β) = ⊤ := rfl
instance bounded_order [has_le α] [has_le β] [order_bot α] [order_top β] :
bounded_order (α ⊕ₗ β) :=
{ .. lex.order_bot, .. lex.order_top }
instance no_min_order [has_lt α] [has_lt β] [no_min_order α] [no_min_order β] :
no_min_order (α ⊕ₗ β) :=
⟨λ a, match a with
| inl a := let ⟨b, h⟩ := exists_lt a in ⟨to_lex (inl b), inl_lt_inl_iff.2 h⟩
| inr a := let ⟨b, h⟩ := exists_lt a in ⟨to_lex (inr b), inr_lt_inr_iff.2 h⟩
end⟩
instance no_max_order [has_lt α] [has_lt β] [no_max_order α] [no_max_order β] :
no_max_order (α ⊕ₗ β) :=
⟨λ a, match a with
| inl a := let ⟨b, h⟩ := exists_gt a in ⟨to_lex (inl b), inl_lt_inl_iff.2 h⟩
| inr a := let ⟨b, h⟩ := exists_gt a in ⟨to_lex (inr b), inr_lt_inr_iff.2 h⟩
end⟩
instance no_min_order_of_nonempty [has_lt α] [has_lt β] [no_min_order α] [nonempty α] :
no_min_order (α ⊕ₗ β) :=
⟨λ a, match a with
| inl a := let ⟨b, h⟩ := exists_lt a in ⟨to_lex (inl b), inl_lt_inl_iff.2 h⟩
| inr a := ⟨to_lex (inl $ classical.arbitrary α), inl_lt_inr _ _⟩
end⟩
instance no_max_order_of_nonempty [has_lt α] [has_lt β] [no_max_order β] [nonempty β] :
no_max_order (α ⊕ₗ β) :=
⟨λ a, match a with
| inl a := ⟨to_lex (inr $ classical.arbitrary β), inl_lt_inr _ _⟩
| inr a := let ⟨b, h⟩ := exists_gt a in ⟨to_lex (inr b), inr_lt_inr_iff.2 h⟩
end⟩
instance densely_ordered_of_no_max_order [has_lt α] [has_lt β] [densely_ordered α]
[densely_ordered β] [no_max_order α] :
densely_ordered (α ⊕ₗ β) :=
⟨λ a b h, match a, b, h with
| inl a, inl b, lex.inl h := let ⟨c, ha, hb⟩ := exists_between h in
⟨to_lex (inl c), inl_lt_inl_iff.2 ha, inl_lt_inl_iff.2 hb⟩
| inl a, inr b, lex.sep _ _ := let ⟨c, h⟩ := exists_gt a in
⟨to_lex (inl c), inl_lt_inl_iff.2 h, inl_lt_inr _ _⟩
| inr a, inr b, lex.inr h := let ⟨c, ha, hb⟩ := exists_between h in
⟨to_lex (inr c), inr_lt_inr_iff.2 ha, inr_lt_inr_iff.2 hb⟩
end⟩
instance densely_ordered_of_no_min_order [has_lt α] [has_lt β] [densely_ordered α]
[densely_ordered β] [no_min_order β] :
densely_ordered (α ⊕ₗ β) :=
⟨λ a b h, match a, b, h with
| inl a, inl b, lex.inl h := let ⟨c, ha, hb⟩ := exists_between h in
⟨to_lex (inl c), inl_lt_inl_iff.2 ha, inl_lt_inl_iff.2 hb⟩
| inl a, inr b, lex.sep _ _ := let ⟨c, h⟩ := exists_lt b in
⟨to_lex (inr c), inl_lt_inr _ _, inr_lt_inr_iff.2 h⟩
| inr a, inr b, lex.inr h := let ⟨c, ha, hb⟩ := exists_between h in
⟨to_lex (inr c), inr_lt_inr_iff.2 ha, inr_lt_inr_iff.2 hb⟩
end⟩
end lex
end sum
/-! ### Order isomorphisms -/
open order_dual sum
namespace order_iso
variables {α β γ : Type*} [has_le α] [has_le β] [has_le γ] (a : α) (b : β) (c : γ)
/-- `equiv.sum_comm` promoted to an order isomorphism. -/
@[simps apply] def sum_comm (α β : Type*) [has_le α] [has_le β] : α ⊕ β ≃o β ⊕ α :=
{ map_rel_iff' := λ a b, swap_le_swap_iff,
..equiv.sum_comm α β }
@[simp] lemma sum_comm_symm (α β : Type*) [has_le α] [has_le β] :
(order_iso.sum_comm α β).symm = order_iso.sum_comm β α := rfl
/-- `equiv.sum_assoc` promoted to an order isomorphism. -/
def sum_assoc (α β γ : Type*) [has_le α] [has_le β] [has_le γ] : (α ⊕ β) ⊕ γ ≃o α ⊕ β ⊕ γ :=
{ map_rel_iff' := by { rintro ((a | a) | a) ((b | b) | b); simp },
..equiv.sum_assoc α β γ }
@[simp] lemma sum_assoc_apply_inl_inl : sum_assoc α β γ (inl (inl a)) = inl a := rfl
@[simp] lemma sum_assoc_apply_inl_inr : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl
@[simp] lemma sum_assoc_apply_inr : sum_assoc α β γ (inr c) = inr (inr c) := rfl
@[simp] lemma sum_assoc_symm_apply_inl : (sum_assoc α β γ).symm (inl a) = inl (inl a) := rfl
@[simp] lemma sum_assoc_symm_apply_inr_inl : (sum_assoc α β γ).symm (inr (inl b)) = inl (inr b) :=
rfl
@[simp] lemma sum_assoc_symm_apply_inr_inr : (sum_assoc α β γ).symm (inr (inr c)) = inr c := rfl
/-- `order_dual` is distributive over `⊕` up to an order isomorphism. -/
def sum_dual_distrib (α β : Type*) [has_le α] [has_le β] :
order_dual (α ⊕ β) ≃o order_dual α ⊕ order_dual β :=
{ map_rel_iff' := begin
rintro (a | a) (b | b),
{ change inl (to_dual a) ≤ inl (to_dual b) ↔ to_dual (inl a) ≤ to_dual (inl b),
simp only [to_dual_le_to_dual, inl_le_inl_iff] },
{ exact iff_of_false not_inl_le_inr not_inr_le_inl },
{ exact iff_of_false not_inr_le_inl not_inl_le_inr },
{ change inr (to_dual a) ≤ inr (to_dual b) ↔ to_dual (inr a) ≤ to_dual (inr b),
simp only [to_dual_le_to_dual, inr_le_inr_iff] }
end,
..equiv.refl _ }
@[simp] lemma sum_dual_distrib_inl :
sum_dual_distrib α β (to_dual (inl a)) = inl (to_dual a) := rfl
@[simp] lemma sum_dual_distrib_inr :
sum_dual_distrib α β (to_dual (inr b)) = inr (to_dual b) := rfl
@[simp] lemma sum_dual_distrib_symm_inl :
(sum_dual_distrib α β).symm (inl (to_dual a)) = to_dual (inl a) := rfl
@[simp] lemma sum_dual_distrib_symm_inr :
(sum_dual_distrib α β).symm (inr (to_dual b)) = to_dual (inr b) := rfl
/-- `equiv.sum_assoc` promoted to an order isomorphism. -/
def sum_lex_assoc (α β γ : Type*) [has_le α] [has_le β] [has_le γ] : (α ⊕ₗ β) ⊕ₗ γ ≃o α ⊕ₗ β ⊕ₗ γ :=
{ map_rel_iff' := λ a b, ⟨λ h, match a, b, h with
| inlₗ (inlₗ a), inlₗ (inlₗ b), lex.inl h := lex.inl $ lex.inl h
| inlₗ (inlₗ a), inlₗ (inrₗ b), lex.sep _ _ := lex.inl $ lex.sep _ _
| inlₗ (inlₗ a), inrₗ b, lex.sep _ _ := lex.sep _ _
| inlₗ (inrₗ a), inlₗ (inrₗ b), lex.inr (lex.inl h) := lex.inl $ lex.inr h
| inlₗ (inrₗ a), inrₗ b, lex.inr (lex.sep _ _) := lex.sep _ _
| inrₗ a, inrₗ b, lex.inr (lex.inr h) := lex.inr h
end, λ h, match a, b, h with
| inlₗ (inlₗ a), inlₗ (inlₗ b), lex.inl (lex.inl h) := lex.inl h
| inlₗ (inlₗ a), inlₗ (inrₗ b), lex.inl (lex.sep _ _) := lex.sep _ _
| inlₗ (inlₗ a), inrₗ b, lex.sep _ _ := lex.sep _ _
| inlₗ (inrₗ a), inlₗ (inrₗ b), lex.inl (lex.inr h) := lex.inr $ lex.inl h
| inlₗ (inrₗ a), inrₗ b, lex.sep _ _ := lex.inr $ lex.sep _ _
| inrₗ a, inrₗ b, lex.inr h := lex.inr $ lex.inr h
end⟩,
..equiv.sum_assoc α β γ }
@[simp] lemma sum_lex_assoc_apply_inl_inl :
sum_lex_assoc α β γ (to_lex $ inl $ to_lex $ inl a) = to_lex (inl a) := rfl
@[simp] lemma sum_lex_assoc_apply_inl_inr :
sum_lex_assoc α β γ (to_lex $ inl $ to_lex $ inr b) = to_lex (inr $ to_lex $ inl b) := rfl
@[simp] lemma sum_lex_assoc_apply_inr :
sum_lex_assoc α β γ (to_lex $ inr c) = to_lex (inr $ to_lex $ inr c) := rfl
@[simp] lemma sum_lex_assoc_symm_apply_inl :
(sum_lex_assoc α β γ).symm (inl a) = inl (inl a) := rfl
@[simp] lemma sum_lex_assoc_symm_apply_inr_inl :
(sum_lex_assoc α β γ).symm (inr (inl b)) = inl (inr b) := rfl
@[simp] lemma sum_lex_assoc_symm_apply_inr_inr :
(sum_lex_assoc α β γ).symm (inr (inr c)) = inr c := rfl
/-- `order_dual` is antidistributive over `⊕ₗ` up to an order isomorphism. -/
def sum_lex_dual_antidistrib (α β : Type*) [has_le α] [has_le β] :
order_dual (α ⊕ₗ β) ≃o order_dual β ⊕ₗ order_dual α :=
{ map_rel_iff' := begin
rintro (a | a) (b | b), simp,
{ change to_lex (inr $ to_dual a) ≤ to_lex (inr $ to_dual b) ↔
to_dual (to_lex $ inl a) ≤ to_dual (to_lex $ inl b),
simp only [to_dual_le_to_dual, lex.inl_le_inl_iff, lex.inr_le_inr_iff] },
{ exact iff_of_false lex.not_inr_le_inl lex.not_inr_le_inl },
{ exact iff_of_true (lex.inl_le_inr _ _) (lex.inl_le_inr _ _) },
{ change to_lex (inl $ to_dual a) ≤ to_lex (inl $ to_dual b) ↔
to_dual (to_lex $ inr a) ≤ to_dual (to_lex $ inr b),
simp only [to_dual_le_to_dual, lex.inl_le_inl_iff, lex.inr_le_inr_iff] }
end,
..equiv.sum_comm α β }
@[simp] lemma sum_lex_dual_antidistrib_inl :
sum_lex_dual_antidistrib α β (to_dual (inl a)) = inr (to_dual a) := rfl
@[simp] lemma sum_lex_dual_antidistrib_inr :
sum_lex_dual_antidistrib α β (to_dual (inr b)) = inl (to_dual b) := rfl
@[simp] lemma sum_lex_dual_antidistrib_symm_inl :
(sum_lex_dual_antidistrib α β).symm (inl (to_dual b)) = to_dual (inr b) := rfl
@[simp] lemma sum_lex_dual_antidistrib_symm_inr :
(sum_lex_dual_antidistrib α β).symm (inr (to_dual a)) = to_dual (inl a) := rfl
end order_iso
|
e4c8b2dc9e49f231a653bf1c54eb5a7510eb0607 | 367134ba5a65885e863bdc4507601606690974c1 | /src/category_theory/limits/shapes/strong_epi.lean | af6de75368ec473338d77426091f9a0237c098b2 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 3,039 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import category_theory.arrow
/-!
# Strong epimorphisms
In this file, we define strong epimorphisms. A strong epimorphism is an epimorphism `f`, such
that for every commutative square with `f` at the top and a monomorphism at the bottom, there is
a diagonal morphism making the two triangles commute. This lift is necessarily unique (as shown in
`comma.lean`).
## Main results
Besides the definition, we show that
* the composition of two strong epimorphisms is a strong epimorphism,
* if `f ≫ g` is a strong epimorphism, then so is `g`,
* if `f` is both a strong epimorphism and a monomorphism, then it is an isomorphism
## Future work
There is also the dual notion of strong monomorphism.
## References
* [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1]
-/
universes v u
namespace category_theory
variables {C : Type u} [category.{v} C]
variables {P Q : C}
/-- A strong epimorphism `f` is an epimorphism such that every commutative square with `f` at the
top and a monomorphism at the bottom has a lift. -/
class strong_epi (f : P ⟶ Q) : Prop :=
(epi : epi f)
(has_lift : Π {X Y : C} {u : P ⟶ X} {v : Q ⟶ Y} {z : X ⟶ Y} [mono z] (h : u ≫ z = f ≫ v),
arrow.has_lift $ arrow.hom_mk' h)
attribute [instance] strong_epi.has_lift
@[priority 100]
instance epi_of_strong_epi (f : P ⟶ Q) [strong_epi f] : epi f := strong_epi.epi
section
variables {R : C} (f : P ⟶ Q) (g : Q ⟶ R)
/-- The composition of two strong epimorphisms is a strong epimorphism. -/
lemma strong_epi_comp [strong_epi f] [strong_epi g] : strong_epi (f ≫ g) :=
{ epi := epi_comp _ _,
has_lift :=
begin
introsI,
have h₀ : u ≫ z = f ≫ g ≫ v, by simpa [category.assoc] using h,
let w : Q ⟶ X := arrow.lift (arrow.hom_mk' h₀),
have h₁ : w ≫ z = g ≫ v, by rw arrow.lift_mk'_right,
exact arrow.has_lift.mk ⟨(arrow.lift (arrow.hom_mk' h₁) : R ⟶ X), by simp, by simp⟩
end }
/-- If `f ≫ g` is a strong epimorphism, then so is g. -/
lemma strong_epi_of_strong_epi [strong_epi (f ≫ g)] : strong_epi g :=
{ epi := epi_of_epi f g,
has_lift :=
begin
introsI,
have h₀ : (f ≫ u) ≫ z = (f ≫ g) ≫ v, by simp only [category.assoc, h],
exact arrow.has_lift.mk
⟨(arrow.lift (arrow.hom_mk' h₀) : R ⟶ X), (cancel_mono z).1 (by simp [h]), by simp⟩,
end }
/-- An isomorphism is in particular a strong epimorphism. -/
@[priority 100] instance strong_epi_of_is_iso [is_iso f] : strong_epi f :=
{ epi := by apply_instance,
has_lift := λ X Y u v z _ h, arrow.has_lift.mk ⟨inv f ≫ u, by simp, by simp [h]⟩ }
end
/-- A strong epimorphism that is a monomorphism is an isomorphism. -/
noncomputable def is_iso_of_mono_of_strong_epi (f : P ⟶ Q) [mono f] [strong_epi f] : is_iso f :=
{ inv := arrow.lift $ arrow.hom_mk' $ show 𝟙 P ≫ f = f ≫ 𝟙 Q, by simp }
end category_theory
|
1cdc66805dfcc880236a37412948eb4310133671 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/geometry/euclidean/circumcenter.lean | fde0f51bd3c715c38f9d158c24ed4c37d6a96ae7 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 38,460 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import geometry.euclidean.basic
import linear_algebra.affine_space.finite_dimensional
import tactic.derive_fintype
noncomputable theory
open_locale big_operators
open_locale classical
open_locale real
open_locale real_inner_product_space
/-!
# Circumcenter and circumradius
This file proves some lemmas on points equidistant from a set of
points, and defines the circumradius and circumcenter of a simplex.
There are also some definitions for use in calculations where it is
convenient to work with affine combinations of vertices together with
the circumcenter.
## Main definitions
* `circumcenter` and `circumradius` are the circumcenter and
circumradius of a simplex.
## References
* https://en.wikipedia.org/wiki/Circumscribed_circle
-/
namespace euclidean_geometry
open inner_product_geometry
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
open affine_subspace
/-- `p` is equidistant from two points in `s` if and only if its
`orthogonal_projection` is. -/
lemma dist_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p1 p2 : P} (p3 : P) (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) :
dist p1 p3 = dist p2 p3 ↔
dist p1 (orthogonal_projection s p3) = dist p2 (orthogonal_projection s p3) :=
begin
rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg,
←mul_self_inj_of_nonneg dist_nonneg dist_nonneg,
dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square
p3 hp1,
dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square
p3 hp2],
simp
end
/-- `p` is equidistant from a set of points in `s` if and only if its
`orthogonal_projection` is. -/
lemma dist_set_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {ps : set P} (hps : ps ⊆ s) (p : P) :
(set.pairwise_on ps (λ p1 p2, dist p1 p = dist p2 p) ↔
(set.pairwise_on ps (λ p1 p2, dist p1 (orthogonal_projection s p) =
dist p2 (orthogonal_projection s p)))) :=
⟨λ h p1 hp1 p2 hp2 hne,
(dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).1 (h p1 hp1 p2 hp2 hne),
λ h p1 hp1 p2 hp2 hne,
(dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).2 (h p1 hp1 p2 hp2 hne)⟩
/-- There exists `r` such that `p` has distance `r` from all the
points of a set of points in `s` if and only if there exists (possibly
different) `r` such that its `orthogonal_projection` has that distance
from all the points in that set. -/
lemma exists_dist_eq_iff_exists_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {ps : set P} (hps : ps ⊆ s) (p : P) :
(∃ r, ∀ p1 ∈ ps, dist p1 p = r) ↔
∃ r, ∀ p1 ∈ ps, dist p1 ↑(orthogonal_projection s p) = r :=
begin
have h := dist_set_eq_iff_dist_orthogonal_projection_eq hps p,
simp_rw set.pairwise_on_eq_iff_exists_eq at h,
exact h
end
/-- The induction step for the existence and uniqueness of the
circumcenter. Given a nonempty set of points in a nonempty affine
subspace whose direction is complete, such that there is a unique
(circumcenter, circumradius) pair for those points in that subspace,
and a point `p` not in that subspace, there is a unique (circumcenter,
circumradius) pair for the set with `p` added, in the span of the
subspace with `p` added. -/
lemma exists_unique_dist_eq_of_insert {s : affine_subspace ℝ P}
[complete_space s.direction] {ps : set P} (hnps : ps.nonempty) {p : P}
(hps : ps ⊆ s) (hp : p ∉ s)
(hu : ∃! cccr : (P × ℝ), cccr.fst ∈ s ∧ ∀ p1 ∈ ps, dist p1 cccr.fst = cccr.snd) :
∃! cccr₂ : (P × ℝ), cccr₂.fst ∈ affine_span ℝ (insert p (s : set P)) ∧
∀ p1 ∈ insert p ps, dist p1 cccr₂.fst = cccr₂.snd :=
begin
haveI : nonempty s := set.nonempty.to_subtype (hnps.mono hps),
rcases hu with ⟨⟨cc, cr⟩, ⟨hcc, hcr⟩, hcccru⟩,
simp only [prod.fst, prod.snd] at hcc hcr hcccru,
let x := dist cc (orthogonal_projection s p),
let y := dist p (orthogonal_projection s p),
have hy0 : y ≠ 0 := dist_orthogonal_projection_ne_zero_of_not_mem hp,
let ycc₂ := (x * x + y * y - cr * cr) / (2 * y),
let cc₂ := (ycc₂ / y) • (p -ᵥ orthogonal_projection s p : V) +ᵥ cc,
let cr₂ := real.sqrt (cr * cr + ycc₂ * ycc₂),
use (cc₂, cr₂),
simp only [prod.fst, prod.snd],
have hpo : p = (1 : ℝ) • (p -ᵥ orthogonal_projection s p : V) +ᵥ orthogonal_projection s p,
{ simp },
split,
{ split,
{ refine vadd_mem_of_mem_direction _ (mem_affine_span ℝ (set.mem_insert_of_mem _ hcc)),
rw direction_affine_span,
exact submodule.smul_mem _ _
(vsub_mem_vector_span ℝ (set.mem_insert _ _)
(set.mem_insert_of_mem _ (orthogonal_projection_mem _))) },
{ intros p1 hp1,
rw [←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _),
real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))],
cases hp1,
{ rw hp1,
rw [hpo,
dist_square_smul_orthogonal_vadd_smul_orthogonal_vadd
(orthogonal_projection_mem p) hcc _ _
(vsub_orthogonal_projection_mem_direction_orthogonal s p),
←dist_eq_norm_vsub V p, dist_comm _ cc],
field_simp [hy0],
ring },
{ rw [dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square
_ (hps hp1),
orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc, subtype.coe_mk,
hcr _ hp1, dist_eq_norm_vsub V cc₂ cc, vadd_vsub, norm_smul, ←dist_eq_norm_vsub V,
real.norm_eq_abs, abs_div, abs_of_nonneg dist_nonneg, div_mul_cancel _ hy0,
abs_mul_abs_self] } } },
{ rintros ⟨cc₃, cr₃⟩ ⟨hcc₃, hcr₃⟩,
simp only [prod.fst, prod.snd] at hcc₃ hcr₃,
obtain ⟨t₃, cc₃', hcc₃', hcc₃''⟩ :
∃ (r : ℝ) (p0 : P) (hp0 : p0 ∈ s), cc₃ = r • (p -ᵥ ↑((orthogonal_projection s) p)) +ᵥ p0,
{ rwa mem_affine_span_insert_iff (orthogonal_projection_mem p) at hcc₃ },
have hcr₃' : ∃ r, ∀ p1 ∈ ps, dist p1 cc₃ = r :=
⟨cr₃, λ p1 hp1, hcr₃ p1 (set.mem_insert_of_mem _ hp1)⟩,
rw [exists_dist_eq_iff_exists_dist_orthogonal_projection_eq hps cc₃, hcc₃'',
orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃'] at hcr₃',
cases hcr₃' with cr₃' hcr₃',
have hu := hcccru (cc₃', cr₃'),
simp only [prod.fst, prod.snd] at hu,
replace hu := hu ⟨hcc₃', hcr₃'⟩,
rw prod.ext_iff at hu,
simp only [prod.fst, prod.snd] at hu,
cases hu with hucc hucr,
substs hucc hucr,
have hcr₃val : cr₃ = real.sqrt (cr₃' * cr₃' + (t₃ * y) * (t₃ * y)),
{ cases hnps with p0 hp0,
have h' : ↑(⟨cc₃', hcc₃'⟩ : s) = cc₃' := rfl,
rw [←hcr₃ p0 (set.mem_insert_of_mem _ hp0), hcc₃'',
←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _),
real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)),
dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square
_ (hps hp0),
orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃', h', hcr p0 hp0,
dist_eq_norm_vsub V _ cc₃', vadd_vsub, norm_smul, ←dist_eq_norm_vsub V p,
real.norm_eq_abs, ←mul_assoc, mul_comm _ (abs t₃), ←mul_assoc, abs_mul_abs_self],
ring },
replace hcr₃ := hcr₃ p (set.mem_insert _ _),
rw [hpo, hcc₃'', hcr₃val, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _),
dist_square_smul_orthogonal_vadd_smul_orthogonal_vadd
(orthogonal_projection_mem p) hcc₃' _ _
(vsub_orthogonal_projection_mem_direction_orthogonal s p),
dist_comm, ←dist_eq_norm_vsub V p,
real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))] at hcr₃,
change x * x + _ * (y * y) = _ at hcr₃,
rw [(show x * x + (1 - t₃) * (1 - t₃) * (y * y) =
x * x + y * y - 2 * y * (t₃ * y) + t₃ * y * (t₃ * y), by ring), add_left_inj] at hcr₃,
have ht₃ : t₃ = ycc₂ / y,
{ field_simp [←hcr₃, hy0],
ring },
subst ht₃,
change cc₃ = cc₂ at hcc₃'',
congr',
rw hcr₃val,
congr' 2,
field_simp [hy0],
ring }
end
/-- Given a finite nonempty affinely independent family of points,
there is a unique (circumcenter, circumradius) pair for those points
in the affine subspace they span. -/
lemma exists_unique_dist_eq_of_affine_independent {ι : Type*} [hne : nonempty ι] [fintype ι]
{p : ι → P} (ha : affine_independent ℝ p) :
∃! cccr : (P × ℝ), cccr.fst ∈ affine_span ℝ (set.range p) ∧
∀ i, dist (p i) cccr.fst = cccr.snd :=
begin
generalize' hn : fintype.card ι = n,
unfreezingI { induction n with m hm generalizing ι },
{ exfalso,
have h := fintype.card_pos_iff.2 hne,
rw hn at h,
exact lt_irrefl 0 h },
{ cases m,
{ rw fintype.card_eq_one_iff at hn,
cases hn with i hi,
haveI : unique ι := ⟨⟨i⟩, hi⟩,
use (p i, 0),
simp only [prod.fst, prod.snd, set.range_unique, affine_subspace.mem_affine_span_singleton],
split,
{ simp_rw [hi (default ι)],
use rfl,
intro i1,
rw hi i1,
exact dist_self _ },
{ rintros ⟨cc, cr⟩,
simp only [prod.fst, prod.snd],
rintros ⟨rfl, hdist⟩,
rw hi (default ι),
congr',
rw ←hdist (default ι),
exact dist_self _ } },
{ have i := hne.some,
let ι2 := {x // x ≠ i},
have hc : fintype.card ι2 = m + 1,
{ rw fintype.card_of_subtype (finset.univ.filter (λ x, x ≠ i)),
{ rw finset.filter_not,
simp_rw eq_comm,
rw [finset.filter_eq, if_pos (finset.mem_univ _),
finset.card_sdiff (finset.subset_univ _), finset.card_singleton, finset.card_univ,
hn],
simp },
{ simp } },
haveI : nonempty ι2 := fintype.card_pos_iff.1 (hc.symm ▸ nat.zero_lt_succ _),
have ha2 : affine_independent ℝ (λ i2 : ι2, p i2) :=
affine_independent_subtype_of_affine_independent ha _,
replace hm := hm ha2 hc,
have hr : set.range p = insert (p i) (set.range (λ i2 : ι2, p i2)),
{ change _ = insert _ (set.range (λ i2 : {x | x ≠ i}, p i2)),
rw [←set.image_eq_range, ←set.image_univ, ←set.image_insert_eq],
congr' with j,
simp [classical.em] },
change ∃! (cccr : P × ℝ), (_ ∧ ∀ i2, (λ q, dist q cccr.fst = cccr.snd) (p i2)),
conv { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } },
dsimp only,
rw hr,
change ∃! (cccr : P × ℝ), (_ ∧ ∀ (i2 : ι2), (λ q, dist q cccr.fst = cccr.snd) (p i2)) at hm,
conv at hm { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } },
rw ←affine_span_insert_affine_span,
refine exists_unique_dist_eq_of_insert
(set.range_nonempty _)
(subset_span_points ℝ _)
_
hm,
convert not_mem_affine_span_diff_of_affine_independent ha i set.univ,
change set.range (λ i2 : {x | x ≠ i}, p i2) = _,
rw ←set.image_eq_range,
congr' with j, simp, refl } }
end
end euclidean_geometry
namespace affine
namespace simplex
open finset affine_subspace euclidean_geometry
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
/-- The pair (circumcenter, circumradius) of a simplex. -/
def circumcenter_circumradius {n : ℕ} (s : simplex ℝ P n) : (P × ℝ) :=
(exists_unique_dist_eq_of_affine_independent s.independent).some
/-- The property satisfied by the (circumcenter, circumradius) pair. -/
lemma circumcenter_circumradius_unique_dist_eq {n : ℕ} (s : simplex ℝ P n) :
(s.circumcenter_circumradius.fst ∈ affine_span ℝ (set.range s.points) ∧
∀ i, dist (s.points i) s.circumcenter_circumradius.fst = s.circumcenter_circumradius.snd) ∧
(∀ cccr : (P × ℝ), (cccr.fst ∈ affine_span ℝ (set.range s.points) ∧
∀ i, dist (s.points i) cccr.fst = cccr.snd) → cccr = s.circumcenter_circumradius) :=
(exists_unique_dist_eq_of_affine_independent s.independent).some_spec
/-- The circumcenter of a simplex. -/
def circumcenter {n : ℕ} (s : simplex ℝ P n) : P :=
s.circumcenter_circumradius.fst
/-- The circumradius of a simplex. -/
def circumradius {n : ℕ} (s : simplex ℝ P n) : ℝ :=
s.circumcenter_circumradius.snd
/-- The circumcenter lies in the affine span. -/
lemma circumcenter_mem_affine_span {n : ℕ} (s : simplex ℝ P n) :
s.circumcenter ∈ affine_span ℝ (set.range s.points) :=
s.circumcenter_circumradius_unique_dist_eq.1.1
/-- All points have distance from the circumcenter equal to the
circumradius. -/
@[simp] lemma dist_circumcenter_eq_circumradius {n : ℕ} (s : simplex ℝ P n) :
∀ i, dist (s.points i) s.circumcenter = s.circumradius :=
s.circumcenter_circumradius_unique_dist_eq.1.2
/-- All points have distance to the circumcenter equal to the
circumradius. -/
@[simp] lemma dist_circumcenter_eq_circumradius' {n : ℕ} (s : simplex ℝ P n) :
∀ i, dist s.circumcenter (s.points i) = s.circumradius :=
begin
intro i,
rw dist_comm,
exact dist_circumcenter_eq_circumradius _ _
end
/-- Given a point in the affine span from which all the points are
equidistant, that point is the circumcenter. -/
lemma eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P}
(hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) :
p = s.circumcenter :=
begin
have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r),
simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h,
exact h.1
end
/-- Given a point in the affine span from which all the points are
equidistant, that distance is the circumradius. -/
lemma eq_circumradius_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P}
(hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) :
r = s.circumradius :=
begin
have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r),
simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h,
exact h.2
end
/-- The circumradius is non-negative. -/
lemma circumradius_nonneg {n : ℕ} (s : simplex ℝ P n) : 0 ≤ s.circumradius :=
s.dist_circumcenter_eq_circumradius 0 ▸ dist_nonneg
/-- The circumradius of a simplex with at least two points is
positive. -/
lemma circumradius_pos {n : ℕ} (s : simplex ℝ P (n + 1)) : 0 < s.circumradius :=
begin
refine lt_of_le_of_ne s.circumradius_nonneg _,
intro h,
have hr := s.dist_circumcenter_eq_circumradius,
simp_rw [←h, dist_eq_zero] at hr,
have h01 := (injective_of_affine_independent s.independent).ne
(dec_trivial : (0 : fin (n + 2)) ≠ 1),
simpa [hr] using h01
end
/-- The circumcenter of a 0-simplex equals its unique point. -/
lemma circumcenter_eq_point (s : simplex ℝ P 0) (i : fin 1) :
s.circumcenter = s.points i :=
begin
have h := s.circumcenter_mem_affine_span,
rw [set.range_unique, mem_affine_span_singleton] at h,
rw h,
congr
end
/-- The circumcenter of a 1-simplex equals its centroid. -/
lemma circumcenter_eq_centroid (s : simplex ℝ P 1) :
s.circumcenter = finset.univ.centroid ℝ s.points :=
begin
have hr : set.pairwise_on set.univ
(λ i j : fin 2, dist (s.points i) (finset.univ.centroid ℝ s.points) =
dist (s.points j) (finset.univ.centroid ℝ s.points)),
{ intros i hi j hj hij,
rw [finset.centroid_insert_singleton_fin, dist_eq_norm_vsub V (s.points i),
dist_eq_norm_vsub V (s.points j), vsub_vadd_eq_vsub_sub, vsub_vadd_eq_vsub_sub,
←one_smul ℝ (s.points i -ᵥ s.points 0), ←one_smul ℝ (s.points j -ᵥ s.points 0)],
fin_cases i; fin_cases j; simp [-one_smul, ←sub_smul]; norm_num },
rw set.pairwise_on_eq_iff_exists_eq at hr,
cases hr with r hr,
exact (s.eq_circumcenter_of_dist_eq
(centroid_mem_affine_span_of_card_eq_add_one ℝ _ (finset.card_fin 2))
(λ i, hr i (set.mem_univ _))).symm
end
/-- If there exists a distance that a point has from all vertices of a
simplex, the orthogonal projection of that point onto the subspace
spanned by that simplex is its circumcenter. -/
lemma orthogonal_projection_eq_circumcenter_of_exists_dist_eq {n : ℕ} (s : simplex ℝ P n)
{p : P} (hr : ∃ r, ∀ i, dist (s.points i) p = r) :
↑(orthogonal_projection (affine_span ℝ (set.range s.points)) p) = s.circumcenter :=
begin
change ∃ r : ℝ, ∀ i, (λ x, dist x p = r) (s.points i) at hr,
conv at hr { congr, funext, rw ←set.forall_range_iff },
rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq (subset_affine_span ℝ _) p at hr,
cases hr with r hr,
exact s.eq_circumcenter_of_dist_eq
(orthogonal_projection_mem p) (λ i, hr _ (set.mem_range_self i)),
end
/-- If a point has the same distance from all vertices of a simplex,
the orthogonal projection of that point onto the subspace spanned by
that simplex is its circumcenter. -/
lemma orthogonal_projection_eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P}
{r : ℝ} (hr : ∀ i, dist (s.points i) p = r) :
↑(orthogonal_projection (affine_span ℝ (set.range s.points)) p) = s.circumcenter :=
s.orthogonal_projection_eq_circumcenter_of_exists_dist_eq ⟨r, hr⟩
/-- The orthogonal projection of the circumcenter onto a face is the
circumcenter of that face. -/
lemma orthogonal_projection_circumcenter {n : ℕ} (s : simplex ℝ P n) {fs : finset (fin (n + 1))}
{m : ℕ} (h : fs.card = m + 1) :
↑(orthogonal_projection (affine_span ℝ (set.range (s.face h).points)) s.circumcenter) =
(s.face h).circumcenter :=
begin
have hr : ∃ r, ∀ i, dist ((s.face h).points i) s.circumcenter = r,
{ use s.circumradius,
simp [face_points] },
exact orthogonal_projection_eq_circumcenter_of_exists_dist_eq _ hr
end
/-- Two simplices with the same points have the same circumcenter. -/
lemma circumcenter_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n}
(h : set.range s₁.points = set.range s₂.points) : s₁.circumcenter = s₂.circumcenter :=
begin
have hs : s₁.circumcenter ∈ affine_span ℝ (set.range s₂.points) :=
h ▸ s₁.circumcenter_mem_affine_span,
have hr : ∀ i, dist (s₂.points i) s₁.circumcenter = s₁.circumradius,
{ intro i,
have hi : s₂.points i ∈ set.range s₂.points := set.mem_range_self _,
rw [←h, set.mem_range] at hi,
rcases hi with ⟨j, hj⟩,
rw [←hj, s₁.dist_circumcenter_eq_circumradius j] },
exact s₂.eq_circumcenter_of_dist_eq hs hr
end
omit V
/-- An index type for the vertices of a simplex plus its circumcenter.
This is for use in calculations where it is convenient to work with
affine combinations of vertices together with the circumcenter. (An
equivalent form sometimes used in the literature is placing the
circumcenter at the origin and working with vectors for the vertices.) -/
@[derive fintype]
inductive points_with_circumcenter_index (n : ℕ)
| point_index : fin (n + 1) → points_with_circumcenter_index
| circumcenter_index : points_with_circumcenter_index
open points_with_circumcenter_index
instance points_with_circumcenter_index_inhabited (n : ℕ) :
inhabited (points_with_circumcenter_index n) :=
⟨circumcenter_index⟩
/-- `point_index` as an embedding. -/
def point_index_embedding (n : ℕ) : fin (n + 1) ↪ points_with_circumcenter_index n :=
⟨λ i, point_index i, λ _ _ h, by injection h⟩
/-- The sum of a function over `points_with_circumcenter_index`. -/
lemma sum_points_with_circumcenter {α : Type*} [add_comm_monoid α] {n : ℕ}
(f : points_with_circumcenter_index n → α) :
∑ i, f i = (∑ (i : fin (n + 1)), f (point_index i)) + f circumcenter_index :=
begin
have h : univ = insert circumcenter_index (univ.map (point_index_embedding n)),
{ ext x,
refine ⟨λ h, _, λ _, mem_univ _⟩,
cases x with i,
{ exact mem_insert_of_mem (mem_map_of_mem _ (mem_univ i)) },
{ exact mem_insert_self _ _ } },
change _ = ∑ i, f (point_index_embedding n i) + _,
rw [add_comm, h, ←sum_map, sum_insert],
simp_rw [mem_map, not_exists],
intros x hx h,
injection h
end
include V
/-- The vertices of a simplex plus its circumcenter. -/
def points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : points_with_circumcenter_index n → P
| (point_index i) := s.points i
| circumcenter_index := s.circumcenter
/-- `points_with_circumcenter`, applied to a `point_index` value,
equals `points` applied to that value. -/
@[simp] lemma points_with_circumcenter_point {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) :
s.points_with_circumcenter (point_index i) = s.points i :=
rfl
/-- `points_with_circumcenter`, applied to `circumcenter_index`, equals the
circumcenter. -/
@[simp] lemma points_with_circumcenter_eq_circumcenter {n : ℕ} (s : simplex ℝ P n) :
s.points_with_circumcenter circumcenter_index = s.circumcenter :=
rfl
omit V
/-- The weights for a single vertex of a simplex, in terms of
`points_with_circumcenter`. -/
def point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : points_with_circumcenter_index n → ℝ
| (point_index j) := if j = i then 1 else 0
| circumcenter_index := 0
/-- `point_weights_with_circumcenter` sums to 1. -/
@[simp] lemma sum_point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) :
∑ j, point_weights_with_circumcenter i j = 1 :=
begin
convert sum_ite_eq' univ (point_index i) (function.const _ (1 : ℝ)),
{ ext j,
cases j ; simp [point_weights_with_circumcenter] },
{ simp }
end
include V
/-- A single vertex, in terms of `points_with_circumcenter`. -/
lemma point_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n)
(i : fin (n + 1)) :
s.points i =
(univ : finset (points_with_circumcenter_index n)).affine_combination
s.points_with_circumcenter (point_weights_with_circumcenter i) :=
begin
rw ←points_with_circumcenter_point,
symmetry,
refine affine_combination_of_eq_one_of_eq_zero _ _ _
(mem_univ _)
(by simp [point_weights_with_circumcenter])
_,
intros i hi hn,
cases i,
{ have h : i_1 ≠ i := λ h, hn (h ▸ rfl),
simp [point_weights_with_circumcenter, h] },
{ refl }
end
omit V
/-- The weights for the centroid of some vertices of a simplex, in
terms of `points_with_circumcenter`. -/
def centroid_weights_with_circumcenter {n : ℕ} (fs : finset (fin (n + 1)))
: points_with_circumcenter_index n → ℝ
| (point_index i) := if i ∈ fs then ((card fs : ℝ) ⁻¹) else 0
| circumcenter_index := 0
/-- `centroid_weights_with_circumcenter` sums to 1, if the `finset` is
nonempty. -/
@[simp] lemma sum_centroid_weights_with_circumcenter {n : ℕ} {fs : finset (fin (n + 1))}
(h : fs.nonempty) :
∑ i, centroid_weights_with_circumcenter fs i = 1 :=
begin
simp_rw [sum_points_with_circumcenter, centroid_weights_with_circumcenter, add_zero,
←fs.sum_centroid_weights_eq_one_of_nonempty ℝ h,
set.sum_indicator_subset _ fs.subset_univ],
rcongr
end
include V
/-- The centroid of some vertices of a simplex, in terms of
`points_with_circumcenter`. -/
lemma centroid_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n)
(fs : finset (fin (n + 1))) :
fs.centroid ℝ s.points =
(univ : finset (points_with_circumcenter_index n)).affine_combination
s.points_with_circumcenter (centroid_weights_with_circumcenter fs) :=
begin
simp_rw [centroid_def, affine_combination_apply,
weighted_vsub_of_point_apply, sum_points_with_circumcenter,
centroid_weights_with_circumcenter, points_with_circumcenter_point, zero_smul,
add_zero, centroid_weights,
set.sum_indicator_subset_of_eq_zero
(function.const (fin (n + 1)) ((card fs : ℝ)⁻¹))
(λ i wi, wi • (s.points i -ᵥ classical.choice add_torsor.nonempty))
fs.subset_univ
(λ i, zero_smul ℝ _),
set.indicator_apply],
congr, funext, congr' 2
end
omit V
/-- The weights for the circumcenter of a simplex, in terms of
`points_with_circumcenter`. -/
def circumcenter_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index n → ℝ
| (point_index i) := 0
| circumcenter_index := 1
/-- `circumcenter_weights_with_circumcenter` sums to 1. -/
@[simp] lemma sum_circumcenter_weights_with_circumcenter (n : ℕ) :
∑ i, circumcenter_weights_with_circumcenter n i = 1 :=
begin
convert sum_ite_eq' univ circumcenter_index (function.const _ (1 : ℝ)),
{ ext ⟨j⟩ ; simp [circumcenter_weights_with_circumcenter] },
{ simp }
end
include V
/-- The circumcenter of a simplex, in terms of
`points_with_circumcenter`. -/
lemma circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ}
(s : simplex ℝ P n) :
s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination
s.points_with_circumcenter (circumcenter_weights_with_circumcenter n) :=
begin
rw ←points_with_circumcenter_eq_circumcenter,
symmetry,
refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) rfl _,
rintros ⟨i⟩ hi hn ; tauto
end
omit V
/-- The weights for the reflection of the circumcenter in an edge of a
simplex. This definition is only valid with `i₁ ≠ i₂`. -/
def reflection_circumcenter_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 1)) :
points_with_circumcenter_index n → ℝ
| (point_index i) := if i = i₁ ∨ i = i₂ then 1 else 0
| circumcenter_index := -1
/-- `reflection_circumcenter_weights_with_circumcenter` sums to 1. -/
@[simp] lemma sum_reflection_circumcenter_weights_with_circumcenter {n : ℕ} {i₁ i₂ : fin (n + 1)}
(h : i₁ ≠ i₂) : ∑ i, reflection_circumcenter_weights_with_circumcenter i₁ i₂ i = 1 :=
begin
simp_rw [sum_points_with_circumcenter, reflection_circumcenter_weights_with_circumcenter,
sum_ite, sum_const, filter_or, filter_eq'],
rw card_union_eq,
{ simp },
{ simp [h.symm] }
end
include V
/-- The reflection of the circumcenter of a simplex in an edge, in
terms of `points_with_circumcenter`. -/
lemma reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ}
(s : simplex ℝ P n) {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) :
reflection (affine_span ℝ (s.points '' {i₁, i₂})) s.circumcenter =
(univ : finset (points_with_circumcenter_index n)).affine_combination
s.points_with_circumcenter (reflection_circumcenter_weights_with_circumcenter i₁ i₂) :=
begin
have hc : card ({i₁, i₂} : finset (fin (n + 1))) = 2,
{ simp [h] },
have h_faces : ↑(orthogonal_projection (affine_span ℝ (s.points '' {i₁, i₂})) s.circumcenter)
= ↑(orthogonal_projection (affine_span ℝ (set.range (s.face hc).points)) s.circumcenter),
{ apply eq_orthogonal_projection_of_eq_subspace,
simp },
rw [reflection_apply, h_faces, s.orthogonal_projection_circumcenter hc, circumcenter_eq_centroid,
s.face_centroid_eq_centroid hc, centroid_eq_affine_combination_of_points_with_circumcenter,
circumcenter_eq_affine_combination_of_points_with_circumcenter, ←@vsub_eq_zero_iff_eq V,
affine_combination_vsub, weighted_vsub_vadd_affine_combination, affine_combination_vsub,
weighted_vsub_apply, sum_points_with_circumcenter],
simp_rw [pi.sub_apply, pi.add_apply, pi.sub_apply, sub_smul, add_smul, sub_smul,
centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter,
reflection_circumcenter_weights_with_circumcenter, ite_smul, zero_smul, sub_zero,
apply_ite2 (+), add_zero, ←add_smul, hc, zero_sub, neg_smul, sub_self, add_zero],
convert sum_const_zero,
norm_num
end
end simplex
end affine
namespace euclidean_geometry
open affine affine_subspace finite_dimensional
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
/-- Given a nonempty affine subspace, whose direction is complete,
that contains a set of points, those points are cospherical if and
only if they are equidistant from some point in that subspace. -/
lemma cospherical_iff_exists_mem_of_complete {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s)
[nonempty s] [complete_space s.direction] :
cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius :=
begin
split,
{ rintro ⟨c, hcr⟩,
rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq h c at hcr,
exact ⟨orthogonal_projection s c, orthogonal_projection_mem _, hcr⟩ },
{ exact λ ⟨c, hc, hd⟩, ⟨c, hd⟩ }
end
/-- Given a nonempty affine subspace, whose direction is
finite-dimensional, that contains a set of points, those points are
cospherical if and only if they are equidistant from some point in
that subspace. -/
lemma cospherical_iff_exists_mem_of_finite_dimensional {s : affine_subspace ℝ P} {ps : set P}
(h : ps ⊆ s) [nonempty s] [finite_dimensional ℝ s.direction] :
cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius :=
cospherical_iff_exists_mem_of_complete h
/-- All n-simplices among cospherical points in an n-dimensional
subspace have the same circumradius. -/
lemma exists_circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P}
(h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction]
(hd : findim ℝ s.direction = n) (hc : cospherical ps) :
∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r :=
begin
rw cospherical_iff_exists_mem_of_finite_dimensional h at hc,
rcases hc with ⟨c, hc, r, hcr⟩,
use r,
intros sx hsxps,
have hsx : affine_span ℝ (set.range sx.points) = s,
{ refine affine_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one sx.independent
(span_points_subset_coe_of_subset_coe (set.subset.trans hsxps h)) _,
simp [hd] },
have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc,
exact (sx.eq_circumradius_of_dist_eq
hc
(λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm
end
/-- Two n-simplices among cospherical points in an n-dimensional
subspace have the same circumradius. -/
lemma circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P}
(h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction]
(hd : findim ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n}
(hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) :
sx₁.circumradius = sx₂.circumradius :=
begin
rcases exists_circumradius_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩,
rw [hr sx₁ hsx₁, hr sx₂ hsx₂]
end
/-- All n-simplices among cospherical points in n-space have the same
circumradius. -/
lemma exists_circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V]
(hd : findim ℝ V = n) (hc : cospherical ps) :
∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r :=
begin
haveI : nonempty (⊤ : affine_subspace ℝ P) := set.univ.nonempty,
rw [←findim_top, ←direction_top ℝ V P] at hd,
refine exists_circumradius_eq_of_cospherical_subset _ hd hc,
exact set.subset_univ _
end
/-- Two n-simplices among cospherical points in n-space have the same
circumradius. -/
lemma circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V]
(hd : findim ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n}
(hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) :
sx₁.circumradius = sx₂.circumradius :=
begin
rcases exists_circumradius_eq_of_cospherical hd hc with ⟨r, hr⟩,
rw [hr sx₁ hsx₁, hr sx₂ hsx₂]
end
/-- All n-simplices among cospherical points in an n-dimensional
subspace have the same circumcenter. -/
lemma exists_circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P}
(h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction]
(hd : findim ℝ s.direction = n) (hc : cospherical ps) :
∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c :=
begin
rw cospherical_iff_exists_mem_of_finite_dimensional h at hc,
rcases hc with ⟨c, hc, r, hcr⟩,
use c,
intros sx hsxps,
have hsx : affine_span ℝ (set.range sx.points) = s,
{ refine affine_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one sx.independent
(span_points_subset_coe_of_subset_coe (set.subset.trans hsxps h)) _,
simp [hd] },
have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc,
exact (sx.eq_circumcenter_of_dist_eq
hc
(λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm
end
/-- Two n-simplices among cospherical points in an n-dimensional
subspace have the same circumcenter. -/
lemma circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P}
(h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction]
(hd : findim ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n}
(hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) :
sx₁.circumcenter = sx₂.circumcenter :=
begin
rcases exists_circumcenter_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩,
rw [hr sx₁ hsx₁, hr sx₂ hsx₂]
end
/-- All n-simplices among cospherical points in n-space have the same
circumcenter. -/
lemma exists_circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V]
(hd : findim ℝ V = n) (hc : cospherical ps) :
∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c :=
begin
haveI : nonempty (⊤ : affine_subspace ℝ P) := set.univ.nonempty,
rw [←findim_top, ←direction_top ℝ V P] at hd,
refine exists_circumcenter_eq_of_cospherical_subset _ hd hc,
exact set.subset_univ _
end
/-- Two n-simplices among cospherical points in n-space have the same
circumcenter. -/
lemma circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V]
(hd : findim ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n}
(hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) :
sx₁.circumcenter = sx₂.circumcenter :=
begin
rcases exists_circumcenter_eq_of_cospherical hd hc with ⟨r, hr⟩,
rw [hr sx₁ hsx₁, hr sx₂ hsx₂]
end
/-- Suppose all distances from `p₁` and `p₂` to the points of a
simplex are equal, and that `p₁` and `p₂` lie in the affine span of
`p` with the vertices of that simplex. Then `p₁` and `p₂` are equal
or reflections of each other in the affine span of the vertices of the
simplex. -/
lemma eq_or_eq_reflection_of_dist_eq {n : ℕ} {s : simplex ℝ P n} {p p₁ p₂ : P} {r : ℝ}
(hp₁ : p₁ ∈ affine_span ℝ (insert p (set.range s.points)))
(hp₂ : p₂ ∈ affine_span ℝ (insert p (set.range s.points)))
(h₁ : ∀ i, dist (s.points i) p₁ = r) (h₂ : ∀ i, dist (s.points i) p₂ = r) :
p₁ = p₂ ∨ p₁ = reflection (affine_span ℝ (set.range s.points)) p₂ :=
begin
let span_s := affine_span ℝ (set.range s.points),
have h₁' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₁,
have h₂' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₂,
have hn : (span_s : set P).nonempty := (affine_span_nonempty ℝ _).2 (set.range_nonempty _),
have hc : is_complete (span_s.direction : set V) := submodule.complete_of_finite_dimensional _,
rw [←affine_span_insert_affine_span,
mem_affine_span_insert_iff (orthogonal_projection_mem p)] at hp₁ hp₂,
obtain ⟨r₁, p₁o, hp₁o, hp₁⟩ := hp₁,
obtain ⟨r₂, p₂o, hp₂o, hp₂⟩ := hp₂,
obtain rfl : ↑(orthogonal_projection span_s p₁) = p₁o,
{ have := orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hp₁o,
rw ← hp₁ at this,
rw this,
refl },
rw h₁' at hp₁,
obtain rfl : ↑(orthogonal_projection span_s p₂) = p₂o,
{ have := orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hp₂o,
rw ← hp₂ at this,
rw this,
refl },
rw h₂' at hp₂,
have h : s.points 0 ∈ span_s := mem_affine_span ℝ (set.mem_range_self _),
have hd₁ : dist p₁ s.circumcenter * dist p₁ s.circumcenter =
r * r - s.circumradius * s.circumradius,
{ rw [dist_comm, ←h₁ 0,
dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square p₁ h],
simp [h₁', dist_comm p₁] },
have hd₂ : dist p₂ s.circumcenter * dist p₂ s.circumcenter =
r * r - s.circumradius * s.circumradius,
{ rw [dist_comm, ←h₂ 0,
dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square p₂ h],
simp [h₂', dist_comm p₂] },
rw [←hd₂, hp₁, hp₂, dist_eq_norm_vsub V _ s.circumcenter,
dist_eq_norm_vsub V _ s.circumcenter, vadd_vsub, vadd_vsub, ←real_inner_self_eq_norm_square,
←real_inner_self_eq_norm_square, real_inner_smul_left, real_inner_smul_left,
real_inner_smul_right, real_inner_smul_right, ←mul_assoc, ←mul_assoc] at hd₁,
by_cases hp : p = orthogonal_projection span_s p,
{ rw [hp₁, hp₂, ←hp],
simp },
{ have hz : ⟪p -ᵥ orthogonal_projection span_s p, p -ᵥ orthogonal_projection span_s p⟫ ≠ 0,
{ simpa using hp },
rw [mul_left_inj' hz, mul_self_eq_mul_self_iff] at hd₁,
rw [hp₁, hp₂],
cases hd₁,
{ left,
rw hd₁ },
{ right,
rw [hd₁,
reflection_vadd_smul_vsub_orthogonal_projection p r₂ s.circumcenter_mem_affine_span,
neg_smul] } }
end
end euclidean_geometry
|
aedc01853b751146422a2b63d292ead856fb1173 | 1dd482be3f611941db7801003235dc84147ec60a | /src/topology/algebra/infinite_sum.lean | c21a05a612a0c0649e1fb69b786f06cf9a64aa7b | [
"Apache-2.0"
] | permissive | sanderdahmen/mathlib | 479039302bd66434bb5672c2a4cecf8d69981458 | 8f0eae75cd2d8b7a083cf935666fcce4565df076 | refs/heads/master | 1,587,491,322,775 | 1,549,672,060,000 | 1,549,672,060,000 | 169,748,224 | 0 | 0 | Apache-2.0 | 1,549,636,694,000 | 1,549,636,694,000 | null | UTF-8 | Lean | false | false | 21,236 | 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
Infinite sum over a topological monoid
This sum is known as unconditionally convergent, as it sums to the same value under all possible
permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute
convergence.
-/
import logic.function algebra.big_operators data.set data.finset
topology.metric_space.basic topology.algebra.topological_structures
noncomputable theory
open lattice finset filter function classical
local attribute [instance] prop_decidable
variables {α : Type*} {β : Type*} {γ : Type*}
section is_sum
variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α]
/-- Infinite sum on a topological monoid
The `at_top` filter on `finset α` is the limit of all finite sets towards the entire type. So we sum
up bigger and bigger sets. This sum operation is still invariant under reordering, and a absolute
sum operator.
This is based on Mario Carneiro's infinite sum in Metamath.
-/
def is_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, s.sum f) at_top (nhds a)
/-- `has_sum f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/
def has_sum (f : β → α) : Prop := ∃a, is_sum f a
/-- `tsum f` is the sum of `f` it exists, or 0 otherwise -/
def tsum (f : β → α) := if h : has_sum f then classical.some h else 0
notation `∑` binders `, ` r:(scoped f, tsum f) := r
variables {f g : β → α} {a b : α} {s : finset β}
lemma is_sum_tsum (ha : has_sum f) : is_sum f (∑b, f b) :=
by simp [ha, tsum]; exact some_spec ha
lemma has_sum_spec (ha : is_sum f a) : has_sum f := ⟨a, ha⟩
lemma is_sum_zero : is_sum (λb, 0 : β → α) 0 :=
by simp [is_sum, tendsto_const_nhds]
lemma has_sum_zero : has_sum (λb, 0 : β → α) := has_sum_spec is_sum_zero
lemma is_sum_add (hf : is_sum f a) (hg : is_sum g b) : is_sum (λb, f b + g b) (a + b) :=
by simp [is_sum, sum_add_distrib]; exact tendsto_add hf hg
lemma has_sum_add (hf : has_sum f) (hg : has_sum g) : has_sum (λb, f b + g b) :=
has_sum_spec $ is_sum_add (is_sum_tsum hf)(is_sum_tsum hg)
lemma is_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} :
(∀i∈s, is_sum (f i) (a i)) → is_sum (λb, s.sum $ λi, f i b) (s.sum a) :=
finset.induction_on s (by simp [is_sum_zero]) (by simp [is_sum_add] {contextual := tt})
lemma has_sum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, has_sum (f i)) :
has_sum (λb, s.sum $ λi, f i b) :=
has_sum_spec $ is_sum_sum $ assume i hi, is_sum_tsum $ hf i hi
lemma is_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : is_sum f (s.sum f) :=
tendsto_infi' s $ tendsto_cong tendsto_const_nhds $
assume t (ht : s ⊆ t), show s.sum f = t.sum f, from sum_subset ht $ assume x _, hf _
lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f :=
has_sum_spec $ is_sum_sum_of_ne_finset_zero hf
lemma is_sum_ite (b : β) (a : α) : is_sum (λb', if b' = b then a else 0) a :=
suffices
is_sum (λb', if b' = b then a else 0) (({b} : finset β).sum (λb', if b' = b then a else 0)), from
by simpa,
is_sum_sum_of_ne_finset_zero $ assume b' hb,
have b' ≠ b, by simpa using hb,
by rw [if_neg this]
lemma is_sum_of_iso {j : γ → β} {i : β → γ}
(hf : is_sum f a) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : is_sum (f ∘ j) a :=
have ∀x y, j x = j y → x = y,
from assume x y h,
have i (j x) = i (j y), by rw [h],
by rwa [h₁, h₁] at this,
have (λs:finset γ, s.sum (f ∘ j)) = (λs:finset β, s.sum f) ∘ (λs:finset γ, s.image j),
from funext $ assume s, (sum_image $ assume x _ y _, this x y).symm,
show tendsto (λs:finset γ, s.sum (f ∘ j)) at_top (nhds a),
by rw [this]; apply (tendsto_finset_image_at_top_at_top h₂).comp hf
lemma is_sum_iff_is_sum_of_iso {j : γ → β} (i : β → γ)
(h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) :
is_sum (f ∘ j) a ↔ is_sum f a :=
iff.intro
(assume hfj,
have is_sum ((f ∘ j) ∘ i) a, from is_sum_of_iso hfj h₂ h₁,
by simp [(∘), h₂] at this; assumption)
(assume hf, is_sum_of_iso hf h₁ h₂)
lemma is_sum_hom (g : α → γ) [add_comm_monoid γ] [topological_space γ] [topological_add_monoid γ]
[is_add_monoid_hom g] (h₃ : continuous g) (hf : is_sum f a) :
is_sum (g ∘ f) (g a) :=
have (λs:finset β, s.sum (g ∘ f)) = g ∘ (λs:finset β, s.sum f),
from funext $ assume s, sum_hom g,
show tendsto (λs:finset β, s.sum (g ∘ f)) at_top (nhds (g a)),
by rw [this]; exact hf.comp (continuous_iff_continuous_at.mp h₃ a)
lemma tendsto_sum_nat_of_is_sum {f : ℕ → α} (h : is_sum f a) :
tendsto (λn:ℕ, (range n).sum f) at_top (nhds a) :=
suffices map (λ (n : ℕ), sum (range n) f) at_top ≤ map (λ (s : finset ℕ), sum s f) at_top,
from le_trans this h,
assume s (hs : {t : finset ℕ | t.sum f ∈ s} ∈ at_top.sets),
let ⟨t, ht⟩ := mem_at_top_sets.mp hs, ⟨n, hn⟩ := @exists_nat_subset_range t in
mem_at_top_sets.mpr ⟨n, assume n' hn', ht _ $ finset.subset.trans hn $ range_subset.mpr hn'⟩
lemma is_sum_sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α}
(hf : ∀b, is_sum (λc, f ⟨b, c⟩) (g b)) (ha : is_sum f a) : is_sum g a :=
assume s' hs',
let
⟨s, hs, hss', hsc⟩ := nhds_is_closed hs',
⟨u, hu⟩ := mem_at_top_sets.mp $ ha $ hs,
fsts := u.image sigma.fst,
snds := λb, u.bind (λp, (if h : p.1 = b then {cast (congr_arg γ h) p.2} else ∅ : finset (γ b)))
in
have u_subset : u ⊆ fsts.sigma snds,
from subset_iff.mpr $ assume ⟨b, c⟩ hu,
have hb : b ∈ fsts, from finset.mem_image.mpr ⟨_, hu, rfl⟩,
have hc : c ∈ snds b, from mem_bind.mpr ⟨_, hu, by simp; refl⟩,
by simp [mem_sigma, hb, hc] ,
mem_at_top_sets.mpr $ exists.intro fsts $ assume bs (hbs : fsts ⊆ bs),
have h : ∀cs : Π b ∈ bs, finset (γ b),
(⋂b (hb : b ∈ bs), (λp:Πb, finset (γ b), p b) ⁻¹' {cs' | cs b hb ⊆ cs' }) ∩
(λp, bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) ⁻¹' s ≠ ∅,
from assume cs,
let cs' := λb, (if h : b ∈ bs then cs b h else ∅) ∪ snds b in
have sum_eq : bs.sum (λb, (cs' b).sum (λc, f ⟨b, c⟩)) = (bs.sigma cs').sum f,
from sum_sigma.symm,
have (bs.sigma cs').sum f ∈ s,
from hu _ $ finset.subset.trans u_subset $ sigma_mono hbs $
assume b, @finset.subset_union_right (γ b) _ _ _,
set.ne_empty_iff_exists_mem.mpr $ exists.intro cs' $
by simp [sum_eq, this]; { intros b hb, simp [cs', hb, finset.subset_union_right] },
have tendsto (λp:(Πb:β, finset (γ b)), bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩)))
(⨅b (h : b ∈ bs), at_top.comap (λp, p b)) (nhds (bs.sum g)),
from tendsto_finset_sum bs $
assume c hc, tendsto_infi' c $ tendsto_infi' hc $ tendsto_comap.comp (hf c),
have bs.sum g ∈ s,
from mem_of_closed_of_tendsto' this hsc $ forall_sets_neq_empty_iff_neq_bot.mp $
by simp [mem_inf_sets, exists_imp_distrib, and_imp, forall_and_distrib,
filter.mem_infi_sets_finset, mem_comap_sets, skolem, mem_at_top_sets,
and_comm];
from
assume s₁ s₂ s₃ hs₁ hs₃ p hs₂ p' hp cs hp',
have (⋂b (h : b ∈ bs), (λp:(Πb, finset (γ b)), p b) ⁻¹' {cs' | cs b h ⊆ cs' }) ≤ (⨅b∈bs, p b),
from infi_le_infi $ assume b, infi_le_infi $ assume hb,
le_trans (set.preimage_mono $ hp' b hb) (hp b hb),
neq_bot_of_le_neq_bot (h _) (le_trans (set.inter_subset_inter (le_trans this hs₂) hs₃) hs₁),
hss' this
lemma has_sum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(hf : ∀b, has_sum (λc, f ⟨b, c⟩)) (ha : has_sum f) : has_sum (λb, ∑c, f ⟨b, c⟩):=
has_sum_spec $ is_sum_sigma (assume b, is_sum_tsum $ hf b) (is_sum_tsum ha)
end is_sum
section is_sum_iff_is_sum_of_iso_ne_zero
variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α]
variables {f : β → α} {g : γ → α} {a : α}
lemma is_sum_of_is_sum
(h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f)
(hf : is_sum g a) : is_sum f a :=
suffices at_top.map (λs:finset β, s.sum f) ≤ at_top.map (λs:finset γ, s.sum g),
from le_trans this hf,
by rw [map_at_top_eq, map_at_top_eq];
from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $
by simp [set.image_subset_iff]; exact hv)
lemma is_sum_iff_is_sum
(h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f)
(h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ v'.sum f = u'.sum g) :
is_sum f a ↔ is_sum g a :=
⟨is_sum_of_is_sum h₂, is_sum_of_is_sum h₁⟩
variables
(i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0)
(j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0)
(hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c)
(hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b)
(hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b)
include hi hj hji hij hgj
lemma is_sum_of_is_sum_ne_zero : is_sum g a → is_sum f a :=
have j_inj : ∀x y (hx : f x ≠ 0) (hy : f y ≠ 0), (j hx = j hy ↔ x = y),
from assume x y hx hy,
⟨assume h,
have i (hj hx) = i (hj hy), by simp [h],
by rwa [hij, hij] at this; assumption,
by simp {contextual := tt}⟩,
let ii : finset γ → finset β := λu, u.bind $ λc, if h : g c = 0 then ∅ else {i h} in
let jj : finset β → finset γ := λv, v.bind $ λb, if h : f b = 0 then ∅ else {j h} in
is_sum_of_is_sum $ assume u, exists.intro (ii u) $
assume v hv, exists.intro (u ∪ jj v) $ and.intro (subset_union_left _ _) $
have ∀c:γ, c ∈ u ∪ jj v → c ∉ jj v → g c = 0,
from assume c hc hnc, classical.by_contradiction $ assume h : g c ≠ 0,
have c ∈ u,
from (finset.mem_union.1 hc).resolve_right hnc,
have i h ∈ v,
from hv $ by simp [mem_bind]; existsi c; simp [h, this],
have j (hi h) ∈ jj v,
by simp [mem_bind]; existsi i h; simp [h, hi, this],
by rw [hji h] at this; exact hnc this,
calc (u ∪ jj v).sum g = (jj v).sum g : (sum_subset (subset_union_right _ _) this).symm
... = v.sum _ : sum_bind $ by intros x hx y hy hxy; by_cases f x = 0; by_cases f y = 0; simp [*]
... = v.sum f : sum_congr rfl $ by intros x hx; by_cases f x = 0; simp [*]
lemma is_sum_iff_is_sum_of_ne_zero : is_sum f a ↔ is_sum g a :=
iff.intro
(is_sum_of_is_sum_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji])
(is_sum_of_is_sum_ne_zero i hi j hj hji hij hgj)
lemma has_sum_iff_has_sum_ne_zero : has_sum g ↔ has_sum f :=
exists_congr $
assume a, is_sum_iff_is_sum_of_ne_zero j hj i hi hij hji $
assume b hb, by rw [←hgj (hi _), hji]
end is_sum_iff_is_sum_of_iso_ne_zero
section tsum
variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α] [t2_space α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma is_sum_unique : is_sum f a₁ → is_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique at_top_ne_bot
lemma tsum_eq_is_sum (ha : is_sum f a) : (∑b, f b) = a := is_sum_unique (is_sum_tsum ⟨a, ha⟩) ha
lemma is_sum_iff_of_has_sum (h : has_sum f) : is_sum f a ↔ (∑b, f b) = a :=
iff.intro tsum_eq_is_sum (assume eq, eq ▸ is_sum_tsum h)
@[simp] lemma tsum_zero : (∑b:β, 0:α) = 0 := tsum_eq_is_sum is_sum_zero
lemma tsum_add (hf : has_sum f) (hg : has_sum g) : (∑b, f b + g b) = (∑b, f b) + (∑b, g b) :=
tsum_eq_is_sum $ is_sum_add (is_sum_tsum hf) (is_sum_tsum hg)
lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, has_sum (f i)) :
(∑b, s.sum (λi, f i b)) = s.sum (λi, ∑b, f i b) :=
tsum_eq_is_sum $ is_sum_sum $ assume i hi, is_sum_tsum $ hf i hi
lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) :
(∑b, f b) = s.sum f :=
tsum_eq_is_sum $ is_sum_sum_of_ne_finset_zero hf
lemma tsum_fintype [fintype β] (f : β → α) : (∑b, f b) = finset.univ.sum f :=
tsum_eq_sum $ λ a h, h.elim (mem_univ _)
lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) :
(∑b, f b) = f b :=
calc (∑b, f b) = (finset.singleton b).sum f : tsum_eq_sum $ by simp [hf] {contextual := tt}
... = f b : by simp
lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(h₁ : ∀b, has_sum (λc, f ⟨b, c⟩)) (h₂ : has_sum f) : (∑p, f p) = (∑b c, f ⟨b, c⟩):=
(tsum_eq_is_sum $ is_sum_sigma (assume b, is_sum_tsum $ h₁ b) $ is_sum_tsum h₂).symm
@[simp] lemma tsum_ite (b : β) (a : α) : (∑b', if b' = b then a else 0) = a :=
tsum_eq_is_sum (is_sum_ite b a)
lemma tsum_eq_tsum_of_is_sum_iff_is_sum {f : β → α} {g : γ → α}
(h : ∀{a}, is_sum f a ↔ is_sum g a) : (∑b, f b) = (∑c, g c) :=
by_cases
(assume : ∃a, is_sum f a,
let ⟨a, hfa⟩ := this in
have hga : is_sum g a, from h.mp hfa,
by rw [tsum_eq_is_sum hfa, tsum_eq_is_sum hga])
(assume hf : ¬ has_sum f,
have hg : ¬ has_sum g, from assume ⟨a, hga⟩, hf ⟨a, h.mpr hga⟩,
by simp [tsum, hf, hg])
lemma tsum_eq_tsum_of_ne_zero {f : β → α} {g : γ → α}
(i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0)
(j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0)
(hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c)
(hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b)
(hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) :
(∑i, f i) = (∑j, g j) :=
tsum_eq_tsum_of_is_sum_iff_is_sum $ assume a, is_sum_iff_is_sum_of_ne_zero i hi j hj hji hij hgj
lemma tsum_eq_tsum_of_ne_zero_bij {f : β → α} {g : γ → α}
(i : Π⦃c⦄, g c ≠ 0 → β)
(h₁ : ∀⦃c₁ c₂⦄ (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂)
(h₂ : ∀⦃b⦄, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b)
(h₃ : ∀⦃c⦄ (h : g c ≠ 0), f (i h) = g c) :
(∑i, f i) = (∑j, g j) :=
have hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0,
from assume c h, by simp [h₃, h],
let j : Π⦃b⦄, f b ≠ 0 → γ := λb h, some $ h₂ h in
have hj : ∀⦃b⦄ (h : f b ≠ 0), ∃(h : g (j h) ≠ 0), i h = b,
from assume b h, some_spec $ h₂ h,
have hj₁ : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0,
from assume b h, let ⟨h₁, _⟩ := hj h in h₁,
have hj₂ : ∀⦃b⦄ (h : f b ≠ 0), i (hj₁ h) = b,
from assume b h, let ⟨h₁, h₂⟩ := hj h in h₂,
tsum_eq_tsum_of_ne_zero i hi j hj₁
(assume c h, h₁ (hj₁ _) h $ hj₂ _) hj₂ (assume b h, by rw [←h₃ (hj₁ _), hj₂])
lemma tsum_eq_tsum_of_iso (j : γ → β) (i : β → γ)
(h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) :
(∑c, f (j c)) = (∑b, f b) :=
tsum_eq_tsum_of_is_sum_iff_is_sum $ assume a, is_sum_iff_is_sum_of_iso i h₁ h₂
lemma tsum_equiv (j : γ ≃ β) : (∑c, f (j c)) = (∑b, f b) :=
tsum_eq_tsum_of_iso j j.symm (by simp) (by simp)
end tsum
section topological_group
variables [add_comm_group α] [topological_space α] [topological_add_group α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma is_sum_neg : is_sum f a → is_sum (λb, - f b) (- a) :=
is_sum_hom has_neg.neg continuous_neg'
lemma has_sum_neg (hf : has_sum f) : has_sum (λb, - f b) :=
has_sum_spec $ is_sum_neg $ is_sum_tsum $ hf
lemma is_sum_sub (hf : is_sum f a₁) (hg : is_sum g a₂) : is_sum (λb, f b - g b) (a₁ - a₂) :=
by simp; exact is_sum_add hf (is_sum_neg hg)
lemma has_sum_sub (hf : has_sum f) (hg : has_sum g) : has_sum (λb, f b - g b) :=
has_sum_spec $ is_sum_sub (is_sum_tsum hf) (is_sum_tsum hg)
section tsum
variables [t2_space α]
lemma tsum_neg (hf : has_sum f) : (∑b, - f b) = - (∑b, f b) :=
tsum_eq_is_sum $ is_sum_neg $ is_sum_tsum $ hf
lemma tsum_sub (hf : has_sum f) (hg : has_sum g) : (∑b, f b - g b) = (∑b, f b) - (∑b, g b) :=
tsum_eq_is_sum $ is_sum_sub (is_sum_tsum hf) (is_sum_tsum hg)
end tsum
end topological_group
section topological_semiring
variables [semiring α] [topological_space α] [topological_semiring α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma is_sum_mul_left (a₂) : is_sum f a₁ → is_sum (λb, a₂ * f b) (a₂ * a₁) :=
is_sum_hom _ (continuous_mul continuous_const continuous_id)
lemma is_sum_mul_right (a₂) (hf : is_sum f a₁) : is_sum (λb, f b * a₂) (a₁ * a₂) :=
@is_sum_hom _ _ _ _ _ _ f a₁ (λa, a * a₂) _ _ _ _
(continuous_mul continuous_id continuous_const) hf
lemma has_sum_mul_left (a) (hf : has_sum f) : has_sum (λb, a * f b) :=
has_sum_spec $ is_sum_mul_left _ $ is_sum_tsum hf
lemma has_sum_mul_right (a) (hf : has_sum f) : has_sum (λb, f b * a) :=
has_sum_spec $ is_sum_mul_right _ $ is_sum_tsum hf
section tsum
variables [t2_space α]
lemma tsum_mul_left (a) (hf : has_sum f) : (∑b, a * f b) = a * (∑b, f b) :=
tsum_eq_is_sum $ is_sum_mul_left _ $ is_sum_tsum hf
lemma tsum_mul_right (a) (hf : has_sum f) : (∑b, f b * a) = (∑b, f b) * a :=
tsum_eq_is_sum $ is_sum_mul_right _ $ is_sum_tsum hf
end tsum
end topological_semiring
section order_topology
variables [ordered_comm_monoid α] [topological_space α] [ordered_topology α] [topological_add_monoid α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma is_sum_le (h : ∀b, f b ≤ g b) (hf : is_sum f a₁) (hg : is_sum g a₂) : a₁ ≤ a₂ :=
le_of_tendsto_of_tendsto at_top_ne_bot hf hg $ univ_mem_sets' $ assume s, sum_le_sum' $ assume b _, h b
lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : has_sum f) (hg : has_sum g) : (∑b, f b) ≤ (∑b, g b) :=
is_sum_le h (is_sum_tsum hf) (is_sum_tsum hg)
end order_topology
section uniform_group
variables [add_comm_group α] [uniform_space α] [complete_space α] [uniform_add_group α]
variables {f g : β → α} {a a₁ a₂ : α}
/- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/
lemma has_sum_of_has_sum_of_sub {f' : β → α} (hf : has_sum f) (h : ∀b, f' b = 0 ∨ f' b = f b) :
has_sum f' :=
let ⟨a, hf⟩ := hf in
suffices cauchy (at_top.map (λs:finset β, s.sum f')),
from complete_space.complete this,
⟨map_ne_bot at_top_ne_bot,
assume s' hs',
have ∃t∈(@uniformity α _).sets, ∀{a₁ a₂ a₃ a₄}, (a₁, a₂) ∈ t → (a₃, a₄) ∈ t → (a₁ - a₃, a₂ - a₄) ∈ s',
begin
have h : {p:(α×α)×(α×α)| (p.1.1 - p.1.2, p.2.1 - p.2.2) ∈ s'} ∈ (@uniformity (α × α) _).sets,
from uniform_continuous_sub' hs',
rw [uniformity_prod_eq_prod, filter.mem_map, mem_prod_same_iff] at h,
rcases h with ⟨t, ht, h⟩,
exact ⟨t, ht, assume a₁ a₂ a₃ a₄ h₁ h₂, @h ((a₁, a₂), (a₃, a₄)) ⟨h₁, h₂⟩⟩
end,
let ⟨s, hs, hss'⟩ := this in
have cauchy (at_top.map (λs:finset β, s.sum f)),
from cauchy_downwards cauchy_nhds (map_ne_bot at_top_ne_bot) hf,
have ∃t, ∀u₁ u₂:finset β, t ⊆ u₁ → t ⊆ u₂ → (u₁.sum f, u₂.sum f) ∈ s,
by simp [cauchy_iff, mem_at_top_sets, and.assoc, and.left_comm, and.comm] at this;
from let ⟨t, ht, u, hu⟩ := this s hs in
⟨u, assume u₁ u₂ h₁ h₂, ht $ set.prod_mk_mem_set_prod_eq.mpr ⟨hu _ h₁, hu _ h₂⟩⟩,
let ⟨t, ht⟩ := this in
let d := (t.filter (λb, f' b = 0)).sum f in
have eq : ∀{u}, t ⊆ u → (t ∪ u.filter (λb, f' b ≠ 0)).sum f - d = u.sum f',
from assume u hu,
have t ∪ u.filter (λb, f' b ≠ 0) = t.filter (λb, f' b = 0) ∪ u.filter (λb, f' b ≠ 0),
from finset.ext.2 $ assume b, by by_cases f' b = 0;
simp [h, subset_iff.mp hu, iff_def, or_imp_distrib] {contextual := tt},
calc (t ∪ u.filter (λb, f' b ≠ 0)).sum f - d =
(t.filter (λb, f' b = 0) ∪ u.filter (λb, f' b ≠ 0)).sum f - d : by rw [this]
... = (d + (u.filter (λb, f' b ≠ 0)).sum f) - d :
by rw [sum_union]; exact (finset.ext.2 $ by simp {contextual := tt})
... = (u.filter (λb, f' b ≠ 0)).sum f :
by simp
... = (u.filter (λb, f' b ≠ 0)).sum f' :
sum_congr rfl $ assume b, by have h := h b; cases h with h h; simp [*]
... = u.sum f' :
by apply sum_subset; by simp [subset_iff, not_not] {contextual := tt},
have ∀{u₁ u₂}, t ⊆ u₁ → t ⊆ u₂ → (u₁.sum f', u₂.sum f') ∈ s',
from assume u₁ u₂ h₁ h₂,
have ((t ∪ u₁.filter (λb, f' b ≠ 0)).sum f, (t ∪ u₂.filter (λb, f' b ≠ 0)).sum f) ∈ s,
from ht _ _ (subset_union_left _ _) (subset_union_left _ _),
have ((t ∪ u₁.filter (λb, f' b ≠ 0)).sum f - d, (t ∪ u₂.filter (λb, f' b ≠ 0)).sum f - d) ∈ s',
from hss' this $ refl_mem_uniformity hs,
by rwa [eq h₁, eq h₂] at this,
mem_prod_same_iff.mpr ⟨(λu:finset β, u.sum f') '' {u | t ⊆ u},
image_mem_map $ mem_at_top t,
assume ⟨a₁, a₂⟩ ⟨⟨t₁, h₁, eq₁⟩, ⟨t₂, h₂, eq₂⟩⟩, by simp at eq₁ eq₂; rw [←eq₁, ←eq₂]; exact this h₁ h₂⟩⟩
end uniform_group
|
a405c630e0a7040798f40f421ccb286d310fb7ac | ce89339993655da64b6ccb555c837ce6c10f9ef4 | /bluejam/chap4_exercise3.lean | 3523e98b0365c328d84ab0409c7dae263a002958 | [] | no_license | zeptometer/LearnLean | ef32dc36a22119f18d843f548d0bb42f907bff5d | bb84d5dbe521127ba134d4dbf9559b294a80b9f7 | refs/heads/master | 1,625,710,824,322 | 1,601,382,570,000 | 1,601,382,570,000 | 195,228,870 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 514 | lean | variables (men : Type) (barber : men)
variable (shaves : men → men → Prop)
example (h : ∀ x : men, shaves barber x ↔ ¬ shaves x x) : false :=
have ¬ shaves barber barber, from (
assume barber_shaves_self: shaves barber barber,
have ¬ shaves barber barber, from (h barber).mp barber_shaves_self,
absurd barber_shaves_self ‹ ¬ shaves barber barber ›
),
have shaves barber barber, from (h barber).mpr ‹ ¬ shaves barber barber ›,
absurd this ‹ ¬ shaves barber barber ›
|
ac76d99ddc65e859679a7a2a32e4c87d9b702352 | cbb1957fc3e28e502582c54cbce826d666350eda | /fabstract/Roux_C_and_vanDoorn_F_PTSs/pure_type_systems.lean | 61f68556badef16abc0763fa618c7ba31b3da288 | [
"CC-BY-4.0"
] | permissive | andrejbauer/formalabstracts | 9040b172da080406448ad1b0260d550122dcad74 | a3b84fd90901ccf4b63eb9f95d4286a8775864d0 | refs/heads/master | 1,609,476,417,918 | 1,501,541,742,000 | 1,501,541,760,000 | 97,241,872 | 1 | 0 | null | 1,500,042,191,000 | 1,500,042,191,000 | null | UTF-8 | Lean | false | false | 4,347 | lean | open list option
/- Pure Type Systems using DeBruijn indices -/
-- the specification of a PTS
structure pure_type_system : Type 2 :=
(Sorts : Type)
(Axioms : Sorts → Sorts → Prop)
(Relations : Sorts → Sorts → Sorts → Prop)
namespace pure_type_system
section
parameter (PTS : pure_type_system)
/- untyped terms of a PTS -/
inductive term : Type
| var : ℕ -> term
| sort : PTS.Sorts -> term
| pi : term -> term -> term
| abs : term -> term -> term
| app : term -> term -> term
local notation `#`:max := term.var
local notation `!`:max := term.sort
local notation `Π'` := term.pi
local notation `λ'` := term.abs
local infix `⬝` := term.app
parameter {PTS}
/- lifting of terms -/
def lift_term : term → ℕ → ℕ → term
| (term.var ._ x) n k := if k ≤ x then #(x+n) else #x
| (term.sort s) n k := !s
| (term.pi A B) n k := Π' (lift_term A n k) (lift_term B n (k+1))
| (term.abs A b) n k := λ' (lift_term A n k) (lift_term b n (k+1))
| (term.app a b) n k := lift_term a n k ⬝ lift_term b n k
local notation t ` ↑ ` n ` # ` k := lift_term t n k
local infix ` ↑ ` := λn k, lift_term n k 0
/- substitution -/
def subst : term → term → ℕ → term
| (term.var ._ x) t n := if n < x then #x else if n = x then t ↑ n else #(x-1)
| (term.sort s) t n := !s
| (term.pi A B) t n := Π' (subst A t n) (subst B t (n+1))
| (term.abs A b) t n := λ' (subst A t n) (subst b t (n+1))
| (term.app a b) t n := subst a t n ⬝ subst b t n
def context := list term
/- t is the n-th term of Γ, correctly lifted -/
def item_lift (Γ : context) (n : ℕ) (t : term) : Prop :=
∃u, t = u ↑ (n+1) ∧ nth Γ n = some u
/- The contextual closure of single-step beta reduction -/
inductive beta : term → term → Prop
| beta : ∀A t u, beta ((λ' A t) ⬝ u) (subst t u 0)
| pil : ∀{t t'} u, beta t t' → beta (Π' t u) (Π' t' u)
| pir : ∀t {u u'}, beta u u' → beta (Π' t u) (Π' t u')
| absl : ∀{t t'} u, beta t t' → beta (λ' t u) (λ' t' u)
| absr : ∀t {u u'}, beta u u' → beta (λ' t u) (λ' t u')
| appl : ∀{t t'} u, beta t t' → beta (t ⬝ u) (t' ⬝ u)
| appr : ∀t {u u'}, beta u u' → beta (t ⬝ u) (t ⬝ u')
local infix ` →β `:50 := beta
/- the transitive closure of beta reduction -/
inductive betas : term → term → Prop
| refl : ∀t, betas t t
| transl : ∀{a b c}, a →β b → betas b c → betas a c
local infix ` ↠β `:50 := betas
/- The congruence closure of beta reduction -/
inductive betac : term → term → Prop
| of_betas : ∀{t s}, t ↠β s → betac t s
| symm : ∀{t s}, betac t s → betac s t
| transl : ∀{a b c}, betac a b → betac b c → betac a c
local infix ` ≡β `:50 := betas
/- terms in normal form -/
definition is_normal (t : term) : Prop :=
∀(s : term), ¬(t →β s)
definition has_normal_form (t : term) : Prop :=
∃(s : term), is_normal s ∧ t ↠β s
definition strongly_normalizing_term (t : term) : Prop :=
¬∃(f : ℕ → term), f 0 = t ∧ ∀n, f n →β f (n+1)
/- well formed contexts, well typed terms -/
mutual inductive wf, typ
with wf : context → Prop
| nil : wf nil
| cons : Π{Γ A s}, typ Γ A (!s) → wf (A::Γ)
with typ : context → term → term → Prop
| sort : Π{Γ s t}, PTS.Axioms s t → wf Γ → typ Γ (!s) (!t)
| var : Π{Γ s x}, wf Γ → item_lift Γ x s → typ Γ (#x) s
| pi : Π{Γ A B s₁ s₂ u}, PTS.Relations s₁ s₂ u → typ Γ A (!s₁) → typ (A::Γ) B (!s₂) →
typ Γ (Π' A B) (!u)
| lam : Π{Γ A B M s₁ s₂ s₃}, PTS.Relations s₁ s₂ s₃ → typ Γ A (!s₁) → typ (A::Γ) B (!s₂) →
typ (A::Γ) M B → typ Γ (λ' A M) (Π' A B)
| app : Π{Γ A B t u}, typ Γ t (Π' A B) → typ Γ u A → typ Γ (t ⬝ u) (subst B u 0)
| conv : Π{Γ A B t s}, A ≡β B → typ Γ t A → typ Γ B (!s) → typ Γ t B
local notation Γ ` ⊢ ` t ` : ` T := typ Γ t T
-- where "Γ ⊢ t : T" := (typ Γ t T) : UT_scope.
definition is_well_typed (t : term) : Prop :=
∃(Γ : context) (A : term), Γ ⊢ t : A
parameter (PTS)
/- weakly and strongly normalizing PTSs -/
definition is_weakly_normalizing : Prop :=
∀(t : term), is_well_typed t → has_normal_form t
definition is_strongly_normalizing : Prop :=
∀(t : term), is_well_typed t → strongly_normalizing_term t
end
end pure_type_system
|
df9ca833532bfbc3c7050ab48c51baf48abf9e5b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/ring_theory/polynomial/tower.lean | 7342032c8b52b8b17b41906615cb9f622d716d14 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 2,252 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yuyang Zhao
-/
import algebra.algebra.tower
import data.polynomial.algebra_map
/-!
# Algebra towers for polynomial
This file proves some basic results about the algebra tower structure for the type `R[X]`.
This structure itself is provided elsewhere as `polynomial.is_scalar_tower`
When you update this file, you can also try to make a corresponding update in
`ring_theory.mv_polynomial.tower`.
-/
open_locale polynomial
variables (R A B : Type*)
namespace polynomial
section semiring
variables [comm_semiring R] [comm_semiring A] [semiring B]
variables [algebra R A] [algebra A B] [algebra R B]
variables [is_scalar_tower R A B]
variables {R B}
@[simp] theorem aeval_map_algebra_map (x : B) (p : R[X]) :
aeval x (map (algebra_map R A) p) = aeval x p :=
by rw [aeval_def, aeval_def, eval₂_map, is_scalar_tower.algebra_map_eq R A B]
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [semiring B]
variables [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B]
variables {R A}
lemma aeval_algebra_map_apply (x : A) (p : R[X]) :
aeval (algebra_map A B x) p = algebra_map A B (aeval x p) :=
by rw [aeval_def, aeval_def, hom_eval₂, ←is_scalar_tower.algebra_map_eq]
@[simp] lemma aeval_algebra_map_eq_zero_iff [no_zero_smul_divisors A B] [nontrivial B]
(x : A) (p : R[X]) :
aeval (algebra_map A B x) p = 0 ↔ aeval x p = 0 :=
by rw [aeval_algebra_map_apply, algebra.algebra_map_eq_smul_one, smul_eq_zero,
iff_false_intro (one_ne_zero' B), or_false]
variables {B}
lemma aeval_algebra_map_eq_zero_iff_of_injective
{x : A} {p : R[X]}
(h : function.injective (algebra_map A B)) :
aeval (algebra_map A B x) p = 0 ↔ aeval x p = 0 :=
by rw [aeval_algebra_map_apply, ← (algebra_map A B).map_zero, h.eq_iff]
end comm_semiring
end polynomial
namespace subalgebra
open polynomial
section comm_semiring
variables {R A} [comm_semiring R] [comm_semiring A] [algebra R A]
@[simp] lemma aeval_coe (S : subalgebra R A) (x : S) (p : R[X]) :
aeval (x : A) p = aeval x p :=
aeval_algebra_map_apply A x p
end comm_semiring
end subalgebra
|
b033018cae2b7991b236a9958e6244ad3253b9b9 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/ring_theory/algebra.lean | 84b3480117febf3cb4e5bf271a608d80371c74d0 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 44,646 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import data.matrix.basic
import linear_algebra.tensor_product
import ring_theory.subsemiring
/-!
# Algebra over Commutative Semiring (under category)
In this file we define algebra over commutative (semi)rings, algebra homomorphisms `alg_hom`,
algebra equivalences `alg_equiv`, and `subalgebra`s. We also define usual operations on `alg_hom`s
(`id`, `comp`) and subalgebras (`map`, `comap`).
If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used
to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now
deprecated and replcaed with `is_algebra_tower`.
## Notations
* `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`.
* `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`.
-/
noncomputable theory
universes u v w u₁ v₁
open_locale tensor_product big_operators
section prio
-- We set this priority to 0 later in this file
set_option default_priority 200 -- see Note [default priority]
/-- The category of R-algebras where R is a commutative
ring is the under category R ↓ CRing. In the categorical
setting we have a forgetful functor R-Alg ⥤ R-Mod.
However here it extends module in order to preserve
definitional equality in certain cases. -/
@[nolint has_inhabited_instance]
class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A]
extends has_scalar R A, R →+* A :=
(commutes' : ∀ r x, to_fun r * x = x * to_fun r)
(smul_def' : ∀ r x, r • x = to_fun r * x)
end prio
/-- Embedding `R →+* A` given by `algebra` structure. -/
def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A :=
algebra.to_ring_hom
/-- Creating an algebra from a morphism to the center of a semiring. -/
def ring_hom.to_algebra' {R S} [comm_semiring R] [semiring S] (i : R →+* S)
(h : ∀ c x, i c * x = x * i c) :
algebra R S :=
{ smul := λ c x, i c * x,
commutes' := h,
smul_def' := λ c x, rfl,
.. i}
/-- Creating an algebra from a morphism to a commutative semiring. -/
def ring_hom.to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) :
algebra R S :=
i.to_algebra' $ λ _, mul_comm _
namespace algebra
variables {R : Type u} {S : Type v} {A : Type w}
/-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure.
If `(r • 1) * x = x * (r • 1) = r • x` for all `r : R` and `x : A`, then `A` is an `algebra`
over `R`. -/
def of_semimodule' [comm_semiring R] [semiring A] [semimodule R A]
(h₁ : ∀ (r : R) (x : A), (r • 1) * x = r • x)
(h₂ : ∀ (r : R) (x : A), x * (r • 1) = r • x) : algebra R A :=
{ to_fun := λ r, r • 1,
map_one' := one_smul _ _,
map_mul' := λ r₁ r₂, by rw [h₁, mul_smul],
map_zero' := zero_smul _ _,
map_add' := λ r₁ r₂, add_smul r₁ r₂ 1,
commutes' := λ r x, by simp only [h₁, h₂],
smul_def' := λ r x, by simp only [h₁] }
/-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure.
If `(r • x) * y = x * (r • y) = r • (x * y)` for all `r : R` and `x y : A`, then `A`
is an `algebra` over `R`. -/
def of_semimodule [comm_semiring R] [semiring A] [semimodule R A]
(h₁ : ∀ (r : R) (x y : A), (r • x) * y = r • (x * y))
(h₂ : ∀ (r : R) (x y : A), x * (r • y) = r • (x * y)) : algebra R A :=
of_semimodule' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one])
section semiring
variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R A]
lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x :=
algebra.smul_def' r x
/--
To prove two algebra structures on a fixed `[comm_semiring R] [semiring A]` agree,
it suffices to check the `algebra_map`s agree.
-/
-- We'll later use this to show `algebra ℤ M` is a subsingleton.
@[ext]
lemma algebra_ext {R : Type*} [comm_semiring R] {A : Type*} [semiring A] (P Q : algebra R A)
(w : ∀ (r : R), by { haveI := P, exact algebra_map R A r } = by { haveI := Q, exact algebra_map R A r }) :
P = Q :=
begin
unfreezingI { rcases P with ⟨⟨P⟩⟩, rcases Q with ⟨⟨Q⟩⟩ },
congr,
{ funext r a,
replace w := congr_arg (λ s, s * a) (w r),
simp only [←algebra.smul_def''] at w,
apply w, },
{ ext r,
exact w r, },
{ apply proof_irrel_heq, },
{ apply proof_irrel_heq, },
end
@[priority 200] -- see Note [lower instance priority]
instance to_semimodule : semimodule R A :=
{ one_smul := by simp [smul_def''],
mul_smul := by simp [smul_def'', mul_assoc],
smul_add := by simp [smul_def'', mul_add],
smul_zero := by simp [smul_def''],
add_smul := by simp [smul_def'', add_mul],
zero_smul := by simp [smul_def''] }
-- from now on, we don't want to use the following instance anymore
attribute [instance, priority 0] algebra.to_has_scalar
lemma smul_def (r : R) (x : A) : r • x = algebra_map R A r * x :=
algebra.smul_def' r x
lemma algebra_map_eq_smul_one (r : R) : algebra_map R A r = r • 1 :=
calc algebra_map R A r = algebra_map R A r * 1 : (mul_one _).symm
... = r • 1 : (algebra.smul_def r 1).symm
theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r :=
algebra.commutes' r x
theorem left_comm (r : R) (x y : A) : x * (algebra_map R A r * y) = algebra_map R A r * (x * y) :=
by rw [← mul_assoc, ← commutes, mul_assoc]
@[simp] lemma mul_smul_comm (s : R) (x y : A) :
x * (s • y) = s • (x * y) :=
by rw [smul_def, smul_def, left_comm]
@[simp] lemma smul_mul_assoc (r : R) (x y : A) :
(r • x) * y = r • (x * y) :=
by rw [smul_def, smul_def, mul_assoc]
variables (R)
instance id : algebra R R := (ring_hom.id R).to_algebra
variables {R}
namespace id
@[simp] lemma map_eq_self (x : R) : algebra_map R R x = x := rfl
@[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl
end id
/-- Algebra over a subsemiring. -/
instance of_subsemiring (S : subsemiring R) : algebra S A :=
{ smul := λ s x, (s : R) • x,
commutes' := λ r x, algebra.commutes r x,
smul_def' := λ r x, algebra.smul_def r x,
.. (algebra_map R A).comp (subsemiring.subtype S) }
/-- Algebra over a subring. -/
instance of_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A]
(S : set R) [is_subring S] : algebra S A :=
{ smul := λ s x, (s : R) • x,
commutes' := λ r x, algebra.commutes r x,
smul_def' := λ r x, algebra.smul_def r x,
.. (algebra_map R A).comp (⟨coe, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ : S →+* R) }
variables (R A)
/-- The multiplication in an algebra is a bilinear map. -/
def lmul : A →ₗ A →ₗ A :=
linear_map.mk₂ R (*)
(λ x y z, add_mul x y z)
(λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y])
(λ x y z, mul_add x y z)
(λ c x y, by rw [smul_def, smul_def, left_comm])
/-- The multiplication on the left in an algebra is a linear map. -/
def lmul_left (r : A) : A →ₗ A :=
lmul R A r
/-- The multiplication on the right in an algebra is a linear map. -/
def lmul_right (r : A) : A →ₗ A :=
(lmul R A).flip r
variables {R A}
@[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl
@[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl
@[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl
end semiring
end algebra
instance module.endomorphism_algebra (R : Type u) (M : Type v)
[comm_ring R] [add_comm_group M] [module R M] : algebra R (M →ₗ[R] M) :=
{ to_fun := λ r, r • linear_map.id,
map_one' := one_smul _ _,
map_zero' := zero_smul _ _,
map_add' := λ r₁ r₂, add_smul _ _ _,
map_mul' := λ r₁ r₂, by { ext x, simp [mul_smul] },
commutes' := by { intros, ext, simp },
smul_def' := by { intros, ext, simp } }
instance matrix_algebra (n : Type u) (R : Type v)
[fintype n] [decidable_eq n] [comm_semiring R] : algebra R (matrix n n R) :=
{ commutes' := by { intros, simp [matrix.scalar], },
smul_def' := by { intros, simp [matrix.scalar], },
..(matrix.scalar n) }
set_option old_structure_cmd true
/-- Defining the homomorphism in the category R-Alg. -/
@[nolint has_inhabited_instance]
structure alg_hom (R : Type u) (A : Type v) (B : Type w)
[comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B :=
(commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r)
run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`"
infixr ` →ₐ `:25 := alg_hom _
notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁}
section semiring
variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D]
variables [algebra R A] [algebra R B] [algebra R C] [algebra R D]
instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩
instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩
instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩
instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩
@[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) :
⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl
@[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl
-- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute.
@[norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl
-- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute.
@[norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl
variables (φ : A →ₐ[R] B)
theorem coe_fn_inj ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ⇑φ₁ = φ₂) : φ₁ = φ₂ :=
by { cases φ₁, cases φ₂, congr, exact H }
theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) :=
λ φ₁ φ₂ H, coe_fn_inj $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B),
from congr_arg _ H
theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →* B)) :=
ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective
theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) :=
ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective
@[ext]
theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ :=
coe_fn_inj $ funext H
theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x :=
⟨by { rintro rfl x, refl }, ext⟩
@[simp]
theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r
theorem comp_algebra_map : φ.to_ring_hom.comp (algebra_map R A) = algebra_map R B :=
ring_hom.ext $ φ.commutes
@[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s :=
φ.to_ring_hom.map_add r s
@[simp] lemma map_zero : φ 0 = 0 :=
φ.to_ring_hom.map_zero
@[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y :=
φ.to_ring_hom.map_mul x y
@[simp] lemma map_one : φ 1 = 1 :=
φ.to_ring_hom.map_one
@[simp] lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x :=
by simp only [algebra.smul_def, map_mul, commutes]
@[simp] lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n :=
φ.to_ring_hom.map_pow x n
lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) :
φ (∑ x in s, f x) = ∑ x in s, φ (f x) :=
φ.to_ring_hom.map_sum f s
@[simp] lemma map_nat_cast (n : ℕ) : φ n = n :=
φ.to_ring_hom.map_nat_cast n
section
variables (R A)
/-- Identity map as an `alg_hom`. -/
protected def id : A →ₐ[R] A :=
{ commutes' := λ _, rfl,
..ring_hom.id A }
end
@[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl
/-- Composition of algebra homeomorphisms. -/
def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C :=
{ commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl,
.. φ₁.to_ring_hom.comp ↑φ₂ }
@[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) :
φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl
@[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ :=
ext $ λ x, rfl
@[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ :=
ext $ λ x, rfl
theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) :
(φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) :=
ext $ λ x, rfl
/-- R-Alg ⥤ R-Mod -/
def to_linear_map : A →ₗ B :=
{ to_fun := φ,
map_add' := φ.map_add,
map_smul' := φ.map_smul }
@[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl
theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ :=
ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H
@[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) :
(g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [comm_semiring B]
variables [algebra R A] [algebra R B]
variables (φ : A →ₐ[R] B)
lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) :
φ (∏ x in s, f x) = ∏ x in s, φ (f x) :=
φ.to_ring_hom.map_prod f s
end comm_semiring
section ring
variables [comm_ring R] [ring A] [ring B] [ring C]
variables [algebra R A] [algebra R B] [algebra R C] (φ : A →ₐ[R] B)
@[simp] lemma map_neg (x) : φ (-x) = -φ x :=
φ.to_ring_hom.map_neg x
@[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y :=
φ.to_ring_hom.map_sub x y
end ring
end alg_hom
set_option old_structure_cmd true
/-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/
structure alg_equiv (R : Type u) (A : Type v) (B : Type w)
[comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B :=
(commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r)
attribute [nolint doc_blame] alg_equiv.to_ring_equiv
attribute [nolint doc_blame] alg_equiv.to_equiv
attribute [nolint doc_blame] alg_equiv.to_add_equiv
attribute [nolint doc_blame] alg_equiv.to_mul_equiv
notation A ` ≃ₐ[`:50 R `] ` A' := alg_equiv R A A'
namespace alg_equiv
variables {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁}
variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃]
variables [algebra R A₁] [algebra R A₂] [algebra R A₃]
instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) := ⟨_, alg_equiv.to_fun⟩
@[ext]
lemma ext {f g : A₁ ≃ₐ[R] A₂} (h : ∀ a, f a = g a) : f = g :=
begin
have h₁ : f.to_equiv = g.to_equiv := equiv.ext h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
lemma coe_fun_injective : @function.injective (A₁ ≃ₐ[R] A₂) (A₁ → A₂) (λ e, (e : A₁ → A₂)) :=
begin
intros f g w,
ext,
exact congr_fun w a,
end
instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) := ⟨alg_equiv.to_ring_equiv⟩
@[simp] lemma mk_apply {to_fun inv_fun left_inv right_inv map_mul map_add commutes a} :
(⟨to_fun, inv_fun, left_inv, right_inv, map_mul, map_add, commutes⟩ : A₁ ≃ₐ[R] A₂) a = to_fun a :=
rfl
@[simp] lemma to_fun_apply {e : A₁ ≃ₐ[R] A₂} {a : A₁} : e.to_fun a = e a := rfl
@[simp, norm_cast] lemma coe_ring_equiv (e : A₁ ≃ₐ[R] A₂) : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl
lemma coe_ring_equiv_injective : function.injective (λ e : A₁ ≃ₐ[R] A₂, (e : A₁ ≃+* A₂)) :=
begin
intros f g w,
ext,
replace w : ((f : A₁ ≃+* A₂) : A₁ → A₂) = ((g : A₁ ≃+* A₂) : A₁ → A₂) :=
congr_arg (λ e : A₁ ≃+* A₂, (e : A₁ → A₂)) w,
exact congr_fun w a,
end
@[simp] lemma map_add (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add
@[simp] lemma map_zero (e : A₁ ≃ₐ[R] A₂) : e 0 = 0 := e.to_add_equiv.map_zero
@[simp] lemma map_mul (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul
@[simp] lemma map_one (e : A₁ ≃ₐ[R] A₂) : e 1 = 1 := e.to_mul_equiv.map_one
@[simp] lemma commutes (e : A₁ ≃ₐ[R] A₂) : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r :=
e.commutes'
@[simp] lemma map_neg {A₁ : Type v} {A₂ : Type w}
[ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) :
∀ x, e (-x) = -(e x) := e.to_add_equiv.map_neg
@[simp] lemma map_sub {A₁ : Type v} {A₂ : Type w}
[ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) :
∀ x y, e (x - y) = e x - e y := e.to_add_equiv.map_sub
lemma map_sum (e : A₁ ≃ₐ[R] A₂) {ι : Type*} (f : ι → A₁) (s : finset ι) :
e (∑ x in s, f x) = ∑ x in s, e (f x) :=
e.to_add_equiv.map_sum f s
instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) :=
⟨λ e, { map_one' := e.map_one, map_zero' := e.map_zero, ..e }⟩
@[simp, norm_cast] lemma coe_alg_hom (e : A₁ ≃ₐ[R] A₂) : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e :=
rfl
lemma injective (e : A₁ ≃ₐ[R] A₂) : function.injective e := e.to_equiv.injective
lemma surjective (e : A₁ ≃ₐ[R] A₂) : function.surjective e := e.to_equiv.surjective
lemma bijective (e : A₁ ≃ₐ[R] A₂) : function.bijective e := e.to_equiv.bijective
instance : has_one (A₁ ≃ₐ[R] A₁) := ⟨{commutes' := λ r, rfl, ..(1 : A₁ ≃+* A₁)}⟩
instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨1⟩
/-- Algebra equivalences are reflexive. -/
@[refl]
def refl : A₁ ≃ₐ[R] A₁ := 1
@[simp] lemma coe_refl : (@refl R A₁ _ _ _ : A₁ →ₐ[R] A₁) = alg_hom.id R A₁ :=
alg_hom.ext (λ x, rfl)
/-- Algebra equivalences are symmetric. -/
@[symm]
def symm (e : A₁ ≃ₐ[R] A₂) : A₂ ≃ₐ[R] A₁ :=
{ commutes' := λ r, by { rw ←e.to_ring_equiv.symm_apply_apply (algebra_map R A₁ r), congr,
change _ = e _, rw e.commutes, },
..e.to_ring_equiv.symm, }
@[simp] lemma inv_fun_apply {e : A₁ ≃ₐ[R] A₂} {a : A₂} : e.inv_fun a = e.symm a := rfl
@[simp] lemma symm_symm {e : A₁ ≃ₐ[R] A₂} : e.symm.symm = e :=
by { ext, refl, }
/-- Algebra equivalences are transitive. -/
@[trans]
def trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ :=
{ commutes' := λ r, show e₂.to_fun (e₁.to_fun _) = _, by rw [e₁.commutes', e₂.commutes'],
..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), }
@[simp] lemma apply_symm_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (e.symm x) = x :=
e.to_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e.symm (e x) = x :=
e.to_equiv.symm_apply_apply
@[simp] lemma trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₁) :
(e₁.trans e₂) x = e₂ (e₁ x) := rfl
@[simp] lemma comp_symm (e : A₁ ≃ₐ[R] A₂) :
alg_hom.comp (e : A₁ →ₐ[R] A₂) ↑e.symm = alg_hom.id R A₂ :=
by { ext, simp }
@[simp] lemma symm_comp (e : A₁ ≃ₐ[R] A₂) :
alg_hom.comp ↑e.symm (e : A₁ →ₐ[R] A₂) = alg_hom.id R A₁ :=
by { ext, simp }
/-- If an algebra morphism has an inverse, it is a algebra isomorphism. -/
def of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ : f.comp g = alg_hom.id R A₂) (h₂ : g.comp f = alg_hom.id R A₁) : A₁ ≃ₐ[R] A₂ :=
{ inv_fun := g,
left_inv := alg_hom.ext_iff.1 h₂,
right_inv := alg_hom.ext_iff.1 h₁,
..f }
end alg_equiv
namespace algebra
variables (R : Type u) (S : Type v) (A : Type w)
include R S A
/-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it
when `algebra R S` and `algebra S A`. If `S` is an `R`-algebra and `A` is an `S`-algebra then
`algebra.comap.algebra R S A` can be used to provide `A` with a structure of an `R`-algebra.
Other than that, `algebra.comap` is now deprecated and replcaed with `is_algebra_tower`. -/
/- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and
`algebra ?m_1 A -/
/- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the
appropriate type classes -/
@[nolint unused_arguments]
def comap : Type w := A
instance comap.inhabited [h : inhabited A] : inhabited (comap R S A) := h
instance comap.semiring [h : semiring A] : semiring (comap R S A) := h
instance comap.ring [h : ring A] : ring (comap R S A) := h
instance comap.comm_semiring [h : comm_semiring A] : comm_semiring (comap R S A) := h
instance comap.comm_ring [h : comm_ring A] : comm_ring (comap R S A) := h
instance comap.algebra' [comm_semiring S] [semiring A] [h : algebra S A] :
algebra S (comap R S A) := h
/-- Identity homomorphism `A →ₐ[S] comap R S A`. -/
def comap.to_comap [comm_semiring S] [semiring A] [algebra S A] :
A →ₐ[S] comap R S A := alg_hom.id S A
/-- Identity homomorphism `comap R S A →ₐ[S] A`. -/
def comap.of_comap [comm_semiring S] [semiring A] [algebra S A] :
comap R S A →ₐ[S] A := alg_hom.id S A
variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A]
/-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/
instance comap.algebra : algebra R (comap R S A) :=
{ smul := λ r x, (algebra_map R S r • x : A),
commutes' := λ r x, algebra.commutes _ _,
smul_def' := λ _ _, algebra.smul_def _ _,
.. (algebra_map S A).comp (algebra_map R S) }
/-- Embedding of `S` into `comap R S A`. -/
def to_comap : S →ₐ[R] comap R S A :=
{ commutes' := λ r, rfl,
.. algebra_map S A }
theorem to_comap_apply (x) : to_comap R S A x = algebra_map S A x := rfl
end algebra
namespace alg_hom
variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁}
variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B]
variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B)
include R
/-- R ⟶ S induces S-Alg ⥤ R-Alg -/
def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B :=
{ commutes' := λ r, φ.commutes (algebra_map R S r)
..φ }
end alg_hom
namespace rat
instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α :=
(rat.cast_hom α).to_algebra' $ λ r x, r.cast_commute x
end rat
/-- A subalgebra is a subring that includes the range of `algebra_map`. -/
structure subalgebra (R : Type u) (A : Type v)
[comm_semiring R] [semiring A] [algebra R A] : Type v :=
(carrier : subsemiring A)
(algebra_map_mem' : ∀ r, algebra_map R A r ∈ carrier)
namespace subalgebra
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
include R
instance : has_coe (subalgebra R A) (subsemiring A) :=
⟨λ S, S.carrier⟩
instance : has_mem A (subalgebra R A) :=
⟨λ x S, x ∈ (S : set A)⟩
variables {A}
theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s :=
iff.rfl
@[ext] theorem ext {S T : subalgebra R A}
(h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T :=
by cases S; cases T; congr; ext x; exact h x
theorem ext_iff {S T : subalgebra R A} : S = T ↔ ∀ x : A, x ∈ S ↔ x ∈ T :=
⟨λ h x, by rw h, ext⟩
variables (S : subalgebra R A)
theorem algebra_map_mem (r : R) : algebra_map R A r ∈ S :=
S.algebra_map_mem' r
theorem srange_le : (algebra_map R A).srange ≤ S :=
λ x ⟨r, _, hr⟩, hr ▸ S.algebra_map_mem r
theorem range_subset : set.range (algebra_map R A) ⊆ S :=
λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r
theorem range_le : set.range (algebra_map R A) ≤ S :=
S.range_subset
theorem one_mem : (1 : A) ∈ S :=
subsemiring.one_mem S
theorem mul_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x * y ∈ S :=
subsemiring.mul_mem S hx hy
theorem smul_mem {x : A} (hx : x ∈ S) (r : R) : r • x ∈ S :=
(algebra.smul_def r x).symm ▸ S.mul_mem (S.algebra_map_mem r) hx
theorem pow_mem {x : A} (hx : x ∈ S) (n : ℕ) : x ^ n ∈ S :=
subsemiring.pow_mem S hx n
theorem zero_mem : (0 : A) ∈ S :=
subsemiring.zero_mem S
theorem add_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x + y ∈ S :=
subsemiring.add_mem S hx hy
theorem neg_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) : -x ∈ S :=
neg_one_smul R x ▸ S.smul_mem hx _
theorem sub_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S :=
S.add_mem hx $ S.neg_mem hy
theorem nsmul_mem {x : A} (hx : x ∈ S) (n : ℕ) : n •ℕ x ∈ S :=
subsemiring.nsmul_mem S hx n
theorem gsmul_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) (n : ℤ) : n •ℤ x ∈ S :=
int.cases_on n (λ i, S.nsmul_mem hx i) (λ i, S.neg_mem $ S.nsmul_mem hx _)
theorem coe_nat_mem (n : ℕ) : (n : A) ∈ S :=
subsemiring.coe_nat_mem S n
theorem coe_int_mem {R : Type u} {A : Type v} [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) (n : ℤ) : (n : A) ∈ S :=
int.cases_on n (λ i, S.coe_nat_mem i) (λ i, S.neg_mem $ S.coe_nat_mem $ i + 1)
theorem list_prod_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.prod ∈ S :=
subsemiring.list_prod_mem S h
theorem list_sum_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.sum ∈ S :=
subsemiring.list_sum_mem S h
theorem multiset_prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.prod ∈ S :=
subsemiring.multiset_prod_mem S m h
theorem multiset_sum_mem {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.sum ∈ S :=
subsemiring.multiset_sum_mem S m h
theorem prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) {ι : Type w} {t : finset ι} {f : ι → A}
(h : ∀ x ∈ t, f x ∈ S) : ∏ x in t, f x ∈ S :=
subsemiring.prod_mem S h
theorem sum_mem {ι : Type w} {t : finset ι} {f : ι → A}
(h : ∀ x ∈ t, f x ∈ S) : ∑ x in t, f x ∈ S :=
subsemiring.sum_mem S h
instance {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
(S : subalgebra R A) : is_add_submonoid (S : set A) :=
{ zero_mem := S.zero_mem,
add_mem := λ _ _, S.add_mem }
instance {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A]
(S : subalgebra R A) : is_submonoid (S : set A) :=
{ one_mem := S.one_mem,
mul_mem := λ _ _, S.mul_mem }
instance {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) :
is_subring (S : set A) :=
{ neg_mem := λ _, S.neg_mem }
instance : inhabited S := ⟨0⟩
instance (R : Type u) (A : Type v) [comm_semiring R] [semiring A]
[algebra R A] (S : subalgebra R A) : semiring S := subsemiring.to_semiring S
instance (R : Type u) (A : Type v) [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) : comm_semiring S := subsemiring.to_comm_semiring S
instance (R : Type u) (A : Type v) [comm_ring R] [ring A]
[algebra R A] (S : subalgebra R A) : ring S := @@subtype.ring _ S.is_subring
instance (R : Type u) (A : Type v) [comm_ring R] [comm_ring A]
[algebra R A] (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring
instance algebra : algebra R S :=
{ smul := λ (c:R) x, ⟨c • x.1, S.smul_mem x.2 c⟩,
commutes' := λ c x, subtype.eq $ algebra.commutes _ _,
smul_def' := λ c x, subtype.eq $ algebra.smul_def _ _,
.. (algebra_map R A).cod_srestrict S $ λ x, S.range_le ⟨x, rfl⟩ }
instance to_algebra {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
[algebra R A] (S : subalgebra R A) : algebra S A :=
algebra.of_subsemiring _
-- todo: standardize on the names these morphisms
-- compare with submodule.subtype
/-- Embedding of a subalgebra into the algebra. -/
def val : S →ₐ[R] A :=
by refine_struct { to_fun := (coe : S → A) }; intros; refl
@[simp]
lemma val_apply (x : S) : S.val x = (x : A) := rfl
/-- Convert a `subalgebra` to `submodule` -/
def to_submodule : submodule R A :=
{ carrier := S,
zero_mem' := (0:S).2,
add_mem' := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2,
smul_mem' := λ c x hx, (algebra.smul_def c x).symm ▸
(⟨algebra_map R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 }
instance coe_to_submodule : has_coe (subalgebra R A) (submodule R A) :=
⟨to_submodule⟩
instance to_submodule.is_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A]
(S : subalgebra R A) : is_subring ((S : submodule R A) : set A) := S.is_subring
@[simp] lemma mem_to_submodule {x} : x ∈ (S : submodule R A) ↔ x ∈ S := iff.rfl
theorem to_submodule_injective {S U : subalgebra R A} (h : (S : submodule R A) = U) : S = U :=
ext $ λ x, by rw [← mem_to_submodule, ← mem_to_submodule, h]
theorem to_submodule_inj {S U : subalgebra R A} : (S : submodule R A) = U ↔ S = U :=
⟨to_submodule_injective, congr_arg _⟩
instance : partial_order (subalgebra R A) :=
{ le := λ S T, (S : set A) ⊆ (T : set A),
le_refl := λ S, set.subset.refl S,
le_trans := λ _ _ _, set.subset.trans,
le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ }
/-- Reinterpret an `S`-subalgebra as an `R`-subalgebra in `comap R S A`. -/
def comap {R : Type u} {S : Type v} {A : Type w}
[comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A]
(iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) :=
{ carrier := (iSB : subsemiring A),
algebra_map_mem' := λ r, iSB.algebra_map_mem (algebra_map R S r) }
/-- If `S` is an `R`-subalgebra of `A` and `T` is an `S`-subalgebra of `A`,
then `T` is an `R`-subalgebra of `A`. -/
def under {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A]
{i : algebra R A} (S : subalgebra R A)
(T : subalgebra S A) : subalgebra R A :=
{ carrier := T,
algebra_map_mem' := λ r, T.algebra_map_mem ⟨algebra_map R A r, S.algebra_map_mem r⟩ }
/-- Transport a subalgebra via an algebra homomorphism. -/
def map (S : subalgebra R A) (f : A →ₐ[R] B) : subalgebra R B :=
{ carrier := subsemiring.map (f : A →+* B) S,
algebra_map_mem' := λ r, f.commutes r ▸ set.mem_image_of_mem _ (S.algebra_map_mem r) }
/-- Preimage of a subalgebra under an algebra homomorphism. -/
def comap' (S : subalgebra R B) (f : A →ₐ[R] B) : subalgebra R A :=
{ carrier := subsemiring.comap (f : A →+* B) S,
algebra_map_mem' := λ r, show f (algebra_map R A r) ∈ S,
from (f.commutes r).symm ▸ S.algebra_map_mem r }
theorem map_le {S : subalgebra R A} {f : A →ₐ[R] B} {U : subalgebra R B} :
map S f ≤ U ↔ S ≤ comap' U f :=
set.image_subset_iff
end subalgebra
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
variables (φ : A →ₐ[R] B)
/-- Range of an `alg_hom` as a subalgebra. -/
protected def range (φ : A →ₐ[R] B) : subalgebra R B :=
{ carrier :=
{ carrier := set.range φ,
one_mem' := ⟨1, φ.map_one⟩,
mul_mem' := λ _ _ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x * y, by rw [φ.map_mul, hx, hy]⟩,
zero_mem' := ⟨0, φ.map_zero⟩,
add_mem' := λ _ _ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x + y, by rw [φ.map_add, hx, hy]⟩ },
algebra_map_mem' := λ r, ⟨algebra_map R A r, φ.commutes r⟩ }
end alg_hom
namespace algebra
variables (R : Type u) (A : Type v)
variables [comm_semiring R] [semiring A] [algebra R A]
/-- `algebra_map` as an `alg_hom`. -/
def of_id : R →ₐ[R] A :=
{ commutes' := λ _, rfl, .. algebra_map R A }
variables {R}
theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl
end algebra
namespace algebra
variables (R : Type u) {A : Type v} {B : Type w}
variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B]
/-- The minimal subalgebra that includes `s`. -/
def adjoin (s : set A) : subalgebra R A :=
{ carrier := subsemiring.closure (set.range (algebra_map R A) ∪ s),
algebra_map_mem' := λ r, subsemiring.subset_closure $ or.inl ⟨r, rfl⟩ }
variables {R}
protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe :=
λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subsemiring.subset_closure) H,
λ H, subsemiring.closure_le.2 $ set.union_subset S.range_subset H⟩
/-- Galois insertion between `adjoin` and `coe`. -/
protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe :=
{ choice := λ s hs, adjoin R s,
gc := algebra.gc,
le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _,
choice_eq := λ _ _, rfl }
instance : complete_lattice (subalgebra R A) :=
galois_insertion.lift_complete_lattice algebra.gi
instance : inhabited (subalgebra R A) := ⟨⊥⟩
theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map R A) :=
suffices (⊥ : subalgebra R A) = (of_id R A).range, by rw this; refl,
le_antisymm bot_le $ subalgebra.range_le _
theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) :=
subsemiring.subset_closure $ or.inr trivial
@[simp] theorem coe_top : ((⊤ : subalgebra R A) : submodule R A) = ⊤ :=
submodule.ext $ λ x, iff_of_true mem_top trivial
theorem eq_top_iff {S : subalgebra R A} :
S = ⊤ ↔ ∀ x : A, x ∈ S :=
⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩
@[simp] theorem map_top (f : A →ₐ[R] B) : subalgebra.map (⊤ : subalgebra R A) f = f.range :=
subalgebra.ext $ λ x, ⟨λ ⟨y, _, hy⟩, ⟨y, hy⟩, λ ⟨y, hy⟩, ⟨y, algebra.mem_top, hy⟩⟩
@[simp] theorem map_bot (f : A →ₐ[R] B) : subalgebra.map (⊥ : subalgebra R A) f = ⊥ :=
eq_bot_iff.2 $ λ x ⟨y, hy, hfy⟩, let ⟨r, hr⟩ := mem_bot.1 hy in subalgebra.range_le _
⟨r, by rwa [← f.commutes, hr]⟩
@[simp] theorem comap_top (f : A →ₐ[R] B) : subalgebra.comap' (⊤ : subalgebra R B) f = ⊤ :=
eq_top_iff.2 $ λ x, mem_top
/-- `alg_hom` to `⊤ : subalgebra R A`. -/
def to_top : A →ₐ[R] (⊤ : subalgebra R A) :=
by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl
end algebra
section nat
variables (R : Type*) [semiring R]
/-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/
def alg_hom_nat
{R : Type u} [semiring R] [algebra ℕ R]
{S : Type v} [semiring S] [algebra ℕ S]
(f : R →+* S) : R →ₐ[ℕ] S :=
{ commutes' := λ i, show f _ = _, by simp, .. f }
/-- Semiring ⥤ ℕ-Alg -/
instance algebra_nat : algebra ℕ R :=
{ commutes' := nat.cast_commute,
smul_def' := λ _ _, nsmul_eq_mul _ _,
.. nat.cast_ring_hom R }
variables {R}
/-- A subsemiring is a `ℕ`-subalgebra. -/
def subalgebra_of_subsemiring (S : subsemiring R) : subalgebra ℕ R :=
{ carrier := S,
algebra_map_mem' := λ i, S.coe_nat_mem i }
@[simp] lemma mem_subalgebra_of_subsemiring {x : R} {S : subsemiring R} :
x ∈ subalgebra_of_subsemiring S ↔ x ∈ S :=
iff.rfl
section span_nat
open submodule
lemma span_nat_eq_add_group_closure (s : set R) :
(span ℕ s).to_add_submonoid = add_submonoid.closure s :=
eq.symm $ add_submonoid.closure_eq_of_le subset_span $ λ x hx, span_induction hx
(λ x hx, add_submonoid.subset_closure hx) (add_submonoid.zero_mem _)
(λ _ _, add_submonoid.add_mem _) (λ _ _ _, add_submonoid.nsmul_mem _ ‹_› _)
@[simp] lemma span_nat_eq (s : add_submonoid R) : (span ℕ (s : set R)).to_add_submonoid = s :=
by rw [span_nat_eq_add_group_closure, s.closure_eq]
end span_nat
end nat
section int
variables (R : Type*) [ring R]
/-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/
def alg_hom_int
{R : Type u} [comm_ring R] [algebra ℤ R]
{S : Type v} [comm_ring S] [algebra ℤ S]
(f : R →+* S) : R →ₐ[ℤ] S :=
{ commutes' := λ i, show f _ = _, by simp, .. f }
/-- Ring ⥤ ℤ-Alg -/
instance algebra_int : algebra ℤ R :=
{ commutes' := int.cast_commute,
smul_def' := λ _ _, gsmul_eq_mul _ _,
.. int.cast_ring_hom R }
/--
Promote a ring homomorphisms to a `ℤ`-algebra homomorphism.
-/
def ring_hom.to_int_alg_hom {R S : Type*} [ring R] [ring S] (f : R →+* S) : R →ₐ[ℤ] S :=
{ commutes' := λ n, by simp,
.. f }
variables {R}
/-- A subring is a `ℤ`-subalgebra. -/
def subalgebra_of_subring (S : set R) [is_subring S] : subalgebra ℤ R :=
{ carrier :=
{ carrier := S,
one_mem' := is_submonoid.one_mem,
mul_mem' := λ _ _, is_submonoid.mul_mem,
zero_mem' := is_add_submonoid.zero_mem,
add_mem' := λ _ _, is_add_submonoid.add_mem, },
algebra_map_mem' := λ i, int.induction_on i (show (0 : R) ∈ S, from is_add_submonoid.zero_mem)
(λ i ih, show (i + 1 : R) ∈ S, from is_add_submonoid.add_mem ih is_submonoid.one_mem)
(λ i ih, show ((-i - 1 : ℤ) : R) ∈ S, by { rw [int.cast_sub, int.cast_one],
exact is_add_subgroup.sub_mem S _ _ ih is_submonoid.one_mem }) }
section
variables {S : Type*} [ring S]
instance int_algebra_subsingleton : subsingleton (algebra ℤ S) :=
⟨λ P Q, by { ext, simp, }⟩
end
section
variables {S : Type*} [semiring S]
instance nat_algebra_subsingleton : subsingleton (algebra ℕ S) :=
⟨λ P Q, by { ext, simp, }⟩
end
@[simp] lemma mem_subalgebra_of_subring {x : R} {S : set R} [is_subring S] :
x ∈ subalgebra_of_subring S ↔ x ∈ S :=
iff.rfl
section span_int
open submodule
lemma span_int_eq_add_group_closure (s : set R) :
(span ℤ s).to_add_subgroup = add_subgroup.closure s :=
eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ λ x hx, span_induction hx
(λ x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _)
(λ _ _, add_subgroup.add_mem _) (λ _ _ _, add_subgroup.gsmul_mem _ ‹_› _)
@[simp] lemma span_int_eq (s : add_subgroup R) : (span ℤ (s : set R)).to_add_subgroup = s :=
by rw [span_int_eq_add_group_closure, s.closure_eq]
end span_int
end int
section restrict_scalars
/- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then
`S`-modules are also `R`-modules. -/
variables (R : Type*) [comm_ring R] (S : Type*) [ring S] [algebra R S]
variables (E : Type*) [add_comm_group E] [module S E] {F : Type*} [add_comm_group F] [module S F]
/--
When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a
module structure over `R`, called `module.restrict_scalars' R S E`.
We do not register this as an instance as `S` can not be inferred.
-/
def module.restrict_scalars' : module R E :=
{ smul := λ c x, (algebra_map R S c) • x,
one_smul := by simp,
mul_smul := by simp [mul_smul],
smul_add := by simp [smul_add],
smul_zero := by simp [smul_zero],
add_smul := by simp [add_smul],
zero_smul := by simp [zero_smul] }
/--
When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a
module structure over `R`, provided as a type synonym `module.restrict_scalars R S E := E`.
-/
@[nolint unused_arguments]
def module.restrict_scalars (R : Type*) (S : Type*) (E : Type*) : Type* := E
instance (R : Type*) (S : Type*) (E : Type*) [I : inhabited E] :
inhabited (module.restrict_scalars R S E) := I
instance (R : Type*) (S : Type*) (E : Type*) [I : add_comm_group E] :
add_comm_group (module.restrict_scalars R S E) := I
instance : module R (module.restrict_scalars R S E) :=
(module.restrict_scalars' R S E : module R E)
lemma module.restrict_scalars_smul_def (c : R) (x : module.restrict_scalars R S E) :
c • x = ((algebra_map R S c) • x : E) := rfl
/--
`module.restrict_scalars R S S` is `R`-linearly equivalent to the original algebra `S`.
Unfortunately these structures are not generally definitionally equal:
the `R`-module structure on `S` is part of the data of `S`,
while the `R`-module structure on `module.restrict_scalars R S S`
comes from the ring homomorphism `R →+* S`, which is a separate part of the data of `S`.
The field `algebra.smul_def'` gives the equation we need here.
-/
def algebra.restrict_scalars_equiv :
(module.restrict_scalars R S S) ≃ₗ[R] S :=
{ to_fun := λ s, s,
inv_fun := λ s, s,
left_inv := λ s, rfl,
right_inv := λ s, rfl,
map_add' := λ x y, rfl,
map_smul' := λ c x, (algebra.smul_def' _ _).symm, }
@[simp]
lemma algebra.restrict_scalars_equiv_apply (s : S) :
algebra.restrict_scalars_equiv R S s = s := rfl
@[simp]
lemma algebra.restrict_scalars_equiv_symm_apply (s : S) :
(algebra.restrict_scalars_equiv R S).symm s = s := rfl
variables {S E}
open module
/--
`V.restrict_scalars R` is the `R`-submodule of the `R`-module given by restriction of scalars,
corresponding to `V`, an `S`-submodule of the original `S`-module.
-/
@[simps]
def submodule.restrict_scalars (V : submodule S E) : submodule R (restrict_scalars R S E) :=
{ carrier := V.carrier,
zero_mem' := V.zero_mem,
smul_mem' := λ c e h, V.smul_mem _ h,
add_mem' := λ x y hx hy, V.add_mem hx hy, }
@[simp]
lemma submodule.restrict_scalars_mem (V : submodule S E) (e : E) :
e ∈ V.restrict_scalars R ↔ e ∈ V :=
iff.refl _
@[simp]
lemma submodule.restrict_scalars_bot :
submodule.restrict_scalars R (⊥ : submodule S E) = ⊥ :=
rfl
@[simp]
lemma submodule.restrict_scalars_top :
submodule.restrict_scalars R (⊤ : submodule S E) = ⊤ :=
rfl
/-- The `R`-linear map induced by an `S`-linear map when `S` is an algebra over `R`. -/
def linear_map.restrict_scalars (f : E →ₗ[S] F) :
(restrict_scalars R S E) →ₗ[R] (restrict_scalars R S F) :=
{ to_fun := f.to_fun,
map_add' := λx y, f.map_add x y,
map_smul' := λc x, f.map_smul (algebra_map R S c) x }
@[simp, norm_cast squash] lemma linear_map.coe_restrict_scalars_eq_coe (f : E →ₗ[S] F) :
(f.restrict_scalars R : E → F) = f := rfl
@[simp]
lemma restrict_scalars_ker (f : E →ₗ[S] F) :
(f.restrict_scalars R).ker = submodule.restrict_scalars R f.ker :=
rfl
variables (𝕜 : Type*) [field 𝕜] (𝕜' : Type*) [field 𝕜'] [algebra 𝕜 𝕜']
variables (W : Type*) [add_comm_group W] [vector_space 𝕜' W]
/--
`V.restrict_scalars 𝕜` is the `𝕜`-subspace of the `𝕜`-vector space given by restriction of scalars,
corresponding to `V`, a `𝕜'`-subspace of the original `𝕜'`-vector space.
-/
def subspace.restrict_scalars (V : subspace 𝕜' W) : subspace 𝕜 (restrict_scalars 𝕜 𝕜' W) :=
{ ..submodule.restrict_scalars 𝕜 (V : submodule 𝕜' W) }
end restrict_scalars
/-!
When `V` and `W` are `S`-modules, for some `R`-algebra `S`,
the collection of `S`-linear maps from `V` to `W` forms an `R`-module.
(But not generally an `S`-module, because `S` may be non-commutative.)
-/
section module_of_linear_maps
variables (R : Type*) [comm_ring R] (S : Type*) [ring S] [algebra R S]
(V : Type*) [add_comm_group V] [module S V]
(W : Type*) [add_comm_group W] [module S W]
/--
For `r : R`, and `f : V →ₗ[S] W` (where `S` is an `R`-algebra) we define
`(r • f) v = f (r • v)`.
-/
def linear_map_algebra_has_scalar : has_scalar R (V →ₗ[S] W) :=
{ smul := λ r f,
{ to_fun := λ v, f ((algebra_map R S r) • v),
map_add' := λ x y, by simp [smul_add],
map_smul' := λ s v, by simp [smul_smul, algebra.commutes], } }
local attribute [instance] linear_map_algebra_has_scalar
/-- The `R`-module structure on `S`-linear maps, for `S` an `R`-algebra. -/
def linear_map_algebra_module : module R (V →ₗ[S] W) :=
{ one_smul := λ f, begin ext v, dsimp [(•)], simp, end,
mul_smul := λ r r' f,
begin
ext v, dsimp [(•)],
rw [linear_map.map_smul, linear_map.map_smul, linear_map.map_smul, ring_hom.map_mul,
smul_smul, algebra.commutes],
end,
smul_zero := λ r, by { ext v, dsimp [(•)], refl, },
smul_add := λ r f g, by { ext v, dsimp [(•)], simp [linear_map.map_add], },
zero_smul := λ f, by { ext v, dsimp [(•)], simp, },
add_smul := λ r r' f, by { ext v, dsimp [(•)], simp [add_smul], }, }
local attribute [instance] linear_map_algebra_module
variables {R S V W}
@[simp]
lemma linear_map_algebra_module.smul_apply (c : R) (f : V →ₗ[S] W) (v : V) :
(c • f) v = (c • (f v) : module.restrict_scalars R S W) :=
begin
erw [linear_map.map_smul],
refl,
end
end module_of_linear_maps
|
25c5c81408a10182c5cd801398fb31e259560fd6 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/measure/null_measurable.lean | 1cdffc8d4a321d12ca76a80329de906d5f01a8f2 | [
"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 | 18,884 | 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 measure_theory.measure.ae_disjoint
/-!
# Null measurable sets and complete measures
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Main definitions
### Null measurable sets and functions
A set `s : set α` is called *null measurable* (`measure_theory.null_measurable_set`) if it satisfies
any of the following equivalent conditions:
* there exists a measurable set `t` such that `s =ᵐ[μ] t` (this is used as a definition);
* `measure_theory.to_measurable μ s =ᵐ[μ] s`;
* there exists a measurable subset `t ⊆ s` such that `t =ᵐ[μ] s` (in this case the latter equality
means that `μ (s \ t) = 0`);
* `s` can be represented as a union of a measurable set and a set of measure zero;
* `s` can be represented as a difference of a measurable set and a set of measure zero.
Null measurable sets form a σ-algebra that is registered as a `measurable_space` instance on
`measure_theory.null_measurable_space α μ`. We also say that `f : α → β` is
`measure_theory.null_measurable` if the preimage of a measurable set is a null measurable set.
In other words, `f : α → β` is null measurable if it is measurable as a function
`measure_theory.null_measurable_space α μ → β`.
### Complete measures
We say that a measure `μ` is complete w.r.t. the `measurable_space α` σ-algebra (or the σ-algebra is
complete w.r.t measure `μ`) if every set of measure zero is measurable. In this case all null
measurable sets and functions are measurable.
For each measure `μ`, we define `measure_theory.measure.completion μ` to be the same measure
interpreted as a measure on `measure_theory.null_measurable_space α μ` and prove that this is a
complete measure.
## Implementation notes
We define `measure_theory.null_measurable_set` as `@measurable_set (null_measurable_space α μ) _` so
that theorems about `measurable_set`s like `measurable_set.union` can be applied to
`null_measurable_set`s. However, these lemmas output terms of the same form
`@measurable_set (null_measurable_space α μ) _ _`. While this is definitionally equal to the
expected output `null_measurable_set s μ`, it looks different and may be misleading. So we copy all
standard lemmas about measurable sets to the `measure_theory.null_measurable_set` namespace and fix
the output type.
## Tags
measurable, measure, null measurable, completion
-/
open filter set encodable
variables {ι α β γ : Type*}
namespace measure_theory
/-- A type tag for `α` with `measurable_set` given by `null_measurable_set`. -/
@[nolint unused_arguments]
def null_measurable_space (α : Type*) [measurable_space α] (μ : measure α . volume_tac) : Type* := α
section
variables {m0 : measurable_space α} {μ : measure α} {s t : set α}
instance [h : inhabited α] : inhabited (null_measurable_space α μ) := h
instance [h : subsingleton α] : subsingleton (null_measurable_space α μ) := h
instance : measurable_space (null_measurable_space α μ) :=
{ measurable_set' := λ s, ∃ t, measurable_set t ∧ s =ᵐ[μ] t,
measurable_set_empty := ⟨∅, measurable_set.empty, ae_eq_refl _⟩,
measurable_set_compl := λ s ⟨t, htm, hts⟩, ⟨tᶜ, htm.compl, hts.compl⟩,
measurable_set_Union := λ s hs, by { choose t htm hts using hs,
exact ⟨⋃ i, t i, measurable_set.Union htm, eventually_eq.countable_Union hts⟩ } }
/-- A set is called `null_measurable_set` if it can be approximated by a measurable set up to
a set of null measure. -/
def null_measurable_set [measurable_space α] (s : set α) (μ : measure α . volume_tac) : Prop :=
@measurable_set (null_measurable_space α μ) _ s
@[simp] lemma _root_.measurable_set.null_measurable_set (h : measurable_set s) :
null_measurable_set s μ :=
⟨s, h, ae_eq_refl _⟩
@[simp] lemma null_measurable_set_empty : null_measurable_set ∅ μ := measurable_set.empty
@[simp] lemma null_measurable_set_univ : null_measurable_set univ μ := measurable_set.univ
namespace null_measurable_set
lemma of_null (h : μ s = 0) : null_measurable_set s μ :=
⟨∅, measurable_set.empty, ae_eq_empty.2 h⟩
lemma compl (h : null_measurable_set s μ) : null_measurable_set sᶜ μ := h.compl
lemma of_compl (h : null_measurable_set sᶜ μ) : null_measurable_set s μ := h.of_compl
@[simp] lemma compl_iff : null_measurable_set sᶜ μ ↔ null_measurable_set s μ :=
measurable_set.compl_iff
@[nontriviality]
lemma of_subsingleton [subsingleton α] : null_measurable_set s μ := subsingleton.measurable_set
protected lemma congr (hs : null_measurable_set s μ) (h : s =ᵐ[μ] t) :
null_measurable_set t μ :=
let ⟨s', hm, hs'⟩ := hs in ⟨s', hm, h.symm.trans hs'⟩
protected lemma Union {ι : Sort*} [countable ι] {s : ι → set α}
(h : ∀ i, null_measurable_set (s i) μ) :
null_measurable_set (⋃ i, s i) μ :=
measurable_set.Union h
protected lemma bUnion_decode₂ [encodable ι] ⦃f : ι → set α⦄ (h : ∀ i, null_measurable_set (f i) μ)
(n : ℕ) : null_measurable_set (⋃ b ∈ encodable.decode₂ ι n, f b) μ :=
measurable_set.bUnion_decode₂ h n
protected lemma bUnion {f : ι → set α} {s : set ι} (hs : s.countable)
(h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋃ b ∈ s, f b) μ :=
measurable_set.bUnion hs h
protected lemma sUnion {s : set (set α)} (hs : s.countable) (h : ∀ t ∈ s, null_measurable_set t μ) :
null_measurable_set (⋃₀ s) μ :=
by { rw sUnion_eq_bUnion, exact measurable_set.bUnion hs h }
protected lemma Inter {ι : Sort*} [countable ι] {f : ι → set α}
(h : ∀ i, null_measurable_set (f i) μ) :
null_measurable_set (⋂ i, f i) μ :=
measurable_set.Inter h
protected lemma bInter {f : β → set α} {s : set β} (hs : s.countable)
(h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋂ b ∈ s, f b) μ :=
measurable_set.bInter hs h
protected lemma sInter {s : set (set α)} (hs : s.countable) (h : ∀ t ∈ s, null_measurable_set t μ) :
null_measurable_set (⋂₀ s) μ :=
measurable_set.sInter hs h
@[simp] protected lemma union (hs : null_measurable_set s μ) (ht : null_measurable_set t μ) :
null_measurable_set (s ∪ t) μ :=
hs.union ht
protected lemma union_null (hs : null_measurable_set s μ) (ht : μ t = 0) :
null_measurable_set (s ∪ t) μ :=
hs.union (of_null ht)
@[simp] protected lemma inter (hs : null_measurable_set s μ) (ht : null_measurable_set t μ) :
null_measurable_set (s ∩ t) μ :=
hs.inter ht
@[simp] protected lemma diff (hs : null_measurable_set s μ) (ht : null_measurable_set t μ) :
null_measurable_set (s \ t) μ :=
hs.diff ht
@[simp] protected lemma disjointed {f : ℕ → set α} (h : ∀ i, null_measurable_set (f i) μ) (n) :
null_measurable_set (disjointed f n) μ :=
measurable_set.disjointed h n
@[simp] protected lemma const (p : Prop) : null_measurable_set {a : α | p} μ :=
measurable_set.const p
instance [measurable_singleton_class α] : measurable_singleton_class (null_measurable_space α μ) :=
⟨λ x, (@measurable_set_singleton α _ _ x).null_measurable_set⟩
protected lemma insert [measurable_singleton_class (null_measurable_space α μ)]
(hs : null_measurable_set s μ) (a : α) :
null_measurable_set (insert a s) μ :=
hs.insert a
lemma exists_measurable_superset_ae_eq (h : null_measurable_set s μ) :
∃ t ⊇ s, measurable_set t ∧ t =ᵐ[μ] s :=
begin
rcases h with ⟨t, htm, hst⟩,
refine ⟨t ∪ to_measurable μ (s \ t), _, htm.union (measurable_set_to_measurable _ _), _⟩,
{ exact diff_subset_iff.1 (subset_to_measurable _ _) },
{ have : to_measurable μ (s \ t) =ᵐ[μ] (∅ : set α), by simp [ae_le_set.1 hst.le],
simpa only [union_empty] using hst.symm.union this }
end
lemma to_measurable_ae_eq (h : null_measurable_set s μ) :
to_measurable μ s =ᵐ[μ] s :=
begin
rw [to_measurable, dif_pos],
exact h.exists_measurable_superset_ae_eq.some_spec.snd.2
end
lemma compl_to_measurable_compl_ae_eq (h : null_measurable_set s μ) :
(to_measurable μ sᶜ)ᶜ =ᵐ[μ] s :=
by simpa only [compl_compl] using h.compl.to_measurable_ae_eq.compl
lemma exists_measurable_subset_ae_eq (h : null_measurable_set s μ) :
∃ t ⊆ s, measurable_set t ∧ t =ᵐ[μ] s :=
⟨(to_measurable μ sᶜ)ᶜ, compl_subset_comm.2 $ subset_to_measurable _ _,
(measurable_set_to_measurable _ _).compl, h.compl_to_measurable_compl_ae_eq⟩
end null_measurable_set
/-- If `sᵢ` is a countable family of (null) measurable pairwise `μ`-a.e. disjoint sets, then there
exists a subordinate family `tᵢ ⊆ sᵢ` of measurable pairwise disjoint sets such that
`tᵢ =ᵐ[μ] sᵢ`. -/
lemma exists_subordinate_pairwise_disjoint [countable ι] {s : ι → set α}
(h : ∀ i, null_measurable_set (s i) μ) (hd : pairwise (ae_disjoint μ on s)) :
∃ t : ι → set α, (∀ i, t i ⊆ s i) ∧ (∀ i, s i =ᵐ[μ] t i) ∧ (∀ i, measurable_set (t i)) ∧
pairwise (disjoint on t) :=
begin
choose t ht_sub htm ht_eq using λ i, (h i).exists_measurable_subset_ae_eq,
rcases exists_null_pairwise_disjoint_diff hd with ⟨u, hum, hu₀, hud⟩,
exact ⟨λ i, t i \ u i, λ i, (diff_subset _ _).trans (ht_sub _),
λ i, (ht_eq _).symm.trans (diff_null_ae_eq_self (hu₀ i)).symm,
λ i, (htm i).diff (hum i), hud.mono $
λ i j h, h.mono (diff_subset_diff_left (ht_sub i)) (diff_subset_diff_left (ht_sub j))⟩
end
lemma measure_Union {m0 : measurable_space α} {μ : measure α} [countable ι] {f : ι → set α}
(hn : pairwise (disjoint on f)) (h : ∀ i, measurable_set (f i)) :
μ (⋃ i, f i) = ∑' i, μ (f i) :=
begin
rw [measure_eq_extend (measurable_set.Union h),
extend_Union measurable_set.empty _ measurable_set.Union _ hn h],
{ simp [measure_eq_extend, h] },
{ exact μ.empty },
{ exact μ.m_Union }
end
lemma measure_Union₀ [countable ι] {f : ι → set α} (hd : pairwise (ae_disjoint μ on f))
(h : ∀ i, null_measurable_set (f i) μ) :
μ (⋃ i, f i) = ∑' i, μ (f i) :=
begin
rcases exists_subordinate_pairwise_disjoint h hd with ⟨t, ht_sub, ht_eq, htm, htd⟩,
calc μ (⋃ i, f i) = μ (⋃ i, t i) : measure_congr (eventually_eq.countable_Union ht_eq)
... = ∑' i, μ (t i) : measure_Union htd htm
... = ∑' i, μ (f i) : tsum_congr (λ i, measure_congr (ht_eq _).symm)
end
lemma measure_union₀_aux (hs : null_measurable_set s μ) (ht : null_measurable_set t μ)
(hd : ae_disjoint μ s t) :
μ (s ∪ t) = μ s + μ t :=
begin
rw [union_eq_Union, measure_Union₀, tsum_fintype, fintype.sum_bool, cond, cond],
exacts [(pairwise_on_bool ae_disjoint.symmetric).2 hd, λ b, bool.cases_on b ht hs]
end
/-- A null measurable set `t` is Carathéodory measurable: for any `s`, we have
`μ (s ∩ t) + μ (s \ t) = μ s`. -/
lemma measure_inter_add_diff₀ (s : set α) (ht : null_measurable_set t μ) :
μ (s ∩ t) + μ (s \ t) = μ s :=
begin
refine le_antisymm _ _,
{ rcases exists_measurable_superset μ s with ⟨s', hsub, hs'm, hs'⟩,
replace hs'm : null_measurable_set s' μ := hs'm.null_measurable_set,
calc μ (s ∩ t) + μ (s \ t) ≤ μ (s' ∩ t) + μ (s' \ t) :
add_le_add (measure_mono $ inter_subset_inter_left _ hsub)
(measure_mono $ diff_subset_diff_left hsub)
... = μ (s' ∩ t ∪ s' \ t) :
(measure_union₀_aux (hs'm.inter ht) (hs'm.diff ht) $
(@disjoint_inf_sdiff _ s' t _).ae_disjoint).symm
... = μ s' : congr_arg μ (inter_union_diff _ _)
... = μ s : hs' },
{ calc μ s = μ (s ∩ t ∪ s \ t) : by rw inter_union_diff
... ≤ μ (s ∩ t) + μ (s \ t) : measure_union_le _ _ }
end
lemma measure_union_add_inter₀ (s : set α) (ht : null_measurable_set t μ) :
μ (s ∪ t) + μ (s ∩ t) = μ s + μ t :=
by rw [← measure_inter_add_diff₀ (s ∪ t) ht, union_inter_cancel_right, union_diff_right,
← measure_inter_add_diff₀ s ht, add_comm, ← add_assoc, add_right_comm]
lemma measure_union_add_inter₀' (hs : null_measurable_set s μ) (t : set α) :
μ (s ∪ t) + μ (s ∩ t) = μ s + μ t :=
by rw [union_comm, inter_comm, measure_union_add_inter₀ t hs, add_comm]
lemma measure_union₀ (ht : null_measurable_set t μ) (hd : ae_disjoint μ s t) :
μ (s ∪ t) = μ s + μ t :=
by rw [← measure_union_add_inter₀ s ht, hd.eq, add_zero]
lemma measure_union₀' (hs : null_measurable_set s μ) (hd : ae_disjoint μ s t) :
μ (s ∪ t) = μ s + μ t :=
by rw [union_comm, measure_union₀ hs hd.symm, add_comm]
lemma measure_add_measure_compl₀ {s : set α} (hs : null_measurable_set s μ) :
μ s + μ sᶜ = μ univ :=
by rw [← measure_union₀' hs ae_disjoint_compl_right, union_compl_self]
section measurable_singleton_class
variable [measurable_singleton_class (null_measurable_space α μ)]
lemma null_measurable_set_singleton (x : α) : null_measurable_set {x} μ :=
measurable_set_singleton x
@[simp] lemma null_measurable_set_insert {a : α} {s : set α} :
null_measurable_set (insert a s) μ ↔ null_measurable_set s μ :=
measurable_set_insert
lemma null_measurable_set_eq {a : α} : null_measurable_set {x | x = a} μ :=
null_measurable_set_singleton a
protected lemma _root_.set.finite.null_measurable_set (hs : s.finite) : null_measurable_set s μ :=
finite.measurable_set hs
protected lemma _root_.finset.null_measurable_set (s : finset α) : null_measurable_set ↑s μ :=
finset.measurable_set s
end measurable_singleton_class
lemma _root_.set.finite.null_measurable_set_bUnion {f : ι → set α} {s : set ι} (hs : s.finite)
(h : ∀ b ∈ s, null_measurable_set (f b) μ) :
null_measurable_set (⋃ b ∈ s, f b) μ :=
finite.measurable_set_bUnion hs h
lemma _root_.finset.null_measurable_set_bUnion {f : ι → set α} (s : finset ι)
(h : ∀ b ∈ s, null_measurable_set (f b) μ) :
null_measurable_set (⋃ b ∈ s, f b) μ :=
finset.measurable_set_bUnion s h
lemma _root_.set.finite.null_measurable_set_sUnion {s : set (set α)} (hs : s.finite)
(h : ∀ t ∈ s, null_measurable_set t μ) :
null_measurable_set (⋃₀ s) μ :=
finite.measurable_set_sUnion hs h
lemma _root_.set.finite.null_measurable_set_bInter {f : ι → set α} {s : set ι} (hs : s.finite)
(h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋂ b ∈ s, f b) μ :=
finite.measurable_set_bInter hs h
lemma _root_.finset.null_measurable_set_bInter {f : ι → set α} (s : finset ι)
(h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋂ b ∈ s, f b) μ :=
s.finite_to_set.null_measurable_set_bInter h
lemma _root_.set.finite.null_measurable_set_sInter {s : set (set α)} (hs : s.finite)
(h : ∀ t ∈ s, null_measurable_set t μ) : null_measurable_set (⋂₀ s) μ :=
null_measurable_set.sInter hs.countable h
lemma null_measurable_set_to_measurable : null_measurable_set (to_measurable μ s) μ :=
(measurable_set_to_measurable _ _).null_measurable_set
end
section null_measurable
variables [measurable_space α] [measurable_space β] [measurable_space γ]
{f : α → β} {μ : measure α}
/-- A function `f : α → β` is null measurable if the preimage of a measurable set is a null
measurable set. -/
def null_measurable (f : α → β) (μ : measure α . volume_tac) : Prop :=
∀ ⦃s : set β⦄, measurable_set s → null_measurable_set (f ⁻¹' s) μ
protected lemma _root_.measurable.null_measurable (h : measurable f) : null_measurable f μ :=
λ s hs, (h hs).null_measurable_set
protected lemma null_measurable.measurable' (h : null_measurable f μ) :
@measurable (null_measurable_space α μ) β _ _ f := h
lemma measurable.comp_null_measurable {g : β → γ} (hg : measurable g)
(hf : null_measurable f μ) : null_measurable (g ∘ f) μ :=
hg.comp hf
lemma null_measurable.congr {g : α → β} (hf : null_measurable f μ) (hg : f =ᵐ[μ] g) :
null_measurable g μ :=
λ s hs, (hf hs).congr $ eventually_eq_set.2 $ hg.mono $
λ x hx, by rw [mem_preimage, mem_preimage, hx]
end null_measurable
section is_complete
/-- A measure is complete if every null set is also measurable.
A null set is a subset of a measurable set with measure `0`.
Since every measure is defined as a special case of an outer measure, we can more simply state
that a set `s` is null if `μ s = 0`. -/
class measure.is_complete {_ : measurable_space α} (μ : measure α) : Prop :=
(out' : ∀ s, μ s = 0 → measurable_set s)
variables {m0 : measurable_space α} {μ : measure α} {s t : set α}
theorem measure.is_complete_iff :
μ.is_complete ↔ ∀ s, μ s = 0 → measurable_set s := ⟨λ h, h.1, λ h, ⟨h⟩⟩
theorem measure.is_complete.out (h : μ.is_complete) :
∀ s, μ s = 0 → measurable_set s := h.1
theorem measurable_set_of_null [μ.is_complete] (hs : μ s = 0) : measurable_set s :=
measure_theory.measure.is_complete.out' s hs
theorem null_measurable_set.measurable_of_complete (hs : null_measurable_set s μ) [μ.is_complete] :
measurable_set s :=
diff_diff_cancel_left (subset_to_measurable μ s) ▸ (measurable_set_to_measurable _ _).diff
(measurable_set_of_null (ae_le_set.1 hs.to_measurable_ae_eq.le))
theorem null_measurable.measurable_of_complete [μ.is_complete] {m1 : measurable_space β} {f : α → β}
(hf : null_measurable f μ) : measurable f :=
λ s hs, (hf hs).measurable_of_complete
lemma _root_.measurable.congr_ae {α β} [measurable_space α] [measurable_space β] {μ : measure α}
[hμ : μ.is_complete] {f g : α → β} (hf : measurable f) (hfg : f =ᵐ[μ] g) :
measurable g :=
(hf.null_measurable.congr hfg).measurable_of_complete
namespace measure
/-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/
def completion {_ : measurable_space α} (μ : measure α) :
@measure_theory.measure (null_measurable_space α μ) _ :=
{ to_outer_measure := μ.to_outer_measure,
m_Union := λ s hs hd, measure_Union₀ (hd.mono $ λ i j h, h.ae_disjoint) hs,
trimmed := begin
refine le_antisymm (λ s, _) (outer_measure.le_trim _),
rw outer_measure.trim_eq_infi, simp only [to_outer_measure_apply],
refine (infi₂_mono _).trans_eq (measure_eq_infi _).symm,
exact λ t ht, infi_mono' (λ h, ⟨h.null_measurable_set, le_rfl⟩)
end }
instance completion.is_complete {m : measurable_space α} (μ : measure α) :
μ.completion.is_complete :=
⟨λ z hz, null_measurable_set.of_null hz⟩
@[simp] lemma coe_completion {_ : measurable_space α} (μ : measure α) :
⇑μ.completion = μ := rfl
lemma completion_apply {_ : measurable_space α} (μ : measure α) (s : set α) :
μ.completion s = μ s := rfl
end measure
end is_complete
end measure_theory
|
4ad6df13379c924abe8feb0b72c250cab23adec1 | c8d830ce6c7de4840cf0c892d8b58e7e8df97e37 | /src/evidence.lean | e0d9d81e231adde84f586a490672f7cf583b661e | [] | no_license | loganrjmurphy/lean-strategies | 4b8dd54771bb421c929a8bcb93a528ce6c1a70f1 | 020e2a65dc2ab475696dfea5ad8935a0a4085918 | refs/heads/main | 1,682,732,168,860 | 1,614,820,630,000 | 1,614,820,630,000 | 278,458,841 | 3 | 0 | null | 1,613,755,728,000 | 1,594,324,763,000 | Lean | UTF-8 | Lean | false | false | 630 | lean | import justification fcs common_meta property_catalogue.LTL
open S A
@[reducible] def fcs_input_1 : property.input (path fcs) := {property.input .
Clm := {Claim . X := {x : path fcs | true}, P := λ (π : path fcs), π⊨absent.globally ↑Damaged},
Props := [λ (π : path fcs), π⊨not_init ↑Damaged, λ (π : path fcs), π⊨holds_over_transition ↑Damaged]}
@[reducible] def fcs_strat_1 : Strategy (path fcs) := property.strategy fcs_input_1
theorem fcs_prf_1 : deductive (path fcs) fcs_strat_1 :=
begin
by_induction,
base_case P1,
end
--holds_over_transition ↑Damaged
--HINT transitions_safe ↑Damaged |
8c8138100c708ec6f93767dbf477e5e7304267bb | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Widget/InteractiveGoal.lean | 82025d2bc08c1b12732fb47ea6254f1b0b1bd337 | [
"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 | 8,041 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki
-/
import Lean.Meta.PPGoal
import Lean.Widget.InteractiveCode
import Lean.Data.Lsp.Extra
/-! Functionality related to tactic-mode and term-mode goals with embedded `CodeWithInfos`. -/
namespace Lean.Widget
open Server
/-- In the infoview, if multiple hypotheses `h₁`, `h₂` have the same type `α`, they are rendered
as `h₁ h₂ : α`. We call this a 'hypothesis bundle'. We use `none` instead of `some false` for
booleans to save space in the json encoding. -/
structure InteractiveHypothesisBundle where
/-- The user-friendly name for each hypothesis. -/
names : Array Name
/-- The ids for each variable. Should have the same length as `names`. -/
fvarIds : Array FVarId
type : CodeWithInfos
/-- The value, in the case the hypothesis is a `let`-binder. -/
val? : Option CodeWithInfos := none
/-- The hypothesis is a typeclass instance. -/
isInstance? : Option Bool := none
/-- The hypothesis is a type. -/
isType? : Option Bool := none
/-- If true, the hypothesis was not present on the previous tactic state.
Only present in tactic-mode goals. -/
isInserted? : Option Bool := none
/-- If true, the hypothesis will be removed in the next tactic state.
Only present in tactic-mode goals. -/
isRemoved? : Option Bool := none
deriving Inhabited, RpcEncodable
/-- The shared parts of interactive term-mode and tactic-mode goals. -/
structure InteractiveGoalCore where
hyps : Array InteractiveHypothesisBundle
/-- The target type. -/
type : CodeWithInfos
/-- Metavariable context that the goal is well-typed in. -/
ctx : WithRpcRef Elab.ContextInfo
/-- An interactive tactic-mode goal. -/
structure InteractiveGoal extends InteractiveGoalCore where
/-- The name `foo` in `case foo`, if any. -/
userName? : Option String
/-- The symbol to display before the target type. Usually `⊢ ` but `conv` goals use `∣ `
and it could be extended. -/
goalPrefix : String
/-- Identifies the goal (ie with the unique name of the MVar that it is a goal for.) -/
mvarId : MVarId
/-- If true, the goal was not present on the previous tactic state. -/
isInserted? : Option Bool := none
/-- If true, the goal will be removed on the next tactic state. -/
isRemoved? : Option Bool := none
deriving RpcEncodable
/-- An interactive term-mode goal. -/
structure InteractiveTermGoal extends InteractiveGoalCore where
/-- Syntactic range of the term. -/
range : Lsp.Range
/-- Information about the term whose type is the term-mode goal. -/
term : WithRpcRef Elab.TermInfo
deriving RpcEncodable
def InteractiveGoalCore.pretty (g : InteractiveGoalCore) (userName? : Option String)
(goalPrefix : String) : Format := Id.run do
let indent := 2 -- Use option
let mut ret := match userName? with
| some userName => f!"case {userName}"
| none => Format.nil
for hyp in g.hyps do
ret := addLine ret
let names := hyp.names
|>.toList
|>.filter (not ∘ Name.isAnonymous)
|>.map toString
|> " ".intercalate
match names with
| "" =>
ret := ret ++ Format.group f!":{Format.nest indent (Format.line ++ hyp.type.stripTags)}"
| _ =>
match hyp.val? with
| some val =>
ret := ret ++ Format.group f!"{names} : {hyp.type.stripTags} :={Format.nest indent (Format.line ++ val.stripTags)}"
| none =>
ret := ret ++ Format.group f!"{names} :{Format.nest indent (Format.line ++ hyp.type.stripTags)}"
ret := addLine ret
ret ++ f!"{goalPrefix}{Format.nest indent g.type.stripTags}"
where
addLine (fmt : Format) : Format :=
if fmt.isNil then fmt else fmt ++ Format.line
def InteractiveGoal.pretty (g : InteractiveGoal) : Format :=
g.toInteractiveGoalCore.pretty g.userName? g.goalPrefix
def InteractiveTermGoal.pretty (g : InteractiveTermGoal) : Format :=
g.toInteractiveGoalCore.pretty none "⊢ "
structure InteractiveGoals where
goals : Array InteractiveGoal
deriving RpcEncodable
def InteractiveGoals.append (l r : InteractiveGoals) : InteractiveGoals where
goals := l.goals ++ r.goals
instance : Append InteractiveGoals := ⟨InteractiveGoals.append⟩
instance : EmptyCollection InteractiveGoals := ⟨{goals := #[]}⟩
open Meta in
/-- Extend an array of hypothesis bundles with another bundle. -/
def addInteractiveHypothesisBundle (hyps : Array InteractiveHypothesisBundle)
(ids : Array (Name × FVarId)) (type : Expr) (value? : Option Expr := none) :
MetaM (Array InteractiveHypothesisBundle) := do
if ids.size == 0 then
throwError "Can only add a nonzero number of ids as an InteractiveHypothesisBundle."
let fvarIds := ids.map Prod.snd
let names := ids.map Prod.fst
return hyps.push {
names
fvarIds
type := (← ppExprTagged type)
val? := (← value?.mapM ppExprTagged)
isInstance? := if (← isClass? type).isSome then true else none
isType? := if (← instantiateMVars type).isSort then true else none
}
open Meta in
variable [MonadControlT MetaM n] [Monad n] [MonadError n] [MonadOptions n] [MonadMCtx n] in
def withGoalCtx (goal : MVarId) (action : LocalContext → MetavarDecl → n α) : n α := do
let mctx ← getMCtx
let some mvarDecl := mctx.findDecl? goal
| throwError "unknown goal {goal.name}"
let lctx := mvarDecl.lctx |>.sanitizeNames.run' {options := (← getOptions)}
withLCtx lctx mvarDecl.localInstances (action lctx mvarDecl)
open Meta in
/-- A variant of `Meta.ppGoal` which preserves subexpression information for interactivity. -/
def goalToInteractive (mvarId : MVarId) : MetaM InteractiveGoal := do
let ppAuxDecls := pp.auxDecls.get (← getOptions)
let ppImplDetailHyps := pp.implementationDetailHyps.get (← getOptions)
let showLetValues := pp.showLetValues.get (← getOptions)
withGoalCtx mvarId fun lctx mvarDecl => do
let pushPending (ids : Array (Name × FVarId)) (type? : Option Expr) (hyps : Array InteractiveHypothesisBundle)
: MetaM (Array InteractiveHypothesisBundle) :=
if ids.isEmpty then
pure hyps
else
match type? with
| none => pure hyps
| some type => addInteractiveHypothesisBundle hyps ids type
let mut varNames : Array (Name × FVarId) := #[]
let mut prevType? : Option Expr := none
let mut hyps : Array InteractiveHypothesisBundle := #[]
for localDecl in lctx do
if !ppAuxDecls && localDecl.isAuxDecl || !ppImplDetailHyps && localDecl.isImplementationDetail then
continue
else
match localDecl with
| LocalDecl.cdecl _index fvarId varName type _ _ =>
let varName := varName.simpMacroScopes
let type ← instantiateMVars type
if prevType? == none || prevType? == some type then
varNames := varNames.push (varName, fvarId)
else
hyps ← pushPending varNames prevType? hyps
varNames := #[(varName, fvarId)]
prevType? := some type
| LocalDecl.ldecl _index fvarId varName type val _ _ => do
let varName := varName.simpMacroScopes
hyps ← pushPending varNames prevType? hyps
let type ← instantiateMVars type
let val? ← if showLetValues then pure (some (← instantiateMVars val)) else pure none
hyps ← addInteractiveHypothesisBundle hyps #[(varName, fvarId)] type val?
varNames := #[]
prevType? := none
hyps ← pushPending varNames prevType? hyps
let goalTp ← instantiateMVars mvarDecl.type
let goalFmt ← ppExprTagged goalTp
let userName? := match mvarDecl.userName with
| Name.anonymous => none
| name => some <| toString name.eraseMacroScopes
return {
hyps
type := goalFmt
ctx := ⟨← Elab.ContextInfo.save⟩
userName?
goalPrefix := getGoalPrefix mvarDecl
mvarId
}
end Lean.Widget
|
2bb0b9928bdb02a1f6d86ce0b319f9fa9595310f | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/elabissues/variable_universe_bug.lean | 01d9bd3295a509fe7fce724e27b84f21cc31c637 | [
"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 | 550 | lean | /-
Courtesy of @rwbarton.
This is just a bug report, but since we are going to soon rewrite the entire module in Lean4,
we don't want to bother fixing the C++ bug, and we don't want to add a failing test either.
The issue is that collecting implicit locals does not collect additional universe parameters
the locals depend on.
-/
universes v u
class Category (C : Type u) :=
(Hom : ∀ (X Y : C), Type v)
variable {C : Type u} [Category.{v, u} C]
def End (X : C) := Category.Hom X X -- invalid reference to undefined universe level parameter 'v'
|
533b1994328505420b2491ea8c7f7fac97e4cbbb | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/set/finite.lean | 545208a13466df3a2fc41a6ae6ba0662d6a8f078 | [
"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 | 25,334 | 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 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))
instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι]
(f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) :=
fintype.of_finset (finset.univ.bind (λ 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_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_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s]
(f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) :=
fintype_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_bind {α β} [decidable_eq β] (s : set α) [fintype s]
(f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) :=
set.fintype_bUnion _ H
instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s]
(f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) :=
fintype_bind _ _ (λ i _, H i)
theorem finite_bind {α β} {s : set α} {f : α → set β} :
finite s → (∀ a ∈ s, finite (f a)) → finite (s >>= f)
| ⟨hs⟩ H := ⟨@fintype_bind _ _ (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_bind'
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_bind {f : α → finset β} : ↑(s.bind 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 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_inter {α : 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
|
944c344bd5b1bf36e49325c539e0ef1028d94dfb | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/meta/expr_lens.lean | 1fdaef3caad7854ed17a45759c6d86f55f1d65d6 | [
"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 | 5,726 | lean | /-
Copyright (c) 2020 Keeley Hoek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Keeley Hoek, Scott Morrison
-/
import meta.expr
/-!
# A lens for zooming into nested `expr` applications
A "lens" for looking into the subterms of an expression, tracking where we've been, so that
when we "zoom out" after making a change we know exactly which order of `congr_fun`s and
`congr_arg`s we need to make things work.
This file defines the `expr_lens` inductive type, defines basic operations this type, and defines a
useful map-like function `expr.app_map` on `expr`s which maps over applications.
This file is for non-tactics.
## Tags
expr, expr_lens, congr, environment, meta, metaprogramming, tactic
-/
/-! ### Declarations about `expr_lens` -/
/-- You're supposed to think of an `expr_lens` as a big set of nested applications with a single
hole which needs to be filled, either in a function spot or argument spot. `expr_lens.fill` can
fill this hole and turn your lens back into a real `expr`. -/
meta inductive expr_lens
| app_fun : expr_lens → expr → expr_lens
| app_arg : expr_lens → expr → expr_lens
| entire : expr_lens
namespace expr_lens
/-- Inductive type with two constructors `F` and `A`,
that represent the function-part `f` and arg-part `a` of an application `f a`. They specify the
directions in which an `expr_lens` should zoom into an `expr`.
This type is used in the development of rewriting tactics such as `nth_rewrite` and
`rewrite_search`. -/
@[derive [decidable_eq, inhabited]]
inductive dir
| F
| A
/-- String representation of `dir`. -/
def dir.to_string : dir → string
| dir.F := "F"
| dir.A := "A"
instance : has_to_string dir := ⟨dir.to_string⟩
open tactic
/-- Fill the function or argument hole in this lens with the given `expr`. -/
meta def fill : expr_lens → expr → expr
| entire e := e
| (app_fun l f) x := l.fill (expr.app f x)
| (app_arg l x) f := l.fill (expr.app f x)
/-- Zoom into `e : expr` given the context of an `expr_lens`, popping out an `expr` and a new
zoomed `expr_lens`, if this is possible (`e` has to be an application). -/
meta def zoom : expr_lens → list dir → expr → option (expr_lens × expr)
| l [] e := (l, e)
| l (dir.F :: rest) (expr.app f x) := (expr_lens.app_arg l x).zoom rest f
| l (dir.A :: rest) (expr.app f x) := (expr_lens.app_fun l f).zoom rest x
| _ _ _ := none
/-- Convert an `expr_lens` into a list of instructions needed to build it; repeatedly inspecting a
function or its argument a finite number of times. -/
meta def to_dirs : expr_lens → list dir
| expr_lens.entire := []
| (expr_lens.app_fun l _) := l.to_dirs.concat dir.A
| (expr_lens.app_arg l _) := l.to_dirs.concat dir.F
/-- Sometimes `mk_congr_arg` fails, when the function is 'superficially dependent'.
Try to `dsimp` the function first before building the `congr_arg` expression. -/
meta def mk_congr_arg_using_dsimp (G W : expr) (u : list name) : tactic expr :=
do s ← simp_lemmas.mk_default,
t ← infer_type G,
t' ← s.dsimplify u t { fail_if_unchanged := ff },
to_expr ```(congr_arg (show %%t', from %%G) %%W)
private meta def trace_congr_error (f : expr) (x_eq : expr) : tactic unit :=
do pp_f ← pp f,
pp_f_t ← (infer_type f >>= λ t, pp t),
pp_x_eq ← pp x_eq,
pp_x_eq_t ← (infer_type x_eq >>= λ t, pp t),
trace format!"expr_lens.congr failed on \n{pp_f} : {pp_f_t}\n{pp_x_eq} : {pp_x_eq_t}"
/-- Turn an `e : expr_lens` and a proof that `a = b` into a series of `congr_arg` or `congr_fun`
applications showing that the expressions obtained from `e.fill a` and `e.fill b` are equal. -/
meta def congr : expr_lens → expr → tactic expr
| entire e_eq := pure e_eq
| (app_fun l f) x_eq := do fx_eq ← try_core $ do {
mk_congr_arg f x_eq
<|> mk_congr_arg_using_dsimp f x_eq [`has_coe_to_fun.F]
},
match fx_eq with
| (some fx_eq) := l.congr fx_eq
| none := trace_congr_error f x_eq >> failed
end
| (app_arg l x) f_eq := mk_congr_fun f_eq x >>= l.congr
/-- Pretty print a lens. -/
meta def to_tactic_string : expr_lens → tactic string
| entire := return "(entire)"
| (app_fun l f) := do pp ← pp f,
rest ← l.to_tactic_string,
return sformat!"(fun \"{pp}\" {rest})"
| (app_arg l x) := do pp ← pp x,
rest ← l.to_tactic_string,
return sformat!"(arg \"{pp}\" {rest})"
end expr_lens
namespace expr
/-- The private internal function used by `app_map`, which "does the work". -/
private meta def app_map_aux {α} (F : expr_lens → expr → tactic (list α)) :
option (expr_lens × expr) → tactic (list α)
| (some (l, e)) := list.join <$> monad.sequence [
F l e,
app_map_aux $ l.zoom [expr_lens.dir.F] e,
app_map_aux $ l.zoom [expr_lens.dir.A] e
] <|> pure []
| none := pure []
/-- `app_map F e` maps a function `F` which understands `expr_lens`es
over the given `e : expr` in the natural way;
that is, make holes in `e` everywhere where that is possible
(generating `expr_lens`es in the process),
and at each stage call the function `F` passing
both the `expr_lens` generated and the `expr` which was removed to make the hole.
At each stage `F` returns a list of some type, and `app_map` collects these lists together and
returns a concatenation of them all. -/
meta def app_map {α} (F : expr_lens → expr → tactic (list α)) (e : expr) : tactic (list α) :=
app_map_aux F (expr_lens.entire, e)
end expr
|
0180b634b6b9c27c4cf5dd7b298a2ddca1974416 | 130c49f47783503e462c16b2eff31933442be6ff | /src/Lean/Elab/Tactic/Basic.lean | c75a16989b23d05fbe8cdee4075200e64b1c5c64 | [
"Apache-2.0"
] | permissive | Hazel-Brown/lean4 | 8aa5860e282435ffc30dcdfccd34006c59d1d39c | 79e6732fc6bbf5af831b76f310f9c488d44e7a16 | refs/heads/master | 1,689,218,208,951 | 1,629,736,869,000 | 1,629,736,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,664 | 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
-- declaration name of the executing elaborator, used by `mkTacticInfo` to persist it in the info tree
elaborator : Name
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
-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the
-- whole monad stack at every use site. May eventually be covered by `deriving`.
instance : Monad TacticM := let i := inferInstanceAs (Monad TacticM); { pure := i.pure, bind := i.bind }
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, elaborator := Name.anonymous } { 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
def mkTacticInfo (mctxBefore : MetavarContext) (goalsBefore : List MVarId) (stx : Syntax) : TacticM Info :=
return Info.ofTacticInfo {
elaborator := (← read).elaborator
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)
/-
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 (KeyedDeclsAttribute.AttributeEntry Tactic)) : TacticM Unit := do
let rec loop
| [] => throwErrorAt stx "unexpected syntax {indentD stx}"
| evalFn::evalFns => do
try
withReader ({ · with elaborator := evalFn.decl }) <| withTacticInfoContext stx <| evalFn.value 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
mutual
partial def expandTacticMacroFns (stx : Syntax) (macros : List (KeyedDeclsAttribute.AttributeEntry Macro)) : TacticM Unit :=
let rec loop
| [] => throwErrorAt stx "tactic '{stx.getKind}' has not been implemented"
| m::ms => do
let scp ← getCurrMacroScope
try
withReader ({ · with elaborator := m.decl }) do
withTacticInfoContext stx do
let stx' ← adaptMacro m.value stx
evalTactic stx'
catch ex =>
if ms.isEmpty then throw ex -- (*)
loop ms
loop macros
partial def expandTacticMacro (stx : Syntax) : TacticM Unit := do
expandTacticMacroFns stx (macroAttribute.getEntries (← getEnv) stx.getKind)
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
match tacticElabAttribute.getEntries (← getEnv) stx.getKind with
| [] => expandTacticMacro stx
| evalFns => evalTacticUsing s stx evalFns
| _ => throwError m!"unexpected tactic{indentD stx}"
partial def evalTactic (stx : Syntax) : TacticM Unit :=
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
instance : Alternative TacticM where
failure := fun {α} => throwError "failed"
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)
@[inline] def liftMetaTactic1 (tactic : MVarId → MetaM (Option MVarId)) : TacticM Unit :=
withMainContext do
if let some mvarId ← tactic (← getMainGoal) then
replaceMainGoal [mvarId]
else
replaceMainGoal []
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
/- Recall that `ident' := ident <|> Term.hole` -/
def getNameOfIdent' (id : Syntax) : Name :=
if id.isIdent then id.getId else `_
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
/--
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
builtin_initialize registerTraceClass `Elab.tactic
end Lean.Elab.Tactic
|
e1439df2c8f09100e0b8efde7be99d57bac42de5 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/pfunctor/univariate/basic_auto.lean | 4356734d4658ddf0d12fee3eb1af998635b6c5a3 | [] | 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,937 | lean | /-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.W
import Mathlib.PostPort
universes u l u_1 u_2 u_3
namespace Mathlib
/-!
# Polynomial functors
This file defines polynomial functors and the W-type construction as a
polynomial functor. (For the M-type construction, see
pfunctor/M.lean.)
-/
/--
A polynomial functor `P` is given by a type `A` and a family `B` of types over `A`. `P` maps
any type `α` to a new type `P.obj α`, which is defined as the sigma type `Σ x, P.B x → α`.
An element of `P.obj α` is a pair `⟨a, f⟩`, where `a` is an element of a type `A` and
`f : B a → α`. Think of `a` as the shape of the object and `f` as an index to the relevant
elements of `α`.
-/
structure pfunctor where
A : Type u
B : A → Type u
namespace pfunctor
protected instance inhabited : Inhabited pfunctor :=
{ default := mk Inhabited.default Inhabited.default }
/-- Applying `P` to an object of `Type` -/
def obj (P : pfunctor) (α : Type u_2) := sigma fun (x : A P) => B P x → α
/-- Applying `P` to a morphism of `Type` -/
def map (P : pfunctor) {α : Type u_2} {β : Type u_3} (f : α → β) : obj P α → obj P β :=
fun (_x : obj P α) => sorry
protected instance obj.inhabited (P : pfunctor) {α : Type u} [Inhabited (A P)] [Inhabited α] :
Inhabited (obj P α) :=
{ default := sigma.mk Inhabited.default fun (_x : B P Inhabited.default) => Inhabited.default }
protected instance obj.functor (P : pfunctor) : Functor (obj P) :=
{ map := map P, mapConst := fun (α β : Type u_2) => map P ∘ function.const β }
protected theorem map_eq (P : pfunctor) {α : Type u_2} {β : Type u_2} (f : α → β) (a : A P)
(g : B P a → α) : f <$> sigma.mk a g = sigma.mk a (f ∘ g) :=
rfl
protected theorem id_map (P : pfunctor) {α : Type u_2} (x : obj P α) : id <$> x = id x := sorry
protected theorem comp_map (P : pfunctor) {α : Type u_2} {β : Type u_2} {γ : Type u_2} (f : α → β)
(g : β → γ) (x : obj P α) : (g ∘ f) <$> x = g <$> f <$> x :=
sorry
protected instance obj.is_lawful_functor (P : pfunctor) : is_lawful_functor (obj P) :=
is_lawful_functor.mk (pfunctor.id_map P) (pfunctor.comp_map P)
/-- re-export existing definition of W-types and
adapt it to a packaged definition of polynomial functor -/
def W (P : pfunctor) := W_type (B P)
/- inhabitants of W types is awkward to encode as an instance
assumption because there needs to be a value `a : P.A`
such that `P.B a` is empty to yield a finite tree -/
/-- root element of a W tree -/
def W.head {P : pfunctor} : W P → A P := sorry
/-- children of the root of a W tree -/
def W.children {P : pfunctor} (x : W P) : B P (W.head x) → W P := sorry
/-- destructor for W-types -/
def W.dest {P : pfunctor} : W P → obj P (W P) := sorry
/-- constructor for W-types -/
def W.mk {P : pfunctor} : obj P (W P) → W P := sorry
@[simp] theorem W.dest_mk {P : pfunctor} (p : obj P (W P)) : W.dest (W.mk p) = p :=
sigma.cases_on p
fun (p_fst : A P) (p_snd : B P p_fst → W P) => Eq.refl (W.dest (W.mk (sigma.mk p_fst p_snd)))
@[simp] theorem W.mk_dest {P : pfunctor} (p : W P) : W.mk (W.dest p) = p :=
W_type.cases_on p
fun (p_a : A P) (p_f : B P p_a → W_type (B P)) => Eq.refl (W.mk (W.dest (W_type.mk p_a p_f)))
/-- `Idx` identifies a location inside the application of a pfunctor.
For `F : pfunctor`, `x : F.obj α` and `i : F.Idx`, `i` can designate
one part of `x` or is invalid, if `i.1 ≠ x.1` -/
def Idx (P : pfunctor) := sigma fun (x : A P) => B P x
protected instance Idx.inhabited (P : pfunctor) [Inhabited (A P)]
[Inhabited (B P Inhabited.default)] : Inhabited (Idx P) :=
{ default := sigma.mk Inhabited.default Inhabited.default }
/-- `x.iget i` takes the component of `x` designated by `i` if any is or returns
a default value -/
def obj.iget {P : pfunctor} [DecidableEq (A P)] {α : Type u_2} [Inhabited α] (x : obj P α)
(i : Idx P) : α :=
dite (sigma.fst i = sigma.fst x)
(fun (h : sigma.fst i = sigma.fst x) => sigma.snd x (cast sorry (sigma.snd i)))
fun (h : ¬sigma.fst i = sigma.fst x) => Inhabited.default
@[simp] theorem fst_map {P : pfunctor} {α : Type u} {β : Type u} (x : obj P α) (f : α → β) :
sigma.fst (f <$> x) = sigma.fst x :=
sigma.cases_on x
fun (x_fst : A P) (x_snd : B P x_fst → α) => Eq.refl (sigma.fst (f <$> sigma.mk x_fst x_snd))
@[simp] theorem iget_map {P : pfunctor} [DecidableEq (A P)] {α : Type u} {β : Type u} [Inhabited α]
[Inhabited β] (x : obj P α) (f : α → β) (i : Idx P) (h : sigma.fst i = sigma.fst x) :
obj.iget (f <$> x) i = f (obj.iget x i) :=
sorry
end pfunctor
/-
Composition of polynomial functors.
-/
namespace pfunctor
/-- functor composition for polynomial functors -/
def comp (P₂ : pfunctor) (P₁ : pfunctor) : pfunctor :=
mk (sigma fun (a₂ : A P₂) => B P₂ a₂ → A P₁)
fun (a₂a₁ : sigma fun (a₂ : A P₂) => B P₂ a₂ → A P₁) =>
sigma fun (u : B P₂ (sigma.fst a₂a₁)) => B P₁ (sigma.snd a₂a₁ u)
/-- constructor for composition -/
def comp.mk (P₂ : pfunctor) (P₁ : pfunctor) {α : Type} (x : obj P₂ (obj P₁ α)) :
obj (comp P₂ P₁) α :=
sigma.mk (sigma.mk (sigma.fst x) (sigma.fst ∘ sigma.snd x))
fun (a₂a₁ : B (comp P₂ P₁) (sigma.mk (sigma.fst x) (sigma.fst ∘ sigma.snd x))) =>
sigma.snd (sigma.snd x (sigma.fst a₂a₁)) (sigma.snd a₂a₁)
/-- destructor for composition -/
def comp.get (P₂ : pfunctor) (P₁ : pfunctor) {α : Type} (x : obj (comp P₂ P₁) α) :
obj P₂ (obj P₁ α) :=
sigma.mk (sigma.fst (sigma.fst x))
fun (a₂ : B P₂ (sigma.fst (sigma.fst x))) =>
sigma.mk (sigma.snd (sigma.fst x) a₂)
fun (a₁ : B P₁ (sigma.snd (sigma.fst x) a₂)) => sigma.snd x (sigma.mk a₂ a₁)
end pfunctor
/-
Lifting predicates and relations.
-/
namespace pfunctor
theorem liftp_iff {P : pfunctor} {α : Type u} (p : α → Prop) (x : obj P α) :
functor.liftp p x ↔ ∃ (a : A P), ∃ (f : B P a → α), x = sigma.mk a f ∧ ∀ (i : B P a), p (f i) :=
sorry
theorem liftp_iff' {P : pfunctor} {α : Type u} (p : α → Prop) (a : A P) (f : B P a → α) :
functor.liftp p (sigma.mk a f) ↔ ∀ (i : B P a), p (f i) :=
sorry
theorem liftr_iff {P : pfunctor} {α : Type u} (r : α → α → Prop) (x : obj P α) (y : obj P α) :
functor.liftr r x y ↔
∃ (a : A P),
∃ (f₀ : B P a → α),
∃ (f₁ : B P a → α),
x = sigma.mk a f₀ ∧ y = sigma.mk a f₁ ∧ ∀ (i : B P a), r (f₀ i) (f₁ i) :=
sorry
theorem supp_eq {P : pfunctor} {α : Type u} (a : A P) (f : B P a → α) :
functor.supp (sigma.mk a f) = f '' set.univ :=
sorry
end Mathlib |
c8410119b78cc329f3a726d7c2ee21d0f9efe5d5 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/endomorphism.lean | 4bd5d4c486229346151eb9d55ae9f93cba1f8094 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 5,087 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Scott Morrison, Simon Hudon
-/
import algebra.hom.equiv
import category_theory.groupoid
import category_theory.opposites
import group_theory.group_action.defs
/-!
# Endomorphisms
Definition and basic properties of endomorphisms and automorphisms of an object in a category.
For each `X : C`, we provide `End X := X ⟶ X` with a monoid structure,
and `Aut X := X ≅ X ` with a group structure.
-/
universes v v' u u'
namespace category_theory
/-- Endomorphisms of an object in a category. Arguments order in multiplication agrees with
`function.comp`, not with `category.comp`. -/
def End {C : Type u} [category_struct.{v} C] (X : C) := X ⟶ X
namespace End
section struct
variables {C : Type u} [category_struct.{v} C] (X : C)
instance has_one : has_one (End X) := ⟨𝟙 X⟩
instance inhabited : inhabited (End X) := ⟨𝟙 X⟩
/-- Multiplication of endomorphisms agrees with `function.comp`, not `category_struct.comp`. -/
instance has_mul : has_mul (End X) := ⟨λ x y, y ≫ x⟩
variable {X}
/-- Assist the typechecker by expressing a morphism `X ⟶ X` as a term of `End X`. -/
def of (f : X ⟶ X) : End X := f
/-- Assist the typechecker by expressing an endomorphism `f : End X` as a term of `X ⟶ X`. -/
def as_hom (f : End X) : X ⟶ X := f
@[simp] lemma one_def : (1 : End X) = 𝟙 X := rfl
@[simp] lemma mul_def (xs ys : End X) : xs * ys = ys ≫ xs := rfl
end struct
/-- Endomorphisms of an object form a monoid -/
instance monoid {C : Type u} [category.{v} C] {X : C} : monoid (End X) :=
{ mul_one := category.id_comp,
one_mul := category.comp_id,
mul_assoc := λ x y z, (category.assoc z y x).symm,
..End.has_mul X, ..End.has_one X }
section mul_action
variables {C : Type u} [category.{v} C]
open opposite
instance mul_action_right {X Y : C} : mul_action (End Y) (X ⟶ Y) :=
{ smul := λ r f, f ≫ r,
one_smul := category.comp_id,
mul_smul := λ r s f, eq.symm $ category.assoc _ _ _ }
instance mul_action_left {X : Cᵒᵖ} {Y : C} : mul_action (End X) (unop X ⟶ Y) :=
{ smul := λ r f, r.unop ≫ f,
one_smul := category.id_comp,
mul_smul := λ r s f, category.assoc _ _ _ }
lemma smul_right {X Y : C} {r : End Y} {f : X ⟶ Y} : r • f = f ≫ r := rfl
lemma smul_left {X : Cᵒᵖ} {Y : C} {r : (End X)} {f : unop X ⟶ Y} : r • f = r.unop ≫ f := rfl
end mul_action
/-- In a groupoid, endomorphisms form a group -/
instance group {C : Type u} [groupoid.{v} C] (X : C) : group (End X) :=
{ mul_left_inv := groupoid.comp_inv, inv := groupoid.inv, ..End.monoid }
end End
lemma is_unit_iff_is_iso {C : Type u} [category.{v} C] {X : C} (f : End X) :
is_unit (f : End X) ↔ is_iso f :=
⟨λ h, { out := ⟨h.unit.inv, ⟨h.unit.inv_val, h.unit.val_inv⟩⟩ },
λ h, by exactI ⟨⟨f, inv f, by simp, by simp⟩, rfl⟩⟩
variables {C : Type u} [category.{v} C] (X : C)
/--
Automorphisms of an object in a category.
The order of arguments in multiplication agrees with
`function.comp`, not with `category.comp`.
-/
def Aut (X : C) := X ≅ X
attribute [ext Aut] iso.ext
namespace Aut
instance inhabited : inhabited (Aut X) := ⟨iso.refl X⟩
instance : group (Aut X) :=
by refine_struct
{ one := iso.refl X,
inv := iso.symm,
mul := flip iso.trans,
div := _,
npow := @npow_rec (Aut X) ⟨iso.refl X⟩ ⟨flip iso.trans⟩,
zpow := @zpow_rec (Aut X) ⟨iso.refl X⟩ ⟨flip iso.trans⟩ ⟨iso.symm⟩ };
intros; try { refl }; ext;
simp [flip, (*), monoid.mul, mul_one_class.mul, mul_one_class.one, has_one.one, monoid.one,
has_inv.inv]
lemma Aut_mul_def (f g : Aut X) : f * g = g.trans f := rfl
/--
Units in the monoid of endomorphisms of an object
are (multiplicatively) equivalent to automorphisms of that object.
-/
def units_End_equiv_Aut : (End X)ˣ ≃* Aut X :=
{ to_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩,
inv_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩,
left_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl,
right_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl,
map_mul' := λ f g, by rcases f; rcases g; refl }
/-- Isomorphisms induce isomorphisms of the automorphism group -/
def Aut_mul_equiv_of_iso {X Y : C} (h : X ≅ Y) : Aut X ≃* Aut Y :=
{ to_fun := λ x, ⟨h.inv ≫ x.hom ≫ h.hom, h.inv ≫ x.inv ≫ h.hom⟩,
inv_fun := λ y, ⟨h.hom ≫ y.hom ≫ h.inv, h.hom ≫ y.inv ≫ h.inv⟩,
left_inv := by tidy,
right_inv := by tidy,
map_mul' := by simp [Aut_mul_def] }
end Aut
namespace functor
variables {D : Type u'} [category.{v'} D] (f : C ⥤ D) (X)
/-- `f.map` as a monoid hom between endomorphism monoids. -/
@[simps] def map_End : End X →* End (f.obj X) :=
{ to_fun := functor.map f,
map_mul' := λ x y, f.map_comp y x,
map_one' := f.map_id X }
/-- `f.map_iso` as a group hom between automorphism groups. -/
def map_Aut : Aut X →* Aut (f.obj X) :=
{ to_fun := f.map_iso,
map_mul' := λ x y, f.map_iso_trans y x,
map_one' := f.map_iso_refl X }
end functor
end category_theory
|
29a77480dafa0b58b42ebc340a374780532ed5e5 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/pred_to_subtype_coercion.lean | d9716ac19024158c6d25dc5168dbe58a2094e5cf | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 402 | lean | universe variables u
attribute [instance]
definition pred2subtype {A : Type u} : has_coe_to_sort (A → Prop) :=
⟨Type u, λ p : A → Prop, subtype p⟩
definition below (n : nat) : nat → Prop :=
λ i, i < n
check λ x : below 10, x
definition f : below 10 → nat
| ⟨a, h⟩ := a
lemma zlt10 : 0 < 10 :=
sorry
check f ⟨0, zlt10⟩
definition g (a : below 10) : nat :=
subtype.elt_of a
|
d464f6c186276c6c60a9ae03ae0d5bf27884db0b | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/LocalContext.lean | c7d0caeb77d0c0eb92471bb432ea071dda2391e9 | [
"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 | 18,934 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.PersistentArray
import Lean.Expr
import Lean.Hygiene
namespace Lean
/--
Whether a local declaration should be found by type class search, tactics, etc.
and shown in the goal display.
-/
inductive LocalDeclKind
/--
Participates fully in type class search, tactics, and is shown even if inaccessible.
For example: the `x` in `fun x => _` has the default kind.
-/
| default
/--
Invisible to type class search or tactics, and hidden in the goal display.
This kind is used for temporary variables in macros.
For example: `return (← foo) + bar` expands to
`foo >>= fun __tmp => pure (__tmp + bar)`,
where `__tmp` has the `implDetail` kind.
-/
| implDetail
/--
Auxiliary local declaration for recursive calls.
The behavior is similar to `implDetail`.
For example: `def foo (n : Nat) : Nat := _` adds the local declaration
`foo : Nat → Nat` to allow recursive calls.
This declaration has the `auxDecl` kind.
-/
| auxDecl
deriving Inhabited, Repr, DecidableEq, Hashable
/-- A declaration for a LocalContext. This is used to register which free variables are in scope.
Each declaration comes with
- `index` the position of the decl in the local context
- `fvarId` the unique id of the free variables
- `userName` the pretty-printable name of the variable
- `type` the type.
A `cdecl` is a local variable, a `ldecl` is a let-bound free variable with a `value : Expr`.
-/
inductive LocalDecl where
| cdecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) (kind : LocalDeclKind)
| ldecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep : Bool) (kind : LocalDeclKind)
deriving Inhabited
@[export lean_mk_local_decl]
def mkLocalDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) : LocalDecl :=
.cdecl index fvarId userName type bi .default
@[export lean_mk_let_decl]
def mkLetDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : LocalDecl :=
.ldecl index fvarId userName type val false .default
@[export lean_local_decl_binder_info]
def LocalDecl.binderInfoEx : LocalDecl → BinderInfo
| .cdecl _ _ _ _ bi _ => bi
| _ => BinderInfo.default
namespace LocalDecl
def isLet : LocalDecl → Bool
| cdecl .. => false
| ldecl .. => true
def index : LocalDecl → Nat
| cdecl (index := i) .. => i
| ldecl (index := i) .. => i
def setIndex : LocalDecl → Nat → LocalDecl
| cdecl _ id n t bi k, idx => cdecl idx id n t bi k
| ldecl _ id n t v nd k, idx => ldecl idx id n t v nd k
def fvarId : LocalDecl → FVarId
| cdecl (fvarId := id) .. => id
| ldecl (fvarId := id) .. => id
def userName : LocalDecl → Name
| cdecl (userName := n) .. => n
| ldecl (userName := n) .. => n
def type : LocalDecl → Expr
| cdecl (type := t) .. => t
| ldecl (type := t) .. => t
def setType : LocalDecl → Expr → LocalDecl
| cdecl idx id n _ bi k, t => cdecl idx id n t bi k
| ldecl idx id n _ v nd k, t => ldecl idx id n t v nd k
def binderInfo : LocalDecl → BinderInfo
| cdecl (bi := bi) .. => bi
| ldecl .. => BinderInfo.default
def kind : LocalDecl → LocalDeclKind
| cdecl .. | ldecl .. => ‹_›
def isAuxDecl (d : LocalDecl) : Bool :=
d.kind = .auxDecl
/--
Is the local declaration an implementation-detail hypothesis
(including auxiliary declarations)?
-/
def isImplementationDetail (d : LocalDecl) : Bool :=
d.kind != .default
def value? : LocalDecl → Option Expr
| cdecl .. => none
| ldecl (value := v) .. => some v
def value : LocalDecl → Expr
| cdecl .. => panic! "let declaration expected"
| ldecl (value := v) .. => v
def hasValue : LocalDecl → Bool
| cdecl .. => false
| ldecl .. => true
def setValue : LocalDecl → Expr → LocalDecl
| ldecl idx id n t _ nd k, v => ldecl idx id n t v nd k
| d, _ => d
def setUserName : LocalDecl → Name → LocalDecl
| cdecl index id _ type bi k, userName => cdecl index id userName type bi k
| ldecl index id _ type val nd k, userName => ldecl index id userName type val nd k
def setBinderInfo : LocalDecl → BinderInfo → LocalDecl
| cdecl index id n type _ k, bi => cdecl index id n type bi k
| ldecl .., _ => panic! "unexpected let declaration"
def toExpr (decl : LocalDecl) : Expr :=
mkFVar decl.fvarId
def hasExprMVar : LocalDecl → Bool
| cdecl (type := t) .. => t.hasExprMVar
| ldecl (type := t) (value := v) .. => t.hasExprMVar || v.hasExprMVar
end LocalDecl
/-- A LocalContext is an ordered set of local variable declarations.
It is used to store the free variables (also known as local constants) that
are in scope.
When inspecting a goal or expected type in the infoview, the local
context is all of the variables above the `⊢` symbol.
-/
structure LocalContext where
fvarIdToDecl : PersistentHashMap FVarId LocalDecl := {}
decls : PersistentArray (Option LocalDecl) := {}
deriving Inhabited
namespace LocalContext
@[export lean_mk_empty_local_ctx]
def mkEmpty : Unit → LocalContext := fun _ => {}
def empty : LocalContext := {}
@[export lean_local_ctx_is_empty]
def isEmpty (lctx : LocalContext) : Bool :=
lctx.fvarIdToDecl.isEmpty
/-- Low level API for creating local declarations.
It is used to implement actions in the monads `Elab` and `Tactic`.
It should not be used directly since the argument `(fvarId : FVarId)` is
assumed to be unique. You can create a unique fvarId with `mkFreshFVarId`. -/
def mkLocalDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo := BinderInfo.default) (kind : LocalDeclKind := .default) : LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
let idx := decls.size
let decl := LocalDecl.cdecl idx fvarId userName type bi kind
{ fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl }
-- `mkLocalDecl` without `kind`
@[export lean_local_ctx_mk_local_decl]
private def mkLocalDeclExported (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) : LocalContext :=
mkLocalDecl lctx fvarId userName type bi
/-- Low level API for let declarations. Do not use directly.-/
def mkLetDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep := false) (kind : LocalDeclKind := default) : LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
let idx := decls.size
let decl := LocalDecl.ldecl idx fvarId userName type value nonDep kind
{ fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl }
@[export lean_local_ctx_mk_let_decl]
private def mkLetDeclExported (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep : Bool) : LocalContext :=
mkLetDecl lctx fvarId userName type value nonDep
/-- Low level API for adding a local declaration.
Do not use directly. -/
def addDecl (lctx : LocalContext) (newDecl : LocalDecl) : LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
let idx := decls.size
let newDecl := newDecl.setIndex idx
{ fvarIdToDecl := map.insert newDecl.fvarId newDecl, decls := decls.push newDecl }
@[export lean_local_ctx_find]
def find? (lctx : LocalContext) (fvarId : FVarId) : Option LocalDecl :=
lctx.fvarIdToDecl.find? fvarId
def findFVar? (lctx : LocalContext) (e : Expr) : Option LocalDecl :=
lctx.find? e.fvarId!
def get! (lctx : LocalContext) (fvarId : FVarId) : LocalDecl :=
match lctx.find? fvarId with
| some d => d
| none => panic! "unknown free variable"
/-- Gets the declaration for expression `e` in the local context.
If `e` is not a free variable or not present then panics. -/
def getFVar! (lctx : LocalContext) (e : Expr) : LocalDecl :=
lctx.get! e.fvarId!
def contains (lctx : LocalContext) (fvarId : FVarId) : Bool :=
lctx.fvarIdToDecl.contains fvarId
/-- Returns true when the lctx contains the free variable `e`.
Panics if `e` is not an fvar. -/
def containsFVar (lctx : LocalContext) (e : Expr) : Bool :=
lctx.contains e.fvarId!
def getFVarIds (lctx : LocalContext) : Array FVarId :=
lctx.decls.foldl (init := #[]) fun r decl? => match decl? with
| some decl => r.push decl.fvarId
| none => r
/-- Return all of the free variables in the given context. -/
def getFVars (lctx : LocalContext) : Array Expr :=
lctx.getFVarIds.map mkFVar
private partial def popTailNoneAux (a : PArray (Option LocalDecl)) : PArray (Option LocalDecl) :=
if a.size == 0 then a
else match a.get! (a.size - 1) with
| none => popTailNoneAux a.pop
| some _ => a
@[export lean_local_ctx_erase]
def erase (lctx : LocalContext) (fvarId : FVarId) : LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
match map.find? fvarId with
| none => lctx
| some decl => { fvarIdToDecl := map.erase fvarId, decls := popTailNoneAux (decls.set decl.index none) }
def pop (lctx : LocalContext): LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
if decls.size == 0 then lctx
else match decls.get! (decls.size - 1) with
| none => lctx -- unreachable
| some decl => { fvarIdToDecl := map.erase decl.fvarId, decls := popTailNoneAux decls.pop }
def findFromUserName? (lctx : LocalContext) (userName : Name) : Option LocalDecl :=
lctx.decls.findSomeRev? fun decl =>
match decl with
| none => none
| some decl => if decl.userName == userName then some decl else none
def usesUserName (lctx : LocalContext) (userName : Name) : Bool :=
(lctx.findFromUserName? userName).isSome
private partial def getUnusedNameAux (lctx : LocalContext) (suggestion : Name) (i : Nat) : Name × Nat :=
let curr := suggestion.appendIndexAfter i
if lctx.usesUserName curr then getUnusedNameAux lctx suggestion (i + 1)
else (curr, i + 1)
def getUnusedName (lctx : LocalContext) (suggestion : Name) : Name :=
let suggestion := suggestion.eraseMacroScopes
if lctx.usesUserName suggestion then (getUnusedNameAux lctx suggestion 1).1
else suggestion
def lastDecl (lctx : LocalContext) : Option LocalDecl :=
lctx.decls.get! (lctx.decls.size - 1)
def setUserName (lctx : LocalContext) (fvarId : FVarId) (userName : Name) : LocalContext :=
let decl := lctx.get! fvarId
let decl := decl.setUserName userName
{ fvarIdToDecl := lctx.fvarIdToDecl.insert decl.fvarId decl,
decls := lctx.decls.set decl.index decl }
def renameUserName (lctx : LocalContext) (fromName : Name) (toName : Name) : LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
match lctx.findFromUserName? fromName with
| none => lctx
| some decl =>
let decl := decl.setUserName toName;
{ fvarIdToDecl := map.insert decl.fvarId decl,
decls := decls.set decl.index decl }
/--
Low-level function for updating the local context.
Assumptions about `f`, the resulting nested expressions must be definitionally equal to their original values,
the `index` nor `fvarId` are modified. -/
@[inline] def modifyLocalDecl (lctx : LocalContext) (fvarId : FVarId) (f : LocalDecl → LocalDecl) : LocalContext :=
match lctx with
| { fvarIdToDecl := map, decls := decls } =>
match lctx.find? fvarId with
| none => lctx
| some decl =>
let decl := f decl
{ fvarIdToDecl := map.insert decl.fvarId decl
decls := decls.set decl.index decl }
def setBinderInfo (lctx : LocalContext) (fvarId : FVarId) (bi : BinderInfo) : LocalContext :=
modifyLocalDecl lctx fvarId fun decl => decl.setBinderInfo bi
@[export lean_local_ctx_num_indices]
def numIndices (lctx : LocalContext) : Nat :=
lctx.decls.size
def getAt? (lctx : LocalContext) (i : Nat) : Option LocalDecl :=
lctx.decls.get! i
@[specialize] def foldlM [Monad m] (lctx : LocalContext) (f : β → LocalDecl → m β) (init : β) (start : Nat := 0) : m β :=
lctx.decls.foldlM (init := init) (start := start) fun b decl => match decl with
| none => pure b
| some decl => f b decl
@[specialize] def foldrM [Monad m] (lctx : LocalContext) (f : LocalDecl → β → m β) (init : β) : m β :=
lctx.decls.foldrM (init := init) fun decl b => match decl with
| none => pure b
| some decl => f decl b
@[specialize] def forM [Monad m] (lctx : LocalContext) (f : LocalDecl → m PUnit) : m PUnit :=
lctx.decls.forM fun decl => match decl with
| none => pure PUnit.unit
| some decl => f decl
@[specialize] def findDeclM? [Monad m] (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) :=
lctx.decls.findSomeM? fun decl => match decl with
| none => pure none
| some decl => f decl
@[specialize] def findDeclRevM? [Monad m] (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) :=
lctx.decls.findSomeRevM? fun decl => match decl with
| none => pure none
| some decl => f decl
instance : ForIn m LocalContext LocalDecl where
forIn lctx init f := lctx.decls.forIn init fun d? b => match d? with
| none => return ForInStep.yield b
| some d => f d b
@[inline] def foldl (lctx : LocalContext) (f : β → LocalDecl → β) (init : β) (start : Nat := 0) : β :=
Id.run <| lctx.foldlM f init start
@[inline] def foldr (lctx : LocalContext) (f : LocalDecl → β → β) (init : β) : β :=
Id.run <| lctx.foldrM f init
def size (lctx : LocalContext) : Nat :=
lctx.foldl (fun n _ => n+1) 0
@[inline] def findDecl? (lctx : LocalContext) (f : LocalDecl → Option β) : Option β :=
Id.run <| lctx.findDeclM? f
@[inline] def findDeclRev? (lctx : LocalContext) (f : LocalDecl → Option β) : Option β :=
Id.run <| lctx.findDeclRevM? f
partial def isSubPrefixOfAux (a₁ a₂ : PArray (Option LocalDecl)) (exceptFVars : Array Expr) (i j : Nat) : Bool :=
if i < a₁.size then
match a₁[i]! with
| none => isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) j
| some decl₁ =>
if exceptFVars.any fun fvar => fvar.fvarId! == decl₁.fvarId then
isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) j
else if j < a₂.size then
match a₂[j]! with
| none => isSubPrefixOfAux a₁ a₂ exceptFVars i (j+1)
| some decl₂ => if decl₁.fvarId == decl₂.fvarId then isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) (j+1) else isSubPrefixOfAux a₁ a₂ exceptFVars i (j+1)
else false
else true
/-- Given `lctx₁ - exceptFVars` of the form `(x_1 : A_1) ... (x_n : A_n)`, then return true
iff there is a local context `B_1* (x_1 : A_1) ... B_n* (x_n : A_n)` which is a prefix
of `lctx₂` where `B_i`'s are (possibly empty) sequences of local declarations. -/
def isSubPrefixOf (lctx₁ lctx₂ : LocalContext) (exceptFVars : Array Expr := #[]) : Bool :=
isSubPrefixOfAux lctx₁.decls lctx₂.decls exceptFVars 0 0
@[inline] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr :=
let b := b.abstract xs
xs.size.foldRev (init := b) fun i b =>
let x := xs[i]!
match lctx.findFVar? x with
| some (.cdecl _ _ n ty bi _) =>
let ty := ty.abstractRange i xs;
if isLambda then
Lean.mkLambda n bi ty b
else
Lean.mkForall n bi ty b
| some (.ldecl _ _ n ty val nonDep _) =>
if b.hasLooseBVar 0 then
let ty := ty.abstractRange i xs
let val := val.abstractRange i xs
mkLet n ty val b nonDep
else
b.lowerLooseBVars 1 1
| none => panic! "unknown free variable"
/-- Creates the expression `fun x₁ .. xₙ => b` for free variables `xs = #[x₁, .., xₙ]`,
suitably abstracting `b` and the types for each of the `xᵢ`. -/
def mkLambda (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr :=
mkBinding true lctx xs b
/-- Creates the expression `(x₁:α₁) → .. → (xₙ:αₙ) → b` for free variables `xs = #[x₁, .., xₙ]`,
suitably abstracting `b` and the types for each of the `xᵢ`, `αᵢ`. -/
def mkForall (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr :=
mkBinding false lctx xs b
@[inline] def anyM [Monad m] (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool :=
lctx.decls.anyM fun d => match d with
| some decl => p decl
| none => pure false
@[inline] def allM [Monad m] (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool :=
lctx.decls.allM fun d => match d with
| some decl => p decl
| none => pure true
/-- Return `true` if `lctx` contains a local declaration satisfying `p`. -/
@[inline] def any (lctx : LocalContext) (p : LocalDecl → Bool) : Bool :=
Id.run <| lctx.anyM p
/-- Return `true` if all declarations in `lctx` satisfy `p`. -/
@[inline] def all (lctx : LocalContext) (p : LocalDecl → Bool) : Bool :=
Id.run <| lctx.allM p
/-- If option `pp.sanitizeNames` is set to `true`, add tombstone to shadowed local declaration names and ones contains macroscopes. -/
def sanitizeNames (lctx : LocalContext) : StateM NameSanitizerState LocalContext := do
let st ← get
if !getSanitizeNames st.options then pure lctx else
StateT.run' (s := ({} : NameSet)) <|
lctx.decls.size.foldRevM (init := lctx) fun i lctx => do
match lctx.decls[i]! with
| none => pure lctx
| some decl =>
if decl.userName.hasMacroScopes || (← get).contains decl.userName then do
modify fun s => s.insert decl.userName
let userNameNew ← liftM <| sanitizeName decl.userName
pure <| lctx.setUserName decl.fvarId userNameNew
else
modify fun s => s.insert decl.userName
pure lctx
end LocalContext
/-- Class used to denote that `m` has a local context. -/
class MonadLCtx (m : Type → Type) where
getLCtx : m LocalContext
export MonadLCtx (getLCtx)
instance [MonadLift m n] [MonadLCtx m] : MonadLCtx n where
getLCtx := liftM (getLCtx : m _)
def LocalDecl.replaceFVarId (fvarId : FVarId) (e : Expr) (d : LocalDecl) : LocalDecl :=
if d.fvarId == fvarId then d
else match d with
| .cdecl idx id n type bi k => .cdecl idx id n (type.replaceFVarId fvarId e) bi k
| .ldecl idx id n type val nonDep k => .ldecl idx id n (type.replaceFVarId fvarId e) (val.replaceFVarId fvarId e) nonDep k
def LocalContext.replaceFVarId (fvarId : FVarId) (e : Expr) (lctx : LocalContext) : LocalContext :=
let lctx := lctx.erase fvarId
{ fvarIdToDecl := lctx.fvarIdToDecl.map (·.replaceFVarId fvarId e)
decls := lctx.decls.map fun localDecl? => localDecl?.map (·.replaceFVarId fvarId e) }
end Lean
|
09809350491ce846c12723ccf139fbbd5cefe19f | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /src/Lean/Meta/ExprDefEq.lean | d1617f86ccb6370e0923d99d8b1ea92886e86b98 | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 54,542 | 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.ProjFns
import Lean.Meta.WHNF
import Lean.Meta.InferType
import Lean.Meta.FunInfo
import Lean.Meta.LevelDefEq
import Lean.Meta.Check
import Lean.Meta.Offset
import Lean.Meta.ForEachExpr
import Lean.Meta.UnificationHint
namespace Lean.Meta
/--
Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`.
Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean.
Example:
```
(fun x : A => f ?m) =?= f
```
The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/
private def isDefEqEta (a b : Expr) : MetaM Bool := do
if a.isLambda && !b.isLambda then
let bType ← inferType b
let bType ← whnfD bType
match bType with
| Expr.forallE n d _ c =>
let b' := mkLambda n c.binderInfo d (mkApp b (mkBVar 0))
commitWhen $ Meta.isExprDefEqAux a b'
| _ => pure false
else
pure false
/-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/
def isDefEqNative (s t : Expr) : MetaM LBool := do
let isDefEq (s t) : MetaM LBool := toLBoolM $ Meta.isExprDefEqAux s t
let s? ← reduceNative? s
let t? ← reduceNative? t
match s?, t? with
| some s, some t => isDefEq s t
| some s, none => isDefEq s t
| none, some t => isDefEq s t
| none, none => pure LBool.undef
/-- Support for reducing Nat basic operations. -/
def isDefEqNat (s t : Expr) : MetaM LBool := do
let isDefEq (s t) : MetaM LBool := toLBoolM $ Meta.isExprDefEqAux s t
if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then
pure LBool.undef
else
let s? ← reduceNat? s
let t? ← reduceNat? t
match s?, t? with
| some s, some t => isDefEq s t
| some s, none => isDefEq s t
| none, some t => isDefEq s t
| none, none => pure LBool.undef
/-- Support for constraints of the form `("..." =?= String.mk cs)` -/
def isDefEqStringLit (s t : Expr) : MetaM LBool := do
let isDefEq (s t) : MetaM LBool := toLBoolM $ Meta.isExprDefEqAux s t
if s.isStringLit && t.isAppOf `String.mk then
isDefEq (toCtorIfLit s) t
else if s.isAppOf `String.mk && t.isStringLit then
isDefEq s (toCtorIfLit t)
else
pure LBool.undef
/--
Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned.
Remark: `n` may be 0. -/
def isEtaUnassignedMVar (e : Expr) : MetaM Bool := do
match e.etaExpanded? with
| some (Expr.mvar mvarId _) =>
if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then
pure false
else if (← isExprMVarAssigned mvarId) then
pure false
else
pure true
| _ => pure false
/-
First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases
Here, we say a case is easy if it is of the form
?m =?= t
or
t =?= ?m
where `?m` is unassigned.
These easy cases are not just an optimization. When
`?m` is a function, by assigning it to t, we make sure
a unification constraint (in the explicit part)
```
?m t =?= f s
```
is not higher-order.
We also handle the eta-expanded cases:
```
fun x₁ ... xₙ => ?m x₁ ... xₙ =?= t
t =?= fun x₁ ... xₙ => ?m x₁ ... xₙ
This is important because type inference often produces
eta-expanded terms, and without this extra case, we could
introduce counter intuitive behavior.
Pre: `paramInfo.size <= args₁.size = args₂.size`
-/
private partial def isDefEqArgsFirstPass
(paramInfo : Array ParamInfo) (args₁ args₂ : Array Expr) : MetaM (Option (Array Nat)) := do
let rec loop (i : Nat) (postponed : Array Nat) := do
if h : i < paramInfo.size then
let info := paramInfo.get ⟨i, h⟩
let a₁ := args₁[i]
let a₂ := args₂[i]
if info.implicit || info.instImplicit then
if (← isEtaUnassignedMVar a₁ <||> isEtaUnassignedMVar a₂) then
if (← Meta.isExprDefEqAux a₁ a₂) then
loop (i+1) postponed
else
pure none
else
loop (i+1) (postponed.push i)
else if (← Meta.isExprDefEqAux a₁ a₂) then
loop (i+1) postponed
else
pure none
else
pure (some postponed)
loop 0 #[]
@[specialize] private def trySynthPending (e : Expr) : MetaM Bool := do
let mvarId? ← getStuckMVar? e
match mvarId? with
| some mvarId => Meta.synthPending mvarId
| none => pure false
private partial def isDefEqArgs (f : Expr) (args₁ args₂ : Array Expr) : MetaM Bool :=
if h : args₁.size = args₂.size then do
let finfo ← getFunInfoNArgs f args₁.size
let (some postponed) ← isDefEqArgsFirstPass finfo.paramInfo args₁ args₂ | pure false
let rec processOtherArgs (i : Nat) : MetaM Bool := do
if h₁ : i < args₁.size then
let a₁ := args₁.get ⟨i, h₁⟩
let a₂ := args₂.get ⟨i, Eq.subst h h₁⟩
if (← Meta.isExprDefEqAux a₁ a₂) then
processOtherArgs (i+1)
else
pure false
else
pure true
if (← processOtherArgs finfo.paramInfo.size) then
postponed.allM fun i => do
/- Second pass: unify implicit arguments.
In the second pass, we make sure we are unfolding at
least non reducible definitions (default setting). -/
let a₁ := args₁[i]
let a₂ := args₂[i]
let info := finfo.paramInfo[i]
if info.instImplicit then
discard <| trySynthPending a₁
discard <| trySynthPending a₂
withAtLeastTransparency TransparencyMode.default $ Meta.isExprDefEqAux a₁ a₂
else
pure false
else
pure false
/--
Check whether the types of the free variables at `fvars` are
definitionally equal to the types at `ds₂`.
Pre: `fvars.size == ds₂.size`
This method also updates the set of local instances, and invokes
the continuation `k` with the updated set.
We can't use `withNewLocalInstances` because the `isDeq fvarType d₂`
may use local instances. -/
@[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds₂ : Array Expr) (k : MetaM Bool) : MetaM Bool :=
let rec loop (i : Nat) := do
if h : i < fvars.size then do
let fvar := fvars.get ⟨i, h⟩
let fvarDecl ← getFVarLocalDecl fvar
let fvarType := fvarDecl.type
let d₂ := ds₂[i]
if (← Meta.isExprDefEqAux fvarType d₂) then
match (← isClass? fvarType) with
| some className => withNewLocalInstance className fvar $ loop (i+1)
| none => loop (i+1)
else
pure false
else
k
loop 0
/- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`.
It accumulates the new free variables in `fvars`, and declare them at `lctx`.
We use the domain types of `e₁` to create the new free variables.
We store the domain types of `e₂` at `ds₂`. -/
private partial def isDefEqBindingAux (lctx : LocalContext) (fvars : Array Expr) (e₁ e₂ : Expr) (ds₂ : Array Expr) : MetaM Bool :=
let process (n : Name) (d₁ d₂ b₁ b₂ : Expr) : MetaM Bool := do
let d₁ := d₁.instantiateRev fvars
let d₂ := d₂.instantiateRev fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLocalDecl fvarId n d₁
let fvars := fvars.push (mkFVar fvarId)
isDefEqBindingAux lctx fvars b₁ b₂ (ds₂.push d₂)
match e₁, e₂ with
| Expr.forallE n d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂
| Expr.lam n d₁ b₁ _, Expr.lam _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂
| _, _ =>
withReader (fun ctx => { ctx with lctx := lctx }) do
isDefEqBindingDomain fvars ds₂ $
Meta.isExprDefEqAux (e₁.instantiateRev fvars) (e₂.instantiateRev fvars)
@[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do
let lctx ← getLCtx
isDefEqBindingAux lctx #[] a b #[]
private def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool :=
traceCtx `Meta.isDefEq.assign.checkTypes do
if !mvar.isMVar then
trace[Meta.isDefEq.assign.final]! "metavariable expected at {mvar} := {v}"
return false
else
-- must check whether types are definitionally equal or not, before assigning and returning true
let mvarType ← inferType mvar
let vType ← inferType v
if (← withTransparency TransparencyMode.default $ Meta.isExprDefEqAux mvarType vType) then
trace[Meta.isDefEq.assign.final]! "{mvar} := {v}"
assignExprMVar mvar.mvarId! v
pure true
else
trace[Meta.isDefEq.assign.typeMismatch]! "{mvar} : {mvarType} := {v} : {vType}"
pure false
/--
Auxiliary method for solving constraints of the form `?m xs := v`.
It creates a lambda using `mkLambdaFVars ys v`, where `ys` is a superset of `xs`.
`ys` is often equal to `xs`. It is a bigger when there are let-declaration dependencies in `xs`.
For example, suppose we have `xs` of the form `#[a, c]` where
```
a : Nat
b : Nat := f a
c : b = a
```
In this scenario, the type of `?m` is `(x1 : Nat) -> (x2 : f x1 = x1) -> C[x1, x2]`,
and type of `v` is `C[a, c]`. Note that, `?m a c` is type correct since `f a = a` is definitionally equal
to the type of `c : b = a`, and the type of `?m a c` is equal to the type of `v`.
Note that `fun xs => v` is the term `fun (x1 : Nat) (x2 : b = x1) => v` which has type
`(x1 : Nat) -> (x2 : b = x1) -> C[x1, x2]` which is not definitionally equal to the type of `?m`,
and may not even be type correct.
The issue here is that we are not capturing the `let`-declarations.
This method collects let-declarations `y` occurring between `xs[0]` and `xs.back` s.t.
some `x` in `xs` depends on `y`.
`ys` is the `xs` with these extra let-declarations included.
In the example above, `ys` is `#[a, b, c]`, and `mkLambdaFVars ys v` produces
`fun a => let b := f a; fun (c : b = a) => v` which has a type definitionally equal to the type of `?m`.
Recall that the method `checkAssignment` ensures `v` does not contain offending `let`-declarations.
This method assumes that for any `xs[i]` and `xs[j]` where `i < j`, we have that `index of xs[i]` < `index of xs[j]`.
where the index is the position in the local context.
-/
private partial def mkLambdaFVarsWithLetDeps (xs : Array Expr) (v : Expr) : MetaM (Option Expr) := do
if not (← hasLetDeclsInBetween) then
mkLambdaFVars xs v
else
let ys ← addLetDeps
trace[Meta.debug]! "ys: {ys}, v: {v}"
mkLambdaFVars ys v
where
/- Return true if there are let-declarions between `xs[0]` and `xs[xs.size-1]`.
We use it a quick-check to avoid the more expensive collection procedure. -/
hasLetDeclsInBetween : MetaM Bool := do
let check (lctx : LocalContext) : Bool := do
let start := lctx.getFVar! xs[0] |>.index
let stop := lctx.getFVar! xs.back |>.index
for i in [start+1:stop] do
match lctx.getAt! i with
| some localDecl =>
if localDecl.isLet then
return true
| _ => pure ()
return false
if xs.size <= 1 then
pure false
else
check (← getLCtx)
/- Traverse `e` and stores in the state `NameHashSet` any let-declaration with index greater than `(← read)`.
The context `Nat` is the position of `xs[0]` in the local context. -/
collectLetDeclsFrom (e : Expr) : ReaderT Nat (StateRefT NameHashSet MetaM) Unit := do
let rec visit (e : Expr) : MonadCacheT Expr Unit (ReaderT Nat (StateRefT NameHashSet MetaM)) Unit :=
checkCache e fun _ => do
match e with
| Expr.forallE _ d b _ => visit d; visit b
| Expr.lam _ d b _ => visit d; visit b
| Expr.letE _ t v b _ => visit t; visit v; visit b
| Expr.app f a _ => visit f; visit a
| Expr.mdata _ b _ => visit b
| Expr.proj _ _ b _ => visit b
| Expr.fvar fvarId _ =>
let localDecl ← getLocalDecl fvarId
if localDecl.isLet && localDecl.index > (← read) then
modify fun s => s.insert localDecl.fvarId
| _ => pure ()
visit (← instantiateMVars e) |>.run
/-
Auxiliary definition for traversing all declarations between `xs[0]` ... `xs.back` backwards.
The `Nat` argument is the current position in the local context being visited, and it is less than
or equal to the position of `xs.back` in the local context.
The `Nat` context `(← read)` is the position of `xs[0]` in the local context.
-/
collectLetDepsAux : Nat → ReaderT Nat (StateRefT NameHashSet MetaM) Unit
| 0 => return ()
| i+1 => do
if i+1 == (← read) then
return ()
else
match (← getLCtx).getAt! (i+1) with
| none => collectLetDepsAux i
| some localDecl =>
if (← get).contains localDecl.fvarId then
collectLetDeclsFrom localDecl.type
match localDecl.value? with
| some val => collectLetDeclsFrom val
| _ => pure ()
collectLetDepsAux i
/- Computes the set `ys`. It is a set of `FVarId`s, -/
collectLetDeps : MetaM NameHashSet := do
let lctx ← getLCtx
let start := lctx.getFVar! xs[0] |>.index
let stop := lctx.getFVar! xs.back |>.index
let s := xs.foldl (init := {}) fun s x => s.insert x.fvarId!
let (_, s) ← collectLetDepsAux stop |>.run start |>.run s
return s
/- Computes the array `ys` containing let-decls between `xs[0]` and `xs.back` that
some `x` in `xs` depends on. -/
addLetDeps : MetaM (Array Expr) := do
let lctx ← getLCtx
let s ← collectLetDeps
/- Convert `s` into the the array `ys` -/
let start := lctx.getFVar! xs[0] |>.index
let stop := lctx.getFVar! xs.back |>.index
let mut ys := #[]
for i in [start:stop+1] do
match lctx.getAt! i with
| none => pure ()
| some localDecl =>
if s.contains localDecl.fvarId then
ys := ys.push localDecl.toExpr
return ys
/-
Each metavariable is declared in a particular local context.
We use the notation `C |- ?m : t` to denote a metavariable `?m` that
was declared at the local context `C` with type `t` (see `MetavarDecl`).
We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`.
The following method process the unification constraint
?m@C a₁ ... aₙ =?= t
We say the unification constraint is a pattern IFF
1) `a₁ ... aₙ` are pairwise distinct free variables that are *not* let-variables.
2) `a₁ ... aₙ` are not in `C`
3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}`
4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C`
5) `?m` does not occur in `t`
Claim: we don't have to check free variable declarations. That is,
if `t` contains a reference to `x : A := v`, we don't need to check `v`.
Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3).
If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`.
So, condition 4 and 5 are satisfied.
If the conditions above have been satisfied, then the
solution for the unification constrain is
?m := fun a₁ ... aₙ => t
Now, we consider some workarounds/approximations.
A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3)
(precise) solution: unfold `x` in `t`.
A2) Suppose some `aᵢ` is in `C` (failed condition 2)
(approximated) solution (when `config.ctxApprox` is set to true) :
ignore condition and also use
?m := fun a₁ ... aₙ => t
Here is an example where this approximation fails:
Given `C` containing `a : nat`, consider the following two constraints
?m@C a =?= a
?m@C b =?= a
If we use the approximation in the first constraint, we get
?m := fun x => x
when we apply this solution to the second one we get a failure.
IMPORTANT: When applying this approximation we need to make sure the
abstracted term `fun a₁ ... aₙ => t` is type correct. The check
can only be skipped in the pattern case described above. Consider
the following example. Given the local context
(α : Type) (a : α)
we try to solve
?m α =?= @id α a
If we use the approximation above we obtain:
?m := (fun α' => @id α' a)
which is a type incorrect term. `a` has type `α` but it is expected to have
type `α'`.
The problem occurs because the right hand side contains a free variable
`a` that depends on the free variable `α` being abstracted. Note that
this dependency cannot occur in patterns.
We can address this by type checking
the term after abstraction. This is not a significant performance
bottleneck because this case doesn't happen very often in practice
(262 times when compiling stdlib on Jan 2018). The second example
is trickier, but it also occurs less frequently (8 times when compiling
stdlib on Jan 2018, and all occurrences were at Init/Control when
we define monads and auxiliary combinators for them).
We considered three options for the addressing the issue on the second example:
A3) `a₁ ... aₙ` are not pairwise distinct (failed condition 1).
In Lean3, we would try to approximate this case using an approach similar to A2.
However, this approximation complicates the code, and is never used in the
Lean3 stdlib and mathlib.
A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`.
If `?m'` is assigned, we substitute.
If not, we create an auxiliary metavariable with a smaller scope.
Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step.
A5) If some `aᵢ` is not a free variable,
then we use first-order unification (if `config.foApprox` is set to true)
?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k
reduces to
?M a_1 ... a_i =?= f
a_{i+1} =?= b_1
...
a_{i+k} =?= b_k
A6) If (m =?= v) is of the form
?m a_1 ... a_n =?= ?m b_1 ... b_k
then we use first-order unification (if `config.foApprox` is set to true)
A7) When `foApprox`, we may use another approximation (`constApprox`) for solving constraints of the form
```
?m s₁ ... sₙ =?= t
```
where `s₁ ... sₙ` are arbitrary terms. We solve them by assigning the constant function to `?m`.
```
?m := fun _ ... _ => t
```
In general, this approximation may produce bad solutions, and may prevent coercions from being tried.
For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`.
In this situation, the
elaborator generates the unification constraint
```
?m Prop =?= IO Bool
```
It is not a higher-order pattern, nor first-order approximation is applicable. However, constant approximation
produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from
the decidable proposition `x > 0` to `Bool`.
On the other hand, the constant approximation is desirable for elaborating the term
```
let f (x : _) := pure "hello"; f ()
```
with expected type `IO String`.
In this example, the following unification contraint is generated.
```
?m () String =?= IO String
```
It is not a higher-order pattern, first-order approximation reduces it to
```
?m () =?= IO
```
which fails to be solved. However, constant approximation solves it by assigning
```
?m := fun _ => IO
```
Note that `f`s type is `(x : ?α) -> ?m x String`. The metavariable `?m` may depend on `x`.
If `constApprox` is set to true, we use constant approximation. Otherwise, we use a heuristic to decide
whether we should apply it or not. The heuristic is based on observing where the constraints above come from.
In the first example, the constraint `?m Prop =?= IO Bool` come from polymorphic method where `?m` is expected to
be a **function** of type `Type -> Type`. In the second example, the first argument of `?m` is used to model
a **potential** dependency on `x`. By using constant approximation here, we are just saying the type of `f`
does **not** depend on `x`. We claim this is a reasonable approximation in practice. Moreover, it is expected
by any functional programmer used to non-dependently type languages (e.g., Haskell).
We distinguish the two cases above by using the field `numScopeArgs` at `MetavarDecl`. This fiels tracks
how many metavariable arguments are representing dependencies.
-/
def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (numScopeArgs : Nat := 0) : MetaM Expr := do
mkFreshExprMVarAt lctx localInsts type MetavarKind.natural Name.anonymous numScopeArgs
namespace CheckAssignment
builtin_initialize checkAssignmentExceptionId : InternalExceptionId ← registerInternalExceptionId `checkAssignment
builtin_initialize outOfScopeExceptionId : InternalExceptionId ← registerInternalExceptionId `outOfScope
structure State where
cache : ExprStructMap Expr := {}
structure Context where
mvarId : MVarId
mvarDecl : MetavarDecl
fvars : Array Expr
hasCtxLocals : Bool
rhs : Expr
abbrev CheckAssignmentM := ReaderT Context $ StateRefT State MetaM
def throwCheckAssignmentFailure {α} : CheckAssignmentM α :=
throw $ Exception.internal checkAssignmentExceptionId
def throwOutOfScopeFVar {α} : CheckAssignmentM α :=
throw $ Exception.internal outOfScopeExceptionId
private def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do
return (← get).cache.find? e
private def cache (e r : Expr) : CheckAssignmentM Unit := do
modify fun s => { s with cache := s.cache.insert e r }
instance : MonadCache Expr Expr CheckAssignmentM := {
findCached? := findCached?, cache := cache
}
@[inline] private def visit (f : Expr → CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr :=
if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e (fun _ => f e)
private def addAssignmentInfo (msg : MessageData) : CheckAssignmentM MessageData := do
let ctx ← read
return m!" @ {mkMVar ctx.mvarId} {ctx.fvars} := {ctx.rhs}"
@[specialize] def checkFVar (check : Expr → CheckAssignmentM Expr) (fvar : Expr) : CheckAssignmentM Expr := do
let ctxMeta ← readThe Meta.Context
let ctx ← read
if ctx.mvarDecl.lctx.containsFVar fvar then
pure fvar
else
let lctx := ctxMeta.lctx
match lctx.findFVar? fvar with
| some (LocalDecl.ldecl _ _ _ _ v _) => visit check v
| _ =>
if ctx.fvars.contains fvar then pure fvar
else
traceM `Meta.isDefEq.assign.outOfScopeFVar do addAssignmentInfo fvar
throwOutOfScopeFVar
@[specialize] def checkMVar (check : Expr → CheckAssignmentM Expr) (mvar : Expr) : CheckAssignmentM Expr := do
let mvarId := mvar.mvarId!
let ctx ← read
let mctx ← getMCtx
if mvarId == ctx.mvarId then
traceM `Meta.isDefEq.assign.occursCheck $ addAssignmentInfo "occurs check failed"
throwCheckAssignmentFailure
else match mctx.getExprAssignment? mvarId with
| some v => check v
| none => match mctx.findDecl? mvarId with
| none => throwUnknownMVar mvarId
| some mvarDecl =>
if ctx.hasCtxLocals then
throwCheckAssignmentFailure -- It is not a pattern, then we fail and fall back to FO unification
else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then
/- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned.
We "substract" variables being abstracted because we use `elimMVarDeps` -/
pure mvar
else if mvarDecl.depth != mctx.depth || mvarDecl.kind.isSyntheticOpaque then
traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx $ addAssignmentInfo (mkMVar mvarId)
throwCheckAssignmentFailure
else
let ctxMeta ← readThe Meta.Context
if ctxMeta.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then
/- Create an auxiliary metavariable with a smaller context and "checked" type.
Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains
a metavariable that we also need to reduce the context.
We remove from `ctx.mvarDecl.lctx` any variable that is not in `mvarDecl.lctx`
or in `ctx.fvars`. We don't need to remove the ones in `ctx.fvars` because
`elimMVarDeps` will take care of them.
First, we collect `toErase` the variables that need to be erased.
Notat that if a variable is `ctx.fvars`, but it depends on variable at `toErase`,
we must also erase it.
-/
let toErase := mvarDecl.lctx.foldl (init := #[]) fun toErase localDecl =>
if ctx.mvarDecl.lctx.contains localDecl.fvarId then
toErase
else if ctx.fvars.any fun fvar => fvar.fvarId! == localDecl.fvarId then
if mctx.findLocalDeclDependsOn localDecl fun fvarId => toErase.contains fvarId then
-- localDecl depends on a variable that will be erased. So, we must add it to `toErase` too
toErase.push localDecl.fvarId
else
toErase
else
toErase.push localDecl.fvarId
let lctx := toErase.foldl (init := mvarDecl.lctx) fun lctx toEraseFVar =>
lctx.erase toEraseFVar
/- Compute new set of local instances. -/
let localInsts := mvarDecl.localInstances.filter fun localInst => toErase.contains localInst.fvar.fvarId!
let mvarType ← check mvarDecl.type
let newMVar ← mkAuxMVar lctx localInsts mvarType mvarDecl.numScopeArgs
modifyThe Meta.State fun s => { s with mctx := s.mctx.assignExpr mvarId newMVar }
pure newMVar
else
pure mvar
/-
Auxiliary function used to "fix" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables,
and one of them is out-of-scope.
See `Expr.app` case at `check`.
If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope,
an assigning `?m := fun _ ... _ => ?n` -/
def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do
let mvarType ← inferType mvar
forallBoundedTelescope mvarType numArgs fun xs _ => do
if xs.size != numArgs then pure false
else
let some v ← mkLambdaFVarsWithLetDeps xs newMVar | return false
checkTypesAndAssign mvar v
partial def check (e : Expr) : CheckAssignmentM Expr := do
match e with
| Expr.mdata _ b _ => return e.updateMData! (← visit check b)
| Expr.proj _ _ s _ => return e.updateProj! (← visit check s)
| Expr.lam _ d b _ => return e.updateLambdaE! (← visit check d) (← visit check b)
| Expr.forallE _ d b _ => return e.updateForallE! (← visit check d) (← visit check b)
| Expr.letE _ t v b _ => return e.updateLet! (← visit check t) (← visit check v) (← visit check b)
| Expr.bvar .. => return e
| Expr.sort .. => return e
| Expr.const .. => return e
| Expr.lit .. => return e
| Expr.fvar .. => visit (checkFVar check) e
| Expr.mvar .. => visit (checkMVar check) e
| Expr.app .. => e.withApp fun f args => do
let ctxMeta ← readThe Meta.Context
if f.isMVar && ctxMeta.config.ctxApprox && args.all Expr.isFVar then
let f ← visit (checkMVar check) f
catchInternalId outOfScopeExceptionId
(do
let args ← args.mapM (visit check)
pure $ mkAppN f args)
(fun ex => do
if (← f.isMVar <&&> isDelayedAssigned f.mvarId!) then
throw ex
else
let eType ← inferType e
let mvarType ← check eType
/- Create an auxiliary metavariable with a smaller context and "checked" type, assign `?f := fun _ => ?newMVar`
Note that `mvarType` may be different from `eType`. -/
let ctx ← read
let newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType
if (← assignToConstFun f args.size newMVar) then
pure newMVar
else
throw ex)
else
let f ← visit check f
let args ← args.mapM (visit check)
pure $ mkAppN f args
@[inline] def run (x : CheckAssignmentM Expr) (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do
let mvarDecl ← getMVarDecl mvarId
let ctx := { mvarId := mvarId, mvarDecl := mvarDecl, fvars := fvars, hasCtxLocals := hasCtxLocals, rhs := v : Context }
let x : CheckAssignmentM (Option Expr) :=
catchInternalIds [outOfScopeExceptionId, checkAssignmentExceptionId]
(do let e ← x; pure $ some e)
(fun _ => pure none)
x.run ctx |>.run' {}
end CheckAssignment
namespace CheckAssignmentQuick
partial def check
(hasCtxLocals ctxApprox : Bool)
(mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) (e : Expr) : Bool :=
let rec visit (e : Expr) : Bool :=
if !e.hasExprMVar && !e.hasFVar then
true
else match e with
| Expr.mdata _ b _ => visit b
| Expr.proj _ _ s _ => visit s
| Expr.app f a _ => visit f && visit a
| Expr.lam _ d b _ => visit d && visit b
| Expr.forallE _ d b _ => visit d && visit b
| Expr.letE _ t v b _ => visit t && visit v && visit b
| Expr.bvar .. => true
| Expr.sort .. => true
| Expr.const .. => true
| Expr.lit .. => true
| Expr.fvar fvarId .. =>
if mvarDecl.lctx.contains fvarId then true
else match lctx.find? fvarId with
| some (LocalDecl.ldecl _ _ _ _ v _) => false -- need expensive CheckAssignment.check
| _ =>
if fvars.any $ fun x => x.fvarId! == fvarId then true
else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it
| Expr.mvar mvarId' _ =>
match mctx.getExprAssignment? mvarId' with
| some _ => false -- use CheckAssignment.check to instantiate
| none =>
if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception
else match mctx.findDecl? mvarId' with
| none => false
| some mvarDecl' =>
if hasCtxLocals then false -- use CheckAssignment.check
else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true
else if mvarDecl'.depth != mctx.depth || mvarDecl'.kind.isSyntheticOpaque then false -- use CheckAssignment.check
else if ctxApprox && mvarDecl.lctx.isSubPrefixOf mvarDecl'.lctx then false -- use CheckAssignment.check
else true
visit e
end CheckAssignmentQuick
-- See checkAssignment
def checkAssignmentAux (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do
CheckAssignment.run (CheckAssignment.check v) mvarId fvars hasCtxLocals v
/--
Auxiliary function for handling constraints of the form `?m a₁ ... aₙ =?= v`.
It will check whether we can perform the assignment
```
?m := fun fvars => t
```
The result is `none` if the assignment can't be performed.
The result is `some newV` where `newV` is a possibly updated `v`. This method may need
to unfold let-declarations. -/
def checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do
if !v.hasExprMVar && !v.hasFVar then
pure (some v)
else
let mvarDecl ← getMVarDecl mvarId
let hasCtxLocals := fvars.any $ fun fvar => mvarDecl.lctx.containsFVar fvar
let ctx ← read
let mctx ← getMCtx
if CheckAssignmentQuick.check hasCtxLocals ctx.config.ctxApprox mctx ctx.lctx mvarDecl mvarId fvars v then
pure (some v)
else
let v ← instantiateMVars v
checkAssignmentAux mvarId fvars hasCtxLocals v
private def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool :=
match v with
| Expr.app f a _ =>
if args.isEmpty then
pure false
else
Meta.isExprDefEqAux args.back a <&&> Meta.isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f
| _ => pure false
/-
Auxiliary method for applying first-order unification. It is an approximation.
Remark: this method is trying to solve the unification constraint:
?m a₁ ... aₙ =?= v
It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`.
We have added support for unfolding here because we want to be able to solve unification problems such as
?m Unit =?= ITactic
where `ITactic` is defined as
def ITactic := Tactic Unit
-/
private partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool :=
let rec loop (v : Expr) := do
let cfg ← getConfig
if !cfg.foApprox then
pure false
else
trace[Meta.isDefEq.foApprox]! "{mvar} {args} := {v}"
let v := v.headBeta
if (← commitWhen $ processAssignmentFOApproxAux mvar args v) then
pure true
else
match (← unfoldDefinition? v) with
| none => pure false
| some v => loop v
loop v
private partial def simpAssignmentArgAux : Expr → MetaM Expr
| Expr.mdata _ e _ => simpAssignmentArgAux e
| e@(Expr.fvar fvarId _) => do
let decl ← getLocalDecl fvarId
match decl.value? with
| some value => simpAssignmentArgAux value
| _ => pure e
| e => pure e
/- Auxiliary procedure for processing `?m a₁ ... aₙ =?= v`.
We apply it to each `aᵢ`. It instantiates assigned metavariables if `aᵢ` is of the form `f[?n] b₁ ... bₘ`,
and then removes metadata, and zeta-expand let-decls. -/
private def simpAssignmentArg (arg : Expr) : MetaM Expr := do
let arg ← if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg
simpAssignmentArgAux arg
/- Assign `mvar := fun a_1 ... a_{numArgs} => v`.
We use it at `processConstApprox` and `isDefEqMVarSelf` -/
private def assignConst (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do
let mvarDecl ← getMVarDecl mvar.mvarId!
forallBoundedTelescope mvarDecl.type numArgs fun xs _ => do
if xs.size != numArgs then
pure false
else
let some v ← mkLambdaFVarsWithLetDeps xs v | pure false
trace[Meta.isDefEq.constApprox]! "{mvar} := {v}"
checkTypesAndAssign mvar v
private def processConstApprox (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do
let cfg ← getConfig
let mvarId := mvar.mvarId!
let mvarDecl ← getMVarDecl mvarId
if mvarDecl.numScopeArgs == numArgs || cfg.constApprox then
match (← checkAssignment mvarId #[] v) with
| none => pure false
| some v => assignConst mvar numArgs v
else
pure false
/-- Tries to solve `?m a₁ ... aₙ =?= v` by assigning `?m`.
It assumes `?m` is unassigned. -/
private partial def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool :=
traceCtx `Meta.isDefEq.assign do
trace[Meta.isDefEq.assign]! "{mvarApp} := {v}"
let mvar := mvarApp.getAppFn
let mvarDecl ← getMVarDecl mvar.mvarId!
let rec process (i : Nat) (args : Array Expr) (v : Expr) := do
let cfg ← getConfig
let useFOApprox (args : Array Expr) : MetaM Bool :=
processAssignmentFOApprox mvar args v <||> processConstApprox mvar args.size v
if h : i < args.size then
let arg := args.get ⟨i, h⟩
let arg ← simpAssignmentArg arg
let args := args.set ⟨i, h⟩ arg
match arg with
| Expr.fvar fvarId _ =>
if args[0:i].any fun prevArg => prevArg == arg then
useFOApprox args
else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then
useFOApprox args
else
process (i+1) args v
| _ =>
useFOApprox args
else
let v ← instantiateMVars v -- enforce A4
if v.getAppFn == mvar then
-- using A6
useFOApprox args
else
let mvarId := mvar.mvarId!
match (← checkAssignment mvarId args v) with
| none => useFOApprox args
| some v => do
trace[Meta.isDefEq.assign.beforeMkLambda]! "{mvar} {args} := {v}"
let some v ← mkLambdaFVarsWithLetDeps args v | return false
if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then
/- We need to type check `v` because abstraction using `mkLambdaFVars` may have produced
a type incorrect term. See discussion at A2 -/
if (← isTypeCorrect v) then
checkTypesAndAssign mvar v
else
trace[Meta.isDefEq.assign.typeError]! "{mvar} := {v}"
useFOApprox args
else
checkTypesAndAssign mvar v
process 0 mvarApp.getAppArgs v
/--
Similar to processAssignment, but if it fails, compute v's whnf and try again.
This helps to solve constraints such as `?m =?= { α := ?m, ... }.α`
Note this is not perfect solution since we still fail occurs check for constraints such as
```lean
?m =?= List { α := ?m, β := Nat }.β
```
-/
private def processAssignment' (mvarApp : Expr) (v : Expr) : MetaM Bool := do
if (← processAssignment mvarApp v) then
return true
else
let vNew ← whnf v
if vNew != v then
if mvarApp == vNew then
return true
else
processAssignment mvarApp vNew
else
return false
private def isDeltaCandidate? (t : Expr) : MetaM (Option ConstantInfo) :=
match t.getAppFn with
| Expr.const c _ _ => getConst? c
| _ => pure none
/-- Auxiliary method for isDefEqDelta -/
private def isListLevelDefEq (us vs : List Level) : MetaM LBool :=
toLBoolM $ isListLevelDefEqAux us vs
/-- Auxiliary method for isDefEqDelta -/
private def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do
trace[Meta.isDefEq.delta.unfoldLeft]! fn
toLBoolM $ Meta.isExprDefEqAux t s
/-- Auxiliary method for isDefEqDelta -/
private def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do
trace[Meta.isDefEq.delta.unfoldRight]! fn
toLBoolM $ Meta.isExprDefEqAux t s
/-- Auxiliary method for isDefEqDelta -/
private def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do
trace[Meta.isDefEq.delta.unfoldLeftRight]! fn
toLBoolM $ Meta.isExprDefEqAux t s
/-- Try to solve `f a₁ ... aₙ =?= f b₁ ... bₙ` by solving `a₁ =?= b₁, ..., aₙ =?= bₙ`.
Auxiliary method for isDefEqDelta -/
private def tryHeuristic (t s : Expr) : MetaM Bool :=
let tFn := t.getAppFn
let sFn := s.getAppFn
traceCtx `Meta.isDefEq.delta do
commitWhen do
let b ← isDefEqArgs tFn t.getAppArgs s.getAppArgs
<&&>
isListLevelDefEqAux tFn.constLevels! sFn.constLevels!
unless b do
trace[Meta.isDefEq.delta]! "heuristic failed {t} =?= {s}"
pure b
/-- Auxiliary method for isDefEqDelta -/
private abbrev unfold {α} (e : Expr) (failK : MetaM α) (successK : Expr → MetaM α) : MetaM α := do
match (← unfoldDefinition? e) with
| some e => successK e
| none => failK
/-- Auxiliary method for isDefEqDelta -/
private def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := do
match t, s with
| Expr.const _ ls₁ _, Expr.const _ ls₂ _ => isListLevelDefEq ls₁ ls₂
| Expr.app _ _ _, Expr.app _ _ _ =>
if (← tryHeuristic t s) then
pure LBool.true
else
unfold t
(unfold s (pure LBool.false) (fun s => isDefEqRight fn t s))
(fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s))
| _, _ => pure LBool.false
private def sameHeadSymbol (t s : Expr) : Bool :=
match t.getAppFn, s.getAppFn with
| Expr.const c₁ _ _, Expr.const c₂ _ _ => true
| _, _ => false
/--
- If headSymbol (unfold t) == headSymbol s, then unfold t
- If headSymbol (unfold s) == headSymbol t, then unfold s
- Otherwise unfold t and s if possible.
Auxiliary method for isDefEqDelta -/
private def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool :=
unfold t
(unfold s
(pure LBool.undef) -- `t` and `s` failed to be unfolded
(fun s => isDefEqRight sInfo.name t s))
(fun tNew =>
if sameHeadSymbol tNew s then
isDefEqLeft tInfo.name tNew s
else
unfold s
(isDefEqLeft tInfo.name tNew s)
(fun sNew =>
if sameHeadSymbol t sNew then
isDefEqRight sInfo.name t sNew
else
isDefEqLeftRight tInfo.name tNew sNew))
/-- If `t` and `s` do not contain metavariables, then use
kernel definitional equality heuristics.
Otherwise, use `unfoldComparingHeadsDefEq`.
Auxiliary method for isDefEqDelta -/
private def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool :=
if !t.hasExprMVar && !s.hasExprMVar then
/- If `t` and `s` do not contain metavariables,
we simulate strategy used in the kernel. -/
if tInfo.hints.lt sInfo.hints then
unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s
else if sInfo.hints.lt tInfo.hints then
unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s
else
unfoldComparingHeadsDefEq tInfo sInfo t s
else
unfoldComparingHeadsDefEq tInfo sInfo t s
/--
When `TransparencyMode` is set to `default` or `all`.
If `t` is reducible and `s` is not ==> `isDefEqLeft (unfold t) s`
If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)`
Otherwise, use `unfoldDefEq`
Auxiliary method for isDefEqDelta -/
private def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do
if (← shouldReduceReducibleOnly) then
unfoldDefEq tInfo sInfo t s
else
let tReducible ← isReducible tInfo.name
let sReducible ← isReducible sInfo.name
if tReducible && !sReducible then
unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s
else if !tReducible && sReducible then
unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s
else
unfoldDefEq tInfo sInfo t s
/--
If `t` is a projection function application and `s` is not ==> `isDefEqRight t (unfold s)`
If `s` is a projection function application and `t` is not ==> `isDefEqRight (unfold t) s`
Otherwise, use `unfoldReducibeDefEq`
Auxiliary method for isDefEqDelta -/
private def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do
let tProj? ← isProjectionFn tInfo.name
let sProj? ← isProjectionFn sInfo.name
if tProj? && !sProj? then
unfold s (unfoldDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s
else if !tProj? && sProj? then
unfold t (unfoldDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s
else
unfoldReducibeDefEq tInfo sInfo t s
/--
isDefEq by lazy delta reduction.
This method implements many different heuristics:
1- If only `t` can be unfolded => then unfold `t` and continue
2- If only `s` can be unfolded => then unfold `s` and continue
3- If `t` and `s` can be unfolded and they have the same head symbol, then
a) First try to solve unification by unifying arguments.
b) If it fails, unfold both and continue.
Implemented by `unfoldBothDefEq`
4- If `t` is a projection function application and `s` is not => then unfold `s` and continue.
5- If `s` is a projection function application and `t` is not => then unfold `t` and continue.
Remark: 4&5 are implemented by `unfoldNonProjFnDefEq`
6- If `t` is reducible and `s` is not => then unfold `t` and continue.
7- If `s` is reducible and `t` is not => then unfold `s` and continue
Remark: 6&7 are implemented by `unfoldReducibeDefEq`
8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel.
Implemented by `unfoldDefEq`
9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue.
10- If `headSymbol (unfold s) == headSymbol t`, then unfold s
11- Otherwise, unfold `t` and `s` and continue.
Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/
private def isDefEqDelta (t s : Expr) : MetaM LBool := do
let tInfo? ← isDeltaCandidate? t.getAppFn
let sInfo? ← isDeltaCandidate? s.getAppFn
match tInfo?, sInfo? with
| none, none => pure LBool.undef
| some tInfo, none => unfold t (pure LBool.undef) fun t => isDefEqLeft tInfo.name t s
| none, some sInfo => unfold s (pure LBool.undef) fun s => isDefEqRight sInfo.name t s
| some tInfo, some sInfo =>
if tInfo.name == sInfo.name then
unfoldBothDefEq tInfo.name t s
else
unfoldNonProjFnDefEq tInfo sInfo t s
private def isAssigned : Expr → MetaM Bool
| Expr.mvar mvarId _ => isExprMVarAssigned mvarId
| _ => pure false
private def isDelayedAssignedHead (tFn : Expr) (t : Expr) : MetaM Bool := do
match tFn with
| Expr.mvar mvarId _ =>
if (← isDelayedAssigned mvarId) then
let tNew ← instantiateMVars t
pure $ tNew != t
else
pure false
| _ => pure false
private def isSynthetic : Expr → MetaM Bool
| Expr.mvar mvarId _ => do
let mvarDecl ← getMVarDecl mvarId
match mvarDecl.kind with
| MetavarKind.synthetic => pure true
| MetavarKind.syntheticOpaque => pure true
| MetavarKind.natural => pure false
| _ => pure false
private def isAssignable : Expr → MetaM Bool
| Expr.mvar mvarId _ => do let b ← isReadOnlyOrSyntheticOpaqueExprMVar mvarId; pure (!b)
| _ => pure false
private def etaEq (t s : Expr) : Bool :=
match t.etaExpanded? with
| some t => t == s
| none => false
private def isLetFVar (fvarId : FVarId) : MetaM Bool := do
let decl ← getLocalDecl fvarId
pure decl.isLet
private def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do
let status ← isProofQuick t
match status with
| LBool.false =>
pure LBool.undef
| LBool.true =>
let tType ← inferType t
let sType ← inferType s
toLBoolM $ Meta.isExprDefEqAux tType sType
| LBool.undef =>
let tType ← inferType t
if (← isProp tType) then
let sType ← inferType s
toLBoolM $ Meta.isExprDefEqAux tType sType
else
pure LBool.undef
/- Try to solve constraint of the form `?m args₁ =?= ?m args₂`.
- First try to unify `args₁` and `args₂`, and return true if successful
- Otherwise, try to assign `?m` to a constant function of the form `fun x_1 ... x_n => ?n`
where `?n` is a fresh metavariable. See `processConstApprox`. -/
private def isDefEqMVarSelf (mvar : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := do
if args₁.size != args₂.size then
pure false
else if (← isDefEqArgs mvar args₁ args₂) then
pure true
else if !(← isAssignable mvar) then
pure false
else
let cfg ← getConfig
let mvarId := mvar.mvarId!
let mvarDecl ← getMVarDecl mvarId
if mvarDecl.numScopeArgs == args₁.size || cfg.constApprox then
let type ← inferType (mkAppN mvar args₁)
let auxMVar ← mkAuxMVar mvarDecl.lctx mvarDecl.localInstances type
assignConst mvar args₁.size auxMVar
else
pure false
/- Remove unnecessary let-decls -/
private def consumeLet : Expr → Expr
| e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b
| e => e
mutual
private partial def isDefEqQuick (t s : Expr) : MetaM LBool :=
let t := consumeLet t
let s := consumeLet s
match t, s with
| Expr.lit l₁ _, Expr.lit l₂ _ => pure (l₁ == l₂).toLBool
| Expr.sort u _, Expr.sort v _ => toLBoolM $ isLevelDefEqAux u v
| t@(Expr.lam _ _ _ _), s@(Expr.lam _ _ _ _) => if t == s then pure LBool.true else toLBoolM $ isDefEqBinding t s
| t@(Expr.forallE _ _ _ _), s@(Expr.forallE _ _ _ _) => if t == s then pure LBool.true else toLBoolM $ isDefEqBinding t s
| Expr.mdata _ t _, s => isDefEqQuick t s
| t, Expr.mdata _ s _ => isDefEqQuick t s
| t@(Expr.fvar fvarId₁ _), s@(Expr.fvar fvarId₂ _) => do
if (← isLetFVar fvarId₁ <||> isLetFVar fvarId₂) then
pure LBool.undef
else if fvarId₁ == fvarId₂ then
pure LBool.true
else
isDefEqProofIrrel t s
| t, s =>
isDefEqQuickOther t s
private partial def isDefEqQuickOther (t s : Expr) : MetaM LBool := do
if t == s then
pure LBool.true
else if etaEq t s || etaEq s t then
pure LBool.true -- t =?= (fun xs => t xs)
else
let tFn := t.getAppFn
let sFn := s.getAppFn
if !tFn.isMVar && !sFn.isMVar then
pure LBool.undef
else if (← isAssigned tFn) then
let t ← instantiateMVars t
isDefEqQuick t s
else if (← isAssigned sFn) then
let s ← instantiateMVars s
isDefEqQuick t s
else if (← isDelayedAssignedHead tFn t) then
let t ← instantiateMVars t
isDefEqQuick t s
else if (← isDelayedAssignedHead sFn s) then
let s ← instantiateMVars s
isDefEqQuick t s
else if (← isSynthetic tFn <&&> trySynthPending tFn) then
let t ← instantiateMVars t
isDefEqQuick t s
else if (← isSynthetic sFn <&&> trySynthPending sFn) then
let s ← instantiateMVars s
isDefEqQuick t s
else if tFn.isMVar && sFn.isMVar && tFn == sFn then
Bool.toLBool <$> isDefEqMVarSelf tFn t.getAppArgs s.getAppArgs
else
let tAssign? ← isAssignable tFn
let sAssign? ← isAssignable sFn
let assignableMsg (b : Bool) := if b then "[assignable]" else "[nonassignable]"
trace[Meta.isDefEq]! "{t} {assignableMsg tAssign?} =?= {s} {assignableMsg sAssign?}"
if tAssign? && !sAssign? then
toLBoolM <| processAssignment' t s
else if !tAssign? && sAssign? then
toLBoolM <| processAssignment' s t
else if !tAssign? && !sAssign? then
if tFn.isMVar || sFn.isMVar then
let ctx ← read
if ctx.config.isDefEqStuckEx then do
trace[Meta.isDefEq.stuck]! "{t} =?= {s}"
Meta.throwIsDefEqStuck
else
pure LBool.false
else
pure LBool.undef
else
isDefEqQuickMVarMVar t s
-- Both `t` and `s` are terms of the form `?m ...`
private partial def isDefEqQuickMVarMVar (t s : Expr) : MetaM LBool := do
let tFn := t.getAppFn
let sFn := s.getAppFn
let tMVarDecl ← getMVarDecl tFn.mvarId!
let sMVarDecl ← getMVarDecl sFn.mvarId!
if s.isMVar && !t.isMVar then
/- Solve `?m t =?= ?n` by trying first `?n := ?m t`.
Reason: this assignment is precise. -/
if (← commitWhen (processAssignment s t)) then
pure LBool.true
else
toLBoolM $ processAssignment t s
else
if (← commitWhen (processAssignment t s)) then
pure LBool.true
else
toLBoolM $ processAssignment s t
end
@[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do
let status ← x
match status with
| LBool.true => pure true
| LBool.false => pure false
| LBool.undef => k
@[specialize] private def unstuckMVar (e : Expr) (successK : Expr → MetaM Bool) (failK : MetaM Bool): MetaM Bool := do
match (← getStuckMVar? e) with
| some mvarId =>
trace[Meta.isDefEq.stuckMVar]! "found stuck MVar {mkMVar mvarId} : {← inferType (mkMVar mvarId)}"
if (← Meta.synthPending mvarId) then
let e ← instantiateMVars e
successK e
else
failK
| none => failK
private def isDefEqOnFailure (t s : Expr) : MetaM Bool :=
unstuckMVar t (fun t => Meta.isExprDefEqAux t s) <|
unstuckMVar s (fun s => Meta.isExprDefEqAux t s) <|
tryUnificationHints t s <||> tryUnificationHints s t
private def isDefEqProj : Expr → Expr → MetaM Bool
| Expr.proj _ i t _, Expr.proj _ j s _ => pure (i == j) <&&> Meta.isExprDefEqAux t s
| _, _ => pure false
partial def isExprDefEqAuxImpl (t : Expr) (s : Expr) : MetaM Bool := do
trace[Meta.isDefEq.step]! "{t} =?= {s}"
withNestedTraces do
whenUndefDo (isDefEqQuick t s) $
whenUndefDo (isDefEqProofIrrel t s) do
let t' ← whnfCore t
let s' ← whnfCore s
if t != t' || s != s' then
isExprDefEqAuxImpl t' s'
else do
if (← (isDefEqEta t s <||> isDefEqEta s t)) then pure true else
if (← isDefEqProj t s) then pure true else
whenUndefDo (isDefEqNative t s) do
whenUndefDo (isDefEqNat t s) do
whenUndefDo (isDefEqOffset t s) do
whenUndefDo (isDefEqDelta t s) do
match t, s with
| Expr.const c us _, Expr.const d vs _ => if c == d then isListLevelDefEqAux us vs else pure false
| Expr.app _ _ _, Expr.app _ _ _ =>
let tFn := t.getAppFn
if (← commitWhen (Meta.isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) then
pure true
else
isDefEqOnFailure t s
| _, _ =>
whenUndefDo (isDefEqStringLit t s) $
isDefEqOnFailure t s
builtin_initialize
isExprDefEqAuxRef.set isExprDefEqAuxImpl
builtin_initialize
registerTraceClass `Meta.isDefEq
registerTraceClass `Meta.isDefEq.foApprox
registerTraceClass `Meta.isDefEq.constApprox
registerTraceClass `Meta.isDefEq.delta
registerTraceClass `Meta.isDefEq.step
registerTraceClass `Meta.isDefEq.assign
end Lean.Meta
|
12911c3e2cfb9100be857fc7df428873a4da6ad3 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/u_eq_max_u_v.lean | 3d07f478f0f2e53d25bde31330999cf67bee591d | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 3,197 | lean | universe variables u v u1 u2 v1 v2
set_option pp.universes true
class semigroup (α : Type u) extends has_mul α :=
(mul_assoc : ∀ a b c : α, a * b * c = a * (b * c))
open smt_tactic
meta def blast : tactic unit := using_smt $ intros >> add_lemmas_from_facts >> iterate_at_most 3 ematch
notation `♮` := by blast
structure semigroup_morphism { α β : Type u } ( s : semigroup α ) ( t: semigroup β ) :=
(map: α → β)
(multiplicative : ∀ x y : α, map(x * y) = map(x) * map(y))
attribute [simp] semigroup_morphism.multiplicative
@[reducible] instance semigroup_morphism_to_map { α β : Type u } { s : semigroup α } { t: semigroup β } : has_coe_to_fun (semigroup_morphism s t) _ :=
{ coe := semigroup_morphism.map }
@[reducible] definition semigroup_identity { α : Type u } ( s: semigroup α ) : semigroup_morphism s s := ⟨ id, ♮ ⟩
@[reducible] definition semigroup_morphism_composition
{ α β γ : Type u } { s: semigroup α } { t: semigroup β } { u: semigroup γ}
( f: semigroup_morphism s t ) ( g: semigroup_morphism t u ) : semigroup_morphism s u :=
{
map := λ x, g (f x),
multiplicative := begin intros, simp [coe_fn] end
}
local attribute [simp] semigroup.mul_assoc
@[reducible] definition semigroup_product { α β : Type u } ( s : semigroup α ) ( t: semigroup β ) : semigroup (α × β) := {
mul := λ p q, (p^.fst * q^.fst, p^.snd * q^.snd),
mul_assoc := begin
intros,
simp [@has_mul.mul (α × β)]
end
}
definition semigroup_morphism_product
{ α β γ δ : Type u }
{ s_f : semigroup α } { s_g: semigroup β } { t_f : semigroup γ} { t_g: semigroup δ }
( f : semigroup_morphism s_f t_f ) ( g : semigroup_morphism s_g t_g )
: semigroup_morphism (semigroup_product s_f s_g) (semigroup_product t_f t_g) := {
map := λ p, (f p.1, g p.2),
multiplicative :=
begin
-- cf https://groups.google.com/d/msg/lean-user/bVs5FdjClp4/tfHiVjLIBAAJ
intros,
unfold has_mul.mul,
dsimp [coe_fn],
simp
end
}
structure Category :=
(Obj : Type u)
(Hom : Obj → Obj → Type v)
structure Functor (C : Category.{ u1 v1 }) (D : Category.{ u2 v2 }) :=
(onObjects : C^.Obj → D^.Obj)
(onMorphisms : Π { X Y : C^.Obj },
C^.Hom X Y → D^.Hom (onObjects X) (onObjects Y))
@[reducible] definition ProductCategory (C : Category) (D : Category) :
Category :=
{
Obj := C^.Obj × D^.Obj,
Hom := (λ X Y : C^.Obj × D^.Obj, C^.Hom (X^.fst) (Y^.fst) × D^.Hom (X^.snd) (Y^.snd))
}
namespace ProductCategory
notation (name := prod) C `×` D := ProductCategory C D
end ProductCategory
structure PreMonoidalCategory
extends carrier : Category :=
(tensor : Functor (carrier × carrier) carrier)
definition CategoryOfSemigroups : Category :=
{
Obj := Σ α : Type u, semigroup α,
Hom := λ s t, semigroup_morphism s.2 t.2
}
definition PreMonoidalCategoryOfSemigroups : PreMonoidalCategory := {
CategoryOfSemigroups with
tensor := {
onObjects := λ p, sigma.mk (p.1.1 × p.2.1) (semigroup_product p.1.2 p.2.2),
onMorphisms := λ s t f, semigroup_morphism_product f.1 f.2
}
}
|
ac0cadf4ed53515390bb06e1a105f23d5fd6f7fc | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/order/filter/pi.lean | ee86f301ba4ef6c85eb3f060c72615fa21969922 | [
"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 | 9,054 | lean | /-
Copyright (c) 2021 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov, Alex Kontorovich
-/
import order.filter.bases
/-!
# (Co)product of a family of filters
In this file we define two filters on `Π i, α i` and prove some basic properties of these filters.
* `filter.pi (f : Π i, filter (α i))` to be the maximal filter on `Π i, α i` such that
`∀ i, filter.tendsto (function.eval i) (filter.pi f) (f i)`. It is defined as
`Π i, filter.comap (function.eval i) (f i)`. This is a generalization of `filter.prod` to indexed
products.
* `filter.Coprod (f : Π i, filter (α i))`: a generalization of `filter.coprod`; it is the supremum
of `comap (eval i) (f i)`.
-/
open set function
open_locale classical filter
namespace filter
variables {ι : Type*} {α : ι → Type*} {f f₁ f₂ : Π i, filter (α i)} {s : Π i, set (α i)}
section pi
/-- The product of an indexed family of filters. -/
def pi (f : Π i, filter (α i)) : filter (Π i, α i) := ⨅ i, comap (eval i) (f i)
instance pi.is_countably_generated [countable ι] [∀ i, is_countably_generated (f i)] :
is_countably_generated (pi f) :=
infi.is_countably_generated _
lemma tendsto_eval_pi (f : Π i, filter (α i)) (i : ι) :
tendsto (eval i) (pi f) (f i) :=
tendsto_infi' i tendsto_comap
lemma tendsto_pi {β : Type*} {m : β → Π i, α i} {l : filter β} :
tendsto m l (pi f) ↔ ∀ i, tendsto (λ x, m x i) l (f i) :=
by simp only [pi, tendsto_infi, tendsto_comap_iff]
lemma le_pi {g : filter (Π i, α i)} : g ≤ pi f ↔ ∀ i, tendsto (eval i) g (f i) := tendsto_pi
@[mono] lemma pi_mono (h : ∀ i, f₁ i ≤ f₂ i) : pi f₁ ≤ pi f₂ := infi_mono $ λ i, comap_mono $ h i
lemma mem_pi_of_mem (i : ι) {s : set (α i)} (hs : s ∈ f i) :
eval i ⁻¹' s ∈ pi f :=
mem_infi_of_mem i $ preimage_mem_comap hs
lemma pi_mem_pi {I : set ι} (hI : I.finite) (h : ∀ i ∈ I, s i ∈ f i) :
I.pi s ∈ pi f :=
begin
rw [pi_def, bInter_eq_Inter],
refine mem_infi_of_Inter hI (λ i, _) subset.rfl,
exact preimage_mem_comap (h i i.2)
end
lemma mem_pi {s : set (Π i, α i)} : s ∈ pi f ↔
∃ (I : set ι), I.finite ∧ ∃ t : Π i, set (α i), (∀ i, t i ∈ f i) ∧ I.pi t ⊆ s :=
begin
split,
{ simp only [pi, mem_infi', mem_comap, pi_def],
rintro ⟨I, If, V, hVf, hVI, rfl, -⟩, choose t htf htV using hVf,
exact ⟨I, If, t, htf, Inter₂_mono (λ i _, htV i)⟩ },
{ rintro ⟨I, If, t, htf, hts⟩,
exact mem_of_superset (pi_mem_pi If $ λ i _, htf i) hts }
end
lemma mem_pi' {s : set (Π i, α i)} : s ∈ pi f ↔
∃ (I : finset ι), ∃ t : Π i, set (α i), (∀ i, t i ∈ f i) ∧ set.pi ↑I t ⊆ s :=
mem_pi.trans exists_finite_iff_finset
lemma mem_of_pi_mem_pi [∀ i, ne_bot (f i)] {I : set ι} (h : I.pi s ∈ pi f) {i : ι} (hi : i ∈ I) :
s i ∈ f i :=
begin
rcases mem_pi.1 h with ⟨I', I'f, t, htf, hts⟩,
refine mem_of_superset (htf i) (λ x hx, _),
have : ∀ i, (t i).nonempty, from λ i, nonempty_of_mem (htf i),
choose g hg,
have : update g i x ∈ I'.pi t,
{ intros j hj, rcases eq_or_ne j i with (rfl|hne); simp * },
simpa using hts this i hi
end
@[simp] lemma pi_mem_pi_iff [∀ i, ne_bot (f i)] {I : set ι} (hI : I.finite) :
I.pi s ∈ pi f ↔ ∀ i ∈ I, s i ∈ f i :=
⟨λ h i hi, mem_of_pi_mem_pi h hi, pi_mem_pi hI⟩
lemma has_basis_pi {ι' : ι → Type} {s : Π i, ι' i → set (α i)} {p : Π i, ι' i → Prop}
(h : ∀ i, (f i).has_basis (p i) (s i)) :
(pi f).has_basis (λ If : set ι × Π i, ι' i, If.1.finite ∧ ∀ i ∈ If.1, p i (If.2 i))
(λ If : set ι × Π i, ι' i, If.1.pi (λ i, s i $ If.2 i)) :=
begin
have : (pi f).has_basis _ _ := has_basis_infi' (λ i, (h i).comap (eval i : (Π j, α j) → α i)),
convert this,
ext,
simp
end
@[simp] lemma pi_inf_principal_univ_pi_eq_bot :
pi f ⊓ 𝓟 (set.pi univ s) = ⊥ ↔ ∃ i, f i ⊓ 𝓟 (s i) = ⊥ :=
begin
split,
{ simp only [inf_principal_eq_bot, mem_pi], contrapose!,
rintros (hsf : ∀ i, ∃ᶠ x in f i, x ∈ s i) I If t htf hts,
have : ∀ i, (s i ∩ t i).nonempty, from λ i, ((hsf i).and_eventually (htf i)).exists,
choose x hxs hxt,
exact hts (λ i hi, hxt i) (mem_univ_pi.2 hxs) },
{ simp only [inf_principal_eq_bot],
rintro ⟨i, hi⟩,
filter_upwards [mem_pi_of_mem i hi] with x using mt (λ h, h i trivial), },
end
@[simp] lemma pi_inf_principal_pi_eq_bot [Π i, ne_bot (f i)] {I : set ι} :
pi f ⊓ 𝓟 (set.pi I s) = ⊥ ↔ ∃ i ∈ I, f i ⊓ 𝓟 (s i) = ⊥ :=
begin
rw [← univ_pi_piecewise I, pi_inf_principal_univ_pi_eq_bot],
refine exists_congr (λ i, _),
by_cases hi : i ∈ I; simp [hi, (‹Π i, ne_bot (f i)› i).ne]
end
@[simp] lemma pi_inf_principal_univ_pi_ne_bot :
ne_bot (pi f ⊓ 𝓟 (set.pi univ s)) ↔ ∀ i, ne_bot (f i ⊓ 𝓟 (s i)) :=
by simp [ne_bot_iff]
@[simp] lemma pi_inf_principal_pi_ne_bot [Π i, ne_bot (f i)] {I : set ι} :
ne_bot (pi f ⊓ 𝓟 (I.pi s)) ↔ ∀ i ∈ I, ne_bot (f i ⊓ 𝓟 (s i)) :=
by simp [ne_bot_iff]
instance pi_inf_principal_pi.ne_bot [h : ∀ i, ne_bot (f i ⊓ 𝓟 (s i))] {I : set ι} :
ne_bot (pi f ⊓ 𝓟 (I.pi s)) :=
(pi_inf_principal_univ_pi_ne_bot.2 ‹_›).mono $ inf_le_inf_left _ $ principal_mono.2 $
λ x hx i hi, hx i trivial
@[simp] lemma pi_eq_bot : pi f = ⊥ ↔ ∃ i, f i = ⊥ :=
by simpa using @pi_inf_principal_univ_pi_eq_bot ι α f (λ _, univ)
@[simp] lemma pi_ne_bot : ne_bot (pi f) ↔ ∀ i, ne_bot (f i) := by simp [ne_bot_iff]
instance [∀ i, ne_bot (f i)] : ne_bot (pi f) := pi_ne_bot.2 ‹_›
@[simp] lemma map_eval_pi (f : Π i, filter (α i)) [∀ i, ne_bot (f i)] (i : ι) :
map (eval i) (pi f) = f i :=
begin
refine le_antisymm (tendsto_eval_pi f i) (λ s hs, _),
rcases mem_pi.1 (mem_map.1 hs) with ⟨I, hIf, t, htf, hI⟩,
rw [← image_subset_iff] at hI,
refine mem_of_superset (htf i) ((subset_eval_image_pi _ _).trans hI),
exact nonempty_of_mem (pi_mem_pi hIf (λ i hi, htf i))
end
@[simp] lemma pi_le_pi [∀ i, ne_bot (f₁ i)] : pi f₁ ≤ pi f₂ ↔ ∀ i, f₁ i ≤ f₂ i :=
⟨λ h i, map_eval_pi f₁ i ▸ (tendsto_eval_pi _ _).mono_left h, pi_mono⟩
@[simp] lemma pi_inj [∀ i, ne_bot (f₁ i)] : pi f₁ = pi f₂ ↔ f₁ = f₂ :=
begin
refine ⟨λ h, _, congr_arg pi⟩,
have hle : f₁ ≤ f₂ := pi_le_pi.1 h.le,
haveI : ∀ i, ne_bot (f₂ i) := λ i, ne_bot_of_le (hle i),
exact hle.antisymm (pi_le_pi.1 h.ge)
end
end pi
/-! ### `n`-ary coproducts of filters -/
section Coprod
/-- Coproduct of filters. -/
protected def Coprod (f : Π i, filter (α i)) : filter (Π i, α i) :=
⨆ i : ι, comap (eval i) (f i)
lemma mem_Coprod_iff {s : set (Π i, α i)} :
(s ∈ filter.Coprod f) ↔ (∀ i : ι, (∃ t₁ ∈ f i, eval i ⁻¹' t₁ ⊆ s)) :=
by simp [filter.Coprod]
lemma compl_mem_Coprod {s : set (Π i, α i)} :
sᶜ ∈ filter.Coprod f ↔ ∀ i, (eval i '' s)ᶜ ∈ f i :=
by simp only [filter.Coprod, mem_supr, compl_mem_comap]
lemma Coprod_ne_bot_iff' :
ne_bot (filter.Coprod f) ↔ (∀ i, nonempty (α i)) ∧ ∃ d, ne_bot (f d) :=
by simp only [filter.Coprod, supr_ne_bot, ← exists_and_distrib_left, ← comap_eval_ne_bot_iff']
@[simp] lemma Coprod_ne_bot_iff [∀ i, nonempty (α i)] :
ne_bot (filter.Coprod f) ↔ ∃ d, ne_bot (f d) :=
by simp [Coprod_ne_bot_iff', *]
lemma Coprod_eq_bot_iff' : filter.Coprod f = ⊥ ↔ (∃ i, is_empty (α i)) ∨ f = ⊥ :=
by simpa [not_and_distrib, funext_iff] using not_congr Coprod_ne_bot_iff'
@[simp] lemma Coprod_eq_bot_iff [∀ i, nonempty (α i)] : filter.Coprod f = ⊥ ↔ f = ⊥ :=
by simpa [funext_iff] using not_congr Coprod_ne_bot_iff
@[simp] lemma Coprod_bot' : filter.Coprod (⊥ : Π i, filter (α i)) = ⊥ :=
Coprod_eq_bot_iff'.2 (or.inr rfl)
@[simp] lemma Coprod_bot : filter.Coprod (λ _, ⊥ : Π i, filter (α i)) = ⊥ := Coprod_bot'
lemma ne_bot.Coprod [∀ i, nonempty (α i)] {i : ι} (h : ne_bot (f i)) :
ne_bot (filter.Coprod f) :=
Coprod_ne_bot_iff.2 ⟨i, h⟩
@[instance] lemma Coprod_ne_bot [∀ i, nonempty (α i)] [nonempty ι] (f : Π i, filter (α i))
[H : ∀ i, ne_bot (f i)] : ne_bot (filter.Coprod f) :=
(H (classical.arbitrary ι)).Coprod
@[mono] lemma Coprod_mono (hf : ∀ i, f₁ i ≤ f₂ i) : filter.Coprod f₁ ≤ filter.Coprod f₂ :=
supr_mono $ λ i, comap_mono (hf i)
variables {β : ι → Type*} {m : Π i, α i → β i}
lemma map_pi_map_Coprod_le :
map (λ (k : Π i, α i), λ i, m i (k i)) (filter.Coprod f) ≤ filter.Coprod (λ i, map (m i) (f i)) :=
begin
simp only [le_def, mem_map, mem_Coprod_iff],
intros s h i,
obtain ⟨t, H, hH⟩ := h i,
exact ⟨{x : α i | m i x ∈ t}, H, λ x hx, hH hx⟩
end
lemma tendsto.pi_map_Coprod {g : Π i, filter (β i)} (h : ∀ i, tendsto (m i) (f i) (g i)) :
tendsto (λ (k : Π i, α i), λ i, m i (k i)) (filter.Coprod f) (filter.Coprod g) :=
map_pi_map_Coprod_le.trans (Coprod_mono h)
end Coprod
end filter
|
36cd7c957dc0132b19f655c51110b0e50b102c01 | acc85b4be2c618b11fc7cb3005521ae6858a8d07 | /algebra/order.lean | ad6b794fe1578041a6fcd990a6153150e4af9a6f | [
"Apache-2.0"
] | permissive | linpingchuan/mathlib | d49990b236574df2a45d9919ba43c923f693d341 | 5ad8020f67eb13896a41cc7691d072c9331b1f76 | refs/heads/master | 1,626,019,377,808 | 1,508,048,784,000 | 1,508,048,784,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,188 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
universe u
variables {α : Type u}
lemma not_le_of_lt [preorder α] {a b : α} (h : a < b) : ¬ b ≤ a :=
(le_not_le_of_lt h).right
lemma not_lt_of_le [preorder α] {a b : α} (h : a ≤ b) : ¬ b < a
| hab := not_le_of_gt hab h
lemma not_lt_of_lt [linear_order α] {a b : α} (h : a < b) : ¬ b < a :=
lt_asymm h
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⟩, lt_of_le_of_ne h1 h2⟩
lemma eq_or_lt_of_le [partial_order α] {a b : α} (h : a ≤ b) : a = b ∨ a < b :=
(lt_or_eq_of_le h).symm
@[simp] lemma not_lt [linear_order α] {a b : α} : ¬ a < b ↔ b ≤ a :=
⟨(lt_or_ge a b).resolve_left, not_lt_of_le⟩
lemma le_of_not_lt [linear_order α] {a b : α} : ¬ a < b → b ≤ a :=
not_lt.1
@[simp] lemma not_le [linear_order α] {a b : α} : ¬ a ≤ b ↔ b < a :=
(lt_iff_le_not_le.trans ⟨and.right,
λ h, ⟨(le_total _ _).resolve_left h, h⟩⟩).symm
lemma not_lt_iff_eq_or_lt [linear_order α] {a b : α} : ¬ a < b ↔ a = b ∨ b < a :=
not_lt.trans $ le_iff_eq_or_lt.trans $ or_congr eq_comm iff.rfl
lemma le_imp_le_iff_lt_imp_lt [linear_order α] {a b c d : α} :
(a ≤ b → c ≤ d) ↔ (d < c → b < a) :=
⟨λ H h, lt_of_not_ge $ λ h', not_lt_of_ge (H h') h,
λ H h, le_of_not_gt $ λ h', not_le_of_gt (H h') h⟩
lemma le_iff_le_iff_lt_iff_lt [linear_order α] {a b c d : α} :
(a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) :=
⟨λ H, not_le.symm.trans $ iff.trans (not_congr H) $ not_le,
λ H, not_lt.symm.trans $ iff.trans (not_congr H) $ not_lt⟩
lemma eq_of_forall_le_iff [partial_order α] {a b : α}
(H : ∀ c, c ≤ a ↔ c ≤ b) : a = b :=
le_antisymm ((H _).1 (le_refl _)) ((H _).2 (le_refl _))
lemma eq_of_forall_ge_iff [partial_order α] {a b : α}
(H : ∀ c, a ≤ c ↔ b ≤ c) : a = b :=
le_antisymm ((H _).2 (le_refl _)) ((H _).1 (le_refl _))
|
fda125c60aa4bb046eb480ce16023cef8624442e | 367134ba5a65885e863bdc4507601606690974c1 | /src/topology/algebra/group_with_zero.lean | 857b9a53f633c76a1ee644eb05c0862bb2ca328a | [
"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,411 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury G. Kudryashov
-/
import topology.algebra.monoid
import algebra.group.pi
/-!
# Topological group with zero
In this file we define `has_continuous_inv'` to be a mixin typeclass a type with `has_inv` and
`has_zero` (e.g., a `group_with_zero`) such that `λ x, x⁻¹` is continuous at all nonzero points. Any
normed (semi)field has this property. Currently the only example of `has_continuous_inv'` in
`mathlib` which is not a normed field is the type `nnnreal` (a.k.a. `ℝ≥0`) of nonnegative real
numbers.
Then we prove lemmas about continuity of `x ↦ x⁻¹` and `f / g` providing dot-style `*.inv'` and
`*.div` operations on `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`,
and `continuous`. As a special case, we provide `*.div_const` operations that require only
`group_with_zero` and `has_continuous_mul` instances.
All lemmas about `(⁻¹)` use `inv'` in their names because lemmas without `'` are used for
`topological_group`s. We also use `'` in the typeclass name `has_continuous_inv'` for the sake of
consistency of notation.
-/
open_locale topological_space
open filter
/-!
### A group with zero with continuous multiplication
If `G₀` is a group with zero with continuous `(*)`, then `(/y)` is continuous for any `y`. In this
section we prove lemmas that immediately follow from this fact providing `*.div_const` dot-style
operations on `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and
`continuous`.
-/
variables {α G₀ : Type*}
section div_const
variables [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀]
{f : α → G₀} {s : set α} {l : filter α}
lemma filter.tendsto.div_const {x y : G₀} (hf : tendsto f l (𝓝 x)) :
tendsto (λa, f a / y) l (𝓝 (x / y)) :=
by simpa only [div_eq_mul_inv] using hf.mul tendsto_const_nhds
variables [topological_space α]
lemma continuous_at.div_const (hf : continuous f) {y : G₀} : continuous (λ x, f x / y) :=
by simpa only [div_eq_mul_inv] using hf.mul continuous_const
lemma continuous_within_at.div_const {a} (hf : continuous_within_at f s a) {y : G₀} :
continuous_within_at (λ x, f x / y) s a :=
hf.div_const
lemma continuous_on.div_const (hf : continuous_on f s) {y : G₀} : continuous_on (λ x, f x / y) s :=
by simpa only [div_eq_mul_inv] using hf.mul continuous_on_const
lemma continuous.div_const (hf : continuous f) {y : G₀} : continuous (λ x, f x / y) :=
by simpa only [div_eq_mul_inv] using hf.mul continuous_const
end div_const
/-- A type with `0` and `has_inv` such that `λ x, x⁻¹` is continuous at all nonzero points. Any
normed (semi)field has this property. -/
class has_continuous_inv' (G₀ : Type*) [has_zero G₀] [has_inv G₀] [topological_space G₀] :=
(continuous_at_inv' : ∀ ⦃x : G₀⦄, x ≠ 0 → continuous_at has_inv.inv x)
export has_continuous_inv' (continuous_at_inv')
section inv'
variables [has_zero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀]
{l : filter α} {f : α → G₀} {s : set α} {a : α}
/-!
### Continuity of `λ x, x⁻¹` at a non-zero point
We define `topological_group_with_zero` to be a `group_with_zero` such that the operation `x ↦ x⁻¹`
is continuous at all nonzero points. In this section we prove dot-style `*.inv'` lemmas for
`filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`.
-/
lemma tendsto_inv' {x : G₀} (hx : x ≠ 0) : tendsto has_inv.inv (𝓝 x) (𝓝 x⁻¹) :=
continuous_at_inv' hx
lemma continuous_on_inv' : continuous_on (has_inv.inv : G₀ → G₀) {0}ᶜ :=
λ x hx, (continuous_at_inv' hx).continuous_within_at
/-- 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' {a : G₀} (hf : tendsto f l (𝓝 a))
(ha : a ≠ 0) :
tendsto (λ x, (f x)⁻¹) l (𝓝 a⁻¹) :=
(tendsto_inv' ha).comp hf
variables [topological_space α]
lemma continuous_within_at.inv' (hf : continuous_within_at f s a) (ha : f a ≠ 0) :
continuous_within_at (λ x, (f x)⁻¹) s a :=
hf.inv' ha
lemma continuous_at.inv' (hf : continuous_at f a) (ha : f a ≠ 0) :
continuous_at (λ x, (f x)⁻¹) a :=
hf.inv' ha
lemma continuous.inv' (hf : continuous f) (h0 : ∀ x, f x ≠ 0) : continuous (λ x, (f x)⁻¹) :=
continuous_iff_continuous_at.2 $ λ x, (hf.tendsto x).inv' (h0 x)
lemma continuous_on.inv' (hf : continuous_on f s) (h0 : ∀ x ∈ s, f x ≠ 0) :
continuous_on (λ x, (f x)⁻¹) s :=
λ x hx, (hf x hx).inv' (h0 x hx)
end inv'
/-!
### Continuity of division
If `G₀` is a `group_with_zero` with `x ↦ x⁻¹` continuous at all nonzero points and `(*)`, then
division `(/)` is continuous at any point where the denominator is continuous.
-/
section div
variables [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀]
[has_continuous_mul G₀] {f g : α → G₀}
lemma filter.tendsto.div {l : filter α} {a b : G₀} (hf : tendsto f l (𝓝 a))
(hg : tendsto g l (𝓝 b)) (hy : b ≠ 0) :
tendsto (f / g) l (𝓝 (a / b)) :=
by simpa only [div_eq_mul_inv] using hf.mul (hg.inv' hy)
variables [topological_space α] {s : set α} {a : α}
lemma continuous_within_at.div (hf : continuous_within_at f s a) (hg : continuous_within_at g s a)
(h₀ : g a ≠ 0) :
continuous_within_at (f / g) s a :=
hf.div hg h₀
lemma continuous_on.div (hf : continuous_on f s) (hg : continuous_on g s) (h₀ : ∀ x ∈ s, g x ≠ 0) :
continuous_on (f / g) s :=
λ x hx, (hf x hx).div (hg x hx) (h₀ x hx)
/-- Continuity at a point of the result of dividing two functions continuous at that point, where
the denominator is nonzero. -/
lemma continuous_at.div (hf : continuous_at f a) (hg : continuous_at g a) (h₀ : g a ≠ 0) :
continuous_at (f / g) a :=
hf.div hg h₀
lemma continuous.div (hf : continuous f) (hg : continuous g) (h₀ : ∀ x, g x ≠ 0) :
continuous (f / g) :=
by simpa only [div_eq_mul_inv] using hf.mul (hg.inv' h₀)
lemma continuous_on_div : continuous_on (λ p : G₀ × G₀, p.1 / p.2) {p | p.2 ≠ 0} :=
continuous_on_fst.div continuous_on_snd $ λ _, id
end div
|
fea3e964cfc67dff459c86bb9bae02f562e7736c | a726f88081e44db9edfd14d32cfe9c4393ee56a4 | /src/game/world5/level2.lean | 798465c378030d2f56ef4a49dac35162d9ce5e70 | [] | no_license | b-mehta/natural_number_game | 80451bf10277adc89a55dbe8581692c36d822462 | 9faf799d0ab48ecbc89b3d70babb65ba64beee3b | refs/heads/master | 1,598,525,389,186 | 1,573,516,674,000 | 1,573,516,674,000 | 217,339,684 | 0 | 0 | null | 1,571,933,100,000 | 1,571,933,099,000 | null | UTF-8 | Lean | false | false | 3,025 | lean | import mynat.add -- + on mynat
import mynat.mul -- * on mynat
/- Tactic : intro
## Summary:
`intro p` will make progress if the goal is of the form `P → Q`.
## Details
If your goal is a function or an implication `⊢ P → Q` then `intro`
will always make progress.
## Example (functions)
What does it mean to define
a function? Given an arbitrary term of type `P` (or an element
of the set `P` if you think set-theoretically) you need
to come up with a term of type `Q`, so your first step is
to choose `p`, an arbitary element of `P`.
`intro p,` is Lean's way of saying "let $p\in P$ be arbitrary".
The tactic `intro p` changes
```
⊢ P → Q
```
into
```
p : P
⊢ Q
```
So `p` is an arbitrary element of `P` about which nothing is known,
and our task is to come up with an element of `Q` (which can of
course depend on `p`).
Note that the opposite of `intro` is `revert`; given a tactic
state
```
p : P
⊢ Q
```
as above, the tactic `revert p` takes us back to `⊢ P → Q`.
## Example (propositions)
If your goal is an implication $P\implies Q$ then Lean writes
this as `⊢ P → Q`, and `intro p,` can be thought of as meaning
"let $p$ be a proof of $P$", or more informally "let's assume that
$P$ is true". The goal changes to `⊢ Q` and the hypothesis `p : P`
appears in the local context.
-/
/-
# Function world.
## Level 2: the `intro` tactic.
Let's make a function. Let's define the function on the natural
numbers which sends a natural number $n$ to $3n+2$. If you delete the
`sorry` you will see that our goal is `mynat → mynat`. A mathematician
might denote this set with some exotic name such as
$\operatorname{Hom}(\mathbb{N},\mathbb{N})$,
but computer scientists use notation `X → Y` to denote the set of
functions from `X` to `Y` and this name definitely has its merits.
In type theory, `X → Y` is a type (the type of all functions from $X$ to $Y$),
and `f : X → Y` means that `f` is a term
of this type, i.e., $f$ is a function from $X$ to $Y$.
To define a function $X\to Y$ we need to choose an arbitrary
element $x\in X$ and then, perhaps using $x$, make an element of $Y$.
The Lean tactic for "let $x\in X$ be arbitrary" is `intro x`.
## Rule of thumb:
If your goal is `P → Q` then `intro p` will make progress.
To solve the goal below, you have to come up with a function from `mynat`
to `mynat`. Start with
`intro n,`
(i.e. "let $n\in\mathbb{N}$ be arbitrary") and note that our
local context now looks like this:
```
n : mynat
⊢ mynat
```
Our job now is to construct a natural number, which is
allowed to depend on $n$. We can do this using `exact` and
writing a formula for the function we want to define. For example
we imported addition and multiplication at the top of this file,
so
`exact 3*n+2,`
will close the goal, ultimately defining the function $f(n)=3n+2$.
-/
/- Definition
We define a function from mynat to mynat.
-/
example : mynat → mynat :=
begin [less_leaky]
intro n,
exact 3*n+2,
end
-- TODO this is a function |
14a861a7d63f5a608100c7bc5d48a712f8391cc9 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/tactic_var_bug.lean | cb2b7f2b33a0c0be2870554fa093c198194c74e5 | [
"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 | 104 | lean | --
variable p : Prop
definition foo (q : Prop) : q → true :=
begin
intro r,
apply true.intro
end
|
a6dcda09c074330090ea489e5e625b58c160ef64 | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/qpf/multivariate/constructions/fix.lean | 7af2786553c28d00384c7f7c86fac359b02ab597 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 12,879 | lean | /-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Simon Hudon
-/
import data.pfunctor.multivariate.W
import data.qpf.multivariate.basic
universes u v
/-!
# The initial algebra of a multivariate qpf is again a qpf.
For a `(n+1)`-ary QPF `F (α₀,..,αₙ)`, we take the least fixed point of `F` with
regards to its last argument `αₙ`. The result is a `n`-ary functor: `fix F (α₀,..,αₙ₋₁)`.
Making `fix F` into a functor allows us to take the fixed point, compose with other functors
and take a fixed point again.
## Main definitions
* `fix.mk` - constructor
* `fix.dest - destructor
* `fix.rec` - recursor: basis for defining functions by structural recursion on `fix F α`
* `fix.drec` - dependent recursor: generalization of `fix.rec` where
the result type of the function is allowed to depend on the `fix F α` value
* `fix.rec_eq` - defining equation for `recursor`
* `fix.ind` - induction principle for `fix F α`
## Implementation notes
For `F` a QPF`, we define `fix F α` in terms of the W-type of the polynomial functor `P` of `F`.
We define the relation `Wequiv` and take its quotient as the definition of `fix F α`.
```lean
inductive Wequiv {α : typevec n} : q.P.W α → q.P.W α → Prop
| ind (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f₀ f₁ : q.P.last.B a → q.P.W α) :
(∀ x, Wequiv (f₀ x) (f₁ x)) → Wequiv (q.P.W_mk a f' f₀) (q.P.W_mk a f' f₁)
| abs (a₀ : q.P.A) (f'₀ : q.P.drop.B a₀ ⟹ α) (f₀ : q.P.last.B a₀ → q.P.W α)
(a₁ : q.P.A) (f'₁ : q.P.drop.B a₁ ⟹ α) (f₁ : q.P.last.B a₁ → q.P.W α) :
abs ⟨a₀, q.P.append_contents f'₀ f₀⟩ = abs ⟨a₁, q.P.append_contents f'₁ f₁⟩ →
Wequiv (q.P.W_mk a₀ f'₀ f₀) (q.P.W_mk a₁ f'₁ f₁)
| trans (u v w : q.P.W α) : Wequiv u v → Wequiv v w → Wequiv u w
```
See [avigad-carneiro-hudon2019] for more details.
## Reference
* [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019]
-/
namespace mvqpf
open typevec
open mvfunctor (liftp liftr)
open_locale mvfunctor
variables {n : ℕ} {F : typevec.{u} (n+1) → Type u} [mvfunctor F] [q : mvqpf F]
include q
/-- `recF` is used as a basis for defining the recursor on `fix F α`. `recF`
traverses recursively the W-type generated by `q.P` using a function on `F`
as a recursive step -/
def recF {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) : q.P.W α → β :=
q.P.W_rec (λ a f' f rec, g (abs ⟨a, split_fun f' rec⟩))
theorem recF_eq {α : typevec n} {β : Type*} (g : F (α.append1 β) → β)
(a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) :
recF g (q.P.W_mk a f' f) = g (abs ⟨a, split_fun f' (recF g ∘ f)⟩) :=
by rw [recF, mvpfunctor.W_rec_eq]; refl
theorem recF_eq' {α : typevec n} {β : Type*} (g : F (α.append1 β) → β)
(x : q.P.W α) :
recF g x = g (abs ((append_fun id (recF g)) <$$> q.P.W_dest' x)) :=
begin
apply q.P.W_cases _ x,
intros a f' f,
rw [recF_eq, q.P.W_dest'_W_mk, mvpfunctor.map_eq, append_fun_comp_split_fun,
typevec.id_comp]
end
/-- Equivalence relation on W-types that represent the same `fix F`
value -/
inductive Wequiv {α : typevec n} : q.P.W α → q.P.W α → Prop
| ind (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f₀ f₁ : q.P.last.B a → q.P.W α) :
(∀ x, Wequiv (f₀ x) (f₁ x)) → Wequiv (q.P.W_mk a f' f₀) (q.P.W_mk a f' f₁)
| abs (a₀ : q.P.A) (f'₀ : q.P.drop.B a₀ ⟹ α) (f₀ : q.P.last.B a₀ → q.P.W α)
(a₁ : q.P.A) (f'₁ : q.P.drop.B a₁ ⟹ α) (f₁ : q.P.last.B a₁ → q.P.W α) :
abs ⟨a₀, q.P.append_contents f'₀ f₀⟩ = abs ⟨a₁, q.P.append_contents f'₁ f₁⟩ →
Wequiv (q.P.W_mk a₀ f'₀ f₀) (q.P.W_mk a₁ f'₁ f₁)
| trans (u v w : q.P.W α) : Wequiv u v → Wequiv v w → Wequiv u w
theorem recF_eq_of_Wequiv (α : typevec n) {β : Type*} (u : F (α.append1 β) → β)
(x y : q.P.W α) :
Wequiv x y → recF u x = recF u y :=
begin
apply q.P.W_cases _ x,
intros a₀ f'₀ f₀,
apply q.P.W_cases _ y,
intros a₁ f'₁ f₁,
intro h, induction h,
case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { simp only [recF_eq, function.comp, ih] },
case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h
{ simp only [recF_eq', abs_map, mvpfunctor.W_dest'_W_mk, h] },
case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂
{ exact eq.trans ih₁ ih₂ }
end
theorem Wequiv.abs' {α : typevec n} (x y : q.P.W α)
(h : abs (q.P.W_dest' x) = abs (q.P.W_dest' y)) :
Wequiv x y :=
begin
revert h,
apply q.P.W_cases _ x,
intros a₀ f'₀ f₀,
apply q.P.W_cases _ y,
intros a₁ f'₁ f₁,
apply Wequiv.abs
end
theorem Wequiv.refl {α : typevec n} (x : q.P.W α) : Wequiv x x :=
by apply q.P.W_cases _ x; intros a f' f; exact Wequiv.abs a f' f a f' f rfl
theorem Wequiv.symm {α : typevec n} (x y : q.P.W α) : Wequiv x y → Wequiv y x :=
begin
intro h, induction h,
case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih
{ exact Wequiv.ind _ _ _ _ ih },
case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h
{ exact Wequiv.abs _ _ _ _ _ _ h.symm },
case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂
{ exact mvqpf.Wequiv.trans _ _ _ ih₂ ih₁}
end
/-- maps every element of the W type to a canonical representative -/
def Wrepr {α : typevec n} : q.P.W α → q.P.W α := recF (q.P.W_mk' ∘ repr)
theorem Wrepr_W_mk {α : typevec n}
(a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) :
Wrepr (q.P.W_mk a f' f) =
q.P.W_mk' (repr (abs ((append_fun id Wrepr) <$$> ⟨a, q.P.append_contents f' f⟩))) :=
by rw [Wrepr, recF_eq', q.P.W_dest'_W_mk]; refl
theorem Wrepr_equiv {α : typevec n} (x : q.P.W α) : Wequiv (Wrepr x) x :=
begin
apply q.P.W_ind _ x, intros a f' f ih,
apply Wequiv.trans _ (q.P.W_mk' ((append_fun id Wrepr) <$$> ⟨a, q.P.append_contents f' f⟩)),
{ apply Wequiv.abs',
rw [Wrepr_W_mk, q.P.W_dest'_W_mk', q.P.W_dest'_W_mk', abs_repr] },
rw [q.P.map_eq, mvpfunctor.W_mk', append_fun_comp_split_fun, id_comp],
apply Wequiv.ind, exact ih
end
theorem Wequiv_map {α β : typevec n} (g : α ⟹ β) (x y : q.P.W α) :
Wequiv x y → Wequiv (g <$$> x) (g <$$> y) :=
begin
intro h, induction h,
case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih
{ rw [q.P.W_map_W_mk, q.P.W_map_W_mk], apply Wequiv.ind, apply ih },
case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h
{ rw [q.P.W_map_W_mk, q.P.W_map_W_mk], apply Wequiv.abs,
show abs (q.P.obj_append1 a₀ (g ⊚ f'₀) (λ x, q.P.W_map g (f₀ x))) =
abs (q.P.obj_append1 a₁ (g ⊚ f'₁) (λ x, q.P.W_map g (f₁ x))),
rw [←q.P.map_obj_append1, ←q.P.map_obj_append1, abs_map, abs_map, h] },
case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂
{ apply mvqpf.Wequiv.trans, apply ih₁, apply ih₂ }
end
/--
Define the fixed point as the quotient of trees under the equivalence relation.
-/
def W_setoid (α : typevec n) : setoid (q.P.W α) :=
⟨Wequiv, @Wequiv.refl _ _ _ _ _, @Wequiv.symm _ _ _ _ _, @Wequiv.trans _ _ _ _ _⟩
local attribute [instance] W_setoid
/-- Least fixed point of functor F. The result is a functor with one fewer parameters
than the input. For `F a b c` a ternary functor, fix F is a binary functor such that
```lean
fix F a b = F a b (fix F a b)
```
-/
def fix {n : ℕ} (F : typevec (n+1) → Type*) [mvfunctor F] [q : mvqpf F] (α : typevec n) :=
quotient (W_setoid α : setoid (q.P.W α))
attribute [nolint has_inhabited_instance] fix
/-- `fix F` is a functor -/
def fix.map {α β : typevec n} (g : α ⟹ β) : fix F α → fix F β :=
quotient.lift (λ x : q.P.W α, ⟦q.P.W_map g x⟧)
(λ a b h, quot.sound (Wequiv_map _ _ _ h))
instance fix.mvfunctor : mvfunctor (fix F) :=
{ map := @fix.map _ _ _ _}
variable {α : typevec.{u} n}
/-- Recursor for `fix F` -/
def fix.rec {β : Type u} (g : F (α ::: β) → β) : fix F α → β :=
quot.lift (recF g) (recF_eq_of_Wequiv α g)
/-- Access W-type underlying `fix F` -/
def fix_to_W : fix F α → q.P.W α :=
quotient.lift Wrepr (recF_eq_of_Wequiv α (λ x, q.P.W_mk' (repr x)))
/-- Constructor for `fix F` -/
def fix.mk (x : F (append1 α (fix F α))) : fix F α :=
quot.mk _ (q.P.W_mk' (append_fun id fix_to_W <$$> repr x))
/-- Destructor for `fix F` -/
def fix.dest : fix F α → F (append1 α (fix F α)) :=
fix.rec (mvfunctor.map (append_fun id fix.mk))
theorem fix.rec_eq {β : Type u} (g : F (append1 α β) → β) (x : F (append1 α (fix F α))) :
fix.rec g (fix.mk x) = g (append_fun id (fix.rec g) <$$> x) :=
have recF g ∘ fix_to_W = fix.rec g,
by { apply funext, apply quotient.ind, intro x, apply recF_eq_of_Wequiv,
apply Wrepr_equiv },
begin
conv { to_lhs, rw [fix.rec, fix.mk], dsimp },
cases h : repr x with a f,
rw [mvpfunctor.map_eq, recF_eq', ←mvpfunctor.map_eq, mvpfunctor.W_dest'_W_mk'],
rw [←mvpfunctor.comp_map, abs_map, ←h, abs_repr, ←append_fun_comp, id_comp, this]
end
theorem fix.ind_aux (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) :
fix.mk (abs ⟨a, q.P.append_contents f' (λ x, ⟦f x⟧)⟩) = ⟦q.P.W_mk a f' f⟧ :=
have fix.mk (abs ⟨a, q.P.append_contents f' (λ x, ⟦f x⟧)⟩) = ⟦Wrepr (q.P.W_mk a f' f)⟧,
begin
apply quot.sound, apply Wequiv.abs',
rw [mvpfunctor.W_dest'_W_mk', abs_map, abs_repr, ←abs_map, mvpfunctor.map_eq],
conv { to_rhs, rw [Wrepr_W_mk, q.P.W_dest'_W_mk', abs_repr, mvpfunctor.map_eq] },
congr' 2, rw [mvpfunctor.append_contents, mvpfunctor.append_contents],
rw [append_fun, append_fun, ←split_fun_comp, ←split_fun_comp],
reflexivity
end,
by { rw this, apply quot.sound, apply Wrepr_equiv }
theorem fix.ind_rec {β : Type*} (g₁ g₂ : fix F α → β)
(h : ∀ x : F (append1 α (fix F α)),
(append_fun id g₁) <$$> x = (append_fun id g₂) <$$> x → g₁ (fix.mk x) = g₂ (fix.mk x)) :
∀ x, g₁ x = g₂ x :=
begin
apply quot.ind,
intro x,
apply q.P.W_ind _ x, intros a f' f ih,
show g₁ ⟦q.P.W_mk a f' f⟧ = g₂ ⟦q.P.W_mk a f' f⟧,
rw [←fix.ind_aux a f' f], apply h,
rw [←abs_map, ←abs_map, mvpfunctor.map_eq, mvpfunctor.map_eq],
congr' 2,
rw [mvpfunctor.append_contents, append_fun, append_fun, ←split_fun_comp, ←split_fun_comp],
have : g₁ ∘ (λ x, ⟦f x⟧) = g₂ ∘ (λ x, ⟦f x⟧),
{ ext x, exact ih x },
rw this
end
theorem fix.rec_unique {β : Type*} (g : F (append1 α β) → β) (h : fix F α → β)
(hyp : ∀ x, h (fix.mk x) = g (append_fun id h <$$> x)) :
fix.rec g = h :=
begin
ext x,
apply fix.ind_rec,
intros x hyp',
rw [hyp, ←hyp', fix.rec_eq]
end
theorem fix.mk_dest (x : fix F α) : fix.mk (fix.dest x) = x :=
begin
change (fix.mk ∘ fix.dest) x = x,
apply fix.ind_rec,
intro x, dsimp,
rw [fix.dest, fix.rec_eq, ←comp_map, ←append_fun_comp, id_comp],
intro h, rw h,
show fix.mk (append_fun id id <$$> x) = fix.mk x,
rw [append_fun_id_id, mvfunctor.id_map]
end
theorem fix.dest_mk (x : F (append1 α (fix F α))) : fix.dest (fix.mk x) = x :=
begin
unfold fix.dest, rw [fix.rec_eq, ←fix.dest, ←comp_map],
conv { to_rhs, rw ←(mvfunctor.id_map x) },
rw [←append_fun_comp, id_comp],
have : fix.mk ∘ fix.dest = id, {ext x, apply fix.mk_dest },
rw [this, append_fun_id_id]
end
theorem fix.ind {α : typevec n} (p : fix F α → Prop)
(h : ∀ x : F (α.append1 (fix F α)), liftp (pred_last α p) x → p (fix.mk x)) :
∀ x, p x :=
begin
apply quot.ind,
intro x,
apply q.P.W_ind _ x, intros a f' f ih,
change p ⟦q.P.W_mk a f' f⟧,
rw [←fix.ind_aux a f' f],
apply h,
rw mvqpf.liftp_iff,
refine ⟨_, _, rfl, _⟩,
intros i j,
cases i,
{ apply ih },
{ triv },
end
instance mvqpf_fix : mvqpf (fix F) :=
{ P := q.P.Wp,
abs := λ α, quot.mk Wequiv,
repr := λ α, fix_to_W,
abs_repr := by { intros α, apply quot.ind, intro a, apply quot.sound, apply Wrepr_equiv },
abs_map :=
begin
intros α β g x, conv { to_rhs, dsimp [mvfunctor.map]},
rw fix.map, apply quot.sound,
apply Wequiv.refl
end }
/-- Dependent recursor for `fix F` -/
def fix.drec {β : fix F α → Type u}
(g : Π x : F (α ::: sigma β), β (fix.mk $ (id ::: sigma.fst) <$$> x)) (x : fix F α) : β x :=
let y := @fix.rec _ F _ _ α (sigma β) (λ i, ⟨_,g i⟩) x in
have x = y.1,
by { symmetry, dsimp [y], apply fix.ind_rec _ id _ x, intros x' ih,
rw fix.rec_eq, dsimp, simp [append_fun_id_id] at ih,
congr, conv { to_rhs, rw [← ih] }, rw [mvfunctor.map_map,← append_fun_comp,id_comp], },
cast (by rw this) y.2
end mvqpf
|
43ae6e7f803c07e39f35538bf2f15854652397ce | 618003631150032a5676f229d13a079ac875ff77 | /test/traversable.lean | bda3f60662483e53e7e8b3a0c68bcb5fd1879417 | [
"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 | 1,939 | lean | import control.traversable.derive
import tactic
universes u
/- traversable -/
open tactic.interactive
run_cmd do
lawful_traversable_derive_handler' `test ``(is_lawful_traversable) ``list
-- the above creates local instances of `traversable` and `is_lawful_traversable`
-- for `list`
-- do not put in instances because they are not universe polymorphic
@[derive [traversable, is_lawful_traversable]]
structure my_struct (α : Type) :=
(y : ℤ)
@[derive [traversable, is_lawful_traversable]]
inductive either (α : Type u)
| left : α → ℤ → either
| right : α → either
@[derive [traversable, is_lawful_traversable]]
structure my_struct2 (α : Type u) : Type u :=
(x : α)
(y : ℤ)
(η : list α)
(k : list (list α))
@[derive [traversable, is_lawful_traversable]]
inductive rec_data3 (α : Type u) : Type u
| nil : rec_data3
| cons : ℕ → α → rec_data3 → rec_data3 → rec_data3
@[derive traversable]
meta structure meta_struct (α : Type u) : Type u :=
(x : α)
(y : ℤ)
(z : list α)
(k : list (list α))
(w : expr)
@[derive [traversable,is_lawful_traversable]]
inductive my_tree (α : Type)
| leaf : my_tree
| node : my_tree → my_tree → α → my_tree
section
open my_tree (hiding traverse)
def x : my_tree (list nat) :=
node
leaf
(node
(node leaf leaf [1,2,3])
leaf
[3,2])
[1]
/-- demonstrate the nested use of `traverse`. It traverses each node of the tree and
in each node, traverses each list. For each `ℕ` visited, apply an action `ℕ -> state (list ℕ) unit`
which adds its argument to the state. -/
def ex : state (list ℕ) (my_tree $ list unit) :=
do xs ← traverse (traverse $ λ a, modify $ list.cons a) x,
pure xs
example : (ex.run []).1 = node leaf (node (node leaf leaf [(), (), ()]) leaf [(), ()]) [()] := rfl
example : (ex.run []).2 = [1, 2, 3, 3, 2, 1] := rfl
example : is_lawful_traversable my_tree := my_tree.is_lawful_traversable
end
|
c62cd168078e8539a54e22e55512d173115996cd | 46125763b4dbf50619e8846a1371029346f4c3db | /src/measure_theory/bochner_integration.lean | 46bfc0224f95255c02474a52406ad1d481a19fb6 | [
"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 | 54,995 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import measure_theory.simple_func_dense
import analysis.normed_space.bounded_linear_maps
/-!
# Bochner integral
The Bochner integral extends the definition of the Lebesgue integral to functions that map from a
measure space into a Banach space (complete normed vector space). It is constructed here by
extending the integral on simple functions.
## Main definitions
The Bochner integral is defined following these steps:
1. Define the integral on simple functions of the type `simple_func α β` (notation : `α →ₛ β`)
where `β` is a real normed space.
(See `simple_func.bintegral` and section `bintegral` for details. Also see `simple_func.integral`
for the integral on simple functions of the type `simple_func α ennreal`.)
2. Use `simple_func α β` to cut out the simple functions from L1 functions, and define integral
on these. The type of simple functions in L1 space is written as `α →₁ₛ β`.
3. Show that the embedding of `α →₁ₛ β` into L1 is a dense and uniform one.
4. Show that the integral defined on `α →₁ₛ β` is a continuous linear map.
5. Define the Bochner integral on L1 functions by extending the integral on integrable simple
functions `α →₁ₛ β` using `continuous_linear_map.extend`. Define the Bochner integral on functions
as the Bochner integral of its equivalence class in L1 space.
## Main statements
1. Basic properties of the Bochner integral on functions of type `α → β`, where `α` is a measure
space and `β` is a real normed space.
* `integral_zero` : `∫ 0 = 0`
* `integral_add` : `∫ f + g = ∫ f + ∫ g`
* `integral_neg` : `∫ -f = - ∫ f`
* `integral_sub` : `∫ f - g = ∫ f - ∫ g`
* `integral_smul` : `∫ r • f = r • ∫ f`
* `integral_congr_ae` : `∀ₘ a, f a = g a → ∫ f = ∫ g`
* `norm_integral_le_integral_norm` : `∥∫ f∥ ≤ ∫ ∥f∥`
2. Basic properties of the Bochner integral on functions of type `α → ℝ`, where `α` is a measure
space.
* `integral_nonneg_of_ae` : `∀ₘ a, 0 ≤ f a → 0 ≤ ∫ f`
* `integral_nonpos_of_nonpos_ae` : `∀ₘ a, f a ≤ 0 → ∫ f ≤ 0`
* `integral_le_integral_of_le_ae` : `∀ₘ a, f a ≤ g a → ∫ f ≤ ∫ g`
3. Propositions connecting the Bochner integral with the integral on `ennreal`-valued functions,
which is called `lintegral` and has the notation `∫⁻`.
* `integral_eq_lintegral_max_sub_lintegral_min` : `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, where `f⁺` is the positive
part of `f` and `f⁻` is the negative part of `f`.
* `integral_eq_lintegral_of_nonneg_ae` : `∀ₘ a, 0 ≤ f a → ∫ f = ∫⁻ f`
4. `tendsto_integral_of_dominated_convergence` : the Lebesgue dominated convergence theorem
## Notes
Some tips on how to prove a proposition if the API for the Bochner integral is not enough so that
you need to unfold the definition of the Bochner integral and go back to simple functions.
See `integral_eq_lintegral_max_sub_lintegral_min` for a complicated example, which proves that
`∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, with the first integral sign being the Bochner integral of a real-valued
function f : α → ℝ, and second and third integral sign being the integral on ennreal-valued
functions (called `lintegral`). The proof of `integral_eq_lintegral_max_sub_lintegral_min` is
scattered in sections with the name `pos_part`.
Here are the usual steps of proving that a property `p`, say `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, holds for all
functions :
1. First go to the `L¹` space.
For example, if you see `ennreal.to_real (∫⁻ a, ennreal.of_real $ ∥f a∥)`, that is the norm of `f` in
`L¹` space. Rewrite using `l1.norm_of_fun_eq_lintegral_norm`.
2. Show that the set `{f ∈ L¹ | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}` is closed in `L¹` using `is_closed_eq`.
3. Show that the property holds for all simple functions `s` in `L¹` space.
Typically, you need to convert various notions to their `simple_func` counterpart, using lemmas like
`l1.integral_coe_eq_integral`.
4. Since simple functions are dense in `L¹`,
```
univ = closure {s simple}
= closure {s simple | ∫ s = ∫⁻ s⁺ - ∫⁻ s⁻} : the property holds for all simple functions
⊆ closure {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}
= {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} : closure of a closed set is itself
```
Use `is_closed_property` or `dense_range.induction_on` for this argument.
## Notations
* `α →ₛ β` : simple functions (defined in `measure_theory/integration`)
* `α →₁ β` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in
`measure_theory/l1_space`)
* `α →₁ₛ β` : simple functions in L1 space, i.e., equivalence classes of integrable simple functions
Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if font is missing.
## Tags
Bochner integral, simple function, function space, Lebesgue dominated convergence theorem
-/
noncomputable theory
open_locale classical topological_space
set_option class.instance_max_depth 100
-- Typeclass inference has difficulty finding `has_scalar ℝ β` where `β` is a `normed_space` on `ℝ`
local attribute [instance, priority 10000]
mul_action.to_has_scalar distrib_mul_action.to_mul_action add_comm_group.to_add_comm_monoid
normed_group.to_add_comm_group normed_space.to_module
module.to_semimodule
namespace measure_theory
universes u v w
variables {α : Type u} [measurable_space α] {β : Type v} [decidable_linear_order β] [has_zero β]
local infixr ` →ₛ `:25 := simple_func
namespace simple_func
section pos_part
/-- Positive part of a simple function. -/
def pos_part (f : α →ₛ β) : α →ₛ β := f.map (λb, max b 0)
/-- Negative part of a simple function. -/
def neg_part [has_neg β] (f : α →ₛ β) : α →ₛ β := pos_part (-f)
lemma pos_part_map_norm (f : α →ₛ ℝ) : (pos_part f).map norm = pos_part f :=
begin
ext,
rw [map_apply, real.norm_eq_abs, abs_of_nonneg],
rw [pos_part, map_apply],
exact le_max_right _ _
end
lemma neg_part_map_norm (f : α →ₛ ℝ) : (neg_part f).map norm = neg_part f :=
by { rw neg_part, exact pos_part_map_norm _ }
lemma pos_part_sub_neg_part (f : α →ₛ ℝ) : f.pos_part - f.neg_part = f :=
begin
simp only [pos_part, neg_part],
ext,
exact max_zero_sub_eq_self (f a)
end
end pos_part
end simple_func
end measure_theory
namespace measure_theory
open set lattice filter topological_space ennreal emetric
universes u v w
variables {α : Type u} [measure_space α] {β : Type v} {γ : Type w}
local infixr ` →ₛ `:25 := simple_func
namespace simple_func
section bintegral
/-!
### The Bochner integral of simple functions
Define the Bochner integral of simple functions of the type `α →ₛ β` where `β` is a normed group,
and prove basic property of this integral.
-/
open finset
variables [normed_group β] [normed_group γ]
lemma integrable_iff_integral_lt_top {f : α →ₛ β} :
integrable f ↔ integral (f.map (coe ∘ nnnorm)) < ⊤ :=
by { rw [integrable, ← lintegral_eq_integral, lintegral_map] }
lemma fin_vol_supp_of_integrable {f : α →ₛ β} (hf : integrable f) : f.fin_vol_supp :=
begin
rw [integrable_iff_integral_lt_top] at hf,
have hf := fin_vol_supp_of_integral_lt_top hf,
refine fin_vol_supp_of_fin_vol_supp_map f hf _,
assume b, simp [nnnorm_eq_zero]
end
lemma integrable_of_fin_vol_supp {f : α →ₛ β} (h : f.fin_vol_supp) : integrable f :=
by { rw [integrable_iff_integral_lt_top], exact integral_map_coe_lt_top h nnnorm_zero }
/-- For simple functions with a `normed_group` as codomain, being integrable is the same as having
finite volume support. -/
lemma integrable_iff_fin_vol_supp (f : α →ₛ β) : integrable f ↔ f.fin_vol_supp :=
iff.intro fin_vol_supp_of_integrable integrable_of_fin_vol_supp
lemma integrable_pair {f : α →ₛ β} {g : α →ₛ γ} (hf : integrable f) (hg : integrable g) :
integrable (pair f g) :=
by { rw integrable_iff_fin_vol_supp at *, apply fin_vol_supp_pair; assumption }
variables [normed_space ℝ γ]
/-- Bochner integral of simple functions whose codomain is a real `normed_space`.
The name `simple_func.integral` has been taken in the file `integration.lean`, which calculates
the integral of a simple function with type `α → ennreal`.
The name `bintegral` stands for Bochner integral. -/
def bintegral [normed_space ℝ β] (f : α →ₛ β) : β :=
f.range.sum (λ x, (ennreal.to_real (volume (f ⁻¹' {x}))) • x)
/-- Calculate the integral of `g ∘ f : α →ₛ γ`, where `f` is an integrable function from `α` to `β`
and `g` is a function from `β` to `γ`. We require `g 0 = 0` so that `g ∘ f` is integrable. -/
lemma map_bintegral (f : α →ₛ β) (g : β → γ) (hf : integrable f) (hg : g 0 = 0) :
(f.map g).bintegral = f.range.sum (λ x, (ennreal.to_real (volume (f ⁻¹' {x}))) • (g x)) :=
begin
/- Just a complicated calculation with `finset.sum`. Real work is done by
`map_preimage_singleton`, `simple_func.volume_bUnion_preimage` and `ennreal.to_real_sum` -/
rw integrable_iff_fin_vol_supp at hf,
simp only [bintegral, range_map],
refine finset.sum_image' _ (assume b hb, _),
rcases mem_range.1 hb with ⟨a, rfl⟩,
let s' := f.range.filter (λb, g b = g (f a)),
calc (ennreal.to_real (volume ((f.map g) ⁻¹' {g (f a)}))) • (g (f a)) =
(ennreal.to_real (volume (⋃b∈s', f ⁻¹' {b}))) • (g (f a)) : by rw map_preimage_singleton
... = (ennreal.to_real (s'.sum (λb, volume (f ⁻¹' {b})))) • (g (f a)) :
by rw volume_bUnion_preimage
... = (s'.sum (λb, ennreal.to_real (volume (f ⁻¹' {b})))) • (g (f a)) :
begin
by_cases h : g (f a) = 0,
{ rw [h, smul_zero, smul_zero] },
{ rw ennreal.to_real_sum,
simp only [mem_filter],
rintros b ⟨_, hb⟩,
have : b ≠ 0, { assume hb', rw [← hb, hb'] at h, contradiction },
apply hf,
assumption }
end
... = s'.sum (λb, (ennreal.to_real (volume (f ⁻¹' {b}))) • (g (f a))) : finset.sum_smul
... = s'.sum (λb, (ennreal.to_real (volume (f ⁻¹' {b}))) • (g b)) :
finset.sum_congr rfl $ by { assume x, simp only [mem_filter], rintro ⟨_, h⟩, rw h }
end
/-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type
`α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion.
See `bintegral_eq_integral'` for a simpler version. -/
lemma bintegral_eq_integral {f : α →ₛ β} {g : β → ennreal} (hf : integrable f) (hg0 : g 0 = 0)
(hgt : ∀b, g b < ⊤):
(f.map (ennreal.to_real ∘ g)).bintegral = ennreal.to_real (f.map g).integral :=
begin
have hf' : f.fin_vol_supp, { rwa integrable_iff_fin_vol_supp at hf },
rw [map_bintegral f _ hf, map_integral, ennreal.to_real_sum],
{ refine finset.sum_congr rfl (λb hb, _),
rw [smul_eq_mul],
rw [to_real_mul_to_real, mul_comm] },
{ assume a ha,
by_cases a0 : a = 0,
{ rw [a0, hg0, zero_mul], exact with_top.zero_lt_top },
apply mul_lt_top (hgt a) (hf' _ a0) },
{ simp [hg0] }
end
/-- `simple_func.bintegral` and `lintegral : (α → ennreal) → ennreal` are the same when the
integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some
form of coercion.
See `bintegral_eq_lintegral'` for a simpler version. -/
lemma bintegral_eq_lintegral (f : α →ₛ β) (g : β → ennreal) (hf : integrable f) (hg0 : g 0 = 0)
(hgt : ∀b, g b < ⊤):
(f.map (ennreal.to_real ∘ g)).bintegral = ennreal.to_real (∫⁻ a, g (f a)) :=
by { rw [bintegral_eq_integral hf hg0 hgt, ← lintegral_eq_integral], refl }
variables [normed_space ℝ β]
lemma bintegral_congr {f g : α →ₛ β} (hf : integrable f) (hg : integrable g) (h : ∀ₘ a, f a = g a):
bintegral f = bintegral g :=
show ((pair f g).map prod.fst).bintegral = ((pair f g).map prod.snd).bintegral, from
begin
have inte := integrable_pair hf hg,
rw [map_bintegral (pair f g) _ inte prod.fst_zero, map_bintegral (pair f g) _ inte prod.snd_zero],
refine finset.sum_congr rfl (assume p hp, _),
rcases mem_range.1 hp with ⟨a, rfl⟩,
by_cases eq : f a = g a,
{ dsimp only [pair_apply], rw eq },
{ have : volume ((pair f g) ⁻¹' {(f a, g a)}) = 0,
{ refine volume_mono_null (assume a' ha', _) h,
simp only [set.mem_preimage, mem_singleton_iff, pair_apply, prod.mk.inj_iff] at ha',
show f a' ≠ g a',
rwa [ha'.1, ha'.2] },
simp only [this, pair_apply, zero_smul, ennreal.zero_to_real] },
end
/-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type
`α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. -/
lemma bintegral_eq_integral' {f : α →ₛ ℝ} (hf : integrable f) (h_pos : ∀ₘ a, 0 ≤ f a) :
f.bintegral = ennreal.to_real (f.map ennreal.of_real).integral :=
begin
have : ∀ₘ a, f a = (f.map (ennreal.to_real ∘ ennreal.of_real)) a,
{ filter_upwards [h_pos],
assume a,
simp only [mem_set_of_eq, map_apply, function.comp_apply],
assume h,
exact (ennreal.to_real_of_real h).symm },
rw ← bintegral_eq_integral hf,
{ refine bintegral_congr hf _ this, exact integrable_of_ae_eq hf this },
{ exact ennreal.of_real_zero },
{ assume b, rw ennreal.lt_top_iff_ne_top, exact ennreal.of_real_ne_top }
end
/-- `simple_func.bintegral` and `lintegral : (α → ennreal) → ennreal` agree when the integrand has
type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. -/
lemma bintegral_eq_lintegral' {f : α →ₛ ℝ} (hf : integrable f) (h_pos : ∀ₘ a, 0 ≤ f a) :
f.bintegral = ennreal.to_real (∫⁻ a, (f.map ennreal.of_real a)) :=
by rw [bintegral_eq_integral' hf h_pos, ← lintegral_eq_integral]
lemma bintegral_add {f g : α →ₛ β} (hf : integrable f) (hg : integrable g) :
bintegral (f + g) = bintegral f + bintegral g :=
calc bintegral (f + g) = sum (pair f g).range
(λx, ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • (x.fst + x.snd)) :
begin
rw [add_eq_map₂, map_bintegral (pair f g)],
{ exact integrable_pair hf hg },
{ simp only [add_zero, prod.fst_zero, prod.snd_zero] }
end
... = sum (pair f g).range
(λx, ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.fst +
ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.snd) :
finset.sum_congr rfl $ assume a ha, smul_add _ _ _
... = sum (simple_func.range (pair f g))
(λ (x : β × β), ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.fst) +
sum (simple_func.range (pair f g))
(λ (x : β × β), ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.snd) :
by rw finset.sum_add_distrib
... = ((pair f g).map prod.fst).bintegral + ((pair f g).map prod.snd).bintegral :
begin
rw [map_bintegral (pair f g), map_bintegral (pair f g)],
{ exact integrable_pair hf hg }, { refl },
{ exact integrable_pair hf hg }, { refl }
end
... = bintegral f + bintegral g : rfl
lemma bintegral_neg {f : α →ₛ β} (hf : integrable f) : bintegral (-f) = - bintegral f :=
calc bintegral (-f) = bintegral (f.map (has_neg.neg)) : rfl
... = - bintegral f :
begin
rw [map_bintegral f _ hf neg_zero, bintegral, ← sum_neg_distrib],
refine finset.sum_congr rfl (λx h, smul_neg _ _),
end
lemma bintegral_sub {f g : α →ₛ β} (hf : integrable f) (hg : integrable g) :
bintegral (f - g) = bintegral f - bintegral g :=
begin
have : f - g = f + (-g) := rfl,
rw [this, bintegral_add hf _, bintegral_neg hg],
{ refl },
exact hg.neg
end
lemma bintegral_smul (r : ℝ) {f : α →ₛ β} (hf : integrable f) :
bintegral (r • f) = r • bintegral f :=
calc bintegral (r • f) = sum f.range (λx, ennreal.to_real (volume (f ⁻¹' {x})) • r • x) :
by rw [smul_eq_map r f, map_bintegral f _ hf (smul_zero _)]
... = (f.range).sum (λ (x : β), ((ennreal.to_real (volume (f ⁻¹' {x}))) * r) • x) :
finset.sum_congr rfl $ λb hb, by apply smul_smul
... = r • bintegral f :
begin
rw [bintegral, smul_sum],
refine finset.sum_congr rfl (λb hb, _),
rw [smul_smul, mul_comm]
end
lemma norm_bintegral_le_bintegral_norm (f : α →ₛ β) (hf : integrable f) :
∥f.bintegral∥ ≤ (f.map norm).bintegral :=
begin
rw map_bintegral f norm hf norm_zero,
rw bintegral,
calc ∥sum f.range (λx, ennreal.to_real (volume (f ⁻¹' {x})) • x)∥ ≤
sum f.range (λx, ∥ennreal.to_real (volume (f ⁻¹' {x})) • x∥) :
norm_sum_le _ _
... = sum f.range (λx, ennreal.to_real (volume (f ⁻¹' {x})) • ∥x∥) :
begin
refine finset.sum_congr rfl (λb hb, _),
rw [norm_smul, smul_eq_mul, real.norm_eq_abs, abs_of_nonneg to_real_nonneg]
end
end
end bintegral
end simple_func
namespace l1
open ae_eq_fun
variables [normed_group β] [second_countable_topology β]
[normed_group γ] [second_countable_topology γ]
variables (α β)
/-- `l1.simple_func` is a subspace of L1 consisting of equivalence classes of an integrable simple
function. -/
def simple_func : Type (max u v) :=
{ f : α →₁ β // ∃ (s : α →ₛ β), integrable s ∧ ae_eq_fun.mk s s.measurable = f}
variables {α β}
infixr ` →₁ₛ `:25 := measure_theory.l1.simple_func
namespace simple_func
section instances
/-! Simple functions in L1 space form a `normed_space`. -/
instance : has_coe (α →₁ₛ β) (α →₁ β) := ⟨subtype.val⟩
protected lemma eq {f g : α →₁ₛ β} : (f : α →₁ β) = (g : α →₁ β) → f = g := subtype.eq
protected lemma eq' {f g : α →₁ₛ β} : (f : α →ₘ β) = (g : α →ₘ β) → f = g := subtype.eq ∘ subtype.eq
@[elim_cast] protected lemma eq_iff {f g : α →₁ₛ β} : (f : α →₁ β) = (g : α →₁ β) ↔ f = g :=
iff.intro (subtype.eq) (congr_arg coe)
@[elim_cast] protected lemma eq_iff' {f g : α →₁ₛ β} : (f : α →ₘ β) = (g : α →ₘ β) ↔ f = g :=
iff.intro (simple_func.eq') (congr_arg _)
/-- L1 simple functions forms a `emetric_space`, with the emetric being inherited from L1 space,
i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`.
Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner
integral. -/
protected def emetric_space : emetric_space (α →₁ₛ β) := subtype.emetric_space
/-- L1 simple functions forms a `metric_space`, with the metric being inherited from L1 space,
i.e., `dist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a)`).
Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner
integral. -/
protected def metric_space : metric_space (α →₁ₛ β) := subtype.metric_space
local attribute [instance] protected lemma is_add_subgroup : is_add_subgroup
(λf:α →₁ β, ∃ (s : α →ₛ β), integrable s ∧ ae_eq_fun.mk s s.measurable = f) :=
{ zero_mem := ⟨0, integrable_zero _ _, rfl⟩,
add_mem :=
begin
rintros f g ⟨s, hsi, hs⟩ ⟨t, hti, ht⟩,
use s + t, split,
{ exact hsi.add s.measurable t.measurable hti },
{ rw [coe_add, ← hs, ← ht], refl }
end,
neg_mem :=
begin
rintros f ⟨s, hsi, hs⟩,
use -s, split,
{ exact hsi.neg },
{ rw [coe_neg, ← hs], refl }
end }
/-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner
integral. -/
protected def add_comm_group : add_comm_group (α →₁ₛ β) := subtype.add_comm_group
local attribute [instance] simple_func.add_comm_group simple_func.metric_space
simple_func.emetric_space
instance : inhabited (α →₁ₛ β) := ⟨0⟩
@[simp, elim_cast] lemma coe_zero : ((0 : α →₁ₛ β) : α →₁ β) = 0 := rfl
@[simp, move_cast] lemma coe_add (f g : α →₁ₛ β) : ((f + g : α →₁ₛ β) : α →₁ β) = f + g := rfl
@[simp, move_cast] lemma coe_neg (f : α →₁ₛ β) : ((-f : α →₁ₛ β) : α →₁ β) = -f := rfl
@[simp, move_cast] lemma coe_sub (f g : α →₁ₛ β) : ((f - g : α →₁ₛ β) : α →₁ β) = f - g := rfl
@[simp] lemma edist_eq (f g : α →₁ₛ β) : edist f g = edist (f : α →₁ β) (g : α →₁ β) := rfl
@[simp] lemma dist_eq (f g : α →₁ₛ β) : dist f g = dist (f : α →₁ β) (g : α →₁ β) := rfl
/-- The norm on `α →₁ₛ β` is inherited from L1 space. That is, `∥f∥ = ∫⁻ a, edist (f a) 0`.
Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner
integral. -/
protected def has_norm : has_norm (α →₁ₛ β) := ⟨λf, ∥(f : α →₁ β)∥⟩
local attribute [instance] simple_func.has_norm
lemma norm_eq (f : α →₁ₛ β) : ∥f∥ = ∥(f : α →₁ β)∥ := rfl
lemma norm_eq' (f : α →₁ₛ β) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ β) 0) := rfl
/-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner
integral. -/
protected def normed_group : normed_group (α →₁ₛ β) :=
normed_group.of_add_dist (λ x, rfl) $ by
{ intros, simp only [dist_eq, coe_add, l1.dist_eq, l1.coe_add], rw edist_eq_add_add }
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β]
/-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner
integral. -/
protected def has_scalar : has_scalar 𝕜 (α →₁ₛ β) := ⟨λk f, ⟨k • f,
begin
rcases f with ⟨f, ⟨s, hsi, hs⟩⟩,
use k • s, split,
{ exact integrable.smul _ hsi },
{ rw [coe_smul, subtype.coe_mk, ← hs], refl }
end ⟩⟩
local attribute [instance, priority 10000] simple_func.has_scalar
@[simp, move_cast] lemma coe_smul (c : 𝕜) (f : α →₁ₛ β) :
((c • f : α →₁ₛ β) : α →₁ β) = c • (f : α →₁ β) := rfl
/-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner
integral. -/
protected def semimodule : semimodule 𝕜 (α →₁ₛ β) :=
{ one_smul := λf, simple_func.eq (by { simp only [coe_smul], exact one_smul _ _ }),
mul_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }),
smul_add := λx f g, simple_func.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }),
smul_zero := λx, simple_func.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }),
add_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact add_smul _ _ _ }),
zero_smul := λf, simple_func.eq (by { simp only [coe_smul], exact zero_smul _ _ }) }
/-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner
integral. -/
protected def module : module 𝕜 (α →₁ₛ β) :=
{ .. simple_func.semimodule }
/-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner
integral. -/
protected def vector_space : vector_space 𝕜 (α →₁ₛ β) :=
{ .. simple_func.semimodule }
local attribute [instance] simple_func.vector_space simple_func.normed_group
/-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner
integral. -/
protected def normed_space : normed_space 𝕜 (α →₁ₛ β) :=
⟨ λc f, by { rw [norm_eq, norm_eq, coe_smul, norm_smul] } ⟩
end instances
local attribute [instance] simple_func.normed_group simple_func.normed_space
section of_simple_func
/-- Construct the equivalence class `[f]` of an integrable simple function `f`. -/
@[reducible] def of_simple_func (f : α →ₛ β) (hf : integrable f) : (α →₁ₛ β) :=
⟨l1.of_fun f f.measurable hf, ⟨f, ⟨hf, rfl⟩⟩⟩
lemma of_simple_func_eq_of_fun (f : α →ₛ β) (hf : integrable f) :
(of_simple_func f hf : α →₁ β) = l1.of_fun f f.measurable hf := rfl
lemma of_simple_func_eq_mk (f : α →ₛ β) (hf : integrable f) :
(of_simple_func f hf : α →ₘ β) = ae_eq_fun.mk f f.measurable := rfl
lemma of_simple_func_zero : of_simple_func (0 : α →ₛ β) (integrable_zero α β) = 0 := rfl
lemma of_simple_func_add (f g : α →ₛ β) (hf hg) :
of_simple_func (f + g) (integrable.add f.measurable hf g.measurable hg) = of_simple_func f hf +
of_simple_func g hg := rfl
lemma of_simple_func_neg (f : α →ₛ β) (hf) :
of_simple_func (-f) (integrable.neg hf) = -of_simple_func f hf := rfl
lemma of_simple_func_sub (f g : α →ₛ β) (hf hg) :
of_simple_func (f - g) (integrable.sub f.measurable hf g.measurable hg) = of_simple_func f hf -
of_simple_func g hg := rfl
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β]
lemma of_simple_func_smul (f : α →ₛ β) (hf) (c : 𝕜) :
of_simple_func (c • f) (integrable.smul _ hf) = c • of_simple_func f hf := rfl
lemma norm_of_simple_func (f : α →ₛ β) (hf) : ∥of_simple_func f hf∥ = ennreal.to_real (∫⁻ a, edist (f a) 0) :=
rfl
end of_simple_func
section to_simple_func
/-- Find a representative of a `l1.simple_func`. -/
def to_simple_func (f : α →₁ₛ β) : α →ₛ β := classical.some f.2
/-- `f.to_simple_func` is measurable. -/
protected lemma measurable (f : α →₁ₛ β) : measurable f.to_simple_func := f.to_simple_func.measurable
/-- `f.to_simple_func` is integrable. -/
protected lemma integrable (f : α →₁ₛ β) : integrable f.to_simple_func :=
let ⟨h, _⟩ := classical.some_spec f.2 in h
lemma of_simple_func_to_simple_func (f : α →₁ₛ β) :
of_simple_func (f.to_simple_func) f.integrable = f :=
by { rw ← simple_func.eq_iff', exact (classical.some_spec f.2).2 }
lemma to_simple_func_of_simple_func (f : α →ₛ β) (hfi) :
∀ₘ a, (of_simple_func f hfi).to_simple_func a = f a :=
by { rw ← mk_eq_mk, exact (classical.some_spec (of_simple_func f hfi).2).2 }
lemma to_simple_func_eq_to_fun (f : α →₁ₛ β) : ∀ₘ a, (f.to_simple_func) a = (f : α →₁ β).to_fun a :=
begin
rw [← of_fun_eq_of_fun (f.to_simple_func) (f : α →₁ β).to_fun f.measurable f.integrable
(f:α→₁β).measurable (f:α→₁β).integrable, ← l1.eq_iff],
simp only [of_fun_eq_mk],
rcases classical.some_spec f.2 with ⟨_, h⟩, convert h, rw mk_to_fun, refl
end
variables (α β)
lemma zero_to_simple_func : ∀ₘ a, (0 : α →₁ₛ β).to_simple_func a = 0 :=
begin
filter_upwards [to_simple_func_eq_to_fun (0 : α →₁ₛ β), l1.zero_to_fun α β],
assume a,
simp only [mem_set_of_eq],
assume h,
rw h,
assume h,
exact h
end
variables {α β}
lemma add_to_simple_func (f g : α →₁ₛ β) :
∀ₘ a, (f + g).to_simple_func a = f.to_simple_func a + g.to_simple_func a :=
begin
filter_upwards [to_simple_func_eq_to_fun (f + g), to_simple_func_eq_to_fun f,
to_simple_func_eq_to_fun g, l1.add_to_fun (f:α→₁β) g],
assume a,
simp only [mem_set_of_eq],
repeat { assume h, rw h },
assume h,
rw ← h,
refl
end
lemma neg_to_simple_func (f : α →₁ₛ β) : ∀ₘ a, (-f).to_simple_func a = - f.to_simple_func a :=
begin
filter_upwards [to_simple_func_eq_to_fun (-f), to_simple_func_eq_to_fun f, l1.neg_to_fun (f:α→₁β)],
assume a,
simp only [mem_set_of_eq],
repeat { assume h, rw h },
assume h,
rw ← h,
refl
end
lemma sub_to_simple_func (f g : α →₁ₛ β) :
∀ₘ a, (f - g).to_simple_func a = f.to_simple_func a - g.to_simple_func a :=
begin
filter_upwards [to_simple_func_eq_to_fun (f - g), to_simple_func_eq_to_fun f,
to_simple_func_eq_to_fun g, l1.sub_to_fun (f:α→₁β) g],
assume a,
simp only [mem_set_of_eq],
repeat { assume h, rw h },
assume h,
rw ← h,
refl
end
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β]
lemma smul_to_simple_func (k : 𝕜) (f : α →₁ₛ β) :
∀ₘ a, (k • f).to_simple_func a = k • f.to_simple_func a :=
begin
filter_upwards [to_simple_func_eq_to_fun (k • f), to_simple_func_eq_to_fun f,
l1.smul_to_fun k (f:α→₁β)],
assume a,
simp only [mem_set_of_eq],
repeat { assume h, rw h },
assume h,
rw ← h,
refl
end
lemma lintegral_edist_to_simple_func_lt_top (f g : α →₁ₛ β) :
(∫⁻ (x : α), edist ((to_simple_func f) x) ((to_simple_func g) x)) < ⊤ :=
begin
rw lintegral_rw₂ (to_simple_func_eq_to_fun f) (to_simple_func_eq_to_fun g),
exact lintegral_edist_to_fun_lt_top _ _
end
lemma dist_to_simple_func (f g : α →₁ₛ β) : dist f g =
ennreal.to_real (∫⁻ x, edist (f.to_simple_func x) (g.to_simple_func x)) :=
begin
rw [dist_eq, l1.dist_to_fun, ennreal.to_real_eq_to_real],
{ rw lintegral_rw₂, repeat { exact all_ae_eq_symm (to_simple_func_eq_to_fun _) } },
{ exact l1.lintegral_edist_to_fun_lt_top _ _ },
{ exact lintegral_edist_to_simple_func_lt_top _ _ }
end
lemma norm_to_simple_func (f : α →₁ₛ β) :
∥f∥ = ennreal.to_real (∫⁻ (a : α), nnnorm ((to_simple_func f) a)) :=
calc ∥f∥ = ennreal.to_real (∫⁻x, edist (f.to_simple_func x) ((0 : α →₁ₛ β).to_simple_func x)) :
begin
rw [← dist_zero_right, dist_to_simple_func]
end
... = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x)) :
begin
rw lintegral_nnnorm_eq_lintegral_edist,
have : (∫⁻ (x : α), edist ((to_simple_func f) x) ((to_simple_func (0:α→₁ₛβ)) x)) =
∫⁻ (x : α), edist ((to_simple_func f) x) 0,
{ apply lintegral_congr_ae, filter_upwards [zero_to_simple_func α β],
assume a,
simp only [mem_set_of_eq],
assume h,
rw h },
rw [ennreal.to_real_eq_to_real],
{ exact this },
{ exact lintegral_edist_to_simple_func_lt_top _ _ },
{ rw ← this, exact lintegral_edist_to_simple_func_lt_top _ _ }
end
lemma norm_eq_bintegral (f : α →₁ₛ β) : ∥f∥ = (f.to_simple_func.map norm).bintegral :=
calc ∥f∥ = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x)) :
by { rw norm_to_simple_func }
... = (f.to_simple_func.map norm).bintegral :
begin
rw ← f.to_simple_func.bintegral_eq_lintegral (coe ∘ nnnorm) f.integrable,
{ congr },
{ simp only [nnnorm_zero, function.comp_app, ennreal.coe_zero] },
{ assume b, exact coe_lt_top }
end
end to_simple_func
section coe_to_l1
/-! The embedding of integrable simple functions `α →₁ₛ β` into L1 is a uniform and dense embedding. -/
lemma exists_simple_func_near (f : α →₁ β) {ε : ℝ} (ε0 : 0 < ε) :
∃ s : α →₁ₛ β, dist f s < ε :=
begin
rcases f with ⟨⟨f, hfm⟩, hfi⟩,
simp only [integrable_mk, quot_mk_eq_mk] at hfi,
rcases simple_func_sequence_tendsto' hfm hfi with ⟨F, ⟨h₁, h₂⟩⟩,
rw ennreal.tendsto_at_top at h₂,
rcases h₂ (ennreal.of_real (ε/2)) (of_real_pos.2 $ half_pos ε0) with ⟨N, hN⟩,
have : (∫⁻ (x : α), nndist (F N x) (f x)) < ennreal.of_real ε :=
calc (∫⁻ (x : α), nndist (F N x) (f x)) ≤ 0 + ennreal.of_real (ε/2) : (hN N (le_refl _)).2
... < ennreal.of_real ε :
by { simp only [zero_add, of_real_lt_of_real_iff ε0], exact half_lt_self ε0 },
{ refine ⟨of_simple_func (F N) (h₁ N), _⟩, rw dist_comm,
rw lt_of_real_iff_to_real_lt _ at this,
{ simpa [edist_mk_mk', of_simple_func, l1.of_fun, l1.dist_eq] },
rw ← lt_top_iff_ne_top, exact lt_trans this (by simp [lt_top_iff_ne_top, of_real_ne_top]) },
{ exact zero_ne_top }
end
protected lemma uniform_continuous : uniform_continuous (coe : (α →₁ₛ β) → (α →₁ β)) :=
uniform_continuous_comap
protected lemma uniform_embedding : uniform_embedding (coe : (α →₁ₛ β) → (α →₁ β)) :=
uniform_embedding_comap subtype.val_injective
protected lemma uniform_inducing : uniform_inducing (coe : (α →₁ₛ β) → (α →₁ β)) :=
simple_func.uniform_embedding.to_uniform_inducing
protected lemma dense_embedding : dense_embedding (coe : (α →₁ₛ β) → (α →₁ β)) :=
simple_func.uniform_embedding.dense_embedding $
λ f, mem_closure_iff_nhds.2 $ λ t ht,
let ⟨ε,ε0, hε⟩ := metric.mem_nhds_iff.1 ht in
let ⟨s, h⟩ := exists_simple_func_near f ε0 in
⟨_, hε (metric.mem_ball'.2 h), s, rfl⟩
protected lemma dense_inducing : dense_inducing (coe : (α →₁ₛ β) → (α →₁ β)) :=
simple_func.dense_embedding.to_dense_inducing
protected lemma dense_range : dense_range (coe : (α →₁ₛ β) → (α →₁ β)) :=
simple_func.dense_inducing.dense
variables (𝕜 : Type*) [normed_field 𝕜] [normed_space 𝕜 β]
variables (α β)
/-- The uniform and dense embedding of L1 simple functions into L1 functions. -/
def coe_to_l1 : (α →₁ₛ β) →L[𝕜] (α →₁ β) :=
{ to_fun := (coe : (α →₁ₛ β) → (α →₁ β)),
add := λf g, rfl,
smul := λk f, rfl,
cont := l1.simple_func.uniform_continuous.continuous, }
variables {α β 𝕜}
end coe_to_l1
section pos_part
/-- Positive part of a simple function in L1 space. -/
def pos_part (f : α →₁ₛ ℝ) : α →₁ₛ ℝ := ⟨l1.pos_part (f : α →₁ ℝ),
begin
rcases f with ⟨f, s, hsi, hsf⟩,
use s.pos_part,
split,
{ exact integrable.max_zero hsi },
{ simp only [subtype.coe_mk],
rw [l1.coe_pos_part, ← hsf, ae_eq_fun.pos_part, ae_eq_fun.zero_def, comp₂_mk_mk, mk_eq_mk],
filter_upwards [],
simp only [mem_set_of_eq],
assume a,
refl }
end ⟩
/-- Negative part of a simple function in L1 space. -/
def neg_part (f : α →₁ₛ ℝ) : α →₁ₛ ℝ := pos_part (-f)
@[move_cast] lemma coe_pos_part (f : α →₁ₛ ℝ) : (f.pos_part : α →₁ ℝ) = (f : α →₁ ℝ).pos_part := rfl
@[move_cast] lemma coe_neg_part (f : α →₁ₛ ℝ) : (f.neg_part : α →₁ ℝ) = (f : α →₁ ℝ).neg_part := rfl
end pos_part
section simple_func_integral
/-! Define the Bochner integral on `α →₁ₛ β` and prove basic properties of this integral. -/
variables [normed_space ℝ β]
/-- The Bochner integral over simple functions in l1 space. -/
def integral (f : α →₁ₛ β) : β := (f.to_simple_func).bintegral
lemma integral_eq_bintegral (f : α →₁ₛ β) : integral f = (f.to_simple_func).bintegral := rfl
lemma integral_eq_lintegral {f : α →₁ₛ ℝ} (h_pos : ∀ₘ a, 0 ≤ f.to_simple_func a) :
integral f = ennreal.to_real (∫⁻ a, ennreal.of_real (f.to_simple_func a)) :=
by { rw [integral, simple_func.bintegral_eq_lintegral' f.integrable h_pos], refl }
lemma integral_congr (f g : α →₁ₛ β) (h : ∀ₘ a, f.to_simple_func a = g.to_simple_func a) :
integral f = integral g :=
by { simp only [integral], apply simple_func.bintegral_congr f.integrable g.integrable, exact h }
lemma integral_add (f g : α →₁ₛ β) : integral (f + g) = integral f + integral g :=
begin
simp only [integral],
rw ← simple_func.bintegral_add f.integrable g.integrable,
apply simple_func.bintegral_congr (f + g).integrable,
{ exact f.integrable.add f.measurable g.measurable g.integrable },
{ apply add_to_simple_func },
end
lemma integral_smul (r : ℝ) (f : α →₁ₛ β) : integral (r • f) = r • integral f :=
begin
simp only [integral],
rw ← simple_func.bintegral_smul _ f.integrable,
apply simple_func.bintegral_congr (r • f).integrable,
{ exact integrable.smul _ f.integrable },
{ apply smul_to_simple_func }
end
lemma norm_integral_le_norm (f : α →₁ₛ β) : ∥ integral f ∥ ≤ ∥f∥ :=
begin
rw [integral, norm_eq_bintegral],
exact f.to_simple_func.norm_bintegral_le_bintegral_norm f.integrable
end
/-- The Bochner integral over simple functions in l1 space as a continuous linear map. -/
def integral_clm : (α →₁ₛ β) →L[ℝ] β :=
linear_map.mk_continuous ⟨integral, integral_add, integral_smul⟩
1 (λf, le_trans (norm_integral_le_norm _) $ by rw one_mul)
local notation `Integral` := @integral_clm α _ β _ _ _
open continuous_linear_map
lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 :=
linear_map.mk_continuous_norm_le _ (zero_le_one) _
section pos_part
lemma pos_part_to_simple_func (f : α →₁ₛ ℝ) :
∀ₘ a, f.pos_part.to_simple_func a = f.to_simple_func.pos_part a :=
begin
have eq : ∀ a, f.to_simple_func.pos_part a = max (f.to_simple_func a) 0 := λa, rfl,
have ae_eq : ∀ₘ a, f.pos_part.to_simple_func a = max (f.to_simple_func a) 0,
{ filter_upwards [to_simple_func_eq_to_fun f.pos_part, pos_part_to_fun (f : α →₁ ℝ),
to_simple_func_eq_to_fun f],
simp only [mem_set_of_eq],
assume a h₁ h₂ h₃,
rw [h₁, coe_pos_part, h₂, ← h₃] },
filter_upwards [ae_eq],
simp only [mem_set_of_eq],
assume a h,
rw [h, eq]
end
lemma neg_part_to_simple_func (f : α →₁ₛ ℝ) :
∀ₘ a, f.neg_part.to_simple_func a = f.to_simple_func.neg_part a :=
begin
rw [simple_func.neg_part, measure_theory.simple_func.neg_part],
filter_upwards [pos_part_to_simple_func (-f), neg_to_simple_func f],
simp only [mem_set_of_eq],
assume a h₁ h₂,
rw h₁,
show max _ _ = max _ _,
rw h₂,
refl
end
lemma integral_eq_norm_pos_part_sub (f : α →₁ₛ ℝ) : f.integral = ∥f.pos_part∥ - ∥f.neg_part∥ :=
begin
-- Convert things in `L¹` to their `simple_func` counterpart
have ae_eq₁ : ∀ₘ a, f.to_simple_func.pos_part a = (f.pos_part).to_simple_func.map norm a,
{ filter_upwards [pos_part_to_simple_func f],
simp only [mem_set_of_eq],
assume a h,
rw [simple_func.map_apply, h],
conv_lhs { rw [← simple_func.pos_part_map_norm, simple_func.map_apply] } },
-- Convert things in `L¹` to their `simple_func` counterpart
have ae_eq₂ : ∀ₘ a, f.to_simple_func.neg_part a = (f.neg_part).to_simple_func.map norm a,
{ filter_upwards [neg_part_to_simple_func f],
simp only [mem_set_of_eq],
assume a h,
rw [simple_func.map_apply, h],
conv_lhs { rw [← simple_func.neg_part_map_norm, simple_func.map_apply] } },
-- Convert things in `L¹` to their `simple_func` counterpart
have ae_eq : ∀ₘ a, f.to_simple_func.pos_part a - f.to_simple_func.neg_part a =
(f.pos_part).to_simple_func.map norm a - (f.neg_part).to_simple_func.map norm a,
{ filter_upwards [ae_eq₁, ae_eq₂],
simp only [mem_set_of_eq],
assume a h₁ h₂,
rw [h₁, h₂] },
rw [integral, norm_eq_bintegral, norm_eq_bintegral, ← simple_func.bintegral_sub],
{ show f.to_simple_func.bintegral =
((f.pos_part.to_simple_func).map norm - f.neg_part.to_simple_func.map norm).bintegral,
apply simple_func.bintegral_congr f.integrable,
{ show integrable (f.pos_part.to_simple_func.map norm - f.neg_part.to_simple_func.map norm),
refine integrable_of_ae_eq _ _,
{ exact (f.to_simple_func.pos_part - f.to_simple_func.neg_part) },
{ exact (integrable.max_zero f.integrable).sub f.to_simple_func.pos_part.measurable
f.to_simple_func.neg_part.measurable (integrable.max_zero f.integrable.neg) },
exact ae_eq },
filter_upwards [ae_eq₁, ae_eq₂],
simp only [mem_set_of_eq],
assume a h₁ h₂, show _ = _ - _,
rw [← h₁, ← h₂],
have := f.to_simple_func.pos_part_sub_neg_part,
conv_lhs {rw ← this},
refl },
{ refine integrable_of_ae_eq (integrable.max_zero f.integrable) ae_eq₁ },
{ refine integrable_of_ae_eq (integrable.max_zero f.integrable.neg) ae_eq₂ }
end
end pos_part
end simple_func_integral
end simple_func
open simple_func
variables [normed_space ℝ β] [normed_space ℝ γ] [complete_space β]
section integration_in_l1
local notation `to_l1` := coe_to_l1 α β ℝ
local attribute [instance] simple_func.normed_group simple_func.normed_space
open continuous_linear_map
/-- The Bochner integral in l1 space as a continuous linear map. -/
def integral_clm : (α →₁ β) →L[ℝ] β :=
integral_clm.extend to_l1 simple_func.dense_range simple_func.uniform_inducing
/-- The Bochner integral in l1 space -/
def integral (f : α →₁ β) : β := (integral_clm).to_fun f
lemma integral_eq (f : α →₁ β) : integral f = (integral_clm).to_fun f := rfl
@[elim_cast] lemma simple_func.integral_eq_integral (f : α →₁ₛ β) :
integral (f : α →₁ β) = f.integral :=
by { refine uniformly_extend_of_ind _ _ _ _, exact simple_func.integral_clm.uniform_continuous }
variables (α β)
@[simp] lemma integral_zero : integral (0 : α →₁ β) = 0 :=
map_zero integral_clm
variables {α β}
lemma integral_add (f g : α →₁ β) : integral (f + g) = integral f + integral g :=
map_add integral_clm f g
lemma integral_neg (f : α →₁ β) : integral (-f) = - integral f :=
map_neg integral_clm f
lemma integral_sub (f g : α →₁ β) : integral (f - g) = integral f - integral g :=
map_sub integral_clm f g
lemma integral_smul (r : ℝ) (f : α →₁ β) : integral (r • f) = r • integral f :=
map_smul r integral_clm f
local notation `Integral` := @integral_clm α _ β _ _ _ _
local notation `sIntegral` := @simple_func.integral_clm α _ β _ _ _
lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 :=
calc ∥Integral∥ ≤ (1 : nnreal) * ∥sIntegral∥ :
op_norm_extend_le _ _ _ $ λs, by {rw [nnreal.coe_one, one_mul], refl}
... = ∥sIntegral∥ : one_mul _
... ≤ 1 : norm_Integral_le_one
lemma norm_integral_le (f : α →₁ β) : ∥integral f∥ ≤ ∥f∥ :=
calc ∥integral f∥ = ∥Integral f∥ : rfl
... ≤ ∥Integral∥ * ∥f∥ : le_op_norm _ _
... ≤ 1 * ∥f∥ : mul_le_mul_of_nonneg_right norm_Integral_le_one $ norm_nonneg _
... = ∥f∥ : one_mul _
section pos_part
lemma integral_eq_norm_pos_part_sub (f : α →₁ ℝ) : integral f = ∥pos_part f∥ - ∥neg_part f∥ :=
begin
-- Use `is_closed_property` and `is_closed_eq`
refine @is_closed_property _ _ _ (coe : (α →₁ₛ ℝ) → (α →₁ ℝ))
(λ f : α →₁ ℝ, integral f = ∥pos_part f∥ - ∥neg_part f∥)
l1.simple_func.dense_range (is_closed_eq _ _) _ f,
{ exact cont _ },
{ refine continuous.sub (continuous_norm.comp l1.continuous_pos_part)
(continuous_norm.comp l1.continuous_neg_part) },
-- Show that the property holds for all simple functions in the `L¹` space.
{ assume s,
norm_cast,
rw [← simple_func.norm_eq, ← simple_func.norm_eq],
exact simple_func.integral_eq_norm_pos_part_sub _}
end
end pos_part
end integration_in_l1
end l1
variables [normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β]
[normed_group γ] [second_countable_topology γ] [normed_space ℝ γ] [complete_space γ]
/-- The Bochner integral -/
def integral (f : α → β) : β :=
if hf : measurable f ∧ integrable f
then (l1.of_fun f hf.1 hf.2).integral
else 0
notation `∫` binders `, ` r:(scoped f, integral f) := r
section properties
open continuous_linear_map measure_theory.simple_func
variables {f g : α → β}
lemma integral_eq (f : α → β) (h₁ : measurable f) (h₂ : integrable f) :
(∫ a, f a) = (l1.of_fun f h₁ h₂).integral :=
dif_pos ⟨h₁, h₂⟩
lemma integral_undef (h : ¬ (measurable f ∧ integrable f)) : (∫ a, f a) = 0 :=
dif_neg h
lemma integral_non_integrable (h : ¬ integrable f) : (∫ a, f a) = 0 :=
integral_undef $ not_and_of_not_right _ h
lemma integral_non_measurable (h : ¬ measurable f) : (∫ a, f a) = 0 :=
integral_undef $ not_and_of_not_left _ h
variables (α β)
@[simp] lemma integral_zero : (∫ a : α, (0:β)) = 0 :=
by rw [integral_eq, l1.of_fun_zero, l1.integral_zero]
variables {α β}
lemma integral_add
(hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) :
(∫ a, f a + g a) = (∫ a, f a) + (∫ a, g a) :=
by rw [integral_eq, integral_eq f hfm hfi, integral_eq g hgm hgi, l1.of_fun_add, l1.integral_add]
lemma integral_neg (f : α → β) : (∫ a, -f a) = - (∫ a, f a) :=
begin
by_cases hf : measurable f ∧ integrable f,
{ rw [integral_eq f hf.1 hf.2, integral_eq (λa, - f a) hf.1.neg hf.2.neg, l1.of_fun_neg,
l1.integral_neg] },
{ have hf' : ¬(measurable (λa, -f a) ∧ integrable (λa, -f a)),
{ rwa [measurable_neg_iff, integrable_neg_iff] },
rw [integral_undef hf, integral_undef hf', neg_zero] }
end
lemma integral_sub
(hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) :
(∫ a, f a - g a) = (∫ a, f a) - (∫ a, g a) :=
by simp only [sub_eq_add_neg, integral_neg, integral_add, measurable_neg_iff, integrable_neg_iff, *]
lemma integral_smul (r : ℝ) (f : α → β) : (∫ a, r • (f a)) = r • (∫ a, f a) :=
begin
by_cases hf : measurable f ∧ integrable f,
{ rw [integral_eq f hf.1 hf.2, integral_eq (λa, r • (f a)), l1.of_fun_smul, l1.integral_smul] },
{ by_cases hr : r = 0,
{ simp only [hr, measure_theory.integral_zero, zero_smul] },
have hf' : ¬(measurable (λa, r • f a) ∧ integrable (λa, r • f a)),
{ rwa [← measurable_smul_iff hr f, ← integrable_smul_iff hr f] at hf },
rw [integral_undef hf, integral_undef hf', smul_zero] }
end
lemma integral_mul_left (r : ℝ) (f : α → ℝ) : (∫ a, r * (f a)) = r * (∫ a, f a) :=
integral_smul r f
lemma integral_mul_right (r : ℝ) (f : α → ℝ) : (∫ a, (f a) * r) = (∫ a, f a) * r :=
by { simp only [mul_comm], exact integral_mul_left r f }
lemma integral_div (r : ℝ) (f : α → ℝ) : (∫ a, (f a) / r) = (∫ a, f a) / r :=
integral_mul_right r⁻¹ f
lemma integral_congr_ae (hfm : measurable f) (hgm : measurable g) (h : ∀ₘ a, f a = g a) :
(∫ a, f a) = (∫ a, g a) :=
begin
by_cases hfi : integrable f,
{ have hgi : integrable g := integrable_of_ae_eq hfi h,
rw [integral_eq f hfm hfi, integral_eq g hgm hgi, (l1.of_fun_eq_of_fun f g hfm hfi hgm hgi).2 h] },
{ have hgi : ¬ integrable g, { rw integrable_congr_ae h at hfi, exact hfi },
rw [integral_non_integrable hfi, integral_non_integrable hgi] },
end
lemma norm_integral_le_lintegral_norm (f : α → β) :
∥(∫ a, f a)∥ ≤ ennreal.to_real (∫⁻ a, ennreal.of_real ∥f a∥) :=
begin
by_cases hf : measurable f ∧ integrable f,
{ rw [integral_eq f hf.1 hf.2, ← l1.norm_of_fun_eq_lintegral_norm f hf.1 hf.2],
exact l1.norm_integral_le _ },
{ rw [integral_undef hf, _root_.norm_zero],
exact to_real_nonneg }
end
/-- Lebesgue dominated convergence theorem provides sufficient conditions under which almost
everywhere convergence of a sequence of functions implies the convergence of their integrals. -/
theorem tendsto_integral_of_dominated_convergence {F : ℕ → α → β} {f : α → β} (bound : α → ℝ)
(F_measurable : ∀ n, measurable (F n))
(f_measurable : measurable f)
(bound_integrable : integrable bound)
(h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a)
(h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
tendsto (λn, ∫ a, F n a) at_top (𝓝 $ (∫ a, f a)) :=
begin
/- To show `(∫ a, F n a) --> (∫ f)`, suffices to show `∥∫ a, F n a - ∫ f∥ --> 0` -/
rw tendsto_iff_norm_tendsto_zero,
/- But `0 ≤ ∥∫ a, F n a - ∫ f∥ = ∥∫ a, (F n a - f a) ∥ ≤ ∫ a, ∥F n a - f a∥, and thus we apply the
sandwich theorem and prove that `∫ a, ∥F n a - f a∥ --> 0` -/
have lintegral_norm_tendsto_zero :
tendsto (λn, ennreal.to_real $ ∫⁻ a, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0) :=
(tendsto_to_real (zero_ne_top)).comp
(tendsto_lintegral_norm_of_dominated_convergence
F_measurable f_measurable bound_integrable h_bound h_lim),
-- Use the sandwich theorem
refine squeeze_zero (λ n, norm_nonneg _) _ lintegral_norm_tendsto_zero,
-- Show `∥∫ a, F n a - ∫ f∥ ≤ ∫ a, ∥F n a - f a∥` for all `n`
{ assume n,
have h₁ : integrable (F n) := integrable_of_integrable_bound bound_integrable (h_bound _),
have h₂ : integrable f := integrable_of_dominated_convergence bound_integrable h_bound h_lim,
rw ← integral_sub (F_measurable _) h₁ f_measurable h₂,
exact norm_integral_le_lintegral_norm _ }
end
/-- Lebesgue dominated convergence theorem for filters with a countable basis -/
lemma tendsto_integral_filter_of_dominated_convergence {ι} {l : filter ι}
{F : ι → α → β} {f : α → β} (bound : α → ℝ)
(hl_cb : l.has_countable_basis)
(hF_meas : ∀ᶠ n in l, measurable (F n))
(f_measurable : measurable f)
(h_bound : ∀ᶠ n in l, ∀ₘ a, ∥F n a∥ ≤ bound a)
(bound_integrable : integrable bound)
(h_lim : ∀ₘ a, tendsto (λ n, F n a) l (𝓝 (f a))) :
tendsto (λn, ∫ a, F n a) l (𝓝 $ (∫ a, f a)) :=
begin
rw hl_cb.tendsto_iff_seq_tendsto,
{ intros x xl,
have hxl, { rw tendsto_at_top' at xl, exact xl },
have h := inter_mem_sets hF_meas h_bound,
replace h := hxl _ h,
rcases h with ⟨k, h⟩,
rw ← tendsto_add_at_top_iff_nat k,
refine tendsto_integral_of_dominated_convergence _ _ _ _ _ _,
{ exact bound },
{ intro, refine (h _ _).1, exact nat.le_add_left _ _ },
{ assumption },
{ assumption },
{ intro, refine (h _ _).2, exact nat.le_add_left _ _ },
{ filter_upwards [h_lim],
simp only [mem_set_of_eq],
assume a h_lim,
apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a),
{ assumption },
rw tendsto_add_at_top_iff_nat,
assumption } },
end
/-- The Bochner integral of a real-valued function `f : α → ℝ` is the difference between the
integral of the positive part of `f` and the integral of the negative part of `f`. -/
lemma integral_eq_lintegral_max_sub_lintegral_min {f : α → ℝ}
(hfm : measurable f) (hfi : integrable f) : (∫ a, f a) =
ennreal.to_real (∫⁻ a, ennreal.of_real $ max (f a) 0) -
ennreal.to_real (∫⁻ a, ennreal.of_real $ - min (f a) 0) :=
let f₁ : α →₁ ℝ := l1.of_fun f hfm hfi in
-- Go to the `L¹` space
have eq₁ : ennreal.to_real (∫⁻ a, ennreal.of_real $ max (f a) 0) = ∥l1.pos_part f₁∥ :=
begin
rw l1.norm_eq_norm_to_fun,
congr' 1,
apply lintegral_congr_ae,
filter_upwards [l1.pos_part_to_fun f₁, l1.to_fun_of_fun f hfm hfi],
simp only [mem_set_of_eq],
assume a h₁ h₂,
rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg],
exact le_max_right _ _
end,
-- Go to the `L¹` space
have eq₂ : ennreal.to_real (∫⁻ a, ennreal.of_real $ -min (f a) 0) = ∥l1.neg_part f₁∥ :=
begin
rw l1.norm_eq_norm_to_fun,
congr' 1,
apply lintegral_congr_ae,
filter_upwards [l1.neg_part_to_fun_eq_min f₁, l1.to_fun_of_fun f hfm hfi],
simp only [mem_set_of_eq],
assume a h₁ h₂,
rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg],
rw [min_eq_neg_max_neg_neg, _root_.neg_neg, neg_zero],
exact le_max_right _ _
end,
begin
rw [eq₁, eq₂, integral, dif_pos],
exact l1.integral_eq_norm_pos_part_sub _,
{ exact ⟨hfm, hfi⟩ }
end
lemma integral_eq_lintegral_of_nonneg_ae {f : α → ℝ} (hf : ∀ₘ a, 0 ≤ f a) (hfm : measurable f) :
(∫ a, f a) = ennreal.to_real (∫⁻ a, ennreal.of_real $ f a) :=
begin
by_cases hfi : integrable f,
{ rw integral_eq_lintegral_max_sub_lintegral_min hfm hfi,
have h_min : (∫⁻ a, ennreal.of_real (-min (f a) 0)) = 0,
{ rw lintegral_eq_zero_iff,
{ filter_upwards [hf],
simp only [mem_set_of_eq],
assume a h,
simp only [min_eq_right h, neg_zero, ennreal.of_real_zero] },
{ refine measurable_of_real.comp
((measurable.neg measurable_id).comp $ measurable.min hfm measurable_const) } },
have h_max : (∫⁻ a, ennreal.of_real (max (f a) 0)) = (∫⁻ a, ennreal.of_real $ f a),
{ apply lintegral_congr_ae,
filter_upwards [hf],
simp only [mem_set_of_eq],
assume a h,
rw max_eq_left h },
rw [h_min, h_max, zero_to_real, _root_.sub_zero] },
{ rw integral_non_integrable hfi,
rw [integrable_iff_norm, lt_top_iff_ne_top, ne.def, not_not] at hfi,
have : (∫⁻ (a : α), ennreal.of_real (f a)) = (∫⁻ a, ennreal.of_real ∥f a∥),
{ apply lintegral_congr_ae,
filter_upwards [hf],
simp only [mem_set_of_eq],
assume a h,
rw [real.norm_eq_abs, abs_of_nonneg h] },
rw [this, hfi], refl }
end
lemma integral_nonneg_of_ae {f : α → ℝ} (hf : ∀ₘ a, 0 ≤ f a) : 0 ≤ (∫ a, f a) :=
begin
by_cases hfm : measurable f,
{ rw integral_eq_lintegral_of_nonneg_ae hf hfm, exact to_real_nonneg },
{ rw integral_non_measurable hfm }
end
lemma integral_nonpos_of_nonpos_ae {f : α → ℝ} (hf : ∀ₘ a, f a ≤ 0) : (∫ a, f a) ≤ 0 :=
begin
have hf : ∀ₘ a, 0 ≤ (-f) a,
{ filter_upwards [hf], simp only [mem_set_of_eq], assume a h, rwa [pi.neg_apply, neg_nonneg] },
have : 0 ≤ (∫ a, -f a) := integral_nonneg_of_ae hf,
rwa [integral_neg, neg_nonneg] at this,
end
lemma integral_le_integral_ae {f g : α → ℝ} (hfm : measurable f) (hfi : integrable f)
(hgm : measurable g) (hgi : integrable g) (h : ∀ₘ a, f a ≤ g a) : (∫ a, f a) ≤ (∫ a, g a) :=
le_of_sub_nonneg
begin
rw ← integral_sub hgm hgi hfm hfi,
apply integral_nonneg_of_ae,
filter_upwards [h],
simp only [mem_set_of_eq],
assume a,
exact sub_nonneg_of_le
end
lemma integral_le_integral {f g : α → ℝ} (hfm : measurable f) (hfi : integrable f)
(hgm : measurable g) (hgi : integrable g) (h : ∀ a, f a ≤ g a) : (∫ a, f a) ≤ (∫ a, g a) :=
integral_le_integral_ae hfm hfi hgm hgi $ univ_mem_sets' h
lemma norm_integral_le_integral_norm (f : α → β) : ∥(∫ a, f a)∥ ≤ ∫ a, ∥f a∥ :=
have le_ae : ∀ₘ (a : α), 0 ≤ ∥f a∥ := by filter_upwards [] λa, norm_nonneg _,
classical.by_cases
( λh : measurable f,
calc ∥(∫ a, f a)∥ ≤ ennreal.to_real (∫⁻ a, ennreal.of_real ∥f a∥) : norm_integral_le_lintegral_norm _
... = ∫ a, ∥f a∥ : (integral_eq_lintegral_of_nonneg_ae le_ae $ measurable.norm h).symm )
( λh : ¬measurable f,
begin
rw [integral_non_measurable h, _root_.norm_zero],
exact integral_nonneg_of_ae le_ae
end )
lemma integral_finset_sum {ι} (s : finset ι) {f : ι → α → β}
(hfm : ∀ i, measurable (f i)) (hfi : ∀ i, integrable (f i)) :
(∫ a, s.sum (λ i, f i a)) = s.sum (λ i, ∫ a, f i a) :=
begin
refine finset.induction_on s _ _,
{ simp only [integral_zero, finset.sum_empty] },
{ assume i s his ih,
simp only [his, finset.sum_insert, not_false_iff],
rw [integral_add (hfm _) (hfi _) (measurable_finset_sum s hfm)
(integrable_finset_sum s hfm hfi), ih] }
end
end properties
mk_simp_attribute integral_simps "Simp set for integral rules."
attribute [integral_simps] integral_neg integral_smul l1.integral_add l1.integral_sub
l1.integral_smul l1.integral_neg
attribute [irreducible] integral l1.integral
end measure_theory
|
70bb7822c532ccc11c3af0c6d8b1eacaee039924 | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch6/ex0202.lean | 42d62bb2145b273c2840b411d07e84f9765d203c | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 298 | lean | section
variables (x y z : ℕ)
variables (h₁ : x = y) (h₂ : y = z)
include h₁ h₂
theorem foo : x = z :=
begin
rw [h₁, h₂]
end
omit h₁ h₂
theorem bar : x = z :=
eq.trans h₁ h₂
theorem baz : x = x := rfl
#check @foo
#check @bar
#check baz
end
|
1c3e1e4a5a882fa966b3c8ba3203de964dc6106c | b7f22e51856f4989b970961f794f1c435f9b8f78 | /library/theories/finite_group_theory/hom.lean | eb32fc10df15b7a63ce4def756c4a35c9d678173 | [
"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 | 7,049 | lean | /-
Copyright (c) 2015 Haitao Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Haitao Zhang
-/
import algebra.group data.set .subgroup
namespace group_theory
-- ⁻¹ in eq.ops conflicts with group ⁻¹
-- open eq.ops
notation H1 ▸ H2 := eq.subst H1 H2
open set
open function
open group_theory.ops
open quot
local attribute set [reducible]
section defs
variables {A B : Type}
variable [s1 : group A]
variable [s2 : group B]
include s1
include s2
-- the Prop of being hom
definition homomorphic [reducible] (f : A → B) : Prop := ∀ a b, f (a*b) = (f a)*(f b)
-- type class for inference
structure is_hom_class [class] (f : A → B) : Type :=
(is_hom : homomorphic f)
-- the proof of hom_prop if the class can be inferred
definition is_hom (f : A → B) [h : is_hom_class f] : homomorphic f :=
@is_hom_class.is_hom A B s1 s2 f h
definition ker (f : A → B) [h : is_hom_class f] : set A := {a : A | f a = 1}
definition isomorphic (f : A → B) := injective f ∧ homomorphic f
structure is_iso_class [class] (f : A → B) extends is_hom_class f : Type :=
(inj : injective f)
lemma iso_is_inj (f : A → B) [h : is_iso_class f] : injective f:=
@is_iso_class.inj A B s1 s2 f h
lemma iso_is_iso (f : A → B) [h : is_iso_class f] : isomorphic f:=
and.intro (iso_is_inj f) (is_hom f)
end defs
section
variables {A B : Type}
variable [s1 : group A]
definition id_is_iso [instance] : @is_hom_class A A s1 s1 (@id A) :=
is_hom_class.mk (take a b, rfl)
variable [s2 : group B]
include s1
include s2
variable f : A → B
variable [h : is_hom_class f]
include h
theorem hom_map_one : f 1 = 1 :=
have P : f 1 = (f 1) * (f 1), from
calc f 1 = f (1*1) : mul_one
... = (f 1) * (f 1) : is_hom f,
eq.symm (mul.right_inv (f 1) ▸ (mul_inv_eq_of_eq_mul P))
theorem hom_map_inv (a : A) : f a⁻¹ = (f a)⁻¹ :=
have P : f 1 = 1, from hom_map_one f,
have P1 : f (a⁻¹ * a) = 1, from (eq.symm (mul.left_inv a)) ▸ P,
have P2 : (f a⁻¹) * (f a) = 1, from (is_hom f a⁻¹ a) ▸ P1,
have P3 : (f a⁻¹) * (f a) = (f a)⁻¹ * (f a), from eq.symm (mul.left_inv (f a)) ▸ P2,
mul_right_cancel P3
theorem hom_map_mul_closed (H : set A) : mul_closed_on H → mul_closed_on (f ' H) :=
assume Pclosed, assume b1, assume b2,
assume Pb1 : b1 ∈ f ' H, assume Pb2 : b2 ∈ f ' H,
obtain a1 (Pa1 : a1 ∈ H ∧ f a1 = b1), from Pb1,
obtain a2 (Pa2 : a2 ∈ H ∧ f a2 = b2), from Pb2,
have Pa1a2 : a1 * a2 ∈ H, from Pclosed a1 a2 (and.left Pa1) (and.left Pa2),
have Pb1b2 : f (a1 * a2) = b1 * b2, from calc
f (a1 * a2) = f a1 * f a2 : is_hom f a1 a2
... = b1 * f a2 : {and.right Pa1}
... = b1 * b2 : {and.right Pa2},
mem_image Pa1a2 Pb1b2
lemma ker.has_one : 1 ∈ ker f := hom_map_one f
lemma ker.has_inv : subgroup.has_inv (ker f) :=
take a, assume Pa : f a = 1, calc
f a⁻¹ = (f a)⁻¹ : by rewrite (hom_map_inv f)
... = 1⁻¹ : by rewrite Pa
... = 1 : by rewrite one_inv
lemma ker.mul_closed : mul_closed_on (ker f) :=
take x y, assume (Px : f x = 1) (Py : f y = 1), calc
f (x*y) = (f x) * (f y) : by rewrite [is_hom f]
... = 1 : by rewrite [Px, Py, mul_one]
lemma ker.normal : same_left_right_coset (ker f) :=
take a, funext (assume x, begin
esimp [ker, set_of, glcoset, grcoset],
rewrite [*(is_hom f), mul_eq_one_iff_mul_eq_one (f a⁻¹) (f x)]
end)
definition ker_is_normal_subgroup : is_normal_subgroup (ker f) :=
is_normal_subgroup.mk (ker.has_one f) (ker.mul_closed f) (ker.has_inv f)
(ker.normal f)
-- additional subgroup variable
variable {H : set A}
variable [is_subgH : is_subgroup H]
include is_subgH
theorem hom_map_subgroup : is_subgroup (f ' H) :=
have Pone : 1 ∈ f ' H, from mem_image (@subg_has_one _ _ H _) (hom_map_one f),
have Pclosed : mul_closed_on (f ' H), from hom_map_mul_closed f H subg_mul_closed,
have Pinv : ∀ b, b ∈ f ' H → b⁻¹ ∈ f ' H, from
assume b, assume Pimg,
obtain a (Pa : a ∈ H ∧ f a = b), from Pimg,
have Painv : a⁻¹ ∈ H, from subg_has_inv a (and.left Pa),
have Pfainv : (f a)⁻¹ ∈ f ' H, from mem_image Painv (hom_map_inv f a),
and.right Pa ▸ Pfainv,
is_subgroup.mk Pone Pclosed Pinv
end
section hom_theorem
variables {A B : Type}
variable [s1 : group A]
variable [s2 : group B]
include s1
include s2
variable {f : A → B}
variable [h : is_hom_class f]
include h
definition ker_nsubg [instance] : is_normal_subgroup (ker f) :=
is_normal_subgroup.mk (ker.has_one f) (ker.mul_closed f)
(ker.has_inv f) (ker.normal f)
definition quot_over_ker [instance] : group (coset_of (ker f)) := mk_quotient_group (ker f)
-- under the wrap the tower of concepts collapse to a simple condition
example (a x : A) : (x ∈ a ∘> ker f) = (f (a⁻¹*x) = 1) := rfl
lemma ker_coset_same_val (a b : A): same_lcoset (ker f) a b → f a = f b :=
assume Psame,
have Pin : f (b⁻¹*a) = 1, from subg_same_lcoset_in_lcoset a b Psame,
have P : (f b)⁻¹ * (f a) = 1, from calc
(f b)⁻¹ * (f a) = (f b⁻¹) * (f a) : (hom_map_inv f)
... = f (b⁻¹*a) : by rewrite [is_hom f]
... = 1 : by rewrite Pin,
eq.symm (inv_inv (f b) ▸ inv_eq_of_mul_eq_one P)
definition ker_natural_map : (coset_of (ker f)) → B :=
quot.lift f ker_coset_same_val
example (a : A) : ker_natural_map ⟦a⟧ = f a := rfl
lemma ker_coset_hom (a b : A) :
ker_natural_map (⟦a⟧*⟦b⟧) = (ker_natural_map ⟦a⟧) * (ker_natural_map ⟦b⟧) := calc
ker_natural_map (⟦a⟧*⟦b⟧) = ker_natural_map ⟦a*b⟧ : rfl
... = f (a*b) : rfl
... = (f a) * (f b) : by rewrite [is_hom f]
... = (ker_natural_map ⟦a⟧) * (ker_natural_map ⟦b⟧) : rfl
lemma ker_map_is_hom : homomorphic (ker_natural_map : coset_of (ker f) → B) :=
take aK bK,
quot.ind (λ a, quot.ind (λ b, ker_coset_hom a b) bK) aK
lemma ker_coset_inj (a b : A) : (ker_natural_map ⟦a⟧ = ker_natural_map ⟦b⟧) → ⟦a⟧ = ⟦b⟧ :=
assume Pfeq : f a = f b,
have Painb : a ∈ b ∘> ker f, from calc
f (b⁻¹*a) = (f b⁻¹) * (f a) : by rewrite [is_hom f]
... = (f b)⁻¹ * (f a) : by rewrite (hom_map_inv f)
... = (f a)⁻¹ * (f a) : by rewrite Pfeq
... = 1 : by rewrite (mul.left_inv (f a)),
quot.sound (@subg_in_lcoset_same_lcoset _ _ (ker f) _ a b Painb)
lemma ker_map_is_inj : injective (ker_natural_map : coset_of (ker f) → B) :=
take aK bK,
quot.ind (λ a, quot.ind (λ b, ker_coset_inj a b) bK) aK
-- a special case of the fundamental homomorphism theorem or the first isomorphism theorem
theorem first_isomorphism_theorem : isomorphic (ker_natural_map : coset_of (ker f) → B) :=
and.intro ker_map_is_inj ker_map_is_hom
end hom_theorem
end group_theory
|
9c0a6805cb9c8be4e649c9099ca550a776e0612d | ac076ebc286fa9b7a67171f6cd11eb98b263d6ef | /src/category_theory.lean | acc8a4a57da9970dea17d3723c3a74a3c1cbbe71 | [] | no_license | Shamrock-Frost/jordan-holder | e891e489d00f8ff9e29c47b3083f22cac7804efb | bab3daccd70a4f3c5b25731b899a2cd72d7b8376 | refs/heads/master | 1,594,962,465,041 | 1,576,197,432,000 | 1,576,197,432,000 | 205,951,913 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,888 | lean | import category_theory.isomorphism
import category_theory.category
import group_theory.category
open category_theory
universes v u
def subtype_val.group_hom {G : Group} {s : set G} [is_subgroup s]
: Group.of s ⟶ G := ⟨subtype.val, subtype_val.is_group_hom⟩
instance is_group_hom.range_factorization {G H : Group} (φ : G → H) [is_group_hom φ]
: is_group_hom (set.range_factorization φ) := is_group_hom.mk' $ by {
intros x y, apply subtype.eq,
rw subtype_val.is_group_hom.map_mul,
transitivity φ (x * y), refl,
transitivity φ x * φ y,
apply is_mul_hom.map_mul, refl
}
noncomputable
def Group.inj_im_iso {G H : Group} (φ : G ⟶ H) (h : function.injective φ)
: G ≅ Group.of (set.range φ) := {
hom := ⟨set.range_factorization φ, by apply_instance⟩,
inv := ⟨λ x : Group.of (set.range φ), @function.inv_fun _ ⟨1⟩ _ φ x.val,
is_group_hom.mk' $ λ x y, by {
cases x with x hx, cases hx with a ha, subst ha,
cases y with y hy, cases hy with b hb, subst hb,
rw is_monoid_hom.map_mul subtype.val,
simp, rw ← is_monoid_hom.map_mul φ,
repeat { rw function.left_inverse_inv_fun },
any_goals { assumption }, exact subtype_val.is_monoid_hom }⟩,
hom_inv_id' := by intros; ext; apply @function.left_inverse_inv_fun; exact h,
inv_hom_id' := by { intros, ext, unfold_coes, simp,
dsimp [set.range_factorization], apply subtype.eq, simp,
apply function.inv_fun_eq, exact x.property } }
def Group.surj_im_iso {G H : Group} (φ : G ⟶ H) (h : function.surjective φ)
: Group.of (set.range φ) ≅ H := {
hom := subtype_val.group_hom,
inv := ⟨λ x, ⟨x, h x⟩, is_group_hom.mk' $ λ x y, subtype.eq $
by rw is_monoid_hom.map_mul subtype.val;
exact subtype_val.is_monoid_hom⟩ }
noncomputable
def Group.iso_of_bijective {G H : Group} (φ : G ⟶ H) (h : function.bijective φ)
:= iso.trans (Group.inj_im_iso φ h.left) (Group.surj_im_iso φ h.right)
def Group.iso_left_inverse {G H : Group} (φ : G ≅ H)
: function.left_inverse φ.inv φ.hom :=
λ x, by { transitivity (φ.inv ∘ φ.hom) x, refl,
transitivity id x, apply congr_fun,
exact subtype.mk.inj φ.hom_inv_id, refl }
lemma Group.iso_inj {G H : Group} (φ : G ≅ H) : function.injective φ.hom :=
function.injective_of_left_inverse (Group.iso_left_inverse φ)
def Group.iso_right_inverse {G H : Group} (φ : G ≅ H)
: function.right_inverse φ.inv φ.hom :=
Group.iso_left_inverse φ.symm
lemma Group.iso_surj {G H : Group} (φ : G ≅ H) : function.surjective φ.hom :=
function.surjective_of_has_right_inverse ⟨_, Group.iso_right_inverse φ⟩
lemma Group.iso_bij {G H : Group} (φ : G ≅ H) : function.bijective φ.hom :=
⟨Group.iso_inj φ, Group.iso_surj φ⟩
def Group.ker_of_inj_comp {G H H' : Group} (φ : G ⟶ H) (ψ : H ⟶ H')
(h : function.injective ψ)
: is_group_hom.ker (φ ≫ ψ) = is_group_hom.ker φ :=
begin
unfold_coes, simp, dsimp [is_group_hom.ker],
rw set.preimage_comp, congr,
rw is_group_hom.inj_iff_trivial_ker ψ at h,
assumption
end
def Group.ker_of_comp_inj {G H K : Group}
(φ : G ⟶ K) (ψ : H ⟶ G) (h : function.injective ψ)
: is_group_hom.ker (ψ ≫ φ) = ψ ⁻¹' is_group_hom.ker φ :=
by apply set.preimage_comp
def Group.subsingleton_iso (G H : Group) [subsingleton G] [subsingleton H] : G ≅ H := {
hom := ⟨λ x, 1, is_group_hom.mk' (λ x y, subsingleton.elim _ _)⟩,
inv := ⟨λ x, 1, is_group_hom.mk' (λ x y, subsingleton.elim _ _)⟩
}
def pullback {A B C : Type _} (f : A → C) (g : B → C)
:= { p : A × B | f p.fst = g p.snd }
def pullback_of_inj_to_inter {A B C : Type _} {f : A → C} {g : B → C}
(hf : function.injective f) (hg : function.injective g)
: pullback f g → set.inter (set.range f) (set.range g) :=
λ x, subtype.mk (f x.val.fst) $
by { constructor, apply set.mem_range_self,
rw (_ : f x.val.fst = g x.val.snd), apply set.mem_range_self,
exact x.property }
lemma pullback_of_inj_to_inter_is_bijective {A B C : Type _} {f : A → C} {g : B → C}
(hf : function.injective f) (hg : function.injective g)
: function.bijective (pullback_of_inj_to_inter hf hg) :=
begin
constructor,
{ intros x y hxy,
cases x with x hx, cases x with x₁ x₂,
cases y with y hy, cases y with y₁ y₂,
simp, simp [pullback_of_inj_to_inter] at hxy,
apply and.intro (hf hxy),
apply hg, transitivity f x₁, exact hx.symm,
rw hxy, exact hy },
{ intro y, cases y with y hy, cases hy with hy₁ hy₂,
cases hy₁ with a ha, cases hy₂ with b hb,
subst hb, use ⟨(a, b), ha⟩, exact subtype.eq ha }
end
noncomputable
def pullback_inj_fin {A B C : Type _} {f : A → C} {g : B → C}
(hf : function.injective f) (hg : function.injective g) [fintype C]
: fintype (pullback f g) :=
fintype.of_injective (subtype.val ∘ pullback_of_inj_to_inter hf hg)
(function.injective_comp subtype.val_injective
$ and.left $ pullback_of_inj_to_inter_is_bijective hf hg)
local attribute [instance] classical.prop_decidable
lemma pullback_card_lt_of_conflict {A B C : Type _} {f : A → C} {g : B → C}
(hf : function.injective f) (hg : function.injective g) [fintype C]
(a : A) (hx : ∀ b : B, f a ≠ g b)
: @fintype.card (pullback f g) (pullback_inj_fin hf hg) < fintype.card C := by {
apply @nat.lt_of_le_of_lt _ (fintype.card (set.inter (set.range f) (set.range g))),
apply fintype.card_le_of_injective,
apply and.left (pullback_of_inj_to_inter_is_bijective hf hg),
unfold_coes, rw fintype.subtype_card,
apply finset.card_lt_card, rw finset.ssubset_iff,
existsi f a, constructor,
{ rw finset.mem_filter, intro h, cases h,
cases h_right, apply hx, symmetry, assumption },
{ intros x h, apply finset.mem_univ }
}
instance {A B} [group A] [group B] : group (A × B) := {
mul := λ p q, ⟨p.fst * q.fst, p.snd * q.snd⟩,
one := ⟨1, 1⟩,
inv := λ p, ⟨p.fst⁻¹, p.snd⁻¹⟩,
mul_assoc := by { intros, simp, constructor; apply mul_assoc },
one_mul := by intros p; apply prod.ext; apply one_mul,
mul_one := by intros p; apply prod.ext; apply mul_one,
mul_left_inv := by intros p; apply prod.ext; apply mul_left_inv
}
instance prod_fst.is_group_hom {α β} [group α] [group β]
: is_group_hom (@prod.fst α β) := is_group_hom.mk' $ λ _ _, rfl
instance prod_snd.is_group_hom {α β} [group α] [group β]
: is_group_hom (@prod.snd α β) := is_group_hom.mk' $ λ _ _, rfl
def Group.fst {A B : Group.{u}} : Group.of (A × B) ⟶ A :=
⟨prod.fst, by apply_instance⟩
def Group.snd {A B : Group.{u}} : Group.of (A × B) ⟶ B :=
⟨prod.snd, by apply_instance⟩
instance {A B C : Group} {f : A ⟶ C} {g : B ⟶ C}
: is_subgroup (pullback f g) := {
inv_mem := by { intros p h, cases p with x y, refine (_ : f x⁻¹ = g y⁻¹),
rw [is_group_hom.map_inv f, is_group_hom.map_inv g],
rw (_ : f x = g y), assumption },
to_is_submonoid := {
one_mem := eq.trans (is_monoid_hom.map_one f) $ eq.symm $ is_monoid_hom.map_one g,
mul_mem := by { intros p q hp hq, cases p with p₁ p₂, cases q with q₁ q₂,
refine (_ : f (p₁ * q₁) = g (p₂ * q₂)),
rw [is_monoid_hom.map_mul f, is_monoid_hom.map_mul g],
congr; assumption } } }
def Group.pullback_of_isos_is_iso {G G' H H': Group} (iso : H ≅ H')
(f : G ⟶ H) (f' : G' ⟶ H')
: Group.of (pullback (f ≫ iso.hom) f') ≅ Group.of (pullback (f' ≫ iso.inv) f) := {
hom := ⟨λ p, ⟨p.val.swap, show iso.inv (f' p.val.snd) = f (p.val.fst),
from eq.trans (eq.symm $ congr_arg iso.inv p.property)
(Group.iso_left_inverse iso (f p.val.fst))⟩,
is_group_hom.mk' $ λ x y, subtype.eq $ by cases x; cases x_val; cases y; cases y_val; refl⟩,
inv := ⟨λ p, ⟨p.val.swap, show iso.hom (f p.val.snd) = f' (p.val.fst),
from eq.trans (eq.symm $ congr_arg iso.hom p.property)
(Group.iso_left_inverse iso.symm (f' p.val.fst))⟩,
is_group_hom.mk' $ λ x y, subtype.eq $ by cases x; cases x_val; cases y; cases y_val; refl⟩,
}
lemma surj_im_normal {G H : Group}
(φ : G ⟶ H) (h : function.surjective φ)
(N : set G) [normal_subgroup N]
: normal_subgroup (φ '' N) := normal_subgroup.mk $ by {
intros n hn x, cases hn with y hn, cases hn with ha ha,
subst ha, cases h x with b hb, subst hb,
rw [← is_group_hom.map_inv φ, ← is_monoid_hom.map_mul φ, ← is_monoid_hom.map_mul φ],
existsi b * y * b⁻¹, refine and.intro _ rfl,
apply normal_subgroup.normal, assumption
}
instance Group.inhabited {G} [group G] : inhabited G := ⟨1⟩
def Group.iso_restrict {G G' : Group} (iso : G ≅ G')
(H : set G) [is_subgroup H] : Group.of H ≅ Group.of (iso.hom '' H) := {
hom := ⟨λ x, ⟨iso.hom x.val, x.val, x.property, rfl⟩,
is_group_hom.mk' $ by {
intros x y, unfold_coes, apply subtype.eq, simp,
rw [is_monoid_hom.map_mul subtype.val, is_monoid_hom.map_mul iso.hom.val],
congr, exact subtype_val.is_monoid_hom
}⟩,
inv := ⟨λ x, ⟨iso.inv x.val,
by { cases x, cases x_property with a ha,
cases ha with ha ha, subst ha, simp,
rw Group.iso_left_inverse, assumption }⟩,
is_group_hom.mk' $ by {
intros x y, unfold_coes, apply subtype.eq, simp,
rw [is_monoid_hom.map_mul subtype.val, is_monoid_hom.map_mul iso.inv.val],
congr, exact subtype_val.is_monoid_hom
}⟩,
hom_inv_id' := by {
unfold_coes, simp, ext,
apply subtype.eq, refine congr_fun _ x,
funext, apply congr_fun (subtype.mk.inj iso.hom_inv_id)
},
inv_hom_id' := by {
unfold_coes, simp, ext,
apply subtype.eq, refine congr_fun _ x,
funext, apply congr_fun (subtype.mk.inj iso.inv_hom_id)
}
}
lemma Group.eq_of_im_eq_and_contain_ker
{G K : Group} (φ : G ⟶ K) {s : set G} [is_subgroup s]
(h1 : φ '' s = set.univ) (h2 : is_group_hom.ker φ ⊆ s)
: s = set.univ := by {
apply set.eq_univ_of_univ_subset, intros x h, clear h,
have : φ x ∈ set.univ := set.mem_univ _, rw ← h1 at this,
cases this with y h,
have := is_group_hom.inv_ker_one' _ h.right,
rw ← is_group_hom.mem_ker φ at this, have := h2 this,
rw (_ : x = y * (y⁻¹ * x)),
apply is_submonoid.mul_mem, exact h.left, assumption,
symmetry, apply mul_inv_cancel_left
}
def Group.subgroup_eq_of_eq {G : Group} {s t : set G}
[is_subgroup s] [is_subgroup t] (h : s = t)
: Group.of s = Group.of t := by {
tactic.unfreeze_local_instances, subst h,
}
-- lemma weird {H G : Group} {s t : set G} [is_subgroup s] [is_subgroup t]
-- (h : s = t)
-- (iso : Group.of t ≅ H)
-- (x : s)
-- : iso.hom.val (@eq.rec _ _ subtype x _ h)
-- = (@eq.rec _ _ (λ K : Group, K ≅ H)
-- iso _ (Group.subroup_eq_of_eq h)
-- .symm).hom.val x :=
-- begin
-- admit
-- end
inductive Group.list_equiv : list Group → list Group → Prop
| nil : Group.list_equiv [] []
| skip : ∀ G G' {xs ys}, (G ≅ G') → Group.list_equiv xs ys → Group.list_equiv (G::xs) (G'::ys)
| swap : ∀ G G' {xs}, Group.list_equiv (G::G'::xs) (G'::G::xs)
| trans : ∀ {xs ys zs},
Group.list_equiv xs ys
→ Group.list_equiv ys zs
→ Group.list_equiv xs zs |
245f11b8a60558a67be2cb3fa00852946700b932 | 618003631150032a5676f229d13a079ac875ff77 | /src/tactic/equiv_rw.lean | 921a0939f596df1f635da364779be9761526d551 | [
"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 | 11,953 | 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 control.equiv_functor
/-!
# The `equiv_rw` tactic transports goals or hypotheses along equivalences.
The basic syntax is `equiv_rw e`, where `e : α ≃ β` is an equivalence.
This will try to replace occurrences of `α` in the goal with `β`, for example
transforming
* `⊢ α` to `⊢ β`,
* `⊢ option α` to `⊢ option β`
* `⊢ {a // P}` to `{b // P (⇑(equiv.symm e) b)}`
The tactic can also be used to rewrite hypotheses, using the syntax `equiv_rw e at h`.
## Implementation details
The main internal function is `equiv_rw_type e t`,
which attempts to turn an expression `e : α ≃ β` into a new equivalence with left hand side `t`.
As an example, with `t = option α`, it will generate `functor.map_equiv option e`.
This is achieved by generating a new synthetic goal `%%t ≃ _`,
and calling `solve_by_elim` with an appropriate set of congruence lemmas.
To avoid having to specify the relevant congruence lemmas by hand,
we mostly rely on `equiv_functor.map_equiv` and `bifunctor.map_equiv`
along with some structural congruence lemmas such as
* `equiv.arrow_congr'`,
* `equiv.subtype_equiv_of_subtype'`,
* `equiv.sigma_congr_left'`, and
* `equiv.Pi_congr_left'`.
The main `equiv_rw` function, when operating on the goal, simply generates a new equivalence `e'`
with left hand side matching the target, and calls `apply e'.inv_fun`.
When operating on a hypothesis `x : α`, we introduce a new fact `h : x = e.symm (e x)`,
revert this, and then attempt to `generalize`, replacing all occurrences of `e x` with a new constant `y`,
before `intro`ing and `subst`ing `h`, and renaming `y` back to `x`.
## Future improvements
In a future PR I anticipate that `derive equiv_functor` should work on many examples,
(internally using `transport`, which is in turn based on `equiv_rw`)
and we can incrementally bootstrap the strength of `equiv_rw`.
An ambitious project might be to add `equiv_rw!`,
a tactic which, when failing to find appropriate `equiv_functor` instances,
attempts to `derive` them on the spot.
For now `equiv_rw` is entirely based on `equiv`,
but the framework can readily be generalised to also work with other types of equivalences,
for example specific notations such as ring equivalence (`≃+*`),
or general categorical isomorphisms (`≅`).
This will allow us to transport across more general types of equivalences,
but this will wait for another subsequent PR.
-/
namespace tactic
/-- A list of lemmas used for constructing congruence equivalences. -/
-- Although this looks 'hard-coded', in fact the lemma `equiv_functor.map_equiv`
-- allows us to extend `equiv_rw` simply by constructing new instance so `equiv_functor`.
-- TODO: We should also use `category_theory.functorial` and `category_theory.hygienic` instances.
-- (example goal: we could rewrite along an isomorphism of rings (either as `R ≅ S` or `R ≃+* S`)
-- and turn an `x : mv_polynomial σ R` into an `x : mv_polynomial σ S`.).
meta def equiv_congr_lemmas : tactic (list expr) :=
do exprs ←
[
`equiv.of_iff,
-- TODO decide what to do with this; it's an equiv_bifunctor?
`equiv.equiv_congr,
-- The function arrow is technically a bifunctor `Typeᵒᵖ → Type → Type`,
-- but the pattern matcher will never see this.
`equiv.arrow_congr',
-- Allow rewriting in subtypes:
`equiv.subtype_equiv_of_subtype',
-- Allow rewriting in the first component of a sigma-type:
`equiv.sigma_congr_left',
-- Allow rewriting ∀s:
-- (You might think that repeated application of `equiv.forall_congr'
-- would handle the higher arity cases, but unfortunately unification is not clever enough.)
`equiv.forall₃_congr',
`equiv.forall₂_congr',
`equiv.forall_congr',
-- Allow rewriting in argument of Pi types:
`equiv.Pi_congr_left',
-- Handles `sum` and `prod`, and many others:
`bifunctor.map_equiv,
-- Handles `list`, `option`, `unique`, and many others:
`equiv_functor.map_equiv,
-- We have to filter results to ensure we don't cheat and use exclusively `equiv.refl` and `iff.refl`!
`equiv.refl,
`iff.refl
].mmap (λ n, try_core (mk_const n)),
return (exprs.map option.to_list).join -- TODO: implement `.mfilter_map mk_const`?
declare_trace equiv_rw_type
/--
Configuration structure for `equiv_rw`.
* `max_depth` bounds the search depth for equivalences to rewrite along.
The default value is 10.
(e.g., if you're rewriting along `e : α ≃ β`, and `max_depth := 2`,
you can rewrite `option (option α))` but not `option (option (option α))`.
-/
meta structure equiv_rw_cfg :=
(max_depth : ℕ := 10)
/--
Implementation of `equiv_rw_type`, using `solve_by_elim`.
Expects a goal of the form `t ≃ _`,
and tries to solve it using `eq : α ≃ β` and congruence lemmas.
-/
meta def equiv_rw_type_core (eq : expr) (cfg : equiv_rw_cfg) : tactic unit :=
do
-- Assemble the relevant lemmas.
equiv_congr_lemmas ← equiv_congr_lemmas,
/-
We now call `solve_by_elim` to try to generate the requested equivalence.
There are a few subtleties!
* We make sure that `eq` is the first lemma, so it is applied whenever possible.
* In `equiv_congr_lemmas`, we put `equiv.refl` last so it is only used when it is not possible
to descend further.
* Since some congruence lemmas generate subgoals with `∀` statements,
we use the `pre_apply` subtactic of `solve_by_elim` to preprocess each new goal with `intros`.
-/
solve_by_elim
{ use_symmetry := false,
use_exfalso := false,
lemmas := some (eq :: equiv_congr_lemmas),
max_depth := cfg.max_depth,
-- Subgoals may contain function types,
-- and we want to continue trying to construct equivalences after the binders.
pre_apply := tactic.intros >> skip,
-- If solve_by_elim gets stuck, make sure it isn't because there's a later `≃` or `↔` goal
-- that we should still attempt.
discharger := `[show _ ≃ _] <|> `[show _ ↔ _] <|>
trace_if_enabled `equiv_rw_type "Failed, no congruence lemma applied!" >> failed,
-- We use the `accept` tactic in `solve_by_elim` to provide tracing.
accept := λ goals, lock_tactic_state (do
when_tracing `equiv_rw_type (do
goals.mmap pp >>= λ goals, trace format!"So far, we've built: {goals}"),
done <|>
when_tracing `equiv_rw_type (do
gs ← get_goals,
gs ← gs.mmap (λ g, infer_type g >>= pp),
trace format!"Attempting to adapt to {gs}")) }
/--
`equiv_rw_type e t` rewrites the type `t` using the equivalence `e : α ≃ β`,
returning a new equivalence `t ≃ t'`.
-/
meta def equiv_rw_type (eqv : expr) (ty : expr) (cfg : equiv_rw_cfg) : tactic expr :=
do
when_tracing `equiv_rw_type (do
ty_pp ← pp ty,
eqv_pp ← pp eqv,
eqv_ty_pp ← infer_type eqv >>= pp,
trace format!"Attempting to rewrite the type `{ty_pp}` using `{eqv_pp} : {eqv_ty_pp}`."),
`(_ ≃ _) ← infer_type eqv | fail format!"{eqv} must be an `equiv`",
-- We prepare a synthetic goal of type `(%%ty ≃ _)`, for some placeholder right hand side.
equiv_ty ← to_expr ``(%%ty ≃ _),
-- Now call `equiv_rw_type_core`.
new_eqv ← prod.snd <$> (solve_aux equiv_ty $ equiv_rw_type_core eqv cfg),
-- Check that we actually used the equivalence `eq`
-- (`equiv_rw_type_core` will always find `equiv.refl`, but hopefully only after all other possibilities)
new_eqv ← instantiate_mvars new_eqv,
guard (eqv.occurs new_eqv) <|> (do
eqv_pp ← pp eqv,
ty_pp ← pp ty,
fail format!"Could not construct an equivalence from {eqv_pp} of the form: {ty_pp} ≃ _"),
-- Finally we simplify the resulting equivalence,
-- to compress away some `map_equiv equiv.refl` subexpressions.
prod.fst <$> new_eqv.simp {fail_if_unchanged := ff}
mk_simp_attribute equiv_rw_simp "The simpset `equiv_rw_simp` is used by the tactic `equiv_rw` to
simplify applications of equivalences and their inverses."
attribute [equiv_rw_simp] equiv.symm_symm equiv.apply_symm_apply equiv.symm_apply_apply
/--
Attempt to replace the hypothesis with name `x`
by transporting it along the equivalence in `e : α ≃ β`.
-/
meta def equiv_rw_hyp (x : name) (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit :=
-- We call `dsimp_result` to perform the beta redex introduced by `revert`
dsimp_result (do
x' ← get_local x,
x_ty ← infer_type x',
-- Adapt `e` to an equivalence with left-hand-side `x_ty`.
e ← equiv_rw_type e x_ty cfg,
eq ← to_expr ``(%%x' = equiv.symm %%e (equiv.to_fun %%e %%x')),
prf ← to_expr ``((equiv.symm_apply_apply %%e %%x').symm),
h ← note_anon eq prf,
-- Revert the new hypothesis, so it is also part of the goal.
revert h,
ex ← to_expr ``(equiv.to_fun %%e %%x'),
-- Now call `generalize`,
-- attempting to replace all occurrences of `e x`,
-- calling it for now `j : β`, with `k : x = e.symm j`.
generalize ex (by apply_opt_param) transparency.none,
-- Reintroduce `x` (now of type `b`), and the hypothesis `h`.
intro x,
h ← intro1,
-- We may need to unfreeze `x` before we can `subst` or `clear` it.
unfreeze x',
-- Finally, if we're working on properties, substitute along `h`, then do some cleanup,
-- and if we're working on data, just throw out the old `x`.
b ← target >>= is_prop,
if b then do
subst h,
`[try { simp only [] with equiv_rw_simp }]
else
clear' tt [x'] <|>
fail format!"equiv_rw expected to be able to clear the original hypothesis {x}, but couldn't.",
skip)
{fail_if_unchanged := ff} tt -- call `dsimp_result` with `no_defaults := tt`.
/-- Rewrite the goal using an equiv `e`. -/
meta def equiv_rw_target (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit :=
do
t ← target,
e ← equiv_rw_type e t cfg,
s ← to_expr ``(equiv.inv_fun %%e),
tactic.eapply s,
skip
end tactic
namespace tactic.interactive
open lean.parser
open interactive interactive.types
open tactic
local postfix `?`:9001 := optional
/--
`equiv_rw e at h`, where `h : α` is a hypothesis, and `e : α ≃ β`,
will attempt to transport `h` along `e`, producing a new hypothesis `h : β`,
with all occurrences of `h` in other hypotheses and the goal replaced with `e.symm h`.
`equiv_rw e` will attempt to transport the goal along an equivalence `e : α ≃ β`.
In its minimal form it replaces the goal `⊢ α` with `⊢ β` by calling `apply e.inv_fun`.
`equiv_rw` will also try rewriting under (equiv_)functors, so can turn
a hypothesis `h : list α` into `h : list β` or
a goal `⊢ unique α` into `⊢ unique β`.
The maximum search depth for rewriting in subexpressions is controlled by
`equiv_rw e {max_depth := n}`.
-/
meta def equiv_rw (e : parse texpr) (loc : parse $ (tk "at" *> ident)?) (cfg : equiv_rw_cfg := {}) : itactic :=
do e ← to_expr e,
match loc with
| (some hyp) := equiv_rw_hyp hyp e cfg
| none := equiv_rw_target e cfg
end
add_tactic_doc
{ name := "equiv_rw",
category := doc_category.tactic,
decl_names := [`tactic.interactive.equiv_rw],
tags := ["rewriting", "equiv", "transport"] }
/--
Solve a goal of the form `t ≃ _`,
by constructing an equivalence from `e : α ≃ β`.
This is the same equivalence that `equiv_rw` would use to rewrite a term of type `t`.
A typical usage might be:
```
have e' : option α ≃ option β := by equiv_rw_type e
```
-/
meta def equiv_rw_type (e : parse texpr) (cfg : equiv_rw_cfg := {}) : itactic :=
do
`(%%t ≃ _) ← target | fail "`equiv_rw_type` solves goals of the form `t ≃ _`.",
e ← to_expr e,
tactic.equiv_rw_type e t cfg >>= tactic.exact
add_tactic_doc
{ name := "equiv_rw_type",
category := doc_category.tactic,
decl_names := [`tactic.interactive.equiv_rw_type],
tags := ["rewriting", "equiv", "transport"] }
end tactic.interactive
|
4c9a5bc1ccc073388ebc2eed5472f7e8c6b85146 | 2d34dfb0a1cc250584282618dc10ea03d3fa858e | /src/type_pow.lean | a9244cd2cb6330ec4a457fdfb2af09bfef5359e7 | [] | no_license | zeta1999/lean-liquid | 61e294ec5adae959d8ee1b65d015775484ff58c2 | 96bb0fa3afc3b451bcd1fb7d974348de2f290541 | refs/heads/master | 1,676,579,150,248 | 1,610,771,445,000 | 1,610,771,445,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 429 | lean | import topology.constructions
def type_pow : has_pow (Type*) ℕ := ⟨λ A n, fin n → A⟩
namespace type_pow_topology
local attribute [instance] type_pow
instance topological_space {n : ℕ} {α : Type*} [topological_space α] : topological_space (α^n) :=
Pi.topological_space
--instance {n : ℕ} {α : Type*} [topological_space α] [discrete_topology α] : discrete_topology (α^n) := sorry
end type_pow_topology
|
4e01e1225505f8f029beeaed84d738a2e7b70a38 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/caching_user_attribute.lean | 5e73ff6299e5af62c4bf25839704d1076b922f8a | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 761 | lean | definition foo_attr : caching_user_attribute :=
⟨`foo, "bar", string, list.join ∘ list.map (list.append "\n" ∘ to_string ∘ declaration.to_name) ⟩
run_command attribute.register `foo_attr
attribute [foo] eq.refl eq.mp
set_option trace.user_attributes_cache true
run_command do
s : string ← caching_user_attribute.get_cache foo_attr,
tactic.trace s
run_command do
s : string ← caching_user_attribute.get_cache foo_attr,
tactic.trace s
attribute [foo] eq.mpr
local attribute [-foo] eq.mp
run_command do
s : string ← caching_user_attribute.get_cache foo_attr,
tactic.trace s
attribute [reducible] eq.mp -- should not affect [foo] cache
run_command do
s : string ← caching_user_attribute.get_cache foo_attr,
tactic.trace s
|
80c66a181a1e69881824234abf25a020e4a915e4 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/ring_theory/unique_factorization_domain.lean | 74ec3f963115424411f4f474f92af7d5afa8ab55 | [
"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 | 57,053 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jens Wagemaker, Aaron Anderson
-/
import algebra.gcd_monoid.basic
import ring_theory.integral_domain
import ring_theory.noetherian
/-!
# Unique factorization
## Main Definitions
* `wf_dvd_monoid` holds for `monoid`s for which a strict divisibility relation is
well-founded.
* `unique_factorization_monoid` holds for `wf_dvd_monoid`s where
`irreducible` is equivalent to `prime`
## To do
* set up the complete lattice structure on `factor_set`.
-/
variables {α : Type*}
local infix ` ~ᵤ ` : 50 := associated
/-- Well-foundedness of the strict version of |, which is equivalent to the descending chain
condition on divisibility and to the ascending chain condition on
principal ideals in an integral domain.
-/
class wf_dvd_monoid (α : Type*) [comm_monoid_with_zero α] : Prop :=
(well_founded_dvd_not_unit : well_founded (@dvd_not_unit α _))
export wf_dvd_monoid (well_founded_dvd_not_unit)
@[priority 100] -- see Note [lower instance priority]
instance is_noetherian_ring.wf_dvd_monoid [comm_ring α] [integral_domain α] [is_noetherian_ring α] :
wf_dvd_monoid α :=
⟨by { convert inv_image.wf (λ a, ideal.span ({a} : set α)) (well_founded_submodule_gt _ _),
ext,
exact ideal.span_singleton_lt_span_singleton.symm }⟩
namespace wf_dvd_monoid
variables [comm_monoid_with_zero α]
open associates nat
theorem of_wf_dvd_monoid_associates (h : wf_dvd_monoid (associates α)): wf_dvd_monoid α :=
⟨begin
haveI := h,
refine (surjective.well_founded_iff mk_surjective _).2 wf_dvd_monoid.well_founded_dvd_not_unit,
intros, rw mk_dvd_not_unit_mk_iff
end⟩
variables [wf_dvd_monoid α]
instance wf_dvd_monoid_associates : wf_dvd_monoid (associates α) :=
⟨begin
refine (surjective.well_founded_iff mk_surjective _).1 wf_dvd_monoid.well_founded_dvd_not_unit,
intros, rw mk_dvd_not_unit_mk_iff
end⟩
theorem well_founded_associates : well_founded ((<) : associates α → associates α → Prop) :=
subrelation.wf (λ x y, dvd_not_unit_of_lt) wf_dvd_monoid.well_founded_dvd_not_unit
local attribute [elab_as_eliminator] well_founded.fix
lemma exists_irreducible_factor {a : α} (ha : ¬ is_unit a) (ha0 : a ≠ 0) :
∃ i, irreducible i ∧ i ∣ a :=
(irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_rfl⟩)
(well_founded.fix
wf_dvd_monoid.well_founded_dvd_not_unit
(λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩,
have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]),
(irreducible_or_factor x hx).elim
(λ hxi, ⟨x, hxi, hxy ▸ by simp⟩)
(λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in
⟨i, hi.1, hi.2.trans (hxy ▸ by simp)⟩)) a ha ha0)
@[elab_as_eliminator] lemma induction_on_irreducible {P : α → Prop} (a : α)
(h0 : P 0) (hu : ∀ u : α, is_unit u → P u)
(hi : ∀ a i : α, a ≠ 0 → irreducible i → P a → P (i * a)) :
P a :=
by haveI := classical.dec; exact
well_founded.fix wf_dvd_monoid.well_founded_dvd_not_unit
(λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0
else if hau : is_unit a then hu a hau
else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in
have hb0 : b ≠ 0, from λ hb0, by simp * at *,
hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i,
hii.1, by rw [hb, mul_comm]⟩))
a
lemma exists_factors (a : α) : a ≠ 0 →
∃f : multiset α, (∀b ∈ f, irreducible b) ∧ associated f.prod a :=
wf_dvd_monoid.induction_on_irreducible a
(λ h, (h rfl).elim)
(λ u hu _, ⟨0, ⟨by simp [hu], associated.symm (by simp [hu, associated_one_iff_is_unit])⟩⟩)
(λ a i ha0 hii ih hia0,
let ⟨s, hs⟩ := ih ha0 in
⟨i ::ₘ s, ⟨by clear _let_match; finish,
by { rw multiset.prod_cons,
exact hs.2.mul_left _ }⟩⟩)
end wf_dvd_monoid
theorem wf_dvd_monoid.of_well_founded_associates [comm_cancel_monoid_with_zero α]
(h : well_founded ((<) : associates α → associates α → Prop)) : wf_dvd_monoid α :=
wf_dvd_monoid.of_wf_dvd_monoid_associates
⟨by { convert h, ext, exact associates.dvd_not_unit_iff_lt }⟩
theorem wf_dvd_monoid.iff_well_founded_associates [comm_cancel_monoid_with_zero α] :
wf_dvd_monoid α ↔ well_founded ((<) : associates α → associates α → Prop) :=
⟨by apply wf_dvd_monoid.well_founded_associates, wf_dvd_monoid.of_well_founded_associates⟩
section prio
set_option default_priority 100 -- see Note [default priority]
/-- unique factorization monoids.
These are defined as `comm_cancel_monoid_with_zero`s with well-founded strict divisibility
relations, but this is equivalent to more familiar definitions:
Each element (except zero) is uniquely represented as a multiset of irreducible factors.
Uniqueness is only up to associated elements.
Each element (except zero) is non-uniquely represented as a multiset
of prime factors.
To define a UFD using the definition in terms of multisets
of irreducible factors, use the definition `of_exists_unique_irreducible_factors`
To define a UFD using the definition in terms of multisets
of prime factors, use the definition `of_exists_prime_factors`
-/
class unique_factorization_monoid (α : Type*) [comm_cancel_monoid_with_zero α]
extends wf_dvd_monoid α : Prop :=
(irreducible_iff_prime : ∀ {a : α}, irreducible a ↔ prime a)
/-- Can't be an instance because it would cause a loop `ufm → wf_dvd_monoid → ufm → ...`. -/
lemma ufm_of_gcd_of_wf_dvd_monoid [comm_cancel_monoid_with_zero α]
[wf_dvd_monoid α] [gcd_monoid α] : unique_factorization_monoid α :=
{ irreducible_iff_prime := λ _, gcd_monoid.irreducible_iff_prime
.. ‹wf_dvd_monoid α› }
instance associates.ufm [comm_cancel_monoid_with_zero α]
[unique_factorization_monoid α] : unique_factorization_monoid (associates α) :=
{ irreducible_iff_prime := by { rw ← associates.irreducible_iff_prime_iff,
apply unique_factorization_monoid.irreducible_iff_prime, }
.. (wf_dvd_monoid.wf_dvd_monoid_associates : wf_dvd_monoid (associates α)) }
end prio
namespace unique_factorization_monoid
variables [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α]
theorem exists_prime_factors (a : α) : a ≠ 0 →
∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a :=
by { simp_rw ← unique_factorization_monoid.irreducible_iff_prime,
apply wf_dvd_monoid.exists_factors a }
@[elab_as_eliminator] lemma induction_on_prime {P : α → Prop}
(a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x)
(h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a :=
begin
simp_rw ← unique_factorization_monoid.irreducible_iff_prime at h₃,
exact wf_dvd_monoid.induction_on_irreducible a h₁ h₂ h₃,
end
lemma factors_unique : ∀{f g : multiset α},
(∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod →
multiset.rel associated f g :=
by haveI := classical.dec_eq α; exact
λ f, multiset.induction_on f
(λ g _ hg h,
multiset.rel_zero_left.2 $
multiset.eq_zero_of_forall_not_mem (λ x hx,
have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm,
(hg x hx).not_unit (is_unit_iff_dvd_one.2 ((multiset.dvd_prod hx).trans
(is_unit_iff_dvd_one.1 this)))))
(λ p f ih g hf hg hfg,
let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod
(irreducible_iff_prime.1 (hf p (by simp)))
(λ q hq, irreducible_iff_prime.1 (hg _ hq)) $
hfg.dvd_iff_dvd_right.1
(show p ∣ (p ::ₘ f).prod, by simp) in
begin
rw ← multiset.cons_erase hbg,
exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq]))
(λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq))
(associated.of_mul_left
(by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb
(hf p (by simp)).ne_zero))
end)
end unique_factorization_monoid
lemma prime_factors_unique [comm_cancel_monoid_with_zero α] : ∀ {f g : multiset α},
(∀ x ∈ f, prime x) → (∀ x ∈ g, prime x) → f.prod ~ᵤ g.prod →
multiset.rel associated f g :=
by haveI := classical.dec_eq α; exact
λ f, multiset.induction_on f
(λ g _ hg h,
multiset.rel_zero_left.2 $
multiset.eq_zero_of_forall_not_mem $ λ x hx,
have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm,
(hg x hx).not_unit $ is_unit_iff_dvd_one.2 $
(multiset.dvd_prod hx).trans (is_unit_iff_dvd_one.1 this))
(λ p f ih g hf hg hfg,
let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod
(hf p (by simp)) (λ q hq, hg _ hq) $
hfg.dvd_iff_dvd_right.1
(show p ∣ (p ::ₘ f).prod, by simp) in
begin
rw ← multiset.cons_erase hbg,
exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq]))
(λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq))
(associated.of_mul_left
(by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb
(hf p (by simp)).ne_zero)),
end)
/-- If an irreducible has a prime factorization,
then it is an associate of one of its prime factors. -/
lemma prime_factors_irreducible [comm_cancel_monoid_with_zero α] {a : α} {f : multiset α}
(ha : irreducible a) (pfa : (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) :
∃ p, a ~ᵤ p ∧ f = {p} :=
begin
haveI := classical.dec_eq α,
refine multiset.induction_on f (λ h, (ha.not_unit
(associated_one_iff_is_unit.1 (associated.symm h))).elim) _ pfa.2 pfa.1,
rintros p s _ ⟨u, hu⟩ hs,
use p,
have hs0 : s = 0,
{ by_contra hs0,
obtain ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0,
apply (hs q (by simp [hq])).2.1,
refine (ha.is_unit_or_is_unit (_ : _ = ((p * ↑u) * (s.erase q).prod) * _)).resolve_left _,
{ rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq, ← hu,
mul_comm, mul_comm p _, mul_assoc],
simp, },
apply mt is_unit_of_mul_is_unit_left (mt is_unit_of_mul_is_unit_left _),
apply (hs p (multiset.mem_cons_self _ _)).2.1 },
simp only [mul_one, multiset.prod_cons, multiset.prod_zero, hs0] at *,
exact ⟨associated.symm ⟨u, hu⟩, rfl⟩,
end
section exists_prime_factors
variables [comm_cancel_monoid_with_zero α]
variables (pf : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a)
include pf
lemma wf_dvd_monoid.of_exists_prime_factors : wf_dvd_monoid α :=
⟨begin
classical,
apply rel_hom.well_founded (rel_hom.mk _ _) (with_top.well_founded_lt nat.lt_wf),
{ intro a,
by_cases h : a = 0, { exact ⊤ },
exact (classical.some (pf a h)).card },
rintros a b ⟨ane0, ⟨c, hc, b_eq⟩⟩,
rw dif_neg ane0,
by_cases h : b = 0, { simp [h, lt_top_iff_ne_top] },
rw [dif_neg h, with_top.coe_lt_coe],
have cne0 : c ≠ 0, { refine mt (λ con, _) h, rw [b_eq, con, mul_zero] },
calc multiset.card (classical.some (pf a ane0))
< _ + multiset.card (classical.some (pf c cne0)) :
lt_add_of_pos_right _ (multiset.card_pos.mpr (λ con, hc (associated_one_iff_is_unit.mp _)))
... = multiset.card (classical.some (pf a ane0) + classical.some (pf c cne0)) :
(multiset.card_add _ _).symm
... = multiset.card (classical.some (pf b h)) :
multiset.card_eq_card_of_rel (prime_factors_unique _ (classical.some_spec (pf _ h)).1 _),
{ convert (classical.some_spec (pf c cne0)).2.symm,
rw [con, multiset.prod_zero] },
{ intros x hadd,
rw multiset.mem_add at hadd,
cases hadd; apply (classical.some_spec (pf _ _)).1 _ hadd },
{ rw multiset.prod_add,
transitivity a * c,
{ apply associated.mul_mul; apply (classical.some_spec (pf _ _)).2 },
{ rw ← b_eq,
apply (classical.some_spec (pf _ _)).2.symm, } }
end⟩
lemma irreducible_iff_prime_of_exists_prime_factors {p : α} : irreducible p ↔ prime p :=
begin
by_cases hp0 : p = 0,
{ simp [hp0] },
refine ⟨λ h, _, prime.irreducible⟩,
obtain ⟨f, hf⟩ := pf p hp0,
obtain ⟨q, hq, rfl⟩ := prime_factors_irreducible h hf,
rw hq.prime_iff,
exact hf.1 q (multiset.mem_singleton_self _)
end
theorem unique_factorization_monoid.of_exists_prime_factors :
unique_factorization_monoid α :=
{ irreducible_iff_prime := λ _, irreducible_iff_prime_of_exists_prime_factors pf,
.. wf_dvd_monoid.of_exists_prime_factors pf }
end exists_prime_factors
theorem unique_factorization_monoid.iff_exists_prime_factors [comm_cancel_monoid_with_zero α] :
unique_factorization_monoid α ↔
(∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) :=
⟨λ h, @unique_factorization_monoid.exists_prime_factors _ _ h,
unique_factorization_monoid.of_exists_prime_factors⟩
theorem irreducible_iff_prime_of_exists_unique_irreducible_factors [comm_cancel_monoid_with_zero α]
(eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a)
(uif : ∀ (f g : multiset α),
(∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod →
multiset.rel associated f g)
(p : α) : irreducible p ↔ prime p :=
⟨by letI := classical.dec_eq α; exact λ hpi,
⟨hpi.ne_zero, hpi.1,
λ a b ⟨x, hx⟩,
if hab0 : a * b = 0
then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim
(λ ha0, by simp [ha0])
(λ hb0, by simp [hb0])
else
have hx0 : x ≠ 0, from λ hx0, by simp * at *,
have ha0 : a ≠ 0, from left_ne_zero_of_mul hab0,
have hb0 : b ≠ 0, from right_ne_zero_of_mul hab0,
begin
cases eif x hx0 with fx hfx,
cases eif a ha0 with fa hfa,
cases eif b hb0 with fb hfb,
have h : multiset.rel associated (p ::ₘ fx) (fa + fb),
{ apply uif,
{ exact λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (hfx.1 _), },
{ exact λ i hi, (multiset.mem_add.1 hi).elim (hfa.1 _) (hfb.1 _), },
calc multiset.prod (p ::ₘ fx)
~ᵤ a * b : by rw [hx, multiset.prod_cons];
exact hfx.2.mul_left _
... ~ᵤ (fa).prod * (fb).prod :
hfa.2.symm.mul_mul hfb.2.symm
... = _ : by rw multiset.prod_add, },
exact let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem h
(multiset.mem_cons_self p _) in
(multiset.mem_add.1 hqf).elim
(λ hqa, or.inl $ hq.dvd_iff_dvd_left.2 $
hfa.2.dvd_iff_dvd_right.1
(multiset.dvd_prod hqa))
(λ hqb, or.inr $ hq.dvd_iff_dvd_left.2 $
hfb.2.dvd_iff_dvd_right.1
(multiset.dvd_prod hqb))
end⟩, prime.irreducible⟩
theorem unique_factorization_monoid.of_exists_unique_irreducible_factors
[comm_cancel_monoid_with_zero α]
(eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a)
(uif : ∀ (f g : multiset α),
(∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod →
multiset.rel associated f g) :
unique_factorization_monoid α :=
unique_factorization_monoid.of_exists_prime_factors (by
{ convert eif,
simp_rw irreducible_iff_prime_of_exists_unique_irreducible_factors eif uif })
namespace unique_factorization_monoid
variables [comm_cancel_monoid_with_zero α] [decidable_eq α]
variables [unique_factorization_monoid α]
/-- Noncomputably determines the multiset of prime factors. -/
noncomputable def factors (a : α) : multiset α := if h : a = 0 then 0 else
classical.some (unique_factorization_monoid.exists_prime_factors a h)
theorem factors_prod {a : α} (ane0 : a ≠ 0) : associated (factors a).prod a :=
begin
rw [factors, dif_neg ane0],
exact (classical.some_spec (exists_prime_factors a ane0)).2
end
theorem prime_of_factor {a : α} : ∀ (x : α), x ∈ factors a → prime x :=
begin
rw [factors],
split_ifs with ane0, { simp only [multiset.not_mem_zero, forall_false_left, forall_const] },
intros x hx,
exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 x hx,
end
theorem irreducible_of_factor {a : α} : ∀ (x : α), x ∈ factors a → irreducible x :=
λ x h, (prime_of_factor x h).irreducible
lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a →
∃ q ∈ factors a, p ~ᵤ q :=
λ ⟨b, hb⟩,
have hb0 : b ≠ 0, from λ hb0, by simp * at *,
have multiset.rel associated (p ::ₘ factors b) (factors a),
from factors_unique
(λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_of_factor _))
irreducible_of_factor
(associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0
... = p * b : hb
... ~ᵤ multiset.prod (p ::ₘ factors b) :
by rw multiset.prod_cons; exact (factors_prod hb0).symm.mul_left _),
multiset.exists_mem_of_rel_of_mem this (by simp)
end unique_factorization_monoid
namespace unique_factorization_monoid
variables [comm_cancel_monoid_with_zero α] [decidable_eq α] [normalization_monoid α]
variables [unique_factorization_monoid α]
/-- Noncomputably determines the multiset of prime factors. -/
noncomputable def normalized_factors (a : α) : multiset α :=
multiset.map normalize $ factors a
theorem normalized_factors_prod {a : α} (ane0 : a ≠ 0) : associated (normalized_factors a).prod a :=
begin
rw [normalized_factors, factors, dif_neg ane0],
refine associated.trans _ (classical.some_spec (exists_prime_factors a ane0)).2,
rw [← associates.mk_eq_mk_iff_associated, ← associates.prod_mk, ← associates.prod_mk,
multiset.map_map],
congr' 2,
ext,
rw [function.comp_apply, associates.mk_normalize],
end
theorem prime_of_normalized_factor {a : α} : ∀ (x : α), x ∈ normalized_factors a → prime x :=
begin
rw [normalized_factors, factors],
split_ifs with ane0, { simp },
intros x hx, rcases multiset.mem_map.1 hx with ⟨y, ⟨hy, rfl⟩⟩,
rw (normalize_associated _).prime_iff,
exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 y hy,
end
theorem irreducible_of_normalized_factor {a : α} :
∀ (x : α), x ∈ normalized_factors a → irreducible x :=
λ x h, (prime_of_normalized_factor x h).irreducible
theorem normalize_normalized_factor {a : α} :
∀ (x : α), x ∈ normalized_factors a → normalize x = x :=
begin
rw [normalized_factors, factors],
split_ifs with h, { simp },
intros x hx,
obtain ⟨y, hy, rfl⟩ := multiset.mem_map.1 hx,
apply normalize_idem
end
lemma normalized_factors_irreducible {a : α} (ha : irreducible a) :
normalized_factors a = {normalize a} :=
begin
obtain ⟨p, a_assoc, hp⟩ := prime_factors_irreducible ha
⟨prime_of_normalized_factor, normalized_factors_prod ha.ne_zero⟩,
have p_mem : p ∈ normalized_factors a,
{ rw hp, exact multiset.mem_singleton_self _ },
convert hp,
rwa [← normalize_normalized_factor p p_mem, normalize_eq_normalize_iff, dvd_dvd_iff_associated]
end
lemma exists_mem_normalized_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a →
∃ q ∈ normalized_factors a, p ~ᵤ q :=
λ ⟨b, hb⟩,
have hb0 : b ≠ 0, from λ hb0, by simp * at *,
have multiset.rel associated (p ::ₘ normalized_factors b) (normalized_factors a),
from factors_unique
(λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp)
(irreducible_of_normalized_factor _))
irreducible_of_normalized_factor
(associated.symm $ calc multiset.prod (normalized_factors a) ~ᵤ a : normalized_factors_prod ha0
... = p * b : hb
... ~ᵤ multiset.prod (p ::ₘ normalized_factors b) :
by rw multiset.prod_cons; exact (normalized_factors_prod hb0).symm.mul_left _),
multiset.exists_mem_of_rel_of_mem this (by simp)
@[simp] lemma normalized_factors_zero : normalized_factors (0 : α) = 0 :=
by simp [normalized_factors, factors]
@[simp] lemma normalized_factors_one : normalized_factors (1 : α) = 0 :=
begin
nontriviality α using [normalized_factors, factors],
rw ← multiset.rel_zero_right,
apply factors_unique irreducible_of_normalized_factor,
{ intros x hx,
exfalso,
apply multiset.not_mem_zero x hx },
{ simp [normalized_factors_prod (@one_ne_zero α _ _)] },
apply_instance
end
@[simp] lemma normalized_factors_mul {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) :
normalized_factors (x * y) = normalized_factors x + normalized_factors y :=
begin
have h : (normalize : α → α) = associates.out ∘ associates.mk,
{ ext, rw [function.comp_apply, associates.out_mk], },
rw [← multiset.map_id' (normalized_factors (x * y)), ← multiset.map_id' (normalized_factors x),
← multiset.map_id' (normalized_factors y), ← multiset.map_congr normalize_normalized_factor,
← multiset.map_congr normalize_normalized_factor,
← multiset.map_congr normalize_normalized_factor,
← multiset.map_add, h, ← multiset.map_map associates.out, eq_comm,
← multiset.map_map associates.out],
refine congr rfl _,
apply multiset.map_mk_eq_map_mk_of_rel,
apply factors_unique,
{ intros x hx,
rcases multiset.mem_add.1 hx with hx | hx;
exact irreducible_of_normalized_factor x hx },
{ exact irreducible_of_normalized_factor },
{ rw multiset.prod_add,
exact ((normalized_factors_prod hx).mul_mul (normalized_factors_prod hy)).trans
(normalized_factors_prod (mul_ne_zero hx hy)).symm }
end
@[simp] lemma normalized_factors_pow {x : α} (n : ℕ) :
normalized_factors (x ^ n) = n • normalized_factors x :=
begin
induction n with n ih,
{ simp },
by_cases h0 : x = 0,
{ simp [h0, zero_pow n.succ_pos, smul_zero] },
rw [pow_succ, succ_nsmul, normalized_factors_mul h0 (pow_ne_zero _ h0), ih],
end
lemma dvd_iff_normalized_factors_le_normalized_factors {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) :
x ∣ y ↔ normalized_factors x ≤ normalized_factors y :=
begin
split,
{ rintro ⟨c, rfl⟩,
simp [hx, right_ne_zero_of_mul hy] },
{ rw [← (normalized_factors_prod hx).dvd_iff_dvd_left,
← (normalized_factors_prod hy).dvd_iff_dvd_right],
apply multiset.prod_dvd_prod }
end
lemma zero_not_mem_normalized_factors (x : α) : (0 : α) ∉ normalized_factors x :=
λ h, prime.ne_zero (prime_of_normalized_factor _ h) rfl
lemma dvd_of_mem_normalized_factors {a p : α} (H : p ∈ normalized_factors a) : p ∣ a :=
begin
by_cases hcases : a = 0,
{ rw hcases,
exact dvd_zero p },
{ exact dvd_trans (multiset.dvd_prod H) (associated.dvd (normalized_factors_prod hcases)) },
end
end unique_factorization_monoid
namespace unique_factorization_monoid
open_locale classical
open multiset associates
noncomputable theory
variables [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α]
/-- Noncomputably defines a `normalization_monoid` structure on a `unique_factorization_monoid`. -/
protected def normalization_monoid : normalization_monoid α :=
normalization_monoid_of_monoid_hom_right_inverse {
to_fun := λ a : associates α, if a = 0 then 0 else ((normalized_factors a).map
(classical.some mk_surjective.has_right_inverse : associates α → α)).prod,
map_one' := by simp,
map_mul' := λ x y, by {
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
simp [hx, hy] } } begin
intro x,
dsimp,
by_cases hx : x = 0, { simp [hx] },
have h : associates.mk_monoid_hom ∘ (classical.some mk_surjective.has_right_inverse) =
(id : associates α → associates α),
{ ext x,
rw [function.comp_apply, mk_monoid_hom_apply,
classical.some_spec mk_surjective.has_right_inverse x],
refl },
rw [if_neg hx, ← mk_monoid_hom_apply, monoid_hom.map_multiset_prod, map_map, h, map_id,
← associated_iff_eq],
apply normalized_factors_prod hx
end
instance : inhabited (normalization_monoid α) := ⟨unique_factorization_monoid.normalization_monoid⟩
end unique_factorization_monoid
namespace unique_factorization_monoid
variables {R : Type*} [comm_cancel_monoid_with_zero R] [unique_factorization_monoid R]
lemma no_factors_of_no_prime_factors {a b : R} (ha : a ≠ 0)
(h : (∀ {d}, d ∣ a → d ∣ b → ¬ prime d)) : ∀ {d}, d ∣ a → d ∣ b → is_unit d :=
λ d, induction_on_prime d
(by { simp only [zero_dvd_iff], intros, contradiction })
(λ x hx _ _, hx)
(λ d q hp hq ih dvd_a dvd_b,
absurd hq (h (dvd_of_mul_right_dvd dvd_a) (dvd_of_mul_right_dvd dvd_b)))
/-- Euclid's lemma: if `a ∣ b * c` and `a` and `c` have no common prime factors, `a ∣ b`.
Compare `is_coprime.dvd_of_dvd_mul_left`. -/
lemma dvd_of_dvd_mul_left_of_no_prime_factors {a b c : R} (ha : a ≠ 0) :
(∀ {d}, d ∣ a → d ∣ c → ¬ prime d) → a ∣ b * c → a ∣ b :=
begin
refine induction_on_prime c _ _ _,
{ intro no_factors,
simp only [dvd_zero, mul_zero, forall_prop_of_true],
haveI := classical.prop_decidable,
exact is_unit_iff_forall_dvd.mp
(no_factors_of_no_prime_factors ha @no_factors (dvd_refl a) (dvd_zero a)) _ },
{ rintros _ ⟨x, rfl⟩ _ a_dvd_bx,
apply units.dvd_mul_right.mp a_dvd_bx },
{ intros c p hc hp ih no_factors a_dvd_bpc,
apply ih (λ q dvd_a dvd_c hq, no_factors dvd_a (dvd_c.mul_left _) hq),
rw mul_left_comm at a_dvd_bpc,
refine or.resolve_left (hp.left_dvd_or_dvd_right_of_dvd_mul a_dvd_bpc) (λ h, _),
exact no_factors h (dvd_mul_right p c) hp }
end
/-- Euclid's lemma: if `a ∣ b * c` and `a` and `b` have no common prime factors, `a ∣ c`.
Compare `is_coprime.dvd_of_dvd_mul_right`. -/
lemma dvd_of_dvd_mul_right_of_no_prime_factors {a b c : R} (ha : a ≠ 0)
(no_factors : ∀ {d}, d ∣ a → d ∣ b → ¬ prime d) : a ∣ b * c → a ∣ c :=
by simpa [mul_comm b c] using dvd_of_dvd_mul_left_of_no_prime_factors ha @no_factors
/-- If `a ≠ 0, b` are elements of a unique factorization domain, then dividing
out their common factor `c'` gives `a'` and `b'` with no factors in common. -/
lemma exists_reduced_factors : ∀ (a ≠ (0 : R)) b,
∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b :=
begin
haveI := classical.prop_decidable,
intros a,
refine induction_on_prime a _ _ _,
{ intros, contradiction },
{ intros a a_unit a_ne_zero b,
use [a, b, 1],
split,
{ intros p p_dvd_a _,
exact is_unit_of_dvd_unit p_dvd_a a_unit },
{ simp } },
{ intros a p a_ne_zero p_prime ih_a pa_ne_zero b,
by_cases p ∣ b,
{ rcases h with ⟨b, rfl⟩,
obtain ⟨a', b', c', no_factor, ha', hb'⟩ := ih_a a_ne_zero b,
refine ⟨a', b', p * c', @no_factor, _, _⟩,
{ rw [mul_assoc, ha'] },
{ rw [mul_assoc, hb'] } },
{ obtain ⟨a', b', c', coprime, rfl, rfl⟩ := ih_a a_ne_zero b,
refine ⟨p * a', b', c', _, mul_left_comm _ _ _, rfl⟩,
intros q q_dvd_pa' q_dvd_b',
cases p_prime.left_dvd_or_dvd_right_of_dvd_mul q_dvd_pa' with p_dvd_q q_dvd_a',
{ have : p ∣ c' * b' := dvd_mul_of_dvd_right (p_dvd_q.trans q_dvd_b') _,
contradiction },
exact coprime q_dvd_a' q_dvd_b' } }
end
lemma exists_reduced_factors' (a b : R) (hb : b ≠ 0) :
∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b :=
let ⟨b', a', c', no_factor, hb, ha⟩ := exists_reduced_factors b hb a
in ⟨a', b', c', λ _ hpb hpa, no_factor hpa hpb, ha, hb⟩
section multiplicity
variables [nontrivial R] [normalization_monoid R] [decidable_eq R]
variables [decidable_rel (has_dvd.dvd : R → R → Prop)]
open multiplicity multiset
lemma le_multiplicity_iff_repeat_le_normalized_factors {a b : R} {n : ℕ}
(ha : irreducible a) (hb : b ≠ 0) :
↑n ≤ multiplicity a b ↔ repeat (normalize a) n ≤ normalized_factors b :=
begin
rw ← pow_dvd_iff_le_multiplicity,
revert b,
induction n with n ih, { simp },
intros b hb,
split,
{ rintro ⟨c, rfl⟩,
rw [ne.def, pow_succ, mul_assoc, mul_eq_zero, decidable.not_or_iff_and_not] at hb,
rw [pow_succ, mul_assoc, normalized_factors_mul hb.1 hb.2, repeat_succ,
normalized_factors_irreducible ha, singleton_add, cons_le_cons_iff, ← ih hb.2],
apply dvd.intro _ rfl },
{ rw [multiset.le_iff_exists_add],
rintro ⟨u, hu⟩,
rw [← (normalized_factors_prod hb).dvd_iff_dvd_right, hu, prod_add, prod_repeat],
exact (associated.pow_pow $ associated_normalize a).dvd.trans (dvd.intro u.prod rfl) }
end
lemma multiplicity_eq_count_normalized_factors {a b : R} (ha : irreducible a) (hb : b ≠ 0) :
multiplicity a b = (normalized_factors b).count (normalize a) :=
begin
apply le_antisymm,
{ apply enat.le_of_lt_add_one,
rw [← nat.cast_one, ← nat.cast_add, lt_iff_not_ge, ge_iff_le,
le_multiplicity_iff_repeat_le_normalized_factors ha hb, ← le_count_iff_repeat_le],
simp },
rw [le_multiplicity_iff_repeat_le_normalized_factors ha hb, ← le_count_iff_repeat_le],
end
end multiplicity
end unique_factorization_monoid
namespace associates
open unique_factorization_monoid associated multiset
variables [comm_cancel_monoid_with_zero α]
/-- `factor_set α` representation elements of unique factorization domain as multisets.
`multiset α` produced by `normalized_factors` are only unique up to associated elements, while the
multisets in `factor_set α` are unique by equality and restricted to irreducible elements. This
gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a
complete lattice struture. Infimum is the greatest common divisor and supremum is the least common
multiple.
-/
@[reducible] def {u} factor_set (α : Type u) [comm_cancel_monoid_with_zero α] :
Type u :=
with_top (multiset { a : associates α // irreducible a })
local attribute [instance] associated.setoid
theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} :
(↑(a + b) : factor_set α) = a + b :=
by norm_cast
lemma factor_set.sup_add_inf_eq_add [decidable_eq (associates α)] :
∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b
| none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp
| a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp
| (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from
begin
rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add,
with_top.coe_eq_coe],
exact multiset.union_add_inter _ _
end
/-- Evaluates the product of a `factor_set` to be the product of the corresponding multiset,
or `0` if there is none. -/
def factor_set.prod : factor_set α → associates α
| none := 0
| (some s) := (s.map coe).prod
@[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl
@[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} :
(s : factor_set α).prod = (s.map coe).prod :=
rfl
@[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod
| none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp
| a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp
| (some a) (some b) :=
show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod,
by rw [← factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add]
theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod
| none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_refl _
| a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top
| (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h
/-- `bcount p s` is the multiplicity of `p` in the factor_set `s` (with bundled `p`)-/
def bcount [decidable_eq (associates α)] (p : {a : associates α // irreducible a}) :
factor_set α → ℕ
| none := 0
| (some s) := s.count p
variables [dec_irr : Π (p : associates α), decidable (irreducible p)]
include dec_irr
/-- `count p s` is the multiplicity of the irreducible `p` in the factor_set `s`.
If `p` is not irreducible, `count p s` is defined to be `0`. -/
def count [decidable_eq (associates α)] (p : associates α) :
factor_set α → ℕ :=
if hp : irreducible p then bcount ⟨p, hp⟩ else 0
@[simp] lemma count_some [decidable_eq (associates α)] {p : associates α} (hp : irreducible p)
(s : multiset _) : count p (some s) = s.count ⟨p, hp⟩:=
by { dunfold count, split_ifs, refl }
@[simp] lemma count_zero [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) :
count p (0 : factor_set α) = 0 :=
by { dunfold count, split_ifs, refl }
lemma count_reducible [decidable_eq (associates α)] {p : associates α} (hp : ¬ irreducible p) :
count p = 0 := dif_neg hp
omit dec_irr
/-- membership in a factor_set (bundled version) -/
def bfactor_set_mem : {a : associates α // irreducible a} → (factor_set α) → Prop
| _ ⊤ := true
| p (some l) := p ∈ l
include dec_irr
/-- `factor_set_mem p s` is the predicate that the irreducible `p` is a member of
`s : factor_set α`.
If `p` is not irreducible, `p` is not a member of any `factor_set`. -/
def factor_set_mem (p : associates α) (s : factor_set α) : Prop :=
if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false
instance : has_mem (associates α) (factor_set α) := ⟨factor_set_mem⟩
@[simp] lemma factor_set_mem_eq_mem (p : associates α) (s : factor_set α) :
factor_set_mem p s = (p ∈ s) := rfl
lemma mem_factor_set_top {p : associates α} {hp : irreducible p} :
p ∈ (⊤ : factor_set α) :=
begin
dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, exact trivial
end
lemma mem_factor_set_some {p : associates α} {hp : irreducible p}
{l : multiset {a : associates α // irreducible a }} :
p ∈ (l : factor_set α) ↔ subtype.mk p hp ∈ l :=
begin
dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, refl
end
lemma reducible_not_mem_factor_set {p : associates α} (hp : ¬ irreducible p)
(s : factor_set α) : ¬ p ∈ s :=
λ (h : if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false),
by rwa [dif_neg hp] at h
omit dec_irr
variable [unique_factorization_monoid α]
theorem unique' {p q : multiset (associates α)} :
(∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q :=
begin
apply multiset.induction_on_multiset_quot p,
apply multiset.induction_on_multiset_quot q,
assume s t hs ht eq,
refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_monoid.factors_unique _ _ _),
{ exact assume a ha, ((irreducible_mk _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) },
{ exact assume a ha, ((irreducible_mk _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) },
simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq
end
private theorem forall_map_mk_factors_irreducible [decidable_eq α] (x : α) (hx : x ≠ 0) :
∀(a : associates α), a ∈ multiset.map associates.mk (factors x) → irreducible a :=
begin
assume a ha,
rcases multiset.mem_map.1 ha with ⟨c, hc, rfl⟩,
exact (irreducible_mk c).2 (irreducible_of_factor _ hc)
end
theorem prod_le_prod_iff_le [nontrivial α] {p q : multiset (associates α)}
(hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) :
p.prod ≤ q.prod ↔ p ≤ q :=
iff.intro
begin
classical,
rintros ⟨⟨c⟩, eqc⟩,
have : c ≠ 0, from (mt mk_eq_zero.2 $
assume (hc : quot.mk setoid.r c = 0),
have (0 : associates α) ∈ q, from prod_eq_zero_iff.1 $ eqc.symm ▸ hc.symm ▸ mul_zero _,
not_irreducible_zero ((irreducible_mk 0).1 $ hq _ this)),
have : associates.mk (factors c).prod = quot.mk setoid.r c,
from mk_eq_mk_iff_associated.2 (factors_prod this),
refine multiset.le_iff_exists_add.2 ⟨(factors c).map associates.mk, unique' hq _ _⟩,
{ assume x hx,
rcases multiset.mem_add.1 hx with h | h,
exact hp x h,
exact forall_map_mk_factors_irreducible c ‹c ≠ 0› _ h },
{ simp [multiset.prod_add, prod_mk, *] at * }
end
prod_le_prod
variables [dec : decidable_eq α] [dec' : decidable_eq (associates α)]
include dec
/-- This returns the multiset of irreducible factors as a `factor_set`,
a multiset of irreducible associates `with_top`. -/
noncomputable def factors' (a : α) :
multiset { a : associates α // irreducible a } :=
(factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk _).2 ha⟩)
(irreducible_of_factor)
@[simp] theorem map_subtype_coe_factors' {a : α} :
(factors' a).map coe = (factors a).map associates.mk :=
by simp [factors', multiset.map_pmap, multiset.pmap_eq_map]
theorem factors'_cong {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : a ~ᵤ b) :
factors' a = factors' b :=
have multiset.rel associated (factors a) (factors b), from
factors_unique irreducible_of_factor irreducible_of_factor
((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm),
by simpa [(multiset.map_eq_map subtype.coe_injective).symm, rel_associated_iff_map_eq_map.symm]
include dec'
/-- This returns the multiset of irreducible factors of an associate as a `factor_set`,
a multiset of irreducible associates `with_top`. -/
noncomputable def factors (a : associates α) :
factor_set α :=
begin
refine (if h : a = 0 then ⊤ else
quotient.hrec_on a (λx h, some $ factors' x) _ h),
assume a b hab,
apply function.hfunext,
{ have : a ~ᵤ 0 ↔ b ~ᵤ 0, from
iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0),
simp only [associated_zero_iff_eq_zero] at this,
simp only [quotient_mk_eq_mk, this, mk_eq_zero] },
exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong
(λ c, ha (mk_eq_zero.2 c)) (λ c, hb (mk_eq_zero.2 c)) hab)
end
@[simp] theorem factors_0 : (0 : associates α).factors = ⊤ :=
dif_pos rfl
@[simp] theorem factors_mk (a : α) (h : a ≠ 0) :
(associates.mk a).factors = factors' a :=
by { classical, apply dif_neg, apply (mt mk_eq_zero.1 h) }
theorem prod_factors [nontrivial α] : ∀(s : factor_set α), s.prod.factors = s
| none := by simp [factor_set.prod]; refl
| (some s) :=
begin
unfold factor_set.prod,
generalize eq_a : (s.map coe).prod = a,
rcases a with ⟨a⟩,
rw quot_mk_eq_mk at *,
have : (s.map (coe : _ → associates α)).prod ≠ 0, from assume ha,
let ⟨⟨a, ha⟩, h, eq⟩ := multiset.mem_map.1 (prod_eq_zero_iff.1 ha) in
have irreducible (0 : associates α), from eq ▸ ha,
not_irreducible_zero ((irreducible_mk _).1 this),
have ha : a ≠ 0, by simp [*] at *,
suffices : (unique_factorization_monoid.factors a).map associates.mk = s.map coe,
{ rw [factors_mk a ha],
apply congr_arg some _,
simpa [(multiset.map_eq_map subtype.coe_injective).symm] },
refine unique'
(forall_map_mk_factors_irreducible _ ha)
(assume a ha, let ⟨⟨x, hx⟩, ha, eq⟩ := multiset.mem_map.1 ha in eq ▸ hx)
_,
rw [prod_mk, eq_a, mk_eq_mk_iff_associated],
exact factors_prod ha
end
@[simp]
theorem factors_prod (a : associates α) : a.factors.prod = a :=
quotient.induction_on a $ assume a, decidable.by_cases
(assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this])
(assume : associates.mk a ≠ 0,
have a ≠ 0, by simp * at *,
by simp [this, quotient_mk_eq_mk, prod_mk,
mk_eq_mk_iff_associated.2 (factors_prod this)])
theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b :=
have a.factors.prod = b.factors.prod, by rw h,
by rwa [factors_prod, factors_prod] at this
omit dec dec'
theorem eq_of_prod_eq_prod [nontrivial α] {a b : factor_set α} (h : a.prod = b.prod) : a = b :=
begin
classical,
have : a.prod.factors = b.prod.factors, by rw h,
rwa [prod_factors, prod_factors] at this
end
include dec dec'
@[simp] theorem factors_mul [nontrivial α] (a b : associates α) :
(a * b).factors = a.factors + b.factors :=
eq_of_prod_eq_prod $ eq_of_factors_eq_factors $
by rw [prod_add, factors_prod, factors_prod, factors_prod]
theorem factors_mono [nontrivial α] : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors
| s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right bot_le
theorem factors_le [nontrivial α] {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b :=
iff.intro
(assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h,
by rwa [factors_prod, factors_prod] at this)
factors_mono
omit dec dec'
theorem prod_le [nontrivial α] {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b :=
begin
classical,
exact iff.intro
(assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h,
by rwa [prod_factors, prod_factors] at this)
prod_mono
end
include dec dec'
noncomputable instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩
noncomputable instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩
noncomputable instance [nontrivial α] : bounded_lattice (associates α) :=
{ sup := (⊔),
inf := (⊓),
sup_le :=
assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)),
le_sup_left := assume a b,
le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left,
le_sup_right := assume a b,
le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right,
le_inf :=
assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)),
inf_le_left := assume a b,
le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)),
inf_le_right := assume a b,
le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)),
.. associates.partial_order,
.. associates.order_top,
.. associates.order_bot }
lemma sup_mul_inf [nontrivial α] (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b :=
show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b,
begin
refine eq_of_factors_eq_factors _,
rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add]
end
include dec_irr
lemma dvd_of_mem_factors {a p : associates α} {hp : irreducible p}
(hm : p ∈ factors a) : p ∣ a :=
begin
by_cases ha0 : a = 0, { rw ha0, exact dvd_zero p },
obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha0,
rw [← associates.factors_prod a],
rw [← ha', factors_mk a0 nza] at hm ⊢,
erw prod_coe,
apply multiset.dvd_prod, apply multiset.mem_map.mpr,
exact ⟨⟨p, hp⟩, mem_factor_set_some.mp hm, rfl⟩
end
omit dec'
lemma dvd_of_mem_factors' {a : α} {p : associates α} {hp : irreducible p} {hz : a ≠ 0}
(h_mem : subtype.mk p hp ∈ factors' a) : p ∣ associates.mk a :=
by { haveI := classical.dec_eq (associates α),
apply @dvd_of_mem_factors _ _ _ _ _ _ _ _ hp,
rw factors_mk _ hz,
apply mem_factor_set_some.2 h_mem }
omit dec_irr
lemma mem_factors'_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) :
subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a :=
begin
obtain ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd ha0 hp hd,
apply multiset.mem_pmap.mpr, use q, use hq,
exact subtype.eq (eq.symm (mk_eq_mk_iff_associated.mpr hpq))
end
include dec_irr
lemma mem_factors'_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) :
subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a ↔ p ∣ a :=
begin
split,
{ rw ← mk_dvd_mk, apply dvd_of_mem_factors', apply ha0 },
{ apply mem_factors'_of_dvd ha0 }
end
include dec'
lemma mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) :
(associates.mk p) ∈ factors (associates.mk a) :=
begin
rw factors_mk _ ha0, exact mem_factor_set_some.mpr (mem_factors'_of_dvd ha0 hp hd)
end
lemma mem_factors_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) :
(associates.mk p) ∈ factors (associates.mk a) ↔ p ∣ a :=
begin
split,
{ rw ← mk_dvd_mk, apply dvd_of_mem_factors, exact (irreducible_mk p).mpr hp },
{ apply mem_factors_of_dvd ha0 hp }
end
lemma exists_prime_dvd_of_not_inf_one {a b : α}
(ha : a ≠ 0) (hb : b ≠ 0) (h : (associates.mk a) ⊓ (associates.mk b) ≠ 1) :
∃ (p : α), prime p ∧ p ∣ a ∧ p ∣ b :=
begin
have hz : (factors (associates.mk a)) ⊓ (factors (associates.mk b)) ≠ 0,
{ contrapose! h with hf,
change ((factors (associates.mk a)) ⊓ (factors (associates.mk b))).prod = 1,
rw hf,
exact multiset.prod_zero },
rw [factors_mk a ha, factors_mk b hb, ← with_top.coe_inf] at hz,
obtain ⟨⟨p0, p0_irr⟩, p0_mem⟩ := multiset.exists_mem_of_ne_zero ((mt with_top.coe_eq_coe.mpr) hz),
rw multiset.inf_eq_inter at p0_mem,
obtain ⟨p, rfl⟩ : ∃ p, associates.mk p = p0 := quot.exists_rep p0,
refine ⟨p, _, _, _⟩,
{ rw [← irreducible_iff_prime, ← irreducible_mk],
exact p0_irr },
{ apply dvd_of_mk_le_mk,
apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).left,
apply ha, },
{ apply dvd_of_mk_le_mk,
apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).right,
apply hb }
end
theorem coprime_iff_inf_one [nontrivial α] {a b : α} (ha0 : a ≠ 0) (hb0 : b ≠ 0) :
(associates.mk a) ⊓ (associates.mk b) = 1 ↔ ∀ {d : α}, d ∣ a → d ∣ b → ¬ prime d :=
begin
split,
{ intros hg p ha hb hp,
refine ((associates.prime_mk _).mpr hp).not_unit (is_unit_of_dvd_one _ _),
rw ← hg,
exact le_inf (mk_le_mk_of_dvd ha) (mk_le_mk_of_dvd hb) },
{ contrapose,
intros hg hc,
obtain ⟨p, hp, hpa, hpb⟩ := exists_prime_dvd_of_not_inf_one ha0 hb0 hg,
exact hc hpa hpb hp }
end
omit dec_irr
theorem factors_prime_pow [nontrivial α] {p : associates α} (hp : irreducible p)
(k : ℕ) : factors (p ^ k) = some (multiset.repeat ⟨p, hp⟩ k) :=
eq_of_prod_eq_prod (by rw [associates.factors_prod, factor_set.prod, multiset.map_repeat,
multiset.prod_repeat, subtype.coe_mk])
include dec_irr
theorem prime_pow_dvd_iff_le [nontrivial α] {m p : associates α} (h₁ : m ≠ 0)
(h₂ : irreducible p) {k : ℕ} : p ^ k ≤ m ↔ k ≤ count p m.factors :=
begin
obtain ⟨a, nz, rfl⟩ := associates.exists_non_zero_rep h₁,
rw [factors_mk _ nz, ← with_top.some_eq_coe, count_some, multiset.le_count_iff_repeat_le,
← factors_le, factors_prime_pow h₂, factors_mk _ nz],
exact with_top.coe_le_coe
end
theorem le_of_count_ne_zero [nontrivial α] {m p : associates α} (h0 : m ≠ 0)
(hp : irreducible p) : count p m.factors ≠ 0 → p ≤ m :=
begin
rw [← pos_iff_ne_zero],
intro h,
rw [← pow_one p],
apply (prime_pow_dvd_iff_le h0 hp).2,
simpa only
end
theorem count_mul [nontrivial α] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0)
{p : associates α} (hp : irreducible p) :
count p (factors (a * b)) = count p a.factors + count p b.factors :=
begin
obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha,
obtain ⟨b0, nzb, hb'⟩ := exists_non_zero_rep hb,
rw [factors_mul, ← ha', ← hb', factors_mk a0 nza, factors_mk b0 nzb, ← factor_set.coe_add,
← with_top.some_eq_coe, ← with_top.some_eq_coe, ← with_top.some_eq_coe, count_some hp,
multiset.count_add, count_some hp, count_some hp]
end
theorem count_of_coprime [nontrivial α] {a : associates α} (ha : a ≠ 0) {b : associates α}
(hb : b ≠ 0)
(hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {p : associates α} (hp : irreducible p) :
count p a.factors = 0 ∨ count p b.factors = 0 :=
begin
rw [or_iff_not_imp_left, ← ne.def],
intro hca,
contrapose! hab with hcb,
exact ⟨p, le_of_count_ne_zero ha hp hca, le_of_count_ne_zero hb hp hcb,
(irreducible_iff_prime.mp hp)⟩,
end
theorem count_mul_of_coprime [nontrivial α] {a : associates α} (ha : a ≠ 0) {b : associates α}
(hb : b ≠ 0)
{p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) :
count p a.factors = 0 ∨ count p a.factors = count p (a * b).factors :=
begin
cases count_of_coprime ha hb hab hp with hz hb0, { tauto },
apply or.intro_right,
rw [count_mul ha hb hp, hb0, add_zero]
end
theorem count_mul_of_coprime' [nontrivial α] {a : associates α} (ha : a ≠ 0) {b : associates α}
(hb : b ≠ 0)
{p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) :
count p (a * b).factors = count p a.factors
∨ count p (a * b).factors = count p b.factors :=
begin
rw [count_mul ha hb hp],
cases count_of_coprime ha hb hab hp with ha0 hb0,
{ apply or.intro_right, rw [ha0, zero_add] },
{ apply or.intro_left, rw [hb0, add_zero] }
end
theorem dvd_count_of_dvd_count_mul [nontrivial α] {a b : associates α} (ha : a ≠ 0) (hb : b ≠ 0)
{p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d)
{k : ℕ} (habk : k ∣ count p (a * b).factors) : k ∣ count p a.factors :=
begin
cases count_of_coprime ha hb hab hp with hz h,
{ rw hz, exact dvd_zero k },
{ rw [count_mul ha hb hp, h] at habk, exact habk }
end
omit dec_irr
@[simp] lemma factors_one [nontrivial α] : factors (1 : associates α) = 0 :=
begin
apply eq_of_prod_eq_prod,
rw associates.factors_prod,
exact multiset.prod_zero,
end
@[simp] theorem pow_factors [nontrivial α] {a : associates α} {k : ℕ} :
(a ^ k).factors = k • a.factors :=
begin
induction k with n h,
{ rw [zero_nsmul, pow_zero], exact factors_one },
{ rw [pow_succ, succ_nsmul, factors_mul, h] }
end
include dec_irr
lemma count_pow [nontrivial α] {a : associates α} (ha : a ≠ 0) {p : associates α}
(hp : irreducible p)
(k : ℕ) : count p (a ^ k).factors = k * count p a.factors :=
begin
induction k with n h,
{ rw [pow_zero, factors_one, zero_mul, count_zero hp] },
{ rw [pow_succ, count_mul ha (pow_ne_zero _ ha) hp, h, nat.succ_eq_add_one], ring }
end
theorem dvd_count_pow [nontrivial α] {a : associates α} (ha : a ≠ 0) {p : associates α}
(hp : irreducible p)
(k : ℕ) : k ∣ count p (a ^ k).factors := by { rw count_pow ha hp, apply dvd_mul_right }
theorem is_pow_of_dvd_count [nontrivial α] {a : associates α} (ha : a ≠ 0) {k : ℕ}
(hk : ∀ (p : associates α) (hp : irreducible p), k ∣ count p a.factors) :
∃ (b : associates α), a = b ^ k :=
begin
obtain ⟨a0, hz, rfl⟩ := exists_non_zero_rep ha,
rw [factors_mk a0 hz] at hk,
have hk' : ∀ p, p ∈ (factors' a0) → k ∣ (factors' a0).count p,
{ rintros p -,
have pp : p = ⟨p.val, p.2⟩, { simp only [subtype.coe_eta, subtype.val_eq_coe] },
rw [pp, ← count_some p.2], exact hk p.val p.2 },
obtain ⟨u, hu⟩ := multiset.exists_smul_of_dvd_count _ hk',
use (u : factor_set α).prod,
apply eq_of_factors_eq_factors,
rw [pow_factors, prod_factors, factors_mk a0 hz, ← with_top.some_eq_coe, hu],
exact with_bot.coe_nsmul u k
end
omit dec
omit dec_irr
omit dec'
theorem eq_pow_of_mul_eq_pow [nontrivial α] {a b c : associates α} (ha : a ≠ 0) (hb : b ≠ 0)
(hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (h : a * b = c ^ k) :
∃ (d : associates α), a = d ^ k :=
begin
classical,
by_cases hk0 : k = 0,
{ use 1,
rw [hk0, pow_zero] at h ⊢,
apply (mul_eq_one_iff.1 h).1 },
{ refine is_pow_of_dvd_count ha _,
intros p hp,
apply dvd_count_of_dvd_count_mul ha hb hp hab,
rw h,
apply dvd_count_pow _ hp,
rintros rfl,
rw zero_pow' _ hk0 at h,
cases mul_eq_zero.mp h; contradiction }
end
end associates
section
open associates unique_factorization_monoid
lemma associates.quot_out {α : Type*} [comm_monoid α] (a : associates α):
associates.mk (quot.out (a)) = a :=
by rw [←quot_mk_eq_mk, quot.out_eq]
/-- `to_gcd_monoid` constructs a GCD monoid out of a unique factorization domain. -/
noncomputable def unique_factorization_monoid.to_gcd_monoid
(α : Type*) [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α]
[decidable_eq (associates α)] [decidable_eq α] : gcd_monoid α :=
{ gcd := λa b, quot.out (associates.mk a ⊓ associates.mk b : associates α),
lcm := λa b, quot.out (associates.mk a ⊔ associates.mk b : associates α),
gcd_dvd_left := λ a b, by {
rw [←mk_dvd_mk, (associates.mk a ⊓ associates.mk b).quot_out, dvd_eq_le],
exact inf_le_left },
gcd_dvd_right := λ a b, by {
rw [←mk_dvd_mk, (associates.mk a ⊓ associates.mk b).quot_out, dvd_eq_le],
exact inf_le_right },
dvd_gcd := λ a b c hac hab, by {
rw [←mk_dvd_mk, (associates.mk c ⊓ associates.mk b).quot_out, dvd_eq_le,
le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff],
exact ⟨hac, hab⟩ },
lcm_zero_left := λ a, by {
have : associates.mk (0 : α) = ⊤ := rfl,
rw [this, top_sup_eq, ←this, ←associated_zero_iff_eq_zero, ←mk_eq_mk_iff_associated,
←associated_iff_eq, associates.quot_out] },
lcm_zero_right := λ a, by {
have : associates.mk (0 : α) = ⊤ := rfl,
rw [this, sup_top_eq, ←this, ←associated_zero_iff_eq_zero, ←mk_eq_mk_iff_associated,
←associated_iff_eq, associates.quot_out] },
gcd_mul_lcm := λ a b, by {
rw [←mk_eq_mk_iff_associated, ←associates.mk_mul_mk, ←associated_iff_eq, associates.quot_out,
associates.quot_out, mul_comm, sup_mul_inf, associates.mk_mul_mk] } }
/-- `to_normalized_gcd_monoid` constructs a GCD monoid out of a normalization on a
unique factorization domain. -/
noncomputable def unique_factorization_monoid.to_normalized_gcd_monoid
(α : Type*) [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α]
[normalization_monoid α] [decidable_eq (associates α)] [decidable_eq α] :
normalized_gcd_monoid α :=
{ gcd := λa b, (associates.mk a ⊓ associates.mk b).out,
lcm := λa b, (associates.mk a ⊔ associates.mk b).out,
gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left,
gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right,
dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out,
by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩,
lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp,
lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp,
gcd_mul_lcm := assume a b, by {
rw [← out_mul, mul_comm, sup_mul_inf, mk_mul_mk, out_mk],
exact normalize_associated (a * b) },
normalize_gcd := assume a b, by convert normalize_out _,
normalize_lcm := assume a b, by convert normalize_out _,
.. ‹normalization_monoid α› }
end
namespace unique_factorization_monoid
/-- If `y` is a nonzero element of a unique factorization monoid with finitely
many units (e.g. `ℤ`, `ideal (ring_of_integers K)`), it has finitely many divisors. -/
noncomputable def fintype_subtype_dvd {M : Type*} [comm_cancel_monoid_with_zero M]
[unique_factorization_monoid M] [fintype (units M)]
(y : M) (hy : y ≠ 0) :
fintype {x // x ∣ y} :=
begin
haveI : nontrivial M := ⟨⟨y, 0, hy⟩⟩,
haveI : normalization_monoid M := unique_factorization_monoid.normalization_monoid,
haveI := classical.dec_eq M,
haveI := classical.dec_eq (associates M),
-- We'll show `λ (u : units M) (f ⊆ factors y) → u * Π f` is injective
-- and has image exactly the divisors of `y`.
refine fintype.of_finset
(((normalized_factors y).powerset.to_finset.product (finset.univ : finset (units M))).image
(λ s, (s.snd : M) * s.fst.prod))
(λ x, _),
simp only [exists_prop, finset.mem_image, finset.mem_product, finset.mem_univ, and_true,
multiset.mem_to_finset, multiset.mem_powerset, exists_eq_right, multiset.mem_map],
split,
{ rintros ⟨s, hs, rfl⟩,
have prod_s_ne : s.fst.prod ≠ 0,
{ intro hz,
apply hy (eq_zero_of_zero_dvd _),
have hz := (@multiset.prod_eq_zero_iff M _ _ _ s.fst).mp hz,
rw ← (normalized_factors_prod hy).dvd_iff_dvd_right,
exact multiset.dvd_prod (multiset.mem_of_le hs hz) },
show (s.snd : M) * s.fst.prod ∣ y,
rw [(unit_associated_one.mul_right s.fst.prod).dvd_iff_dvd_left, one_mul,
← (normalized_factors_prod hy).dvd_iff_dvd_right],
exact multiset.prod_dvd_prod hs },
{ rintro (h : x ∣ y),
have hx : x ≠ 0, { refine mt (λ hx, _) hy, rwa [hx, zero_dvd_iff] at h },
obtain ⟨u, hu⟩ := normalized_factors_prod hx,
refine ⟨⟨normalized_factors x, u⟩, _, (mul_comm _ _).trans hu⟩,
exact (dvd_iff_normalized_factors_le_normalized_factors hx hy).mp h }
end
end unique_factorization_monoid
|
a91be551e950f5623fed33c5c0a14f1293457b24 | b328e8ebb2ba923140e5137c83f09fa59516b793 | /stage0/src/Init/Coe.lean | b2cd17e0ef8f421106ea9dd6740b9ba32a7a71c7 | [
"Apache-2.0"
] | permissive | DrMaxis/lean4 | a781bcc095511687c56ab060e816fd948553e162 | 5a02c4facc0658aad627cfdcc3db203eac0cb544 | refs/heads/master | 1,677,051,517,055 | 1,611,876,226,000 | 1,611,876,226,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,327 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Core
universes u v w w'
class Coe (α : Sort u) (β : Sort v) where
coe : α → β
/-- Auxiliary class that contains the transitive closure of `Coe`. -/
class CoeTC (α : Sort u) (β : Sort v) where
coe : α → β
/- Expensive coercion that can only appear at the beginning of a sequence of coercions. -/
class CoeHead (α : Sort u) (β : Sort v) where
coe : α → β
/- Expensive coercion that can only appear at the end of a sequence of coercions. -/
class CoeTail (α : Sort u) (β : Sort v) where
coe : α → β
/-- Auxiliary class that contains `CoeHead` + `CoeTC` + `CoeTail`. -/
class CoeHTCT (α : Sort u) (β : Sort v) where
coe : α → β
class CoeDep (α : Sort u) (a : α) (β : Sort v) where
coe : β
/- Combines CoeHead, CoeTC, CoeTail, CoeDep -/
class CoeT (α : Sort u) (a : α) (β : Sort v) where
coe : β
class CoeFun (α : Sort u) (γ : outParam (α → outParam (Sort v))) where
coe : (a : α) → γ a
class CoeSort (α : Sort u) (β : outParam (Sort v)) where
coe : α → β
abbrev coeB {α : Sort u} {β : Sort v} [Coe α β] (a : α) : β :=
Coe.coe a
abbrev coeHead {α : Sort u} {β : Sort v} [CoeHead α β] (a : α) : β :=
CoeHead.coe a
abbrev coeTail {α : Sort u} {β : Sort v} [CoeTail α β] (a : α) : β :=
CoeTail.coe a
abbrev coeD {α : Sort u} {β : Sort v} (a : α) [CoeDep α a β] : β :=
CoeDep.coe a
abbrev coeTC {α : Sort u} {β : Sort v} [CoeTC α β] (a : α) : β :=
CoeTC.coe a
/-- Apply coercion manually. -/
abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β :=
CoeT.coe a
prefix:max "↑" => coe
abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a :=
CoeFun.coe a
abbrev coeSort {α : Sort u} {β : Sort v} (a : α) [CoeSort α β] : β :=
CoeSort.coe a
instance coeTrans {α : Sort u} {β : Sort v} {δ : Sort w} [Coe β δ] [CoeTC α β] : CoeTC α δ where
coe a := coeB (coeTC a : β)
instance coeBase {α : Sort u} {β : Sort v} [Coe α β] : CoeTC α β where
coe a := coeB a
instance coeOfHeafOfTCOfTail {α : Sort u} {β : Sort v} {δ : Sort w} {γ : Sort w'} [CoeHead α β] [CoeTail δ γ] [CoeTC β δ] : CoeHTCT α γ where
coe a := coeTail (coeTC (coeHead a : β) : δ)
instance coeOfHeadOfTC {α : Sort u} {β : Sort v} {δ : Sort w} [CoeHead α β] [CoeTC β δ] : CoeHTCT α δ where
coe a := coeTC (coeHead a : β)
instance coeOfTCOfTail {α : Sort u} {β : Sort v} {δ : Sort w} [CoeTail β δ] [CoeTC α β] : CoeHTCT α δ where
coe a := coeTail (coeTC a : β)
instance coeOfHead {α : Sort u} {β : Sort v} [CoeHead α β] : CoeHTCT α β where
coe a := coeHead a
instance coeOfTail {α : Sort u} {β : Sort v} [CoeTail α β] : CoeHTCT α β where
coe a := coeTail a
instance coeOfTC {α : Sort u} {β : Sort v} [CoeTC α β] : CoeHTCT α β where
coe a := coeTC a
instance coeOfHTCT {α : Sort u} {β : Sort v} [CoeHTCT α β] (a : α) : CoeT α a β where
coe := CoeHTCT.coe a
instance coeOfDep {α : Sort u} {β : Sort v} (a : α) [CoeDep α a β] : CoeT α a β where
coe := coeD a
instance coeId {α : Sort u} (a : α) : CoeT α a α where
coe := a
/- Basic instances -/
@[inline] instance boolToProp : Coe Bool Prop where
coe b := b = true
@[inline] instance coeDecidableEq (x : Bool) : Decidable (coe x) :=
inferInstanceAs (Decidable (x = true))
instance decPropToBool (p : Prop) [Decidable p] : CoeDep Prop p Bool where
coe := decide p
instance optionCoe {α : Type u} : CoeTail α (Option α) where
coe := some
instance subtypeCoe {α : Sort u} {p : α → Prop} : CoeHead { x // p x } α where
coe v := v.val
/- Coe & OfNat bridge -/
/-
Remark: one may question why we use `OfNat α` instead of `Coe Nat α`.
Reason: `OfNat` is for implementing polymorphic numeric literals, and we may
want to have numeric literals for a type α and **no** coercion from `Nat` to `α`. -/
instance hasOfNatOfCoe [Coe α β] [OfNat α n] : OfNat β n where
ofNat := coe (OfNat.ofNat n : α)
@[inline] def liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β := do
let a ← liftM x
pure (coe a)
@[inline] def coeM {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] (x : m α) : m β := do
let a ← x
pure <| coe a
instance [CoeFun α β] (a : α) : CoeDep α a (β a) where
coe := coeFun a
instance [CoeFun α (fun _ => β)] : CoeTail α β where
coe a := coeFun a
instance [CoeSort α β] : CoeTail α β where
coe a := coeSort a
/- Coe and heterogeneous operators, we use `CoeHTCT` instead of `CoeT` to avoid expensive coercions such as `CoeDep` -/
instance [CoeHTCT α β] [Add β] : HAdd α β β where
hAdd a b := Add.add a b
instance [CoeHTCT α β] [Add β] : HAdd β α β where
hAdd a b := Add.add a b
instance [CoeHTCT α β] [Sub β] : HSub α β β where
hSub a b := Sub.sub a b
instance [CoeHTCT α β] [Sub β] : HSub β α β where
hSub a b := Sub.sub a b
instance [CoeHTCT α β] [Mul β] : HMul α β β where
hMul a b := Mul.mul a b
instance [CoeHTCT α β] [Mul β] : HMul β α β where
hMul a b := Mul.mul a b
instance [CoeHTCT α β] [Div β] : HDiv α β β where
hDiv a b := Div.div a b
instance [CoeHTCT α β] [Div β] : HDiv β α β where
hDiv a b := Div.div a b
instance [CoeHTCT α β] [Mod β] : HMod α β β where
hMod a b := Mod.mod a b
instance [CoeHTCT α β] [Mod β] : HMod β α β where
hMod a b := Mod.mod a b
instance [CoeHTCT α β] [Append β] : HAppend α β β where
hAppend a b := Append.append a b
instance [CoeHTCT α β] [Append β] : HAppend β α β where
hAppend a b := Append.append a b
instance [CoeHTCT α β] [OrElse β] : HOrElse α β β where
hOrElse a b := OrElse.orElse a b
instance [CoeHTCT α β] [OrElse β] : HOrElse β α β where
hOrElse a b := OrElse.orElse a b
instance [CoeHTCT α β] [AndThen β] : HAndThen α β β where
hAndThen a b := AndThen.andThen a b
instance [CoeHTCT α β] [AndThen β] : HAndThen β α β where
hAndThen a b := AndThen.andThen a b
|
c5dbd81366e5f97e159bb74f899b8d0480670eea | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /examples/lean/dep_if.lean | d01d9445d61477f781615267830681606e1b8173 | [
"Apache-2.0"
] | permissive | codyroux/lean0.1 | 1ce92751d664aacff0529e139083304a7bbc8a71 | 0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef | refs/heads/master | 1,610,830,535,062 | 1,402,150,480,000 | 1,402,150,480,000 | 19,588,851 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,203 | lean | import macros
import tactic
-- "Dependent" if-then-else (dep_if c t e)
-- The then-branch t gets a proof for c, and the else-branch e gets a proof for ¬ c
-- We also prove that
-- 1) given H : c, (dep_if c t e) = t H
-- 2) given H : ¬ c, (dep_if c t e) = e H
-- We define the "dependent" if-then-else using Hilbert's choice operator ε.
-- Note that ε is only applicable to non-empty types. Thus, we first
-- prove the following auxiliary theorem.
theorem inhabited_resolve {A : (Type U)} {c : Bool} (t : c → A) (e : ¬ c → A) : inhabited A
:= or_elim (em c)
(λ Hc, inhabited_range (inhabited_intro t) Hc)
(λ Hnc, inhabited_range (inhabited_intro e) Hnc)
-- The actual definition
definition dep_if {A : (Type U)} (c : Bool) (t : c → A) (e : ¬ c → A) : A
:= ε (inhabited_resolve t e) (λ r, (∀ Hc : c, r = t Hc) ∧ (∀ Hnc : ¬ c, r = e Hnc))
theorem then_simp (A : (Type U)) (c : Bool) (r : A) (t : c → A) (e : ¬ c → A) (H : c)
: (∀ Hc : c, r = t Hc) ∧ (∀ Hnc : ¬ c, r = e Hnc) ↔ r = t H
:= let s1 : (∀ Hc : c, r = t Hc) ↔ r = t H
:= iff_intro
(assume Hl : (∀ Hc : c, r = t Hc),
Hl H)
(assume Hr : r = t H,
λ Hc : c, subst Hr (proof_irrel H Hc)),
s2 : (∀ Hnc : ¬ c, r = e Hnc) ↔ true
:= eqt_intro (λ Hnc : ¬ c, absurd_elim (r = e Hnc) H Hnc)
in by simp
-- Given H : c, (dep_if c t e) = t H
theorem dep_if_elim_then {A : (Type U)} (c : Bool) (t : c → A) (e : ¬ c → A) (H : c) : dep_if c t e = t H
:= let s1 : (λ r, (∀ Hc : c, r = t Hc) ∧ (∀ Hnc : ¬ c, r = e Hnc)) = (λ r, r = t H)
:= funext (λ r, then_simp A c r t e H)
in calc dep_if c t e = ε (inhabited_resolve t e) (λ r, (∀ Hc : c, r = t Hc) ∧ (∀ Hnc : ¬ c, r = e Hnc)) : refl (dep_if c t e)
... = ε (inhabited_resolve t e) (λ r, r = t H) : { s1 }
... = t H : eps_singleton (inhabited_resolve t e) (t H)
theorem dep_if_true {A : (Type U)} (t : true → A) (e : ¬ true → A) : dep_if true t e = t trivial
:= dep_if_elim_then true t e trivial
theorem else_simp (A : (Type U)) (c : Bool) (r : A) (t : c → A) (e : ¬ c → A) (H : ¬ c)
: (∀ Hc : c, r = t Hc) ∧ (∀ Hnc : ¬ c, r = e Hnc) ↔ r = e H
:= let s1 : (∀ Hc : c, r = t Hc) ↔ true
:= eqt_intro (λ Hc : c, absurd_elim (r = t Hc) Hc H),
s2 : (∀ Hnc : ¬ c, r = e Hnc) ↔ r = e H
:= iff_intro
(assume Hl : (∀ Hnc : ¬ c, r = e Hnc),
Hl H)
(assume Hr : r = e H,
λ Hnc : ¬ c, subst Hr (proof_irrel H Hnc))
in by simp
-- Given H : ¬ c, (dep_if c t e) = e H
theorem dep_if_elim_else {A : (Type U)} (c : Bool) (t : c → A) (e : ¬ c → A) (H : ¬ c) : dep_if c t e = e H
:= let s1 : (λ r, (∀ Hc : c, r = t Hc) ∧ (∀ Hnc : ¬ c, r = e Hnc)) = (λ r, r = e H)
:= funext (λ r, else_simp A c r t e H)
in calc dep_if c t e = ε (inhabited_resolve t e) (λ r, (∀ Hc : c, r = t Hc) ∧ (∀ Hnc : ¬ c, r = e Hnc)) : refl (dep_if c t e)
... = ε (inhabited_resolve t e) (λ r, r = e H) : { s1 }
... = e H : eps_singleton (inhabited_resolve t e) (e H)
theorem dep_if_false {A : (Type U)} (t : false → A) (e : ¬ false → A) : dep_if false t e = e not_false_trivial
:= dep_if_elim_else false t e not_false_trivial
set_option simplifier::heq true -- enable heterogeneous equality support
universe M >= 1
theorem dep_if_congr {A : (Type M)} (c1 c2 : Bool)
(t1 : c1 → A) (t2 : c2 → A)
(e1 : ¬ c1 → A) (e2 : ¬ c2 → A)
(Hc : c1 = c2)
(Ht : t1 = cast (by simp) t2)
(He : e1 = cast (by simp) e2)
: dep_if c1 t1 e1 = dep_if c2 t2 e2
:= by simp
scope
-- Here is an example where dep_if is useful
-- Suppose we have a (div s t H) where H is a proof for t ≠ 0
variable div (s : Nat) (t : Nat) (H : t ≠ 0) : Nat
-- Now, we want to define a function that
-- returns 0 if x = 0
-- and div 10 x _ otherwise
-- We can't use the standard if-the-else, because we don't have a way to synthesize the proof for x ≠ 0
check λ x, dep_if (x = 0) (λ H, 0) (λ H : ¬ x = 0, div 10 x H)
pop_scope
-- If the dependent then/else branches do not use the proofs Hc : c and Hn : ¬ c, then we
-- can reduce the dependent-if to a regular if
theorem dep_if_if {A : (Type U)} (c : Bool) (t e : A) : dep_if c (λ Hc, t) (λ Hn, e) = if c then t else e
:= or_elim (em c)
(assume Hc : c, calc dep_if c (λ Hc, t) (λ Hn, e) = (λ Hc, t) Hc : dep_if_elim_then _ _ _ Hc
... = if c then t else e : by simp)
(assume Hn : ¬ c, calc dep_if c (λ Hc, t) (λ Hn, e) = (λ Hn, e) Hn : dep_if_elim_else _ _ _ Hn
... = if c then t else e : by simp)
|
92893c529099d583d4bd6bd46cce01085d978fc8 | 7cdf3413c097e5d36492d12cdd07030eb991d394 | /src/game/world3/level7.lean | f8baa028b1b29b8a7875948e7080a3632f677f26 | [] | 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 | 1,846 | lean | import game.world3.level6 -- hide
namespace mynat -- hide
/-
# Multiplication World
## Level 7: `add_mul`
We proved `mul_add` already, but because we don't have commutativity yet
we also need to prove `add_mul`. We have a bunch of tools now, so this won't
be too hard. You know what -- you can do this one by induction on any of
the variables. Try them all! Which works best? If you can't face
doing all the commutativity and associativity, remember the high-powered
`simp` tactic mentioned at the bottom of Addition World level 6,
which will solve any puzzle which needs only commutativity
and associativity. If your goal looks like `a+(b+c)=c+b+a` or something,
don't mess around doing it explicitly with `add_comm` and `add_assoc`,
just try `simp`.
-/
/- Lemma
Addition is distributive over multiplication.
In other words, for all natural numbers $a$, $b$ and $c$, we have
$$ (a + b) \times t = at + bt. $$
-/
lemma add_mul (a b t : mynat) : (a + b) * t = a * t + b * t :=
begin [less_leaky]
induction b with d hd,
{
rw zero_mul,
rw add_zero,
rw add_zero,
refl
},
{
rw add_succ,
rw succ_mul,
rw hd,
rw succ_mul,
rw add_assoc,
refl
}
end
/-
A mathematician would now say that you have proved that the natural
numbers are a semiring.
Lean would add that you have also proved that they are a `distrib`.
However this concept has no mathematical name at all -- this says something
about the regard with which we hold this collectible. You consider politely
declining Lean's offer of a `distrib` collectible.
You are dreaming of the big collectible at the end of world 4.
-/
def right_distrib := add_mul -- stupid field name, -- hide
def collectible_045 : distrib mynat := by structure_helper -- hide
def collectible_05 : semiring mynat := by structure_helper -- hide
end mynat -- hide
|
6d811fa6a83ed120c9348089a7f4c5a8e045727b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/metric_space/kuratowski.lean | f5e0eba9714074c31970d420b5d599aa815cf9bd | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 5,327 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.normed_space.lp_space
import topology.sets.compacts
/-!
# The Kuratowski embedding
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Any separable metric space can be embedded isometrically in `ℓ^∞(ℝ)`.
-/
noncomputable theory
open set metric topological_space
open_locale ennreal
local notation `ℓ_infty_ℝ`:= lp (λ n : ℕ, ℝ) ∞
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
namespace Kuratowski_embedding
/-! ### Any separable metric space can be embedded isometrically in ℓ^∞(ℝ) -/
variables {f g : ℓ_infty_ℝ} {n : ℕ} {C : ℝ} [metric_space α] (x : ℕ → α) (a b : α)
/-- A metric space can be embedded in `l^∞(ℝ)` via the distances to points in
a fixed countable set, if this set is dense. This map is given in `Kuratowski_embedding`,
without density assumptions. -/
def embedding_of_subset : ℓ_infty_ℝ :=
⟨ λ n, dist a (x n) - dist (x 0) (x n),
begin
apply mem_ℓp_infty,
use dist a (x 0),
rintros - ⟨n, rfl⟩,
exact abs_dist_sub_le _ _ _
end ⟩
lemma embedding_of_subset_coe : embedding_of_subset x a n = dist a (x n) - dist (x 0) (x n) := rfl
/-- The embedding map is always a semi-contraction. -/
lemma embedding_of_subset_dist_le (a b : α) :
dist (embedding_of_subset x a) (embedding_of_subset x b) ≤ dist a b :=
begin
refine lp.norm_le_of_forall_le dist_nonneg (λn, _),
simp only [lp.coe_fn_sub, pi.sub_apply, embedding_of_subset_coe, real.dist_eq],
convert abs_dist_sub_le a b (x n) using 2,
ring
end
/-- When the reference set is dense, the embedding map is an isometry on its image. -/
lemma embedding_of_subset_isometry (H : dense_range x) : isometry (embedding_of_subset x) :=
begin
refine isometry.of_dist_eq (λa b, _),
refine (embedding_of_subset_dist_le x a b).antisymm (le_of_forall_pos_le_add (λe epos, _)),
/- First step: find n with dist a (x n) < e -/
rcases metric.mem_closure_range_iff.1 (H a) (e/2) (half_pos epos) with ⟨n, hn⟩,
/- Second step: use the norm control at index n to conclude -/
have C : dist b (x n) - dist a (x n) = embedding_of_subset x b n - embedding_of_subset x a n :=
by { simp only [embedding_of_subset_coe, sub_sub_sub_cancel_right] },
have := calc
dist a b ≤ dist a (x n) + dist (x n) b : dist_triangle _ _ _
... = 2 * dist a (x n) + (dist b (x n) - dist a (x n)) : by { simp [dist_comm], ring }
... ≤ 2 * dist a (x n) + |dist b (x n) - dist a (x n)| :
by apply_rules [add_le_add_left, le_abs_self]
... ≤ 2 * (e/2) + |embedding_of_subset x b n - embedding_of_subset x a n| :
begin rw C, apply_rules [add_le_add, mul_le_mul_of_nonneg_left, hn.le, le_refl], norm_num end
... ≤ 2 * (e/2) + dist (embedding_of_subset x b) (embedding_of_subset x a) :
begin
have : |embedding_of_subset x b n - embedding_of_subset x a n|
≤ dist (embedding_of_subset x b) (embedding_of_subset x a),
{ simpa [dist_eq_norm] using lp.norm_apply_le_norm ennreal.top_ne_zero
(embedding_of_subset x b - embedding_of_subset x a) n },
nlinarith,
end
... = dist (embedding_of_subset x b) (embedding_of_subset x a) + e : by ring,
simpa [dist_comm] using this
end
/-- Every separable metric space embeds isometrically in `ℓ_infty_ℝ`. -/
theorem exists_isometric_embedding (α : Type u) [metric_space α] [separable_space α] :
∃(f : α → ℓ_infty_ℝ), isometry f :=
begin
cases (univ : set α).eq_empty_or_nonempty with h h,
{ use (λ_, 0), assume x, exact absurd h (nonempty.ne_empty ⟨x, mem_univ x⟩) },
{ /- We construct a map x : ℕ → α with dense image -/
rcases h with ⟨basepoint⟩,
haveI : inhabited α := ⟨basepoint⟩,
have : ∃s:set α, s.countable ∧ dense s := exists_countable_dense α,
rcases this with ⟨S, ⟨S_countable, S_dense⟩⟩,
rcases set.countable_iff_exists_subset_range.1 S_countable with ⟨x, x_range⟩,
/- Use embedding_of_subset to construct the desired isometry -/
exact ⟨embedding_of_subset x, embedding_of_subset_isometry x (S_dense.mono x_range)⟩ }
end
end Kuratowski_embedding
open topological_space Kuratowski_embedding
/-- The Kuratowski embedding is an isometric embedding of a separable metric space in `ℓ^∞(ℝ)`. -/
def Kuratowski_embedding (α : Type u) [metric_space α] [separable_space α] : α → ℓ_infty_ℝ :=
classical.some (Kuratowski_embedding.exists_isometric_embedding α)
/-- The Kuratowski embedding is an isometry. -/
protected lemma Kuratowski_embedding.isometry (α : Type u) [metric_space α] [separable_space α] :
isometry (Kuratowski_embedding α) :=
classical.some_spec (exists_isometric_embedding α)
/-- Version of the Kuratowski embedding for nonempty compacts -/
def nonempty_compacts.Kuratowski_embedding (α : Type u) [metric_space α] [compact_space α]
[nonempty α] :
nonempty_compacts ℓ_infty_ℝ :=
{ carrier := range (Kuratowski_embedding α),
is_compact' := is_compact_range (Kuratowski_embedding.isometry α).continuous,
nonempty' := range_nonempty _ }
|
92e1ed23da2fb40578dd48fdecdc871608966a7a | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/data/nat/choose/factorization.lean | 0dc2dfedbecdec13eba70c0f0889dee5c29c458f | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 6,650 | lean | /-
Copyright (c) 2022 Bolton Bailey. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bolton Bailey, Patrick Stevens, Thomas Browning
-/
import data.nat.choose.central
import data.nat.factorization.basic
import data.nat.multiplicity
/-!
# Factorization of Binomial Coefficients
This file contains a few results on the multiplicity of prime factors within certain size
bounds in binomial coefficients. These include:
* `nat.factorization_choose_le_log`: a logarithmic upper bound on the multiplicity of a prime in
a binomial coefficient.
* `nat.factorization_choose_le_one`: Primes above `sqrt n` appear at most once
in the factorization of `n` choose `k`.
* `nat.factorization_central_binom_of_two_mul_self_lt_three_mul`: Primes from `2 * n / 3` to `n`
do not appear in the factorization of the `n`th central binomial coefficient.
* `nat.factorization_choose_eq_zero_of_lt`: Primes greater than `n` do not
appear in the factorization of `n` choose `k`.
These results appear in the [Erdős proof of Bertrand's postulate](aigner1999proofs).
-/
open_locale big_operators
namespace nat
variables {p n k : ℕ}
/--
A logarithmic upper bound on the multiplicity of a prime in a binomial coefficient.
-/
lemma factorization_choose_le_log : (choose n k).factorization p ≤ log p n :=
begin
by_cases h : (choose n k).factorization p = 0, { simp [h] },
have hp : p.prime := not.imp_symm (choose n k).factorization_eq_zero_of_non_prime h,
have hkn : k ≤ n, { refine le_of_not_lt (λ hnk, h _), simp [choose_eq_zero_of_lt hnk] },
rw [factorization_def _ hp, @padic_val_nat_def _ ⟨hp⟩ _ (choose_pos hkn)],
simp only [hp.multiplicity_choose hkn (lt_add_one _), part_enat.get_coe],
refine (finset.card_filter_le _ _).trans (le_of_eq (nat.card_Ico _ _)),
end
/--
A `pow` form of `nat.factorization_choose_le`
-/
lemma pow_factorization_choose_le (hn : 0 < n) : p ^ (choose n k).factorization p ≤ n :=
begin
cases le_or_lt p 1,
{ exact (pow_le_pow_of_le h).trans ((le_of_eq (one_pow _)).trans hn) },
{ exact (pow_le_iff_le_log h hn).mpr factorization_choose_le_log },
end
/--
Primes greater than about `sqrt n` appear only to multiplicity 0 or 1 in the binomial coefficient.
-/
lemma factorization_choose_le_one (p_large : n < p ^ 2) : (choose n k).factorization p ≤ 1 :=
begin
apply factorization_choose_le_log.trans,
rcases n.eq_zero_or_pos with rfl | hn0, { simp },
refine lt_succ_iff.1 ((lt_pow_iff_log_lt _ hn0).1 p_large),
contrapose! hn0,
exact lt_succ_iff.1 (lt_of_lt_of_le p_large (pow_le_one' hn0 2)),
end
lemma factorization_choose_of_lt_three_mul
(hp' : p ≠ 2) (hk : p ≤ k) (hk' : p ≤ n - k) (hn : n < 3 * p) :
(choose n k).factorization p = 0 :=
begin
cases em' p.prime with hp hp,
{ exact factorization_eq_zero_of_non_prime (choose n k) hp },
cases lt_or_le n k with hnk hkn,
{ simp [choose_eq_zero_of_lt hnk] },
rw [factorization_def _ hp, @padic_val_nat_def _ ⟨hp⟩ _ (choose_pos hkn)],
simp only [hp.multiplicity_choose hkn (lt_add_one _), part_enat.get_coe,
finset.card_eq_zero, finset.filter_eq_empty_iff, not_le],
intros i hi,
rcases eq_or_lt_of_le (finset.mem_Ico.mp hi).1 with rfl | hi,
{ rw [pow_one, ←add_lt_add_iff_left (2 * p), ←succ_mul, two_mul, add_add_add_comm],
exact lt_of_le_of_lt (add_le_add
(add_le_add_right (le_mul_of_one_le_right' ((one_le_div_iff hp.pos).mpr hk)) (k % p))
(add_le_add_right (le_mul_of_one_le_right' ((one_le_div_iff hp.pos).mpr hk')) ((n - k) % p)))
(by rwa [div_add_mod, div_add_mod, add_tsub_cancel_of_le hkn]) },
{ replace hn : n < p ^ i,
{ calc n < 3 * p : hn
... ≤ p * p : mul_le_mul_right' (lt_of_le_of_ne hp.two_le hp'.symm) p
... = p ^ 2 : (sq p).symm
... ≤ p ^ i : pow_le_pow hp.one_lt.le hi },
rwa [mod_eq_of_lt (lt_of_le_of_lt hkn hn), mod_eq_of_lt (lt_of_le_of_lt tsub_le_self hn),
add_tsub_cancel_of_le hkn] },
end
/--
Primes greater than about `2 * n / 3` and less than `n` do not appear in the factorization of
`central_binom n`.
-/
lemma factorization_central_binom_of_two_mul_self_lt_three_mul
(n_big : 2 < n) (p_le_n : p ≤ n) (big : 2 * n < 3 * p) :
(central_binom n).factorization p = 0 :=
begin
refine factorization_choose_of_lt_three_mul _ p_le_n (p_le_n.trans _) big,
{ rintro rfl, linarith },
{ rw [two_mul, add_tsub_cancel_left] },
end
lemma factorization_factorial_eq_zero_of_lt (h : n < p) :
(factorial n).factorization p = 0 :=
begin
induction n with n hn, { simp },
rw [factorial_succ, factorization_mul n.succ_ne_zero n.factorial_ne_zero, finsupp.coe_add,
pi.add_apply, hn (lt_of_succ_lt h), add_zero, factorization_eq_zero_of_lt h],
end
lemma factorization_choose_eq_zero_of_lt (h : n < p) :
(choose n k).factorization p = 0 :=
begin
by_cases hnk : n < k, { simp [choose_eq_zero_of_lt hnk] },
rw [choose_eq_factorial_div_factorial (le_of_not_lt hnk),
factorization_div (factorial_mul_factorial_dvd_factorial (le_of_not_lt hnk)),
finsupp.coe_tsub, pi.sub_apply, factorization_factorial_eq_zero_of_lt h, zero_tsub],
end
/--
If a prime `p` has positive multiplicity in the `n`th central binomial coefficient,
`p` is no more than `2 * n`
-/
lemma factorization_central_binom_eq_zero_of_two_mul_lt (h : 2 * n < p) :
(central_binom n).factorization p = 0 :=
factorization_choose_eq_zero_of_lt h
/--
Contrapositive form of `nat.factorization_central_binom_eq_zero_of_two_mul_lt`
-/
lemma le_two_mul_of_factorization_central_binom_pos
(h_pos : 0 < (central_binom n).factorization p) : p ≤ 2 * n :=
le_of_not_lt (pos_iff_ne_zero.mp h_pos ∘ factorization_central_binom_eq_zero_of_two_mul_lt)
/-- A binomial coefficient is the product of its prime factors, which are at most `n`. -/
lemma prod_pow_factorization_choose (n k : ℕ) (hkn : k ≤ n) :
∏ p in (finset.range (n + 1)),
p ^ ((nat.choose n k).factorization p)
= choose n k :=
begin
nth_rewrite_rhs 0 ←factorization_prod_pow_eq_self (choose_pos hkn).ne',
rw eq_comm,
apply finset.prod_subset,
{ intros p hp,
rw finset.mem_range,
contrapose! hp,
rw [finsupp.mem_support_iff, not_not, factorization_choose_eq_zero_of_lt hp] },
{ intros p _ h2, simp [not_not.1 (mt finsupp.mem_support_iff.2 h2)] },
end
/-- The `n`th central binomial coefficient is the product of its prime factors, which are
at most `2n`. -/
lemma prod_pow_factorization_central_binom (n : ℕ) :
∏ p in (finset.range (2 * n + 1)),
p ^ ((central_binom n).factorization p)
= central_binom n :=
begin
apply prod_pow_factorization_choose,
linarith,
end
end nat
|
455f6c25deb17f9456eade551b8c92b52319c02e | 6b45072eb2b3db3ecaace2a7a0241ce81f815787 | /tools/auto/finish.lean | 0479adb9981f64b32ab043d0134fd934e214dc00 | [] | no_license | avigad/library_dev | 27b47257382667b5eb7e6476c4f5b0d685dd3ddc | 9d8ac7c7798ca550874e90fed585caad030bbfac | refs/heads/master | 1,610,452,468,791 | 1,500,712,839,000 | 1,500,713,478,000 | 69,311,142 | 1 | 0 | null | 1,474,942,903,000 | 1,474,942,902,000 | null | UTF-8 | Lean | false | false | 15,587 | lean | /-
Copyright (c) 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
These tactics do straightforward things: they call the simplifier, split conjunctive assumptions,
eliminate existential quantifiers on the left, and look for contradictions. They rely on ematching
and congruence closure to try to finish off a goal at the end.
The procedures *do* split on disjunctions and recreate the smt state for each terminal call, so
they are only meant to be used on small, straightforward problems.
We provide the following tactics:
finish -- solves the goal or fails
clarify -- makes as much progress as possible while not leaving more than one goal
safe -- splits freely, finishes off whatever subgoals it can, and leaves the rest
All accept an optional list of simplifier rules, typically definitions that should be expanded.
(The equations and identities should not refer to the local context.)
The variants ifinish, iclarify, and isafe restrict to intuitionistic logic. They do not work
well with the current heuristic instantiation method used by ematch, so they should be revisited
when the API changes.
-/
import ..tactic.tactic ...logic.basic
open tactic expr
declare_trace auto.done
declare_trace auto.finish
-- TODO(Jeremy): move these
theorem implies_and_iff (p q r : Prop) : (p → q ∧ r) ↔ (p → q) ∧ (p → r) :=
iff.intro (λ h, ⟨λ hp, (h hp).left, λ hp, (h hp).right⟩) (λ h hp, ⟨h.left hp, h.right hp⟩)
theorem curry_iff (p q r : Prop) : (p ∧ q → r) ↔ (p → q → r) :=
iff.intro (λ h hp hq, h ⟨hp, hq⟩) (λ h ⟨hp, hq⟩, h hp hq)
theorem iff_def (p q : Prop) : (p ↔ q) ↔ (p → q) ∧ (q → p) :=
⟨ λh, ⟨h.1, h.2⟩, λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩ ⟩
theorem {u} bexists_def {α : Type u} (p q : α → Prop) : (∃ x (h : p x), q x) ↔ ∃ x, p x ∧ q x :=
⟨λ ⟨x, px, qx⟩, ⟨x, px, qx⟩, λ ⟨x, px, qx⟩, ⟨x, px, qx⟩⟩
namespace auto
/- Utilities -/
meta def whnf_reducible (e : expr) : tactic expr := whnf e reducible
-- stolen from interactive.lean
meta def add_simps : simp_lemmas → list name → tactic simp_lemmas
| s [] := return s
| s (n::ns) := do s' ← s.add_simp n, add_simps s' ns
/-
Configuration information for the auto tactics.
-/
structure auto_config : Type :=
(use_simp := tt) -- call the simplifier
(classical := tt) -- use classical logic
(max_ematch_rounds := 20) -- for the "done" tactic
/-
Preprocess goal.
We want to move everything to the left of the sequent arrow. For intuitionistic logic,
we replace the goal p with ∀ f, (p → f) → f and introduce.
-/
theorem by_contradiction_trick (p : Prop) (h : ∀ f : Prop, (p → f) → f) : p :=
h p id
meta def preprocess_goal (cfg : auto_config) : tactic unit :=
do repeat (intro1 >> skip),
tgt ← target >>= whnf_reducible,
if (¬ (is_false tgt)) then
if cfg.classical then
(mk_mapp ``classical.by_contradiction [some tgt]) >>= apply >> intro1 >> skip
else
(mk_mapp ``decidable.by_contradiction [some tgt, none] >>= apply >> intro1 >> skip) <|>
applyc ``by_contradiction_trick >> intro1 >> intro1 >> skip
else
skip
/-
Normalize hypotheses. Bring conjunctions to the outside (for splitting),
bring universal quantifiers to the outside (for ematching). The classical normalizer
eliminates a → b in favor of ¬ a ∨ b.
For efficiency, we push negations inwards from the top down. (For example, consider
simplifying ¬ ¬ (p ∨ q).)
-/
section
universe u
variable {α : Type u}
variables (p q : Prop)
variable (s : α → Prop)
theorem not_not_eq : (¬ ¬ p) = p := propext (classical.not_not_iff p)
theorem not_and_eq : (¬ (p ∧ q)) = (¬ p ∨ ¬ q) := propext (classical.not_and_iff p q)
theorem not_or_eq : (¬ (p ∨ q)) = (¬ p ∧ ¬ q) := propext (not_or_iff p q)
theorem not_forall_eq : (¬ ∀ x, s x) = (∃ x, ¬ s x) := propext (classical.not_forall_iff_exists_not s)
theorem not_exists_eq : (¬ ∃ x, s x) = (∀ x, ¬ s x) := propext (not_exists_iff_forall_not s)
theorem not_implies_eq : (¬ (p → q)) = (p ∧ ¬ q) := propext (classical.not_implies_iff_and_not p q)
end
def common_normalize_lemma_names : list name :=
[``bexists_def, ``forall_and_distrib, ``exists_implies_distrib]
def classical_normalize_lemma_names : list name :=
common_normalize_lemma_names ++ [``classical.implies_iff_not_or]
-- optionally returns an equivalent expression and proof of equivalence
private meta def transform_negation_step (cfg : auto_config) (e : expr) :
tactic (option (expr × expr)) :=
do e ← whnf_reducible e,
match e with
| `(¬ %%ne) :=
(do ne ← whnf_reducible ne,
match ne with
| `(¬ %%a) := do pr ← mk_app ``not_not_eq [a],
return (some (a, pr))
| `(%%a ∧ %%b) := do pr ← mk_app ``not_and_eq [a, b],
return (some (`(¬ %%a ∨ ¬ %%b), pr))
| `(%%a ∨ %%b) := do pr ← mk_app ``not_or_eq [a, b],
return (some (`(¬ %%a ∧ ¬ %%b), pr))
| `(Exists %%p) := do pr ← mk_app ``not_exists_eq [p],
`(%%_ = %%e') ← infer_type pr,
return (some (e', pr))
| (pi n bi d p) := if ¬ cfg.classical then return none
else if p.has_var then do
pr ← mk_app ``not_forall_eq [lam n bi d (expr.abstract_local p n)],
`(%%_ = %%e') ← infer_type pr,
return (some (e', pr))
else do
pr ← mk_app ``not_implies_eq [d, p],
`(%%_ = %%e') ← infer_type pr,
return (some (e', pr))
| _ := return none
end)
| _ := return none
end
-- given an expr 'e', returns a new expression and a proof of equality
private meta def transform_negation (cfg : auto_config) : expr → tactic (option (expr × expr)) :=
λ e, do
opr ← transform_negation_step cfg e,
match opr with
| (some (e', pr)) := do
opr' ← transform_negation e',
match opr' with
| none := return (some (e', pr))
| (some (e'', pr')) := do pr'' ← mk_eq_trans pr pr',
return (some (e'', pr''))
end
| none := return none
end
meta def normalize_negations (cfg : auto_config) (h : expr) : tactic unit :=
do t ← infer_type h,
(_, e, pr) ← simplify_top_down ()
(λ _, λ e, do
oepr ← transform_negation cfg e,
match oepr with
| (some (e', pr)) := return ((), e', pr)
| none := do pr ← mk_eq_refl e, return ((), e, pr)
end)
t,
replace_hyp h e pr,
skip
meta def normalize_hyp (cfg : auto_config) (simps : simp_lemmas) (h : expr) : tactic unit :=
(do h ← simp_hyp simps [] h, try (normalize_negations cfg h)) <|>
try (normalize_negations cfg h)
meta def normalize_hyps (cfg : auto_config) : tactic unit :=
do simps ← if cfg.classical then
add_simps simp_lemmas.mk classical_normalize_lemma_names
else
add_simps simp_lemmas.mk common_normalize_lemma_names,
local_context >>= monad.mapm' (normalize_hyp cfg simps)
/-
Eliminate existential quantifiers.
-/
-- eliminate an existential quantifier if there is one
meta def eelim : tactic unit :=
do ctx ← local_context,
first $ ctx.for $ λ h,
do t ← infer_type h >>= whnf_reducible,
guard (is_app_of t ``Exists),
tgt ← target,
to_expr ``(@exists.elim _ _ %%tgt %%h) >>= apply,
intros,
clear h
-- eliminate all existential quantifiers, fails if there aren't any
meta def eelims : tactic unit := eelim >> repeat eelim
/-
Substitute if there is a hypothesis x = t or t = x.
-/
-- carries out a subst if there is one, fails otherwise
meta def do_subst : tactic unit :=
do ctx ← local_context,
first $ ctx.for $ λ h,
do t ← infer_type h >>= whnf_reducible,
match t with
| `(%%a = %%b) := subst h
| _ := failed
end
meta def do_substs : tactic unit := do_subst >> repeat do_subst
/-
Split all conjunctions.
-/
-- Assumes pr is a proof of t. Adds the consequences of t to the context
-- and returns tt if anything nontrivial has been added.
meta def add_conjuncts : expr → expr → tactic bool :=
λ pr t,
let assert_consequences := λ e t, mcond (add_conjuncts e t) skip (assertv_fresh t e >> skip) in
do t' ← whnf_reducible t,
match t' with
| `(%%a ∧ %%b) :=
do e₁ ← mk_app ``and.left [pr],
assert_consequences e₁ a,
e₂ ← mk_app ``and.right [pr],
assert_consequences e₂ b,
return tt
| `(true) :=
do return tt
| _ := return ff
end
-- return tt if any progress is made
meta def split_hyp (h : expr) : tactic bool :=
do t ← infer_type h,
mcond (add_conjuncts h t) (clear h >> return tt) (return ff)
-- return tt if any progress is made
meta def split_hyps_aux : list expr → tactic bool
| [] := return ff
| (h :: hs) := do b₁ ← split_hyp h,
b₂ ← split_hyps_aux hs,
return (b₁ || b₂)
-- fail if no progress is made
meta def split_hyps : tactic unit := local_context >>= split_hyps_aux >>= guardb
/-
Eagerly apply all the preprocessing rules.
-/
meta def preprocess_hyps (cfg : auto_config) : tactic unit :=
do repeat (intro1 >> skip),
preprocess_goal cfg,
normalize_hyps cfg,
repeat (do_substs <|> split_hyps <|> eelim /-<|> self_simplify_hyps-/)
/-
The terminal tactic, used to try to finish off goals:
- Call the contradiction tactic.
- Open an SMT state, and use ematching and congruence closure, with all the universal
statements in the context.
TODO(Jeremy): allow users to specify attribute for ematching lemmas?
-/
meta def mk_hinst_lemmas : list expr → smt_tactic hinst_lemmas
| [] := -- return hinst_lemmas.mk
do get_hinst_lemmas_for_attr `ematch
| (h :: hs) := do his ← mk_hinst_lemmas hs,
t ← infer_type h,
match t with
| (pi _ _ _ _) :=
do t' ← infer_type t,
if t' = `(Prop) then
(do new_lemma ← hinst_lemma.mk h,
return (hinst_lemmas.add his new_lemma)) <|> return his
else return his
| _ := return his
end
meta def done (cfg : auto_config := {}) : tactic unit :=
do when_tracing `auto.done (trace "entering done" >> trace_state),
contradiction <|>
(solve1 $
(do revert_all,
using_smt
(do smt_tactic.intros,
ctx ← local_context,
hs ← mk_hinst_lemmas ctx,
smt_tactic.repeat_at_most cfg.max_ematch_rounds
(smt_tactic.ematch_using hs >> smt_tactic.try smt_tactic.close))))
/-
Tactics that perform case splits.
-/
inductive case_option
| force -- fail unless all goals are solved
| at_most_one -- leave at most one goal
| accept -- leave as many goals as necessary
private meta def case_cont (s : case_option) (cont : case_option → tactic unit) : tactic unit :=
do match s with
| case_option.force := cont case_option.force >> cont case_option.force
| case_option.at_most_one :=
-- if the first one succeeds, commit to it, and try the second
(mcond (cont case_option.force >> return tt) (cont case_option.at_most_one) skip) <|>
-- otherwise, try the second
(swap >> cont case_option.force >> cont case_option.at_most_one)
| case_option.accept := focus [cont case_option.accept, cont case_option.accept]
end
-- three possible outcomes:
-- finds something to case, the continuations succeed ==> returns tt
-- finds something to case, the continutations fail ==> fails
-- doesn't find anything to case ==> returns ff
meta def case_hyp (h : expr) (s : case_option) (cont : case_option → tactic unit) : tactic bool :=
do t ← infer_type h,
match t with
| `(%%a ∨ %%b) := cases h >> case_cont s cont >> return tt
| _ := return ff
end
meta def case_some_hyp_aux (s : case_option) (cont : case_option → tactic unit) :
list expr → tactic bool
| [] := return ff
| (h::hs) := mcond (case_hyp h s cont) (return tt) (case_some_hyp_aux hs)
meta def case_some_hyp (s : case_option) (cont : case_option → tactic unit) : tactic bool :=
local_context >>= case_some_hyp_aux s cont
/-
The main tactics.
-/
meta def safe_core (s : simp_lemmas × list name) (cfg : auto_config) : case_option → tactic unit :=
λ co, focus1 $
do when_tracing `auto.finish (trace "entering safe_core" >> trace_state),
if cfg^.use_simp then do
when_tracing `auto.finish (trace "simplifying hypotheses"),
simp_all s.1 s.2 { fail_if_unchanged := ff },
when_tracing `auto.finish (trace "result:" >> trace_state)
else skip,
tactic.done <|>
do when_tracing `auto.finish (trace "preprocessing hypotheses"),
preprocess_hyps cfg,
when_tracing `auto.finish (trace "result:" >> trace_state),
done cfg <|>
(mcond (case_some_hyp co safe_core)
skip
(match co with
| case_option.force := done cfg
| case_option.at_most_one := try (done cfg)
| case_option.accept := try (done cfg)
end))
meta def clarify (s : simp_lemmas × list name) (cfg : auto_config := {}) : tactic unit :=
safe_core s cfg case_option.at_most_one
meta def safe (s : simp_lemmas × list name) (cfg : auto_config := {}) : tactic unit :=
safe_core s cfg case_option.accept
meta def finish (s : simp_lemmas × list name) (cfg : auto_config := {}) : tactic unit :=
safe_core s cfg case_option.force
meta def iclarify (s : simp_lemmas × list name) (cfg : auto_config := {}) : tactic unit :=
clarify s {cfg with classical := false}
meta def isafe (s : simp_lemmas × list name) (cfg : auto_config := {}) : tactic unit :=
safe s {cfg with classical := false}
meta def ifinish (s : simp_lemmas × list name) (cfg : auto_config := {}) : tactic unit :=
finish s {cfg with classical := false}
end auto
/- interactive versions -/
open auto
namespace tactic
namespace interactive
open lean lean.parser interactive interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many
meta def clarify (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit :=
do s ← mk_simp_set ff [] hs,
auto.clarify s cfg
meta def safe (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit :=
do s ← mk_simp_set ff [] hs,
auto.safe s cfg
meta def finish (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit :=
do s ← mk_simp_set ff [] hs,
auto.finish s cfg
meta def iclarify (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit :=
do s ← mk_simp_set ff [] hs,
auto.iclarify s cfg
meta def isafe (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit :=
do s ← mk_simp_set ff [] hs,
auto.isafe s cfg
meta def ifinish (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit :=
do s ← mk_simp_set ff [] hs,
auto.ifinish s cfg
end interactive
end tactic
|
cf4a95e4ae3e15e43500a84e48f1a831cfac3706 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/fintype/sort.lean | d848603a4ae2d790f1f05f0ffae2fb939bd03030 | [] | 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 | 964 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.fintype.basic
import Mathlib.data.finset.sort
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-- Given a linearly ordered fintype `α` of cardinal `k`, the order isomorphism
`mono_equiv_of_fin α h` is the increasing bijection between `fin k` and `α`. Here, `h` is a proof
that the cardinality of `s` is `k`. We use this instead of an isomorphism `fin s.card ≃o α` to avoid
casting issues in further uses of this function. -/
def mono_equiv_of_fin (α : Type u_1) [fintype α] [linear_order α] {k : ℕ} (h : fintype.card α = k) : fin k ≃o α :=
order_iso.trans (finset.order_iso_of_fin finset.univ h)
(order_iso.trans (order_iso.set_congr (↑finset.univ) set.univ finset.coe_univ) order_iso.set.univ)
|
a1fda1ed5539224cd8eab1300e191e61999c96bb | 4e0d7c3132ce31edc5829849735dd25db406b144 | /lean/love13_rational_and_real_numbers_exercise_sheet.lean | 9dfac34f7660eff175cd836dd63c83f4328e4817 | [] | no_license | gonzalgu/logical_verification_2020 | a0013a6c22ea254e9f4d245f2948f0f4d44df4bb | 724d0457dff2c3ff10f9ab2170388f4c5e958b75 | refs/heads/master | 1,660,886,374,533 | 1,589,859,641,000 | 1,589,859,641,000 | 256,069,971 | 0 | 0 | null | 1,586,997,430,000 | 1,586,997,429,000 | null | UTF-8 | Lean | false | false | 1,351 | 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
#check fraction.mk.inj
lemma fraction.ext (a b : fraction) (hnum : fraction.num a = fraction.num b)
(hdenom : fraction.denom a = fraction.denom b) :
a = b :=
begin
cases a with an ad adnz,
cases b with bn bd bdnz,
rw fraction.mk.inj_eq,
exact ⟨ hnum, hdenom ⟩,
end
/-! 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 :=
begin
intros a b c,
apply fraction.ext;simp;rw mul_assoc,
end,
..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 :=
begin
sorry,
end,
..rat.has_mul }
end LoVe
|
e1ff68161f621b9f232e1a3ef142e0e3d7059eed | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /hott/arity.hlean | 8444a40b6fcb97f41818b98455485b8daabdb484 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 11,067 | 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
Theorems about functions with multiple arguments
-/
variables {A U V W X Y Z : Type} {B : A → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type}
{E : Πa b c, D a b c → Type} {F : Πa b c d, E a b c d → Type}
{G : Πa b c d e, F a b c d e → Type} {H : Πa b c d e f, G a b c d e f → Type}
variables {a a' : A} {u u' : U} {v v' : V} {w w' : W} {x x' x'' : X} {y y' : Y} {z z' : Z}
{b : B a} {b' : B a'}
{c : C a b} {c' : C a' b'}
{d : D a b c} {d' : D a' b' c'}
{e : E a b c d} {e' : E a' b' c' d'}
{ff : F a b c d e} {f' : F a' b' c' d' e'}
{g : G a b c d e ff} {g' : G a' b' c' d' e' f'}
{h : H a b c d e ff g} {h' : H a' b' c' d' e' f' g'}
namespace eq
/-
Naming convention:
The theorem which states how to construct an path between two function applications is
api₀i₁...iₙ.
Here i₀, ... iₙ are digits, n is the arity of the function(s),
and iⱼ specifies the dimension of the path between the jᵗʰ argument
(i₀ specifies the dimension of the path between the functions).
A value iⱼ ≡ 0 means that the jᵗʰ arguments are definitionally equal
The functions are non-dependent, except when the theorem name contains trailing zeroes
(where the function is dependent only in the arguments where it doesn't result in any
transports in the theorem statement).
For the fully-dependent versions (except that the conclusion doesn't contain a transport)
we write
apdi₀i₁...iₙ.
For versions where only some arguments depend on some other arguments,
or for versions with transport in the conclusion (like apd), we don't have a
consistent naming scheme (yet).
We don't prove each theorem systematically, but prove only the ones which we actually need.
-/
definition homotopy2 [reducible] (f g : Πa b, C a b) : Type :=
Πa b, f a b = g a b
definition homotopy3 [reducible] (f g : Πa b c, D a b c) : Type :=
Πa b c, f a b c = g a b c
definition homotopy4 [reducible] (f g : Πa b c d, E a b c d) : Type :=
Πa b c d, f a b c d = g a b c d
infix ` ~2 `:50 := homotopy2
infix ` ~3 `:50 := homotopy3
definition ap0111 (f : U → V → W → X) (Hu : u = u') (Hv : v = v') (Hw : w = w')
: f u v w = f u' v' w' :=
by cases Hu; congruence; repeat assumption
definition ap01111 (f : U → V → W → X → Y)
(Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x')
: f u v w x = f u' v' w' x' :=
by cases Hu; congruence; repeat assumption
definition ap011111 (f : U → V → W → X → Y → Z)
(Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y')
: f u v w x y = f u' v' w' x' y' :=
by cases Hu; congruence; repeat assumption
definition ap0111111 (f : U → V → W → X → Y → Z → A)
(Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y') (Hz : z = z')
: f u v w x y z = f u' v' w' x' y' z' :=
by cases Hu; congruence; repeat assumption
definition ap010 (f : X → Πa, B a) (Hx : x = x') : f x ~ f x' :=
by intros; cases Hx; reflexivity
definition ap0100 (f : X → Πa b, C a b) (Hx : x = x') : f x ~2 f x' :=
by intros; cases Hx; reflexivity
definition ap01000 (f : X → Πa b c, D a b c) (Hx : x = x') : f x ~3 f x' :=
by intros; cases Hx; reflexivity
definition apd011 (f : Πa, B a → Z) (Ha : a = a') (Hb : transport B Ha b = b')
: f a b = f a' b' :=
by cases Ha; cases Hb; reflexivity
definition apd0111 (f : Πa b, C a b → Z) (Ha : a = a') (Hb : transport B Ha b = b')
(Hc : cast (apd011 C Ha Hb) c = c')
: f a b c = f a' b' c' :=
by cases Ha; cases Hb; cases Hc; reflexivity
definition apd01111 (f : Πa b c, D a b c → Z) (Ha : a = a') (Hb : transport B Ha b = b')
(Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d')
: f a b c d = f a' b' c' d' :=
by cases Ha; cases Hb; cases Hc; cases Hd; reflexivity
definition apd011111 (f : Πa b c d, E a b c d → Z) (Ha : a = a') (Hb : transport B Ha b = b')
(Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d')
(He : cast (apd01111 E Ha Hb Hc Hd) e = e')
: f a b c d e = f a' b' c' d' e' :=
by cases Ha; cases Hb; cases Hc; cases Hd; cases He; reflexivity
definition apd0111111 (f : Πa b c d e, F a b c d e → Z) (Ha : a = a') (Hb : transport B Ha b = b')
(Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d')
(He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f')
: f a b c d e ff = f a' b' c' d' e' f' :=
begin cases Ha, cases Hb, cases Hc, cases Hd, cases He, cases Hf, reflexivity end
-- definition apd0111111 (f : Πa b c d e ff, G a b c d e ff → Z) (Ha : a = a') (Hb : transport B Ha b = b')
-- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d')
-- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f')
-- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g')
-- : f a b c d e ff g = f a' b' c' d' e' f' g' :=
-- by cases Ha; cases Hb; cases Hc; cases Hd; cases He; cases Hf; cases Hg; reflexivity
-- definition apd01111111 (f : Πa b c d e ff g, G a b c d e ff g → Z) (Ha : a = a') (Hb : transport B Ha b = b')
-- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d')
-- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f')
-- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g') (Hh : cast (apd01111111 H Ha Hb Hc Hd He Hf Hg) h = h')
-- : f a b c d e ff g h = f a' b' c' d' e' f' g' h' :=
-- by cases Ha; cases Hb; cases Hc; cases Hd; cases He; cases Hf; cases Hg; cases Hh; reflexivity
definition apd100 [unfold 6] {f g : Πa b, C a b} (p : f = g) : f ~2 g :=
λa b, apd10 (apd10 p a) b
definition apd1000 [unfold 7] {f g : Πa b c, D a b c} (p : f = g) : f ~3 g :=
λa b c, apd100 (apd10 p a) b c
/- some properties of these variants of ap -/
-- we only prove what we currently need
definition ap010_con (f : X → Πa, B a) (p : x = x') (q : x' = x'') :
ap010 f (p ⬝ q) a = ap010 f p a ⬝ ap010 f q a :=
eq.rec_on q (eq.rec_on p idp)
definition ap010_ap (f : X → Πa, B a) (g : Y → X) (p : y = y') :
ap010 f (ap g p) a = ap010 (λy, f (g y)) p a :=
eq.rec_on p idp
/- the following theorems are function extentionality for functions with multiple arguments -/
definition eq_of_homotopy2 {f g : Πa b, C a b} (H : f ~2 g) : f = g :=
eq_of_homotopy (λa, eq_of_homotopy (H a))
definition eq_of_homotopy3 {f g : Πa b c, D a b c} (H : f ~3 g) : f = g :=
eq_of_homotopy (λa, eq_of_homotopy2 (H a))
definition eq_of_homotopy2_id (f : Πa b, C a b)
: eq_of_homotopy2 (λa b, idpath (f a b)) = idpath f :=
begin
transitivity eq_of_homotopy (λ a, idpath (f a)),
{apply (ap eq_of_homotopy), apply eq_of_homotopy, intros, apply eq_of_homotopy_idp},
apply eq_of_homotopy_idp
end
definition eq_of_homotopy3_id (f : Πa b c, D a b c)
: eq_of_homotopy3 (λa b c, idpath (f a b c)) = idpath f :=
begin
transitivity _,
{apply (ap eq_of_homotopy), apply eq_of_homotopy, intros, apply eq_of_homotopy2_id},
apply eq_of_homotopy_idp
end
definition eq_of_homotopy2_inv {f g : Πa b, C a b} (H : f ~2 g)
: eq_of_homotopy2 (λa b, (H a b)⁻¹) = (eq_of_homotopy2 H)⁻¹ :=
ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy_inv)) ⬝ !eq_of_homotopy_inv
definition eq_of_homotopy3_inv {f g : Πa b c, D a b c} (H : f ~3 g)
: eq_of_homotopy3 (λa b c, (H a b c)⁻¹) = (eq_of_homotopy3 H)⁻¹ :=
ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy2_inv)) ⬝ !eq_of_homotopy_inv
definition eq_of_homotopy2_con {f g h : Πa b, C a b} (H1 : f ~2 g) (H2 : g ~2 h)
: eq_of_homotopy2 (λa b, H1 a b ⬝ H2 a b) = eq_of_homotopy2 H1 ⬝ eq_of_homotopy2 H2 :=
ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy_con)) ⬝ !eq_of_homotopy_con
definition eq_of_homotopy3_con {f g h : Πa b c, D a b c} (H1 : f ~3 g) (H2 : g ~3 h)
: eq_of_homotopy3 (λa b c, H1 a b c ⬝ H2 a b c) = eq_of_homotopy3 H1 ⬝ eq_of_homotopy3 H2 :=
ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy2_con)) ⬝ !eq_of_homotopy_con
end eq
open eq equiv is_equiv
namespace funext
definition is_equiv_apd100 [instance] (f g : Πa b, C a b)
: is_equiv (@apd100 A B C f g) :=
adjointify _
eq_of_homotopy2
begin
intro H, esimp [apd100, eq_of_homotopy2],
apply eq_of_homotopy, intro a,
apply concat, apply (ap (λx, apd10 (x a))), apply (right_inv apd10),
apply (right_inv apd10)
end
begin
intro p, cases p, apply eq_of_homotopy2_id
end
definition is_equiv_apd1000 [instance] (f g : Πa b c, D a b c)
: is_equiv (@apd1000 A B C D f g) :=
adjointify _
eq_of_homotopy3
begin
intro H, esimp,
apply eq_of_homotopy, intro a,
transitivity apd100 (eq_of_homotopy2 (H a)),
{apply ap (λx, apd100 (x a)),
apply right_inv apd10},
apply right_inv apd100
end
begin
intro p, cases p, apply eq_of_homotopy3_id
end
end funext
attribute funext.is_equiv_apd100 funext.is_equiv_apd1000 [constructor]
namespace eq
open funext
local attribute funext.is_equiv_apd100 [instance]
protected definition homotopy2.rec_on {f g : Πa b, C a b} {P : (f ~2 g) → Type}
(p : f ~2 g) (H : Π(q : f = g), P (apd100 q)) : P p :=
right_inv apd100 p ▸ H (eq_of_homotopy2 p)
protected definition homotopy3.rec_on {f g : Πa b c, D a b c} {P : (f ~3 g) → Type}
(p : f ~3 g) (H : Π(q : f = g), P (apd1000 q)) : P p :=
right_inv apd1000 p ▸ H (eq_of_homotopy3 p)
definition eq_equiv_homotopy2 [constructor] (f g : Πa b, C a b) : (f = g) ≃ (f ~2 g) :=
equiv.mk apd100 _
definition eq_equiv_homotopy3 [constructor] (f g : Πa b c, D a b c) : (f = g) ≃ (f ~3 g) :=
equiv.mk apd1000 _
definition apd10_ap (f : X → Πa, B a) (p : x = x')
: apd10 (ap f p) = ap010 f p :=
eq.rec_on p idp
definition eq_of_homotopy_ap010 (f : X → Πa, B a) (p : x = x')
: eq_of_homotopy (ap010 f p) = ap f p :=
inv_eq_of_eq !apd10_ap⁻¹
definition ap_eq_ap_of_homotopy {f : X → Πa, B a} {p q : x = x'} (H : ap010 f p ~ ap010 f q)
: ap f p = ap f q :=
calc
ap f p = eq_of_homotopy (ap010 f p) : eq_of_homotopy_ap010
... = eq_of_homotopy (ap010 f q) : eq_of_homotopy H
... = ap f q : eq_of_homotopy_ap010
end eq
|
da005e5fffc66af743ad25d2481a1c735e95b915 | 54d7e71c3616d331b2ec3845d31deb08f3ff1dea | /tests/lean/key_eqv1.lean | f46d0607d36554a8dbcf6e16bdaedad48988f0a7 | [
"Apache-2.0"
] | permissive | pachugupta/lean | 6f3305c4292288311cc4ab4550060b17d49ffb1d | 0d02136a09ac4cf27b5c88361750e38e1f485a1a | refs/heads/master | 1,611,110,653,606 | 1,493,130,117,000 | 1,493,167,649,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 125 | lean | add_key_equivalence add nat.add
add_key_equivalence nat.add nat.succ
add_key_equivalence mul nat.mul
#print key_equivalences
|
ab1fce03006b92239e87ef5f9f3cdb236f685c36 | 130c49f47783503e462c16b2eff31933442be6ff | /stage0/src/Lean/Meta/SynthInstance.lean | 6942f2f37cf8403f3957a74c11930bc3f081636f | [
"Apache-2.0"
] | permissive | Hazel-Brown/lean4 | 8aa5860e282435ffc30dcdfccd34006c59d1d39c | 79e6732fc6bbf5af831b76f310f9c488d44e7a16 | refs/heads/master | 1,689,218,208,951 | 1,629,736,869,000 | 1,629,736,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 28,061 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam, Leonardo de Moura
Type class instance synthesizer using tabled resolution.
-/
import Lean.Meta.Basic
import Lean.Meta.Instances
import Lean.Meta.LevelDefEq
import Lean.Meta.AbstractMVars
import Lean.Meta.WHNF
import Lean.Util.Profile
namespace Lean.Meta
register_builtin_option synthInstance.maxHeartbeats : Nat := {
defValue := 500
descr := "maximum amount of heartbeats per typeclass resolution problem. A heartbeat is number of (small) memory allocations (in thousands), 0 means no limit"
}
register_builtin_option synthInstance.maxSize : Nat := {
defValue := 128
descr := "maximum number of instances used to construct a solution in the type class instance synthesis procedure"
}
namespace SynthInstance
def getMaxHeartbeats (opts : Options) : Nat :=
synthInstance.maxHeartbeats.get opts * 1000
open Std (HashMap)
builtin_initialize inferTCGoalsRLAttr : TagAttribute ←
registerTagAttribute `inferTCGoalsRL "instruct type class resolution procedure to solve goals from right to left for this instance"
def hasInferTCGoalsRLAttribute (env : Environment) (constName : Name) : Bool :=
inferTCGoalsRLAttr.hasTag env constName
structure GeneratorNode where
mvar : Expr
key : Expr
mctx : MetavarContext
instances : Array Expr
currInstanceIdx : Nat
deriving Inhabited
structure ConsumerNode where
mvar : Expr
key : Expr
mctx : MetavarContext
subgoals : List Expr
size : Nat -- instance size so far
deriving Inhabited
inductive Waiter where
| consumerNode : ConsumerNode → Waiter
| root : Waiter
def Waiter.isRoot : Waiter → Bool
| Waiter.consumerNode _ => false
| Waiter.root => true
/-
In tabled resolution, we creating a mapping from goals (e.g., `Coe Nat ?x`) to
answers and waiters. Waiters are consumer nodes that are waiting for answers for a
particular node.
We implement this mapping using a `HashMap` where the keys are
normalized expressions. That is, we replace assignable metavariables
with auxiliary free variables of the form `_tc.<idx>`. We do
not declare these free variables in any local context, and we should
view them as "normalized names" for metavariables. For example, the
term `f ?m ?m ?n` is normalized as
`f _tc.0 _tc.0 _tc.1`.
This approach is structural, and we may visit the same goal more
than once if the different occurrences are just definitionally
equal, but not structurally equal.
Remark: a metavariable is assignable only if its depth is equal to
the metavar context depth.
-/
namespace MkTableKey
structure State where
nextIdx : Nat := 0
lmap : HashMap MVarId Level := {}
emap : HashMap MVarId Expr := {}
abbrev M := ReaderT MetavarContext (StateM State)
partial def normLevel (u : Level) : M Level := do
if !u.hasMVar then
pure u
else match u with
| Level.succ v _ => return u.updateSucc! (← normLevel v)
| Level.max v w _ => return u.updateMax! (← normLevel v) (← normLevel w)
| Level.imax v w _ => return u.updateIMax! (← normLevel v) (← normLevel w)
| Level.mvar mvarId _ =>
let mctx ← read
if !mctx.isLevelAssignable mvarId then
pure u
else
let s ← get
match s.lmap.find? mvarId with
| some u' => pure u'
| none =>
let u' := mkLevelParam $ Name.mkNum `_tc s.nextIdx
modify fun s => { s with nextIdx := s.nextIdx + 1, lmap := s.lmap.insert mvarId u' }
pure u'
| u => pure u
partial def normExpr (e : Expr) : M Expr := do
if !e.hasMVar then
pure e
else match e with
| Expr.const _ us _ => return e.updateConst! (← us.mapM normLevel)
| Expr.sort u _ => return e.updateSort! (← normLevel u)
| Expr.app f a _ => return e.updateApp! (← normExpr f) (← normExpr a)
| Expr.letE _ t v b _ => return e.updateLet! (← normExpr t) (← normExpr v) (← normExpr b)
| Expr.forallE _ d b _ => return e.updateForallE! (← normExpr d) (← normExpr b)
| Expr.lam _ d b _ => return e.updateLambdaE! (← normExpr d) (← normExpr b)
| Expr.mdata _ b _ => return e.updateMData! (← normExpr b)
| Expr.proj _ _ b _ => return e.updateProj! (← normExpr b)
| Expr.mvar mvarId _ =>
let mctx ← read
if !mctx.isExprAssignable mvarId then
pure e
else
let s ← get
match s.emap.find? mvarId with
| some e' => pure e'
| none => do
let e' := mkFVar $ Name.mkNum `_tc s.nextIdx
modify fun s => { s with nextIdx := s.nextIdx + 1, emap := s.emap.insert mvarId e' }
pure e'
| _ => pure e
end MkTableKey
/- Remark: `mkTableKey` assumes `e` does not contain assigned metavariables. -/
def mkTableKey (mctx : MetavarContext) (e : Expr) : Expr :=
MkTableKey.normExpr e mctx |>.run' {}
structure Answer where
result : AbstractMVarsResult
resultType : Expr
size : Nat
instance : Inhabited Answer where
default := { result := arbitrary, resultType := arbitrary, size := 0 }
structure TableEntry where
waiters : Array Waiter
answers : Array Answer := #[]
structure Context where
maxResultSize : Nat
maxHeartbeats : Nat
/-
Remark: the SynthInstance.State is not really an extension of `Meta.State`.
The field `postponed` is not needed, and the field `mctx` is misleading since
`synthInstance` methods operate over different `MetavarContext`s simultaneously.
That being said, we still use `extends` because it makes it simpler to move from
`M` to `MetaM`.
-/
structure State where
result : Option Expr := none
generatorStack : Array GeneratorNode := #[]
resumeStack : Array (ConsumerNode × Answer) := #[]
tableEntries : HashMap Expr TableEntry := {}
abbrev SynthM := ReaderT Context $ StateRefT State MetaM
def checkMaxHeartbeats : SynthM Unit := do
Core.checkMaxHeartbeatsCore "typeclass" `synthInstance.maxHeartbeats (← read).maxHeartbeats
@[inline] def mapMetaM (f : forall {α}, MetaM α → MetaM α) {α} : SynthM α → SynthM α :=
monadMap @f
instance : Inhabited (SynthM α) where
default := fun _ _ => arbitrary
/-- Return globals and locals instances that may unify with `type` -/
def getInstances (type : Expr) : MetaM (Array Expr) := do
-- We must retrieve `localInstances` before we use `forallTelescopeReducing` because it will update the set of local instances
let localInstances ← getLocalInstances
forallTelescopeReducing type fun _ type => do
let className? ← isClass? type
match className? with
| none => throwError "type class instance expected{indentExpr type}"
| some className =>
let globalInstances ← getGlobalInstancesIndex
let result ← globalInstances.getUnify type
-- Using insertion sort because it is stable and the array `result` should be mostly sorted.
-- Most instances have default priority.
let result := result.insertionSort fun e₁ e₂ => e₁.priority < e₂.priority
let result ← result.mapM fun e => match e.val with
| Expr.const constName us _ => return e.val.updateConst! (← us.mapM (fun _ => mkFreshLevelMVar))
| _ => panic! "global instance is not a constant"
trace[Meta.synthInstance.globalInstances] "{type}, {result}"
let result := localInstances.foldl (init := result) fun (result : Array Expr) linst =>
if linst.className == className then result.push linst.fvar else result
pure result
def mkGeneratorNode? (key mvar : Expr) : MetaM (Option GeneratorNode) := do
let mvarType ← inferType mvar
let mvarType ← instantiateMVars mvarType
let instances ← getInstances mvarType
if instances.isEmpty then
pure none
else
let mctx ← getMCtx
pure $ some {
mvar := mvar,
key := key,
mctx := mctx,
instances := instances,
currInstanceIdx := instances.size
}
/-- Create a new generator node for `mvar` and add `waiter` as its waiter.
`key` must be `mkTableKey mctx mvarType`. -/
def newSubgoal (mctx : MetavarContext) (key : Expr) (mvar : Expr) (waiter : Waiter) : SynthM Unit :=
withMCtx mctx do
trace[Meta.synthInstance.newSubgoal] key
match (← mkGeneratorNode? key mvar) with
| none => pure ()
| some node =>
let entry : TableEntry := { waiters := #[waiter] }
modify fun s =>
{ s with
generatorStack := s.generatorStack.push node,
tableEntries := s.tableEntries.insert key entry }
def findEntry? (key : Expr) : SynthM (Option TableEntry) := do
return (← get).tableEntries.find? key
def getEntry (key : Expr) : SynthM TableEntry := do
match (← findEntry? key) with
| none => panic! "invalid key at synthInstance"
| some entry => pure entry
/--
Create a `key` for the goal associated with the given metavariable.
That is, we create a key for the type of the metavariable.
We must instantiate assigned metavariables before we invoke `mkTableKey`. -/
def mkTableKeyFor (mctx : MetavarContext) (mvar : Expr) : SynthM Expr :=
withMCtx mctx do
let mvarType ← inferType mvar
let mvarType ← instantiateMVars mvarType
return mkTableKey mctx mvarType
/- See `getSubgoals` and `getSubgoalsAux`
We use the parameter `j` to reduce the number of `instantiate*` invocations.
It is the same approach we use at `forallTelescope` and `lambdaTelescope`.
Given `getSubgoalsAux args j subgoals instVal type`,
we have that `type.instantiateRevRange j args.size args` does not have loose bound variables. -/
structure SubgoalsResult where
subgoals : List Expr
instVal : Expr
instTypeBody : Expr
private partial def getSubgoalsAux (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr)
: Array Expr → Nat → List Expr → Expr → Expr → MetaM SubgoalsResult
| args, j, subgoals, instVal, Expr.forallE n d b c => do
let d := d.instantiateRevRange j args.size args
let mvarType ← mkForallFVars xs d
let mvar ← mkFreshExprMVarAt lctx localInsts mvarType
let arg := mkAppN mvar xs
let instVal := mkApp instVal arg
let subgoals := if c.binderInfo.isInstImplicit then mvar::subgoals else subgoals
let args := args.push (mkAppN mvar xs)
getSubgoalsAux lctx localInsts xs args j subgoals instVal b
| args, j, subgoals, instVal, type => do
let type := type.instantiateRevRange j args.size args
let type ← whnf type
if type.isForall then
getSubgoalsAux lctx localInsts xs args args.size subgoals instVal type
else
pure ⟨subgoals, instVal, type⟩
/--
`getSubgoals lctx localInsts xs inst` creates the subgoals for the instance `inst`.
The subgoals are in the context of the free variables `xs`, and
`(lctx, localInsts)` is the local context and instances before we added the free variables to it.
This extra complication is required because
1- We want all metavariables created by `synthInstance` to share the same local context.
2- We want to ensure that applications such as `mvar xs` are higher order patterns.
The method `getGoals` create a new metavariable for each parameter of `inst`.
For example, suppose the type of `inst` is `forall (x_1 : A_1) ... (x_n : A_n), B x_1 ... x_n`.
Then, we create the metavariables `?m_i : forall xs, A_i`, and return the subset of these
metavariables that are instance implicit arguments, and the expressions:
- `inst (?m_1 xs) ... (?m_n xs)` (aka `instVal`)
- `B (?m_1 xs) ... (?m_n xs)` -/
def getSubgoals (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) (inst : Expr) : MetaM SubgoalsResult := do
let instType ← inferType inst
let result ← getSubgoalsAux lctx localInsts xs #[] 0 [] inst instType
match inst.getAppFn with
| Expr.const constName _ _ =>
let env ← getEnv
if hasInferTCGoalsRLAttribute env constName then
pure result
else
pure { result with subgoals := result.subgoals.reverse }
| _ => pure result
def tryResolveCore (mvar : Expr) (inst : Expr) : MetaM (Option (MetavarContext × List Expr)) := do
let mvar ← instantiateMVars mvar
if !(← hasAssignableMVar mvar) then
/- The metavariable `mvar` may have been assinged when solving typing constraints.
This may happen when a local instance type depends on other local instances.
For example, in Mathlib, we have
```
@Submodule.setLike : {R : Type u_1} → {M : Type u_2} →
[_inst_1 : Semiring R] →
[_inst_2 : AddCommMonoid M] →
[_inst_3 : @ModuleS R M _inst_1 _inst_2] →
SetLike (@Submodule R M _inst_1 _inst_2 _inst_3) M
```
TODO: discuss what is the correct behavior here. There are other possibilities.
1) We could try to synthesize the instances `_inst_1` and `_inst_2` and check
whether it is defeq to the one inferred by typing constraints. That is, we
remove this `if`-statement. We discarded this one because some Mathlib theorems
failed to be elaborated using it.
2) Generate an error/warning message when instances such as `Submodule.setLike` are declared,
and instruct user to use `{}` binder annotation for `_inst_1` `_inst_2`.
-/
return some ((← getMCtx), [])
let mvarType ← inferType mvar
let lctx ← getLCtx
let localInsts ← getLocalInstances
forallTelescopeReducing mvarType fun xs mvarTypeBody => do
let ⟨subgoals, instVal, instTypeBody⟩ ← getSubgoals lctx localInsts xs inst
trace[Meta.synthInstance.tryResolve] "{mvarTypeBody} =?= {instTypeBody}"
if (← isDefEq mvarTypeBody instTypeBody) then
let instVal ← mkLambdaFVars xs instVal
if (← isDefEq mvar instVal) then
trace[Meta.synthInstance.tryResolve] "success"
pure (some ((← getMCtx), subgoals))
else
trace[Meta.synthInstance.tryResolve] "failure assigning"
pure none
else
trace[Meta.synthInstance.tryResolve] "failure"
pure none
/--
Try to synthesize metavariable `mvar` using the instance `inst`.
Remark: `mctx` contains `mvar`.
If it succeeds, the result is a new updated metavariable context and a new list of subgoals.
A subgoal is created for each instance implicit parameter of `inst`. -/
def tryResolve (mctx : MetavarContext) (mvar : Expr) (inst : Expr) : SynthM (Option (MetavarContext × List Expr)) :=
traceCtx `Meta.synthInstance.tryResolve <| withMCtx mctx <| tryResolveCore mvar inst
/--
Assign a precomputed answer to `mvar`.
If it succeeds, the result is a new updated metavariable context and a new list of subgoals. -/
def tryAnswer (mctx : MetavarContext) (mvar : Expr) (answer : Answer) : SynthM (Option MetavarContext) :=
withMCtx mctx do
let (_, _, val) ← openAbstractMVarsResult answer.result
if (← isDefEq mvar val) then
pure (some (← getMCtx))
else
pure none
/-- Move waiters that are waiting for the given answer to the resume stack. -/
def wakeUp (answer : Answer) : Waiter → SynthM Unit
| Waiter.root => do
if answer.result.paramNames.isEmpty && answer.result.numMVars == 0 then
modify fun s => { s with result := answer.result.expr }
else
let (_, _, answerExpr) ← openAbstractMVarsResult answer.result
trace[Meta.synthInstance] "skip answer containing metavariables {answerExpr}"
pure ()
| Waiter.consumerNode cNode =>
modify fun s => { s with resumeStack := s.resumeStack.push (cNode, answer) }
def isNewAnswer (oldAnswers : Array Answer) (answer : Answer) : Bool :=
oldAnswers.all fun oldAnswer => do
-- Remark: isDefEq here is too expensive. TODO: if `==` is too imprecise, add some light normalization to `resultType` at `addAnswer`
-- iseq ← isDefEq oldAnswer.resultType answer.resultType; pure (!iseq)
oldAnswer.resultType != answer.resultType
private def mkAnswer (cNode : ConsumerNode) : MetaM Answer :=
withMCtx cNode.mctx do
traceM `Meta.synthInstance.newAnswer do m!"size: {cNode.size}, {← inferType cNode.mvar}"
let val ← instantiateMVars cNode.mvar
trace[Meta.synthInstance.newAnswer] "val: {val}"
let result ← abstractMVars val -- assignable metavariables become parameters
let resultType ← inferType result.expr
pure { result := result, resultType := resultType, size := cNode.size + 1 }
/--
Create a new answer after `cNode` resolved all subgoals.
That is, `cNode.subgoals == []`.
And then, store it in the tabled entries map, and wakeup waiters. -/
def addAnswer (cNode : ConsumerNode) : SynthM Unit := do
if cNode.size ≥ (← read).maxResultSize then
traceM `Meta.synthInstance.discarded do m!"size: {cNode.size} ≥ {(← read).maxResultSize}, {← inferType cNode.mvar}"
return ()
else
let answer ← mkAnswer cNode
-- Remark: `answer` does not contain assignable or assigned metavariables.
let key := cNode.key
let entry ← getEntry key
if isNewAnswer entry.answers answer then
let newEntry := { entry with answers := entry.answers.push answer }
modify fun s => { s with tableEntries := s.tableEntries.insert key newEntry }
entry.waiters.forM (wakeUp answer)
/-- Process the next subgoal in the given consumer node. -/
def consume (cNode : ConsumerNode) : SynthM Unit :=
match cNode.subgoals with
| [] => addAnswer cNode
| mvar::_ => do
let waiter := Waiter.consumerNode cNode
let key ← mkTableKeyFor cNode.mctx mvar
let entry? ← findEntry? key
match entry? with
| none => newSubgoal cNode.mctx key mvar waiter
| some entry => modify fun s =>
{ s with
resumeStack := entry.answers.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack,
tableEntries := s.tableEntries.insert key { entry with waiters := entry.waiters.push waiter } }
def getTop : SynthM GeneratorNode := do
pure (← get).generatorStack.back
@[inline] def modifyTop (f : GeneratorNode → GeneratorNode) : SynthM Unit :=
modify fun s => { s with generatorStack := s.generatorStack.modify (s.generatorStack.size - 1) f }
/-- Try the next instance in the node on the top of the generator stack. -/
def generate : SynthM Unit := do
let gNode ← getTop
if gNode.currInstanceIdx == 0 then
modify fun s => { s with generatorStack := s.generatorStack.pop }
else do
let key := gNode.key
let idx := gNode.currInstanceIdx - 1
let inst := gNode.instances.get! idx
let mctx := gNode.mctx
let mvar := gNode.mvar
trace[Meta.synthInstance.generate] "instance {inst}"
modifyTop fun gNode => { gNode with currInstanceIdx := idx }
match (← tryResolve mctx mvar inst) with
| none => pure ()
| some (mctx, subgoals) => consume { key := key, mvar := mvar, subgoals := subgoals, mctx := mctx, size := 0 }
def getNextToResume : SynthM (ConsumerNode × Answer) := do
let s ← get
let r := s.resumeStack.back
modify fun s => { s with resumeStack := s.resumeStack.pop }
pure r
/--
Given `(cNode, answer)` on the top of the resume stack, continue execution by using `answer` to solve the
next subgoal. -/
def resume : SynthM Unit := do
let (cNode, answer) ← getNextToResume
match cNode.subgoals with
| [] => panic! "resume found no remaining subgoals"
| mvar::rest =>
match (← tryAnswer cNode.mctx mvar answer) with
| none => pure ()
| some mctx =>
withMCtx mctx <| traceM `Meta.synthInstance.resume do
let goal ← inferType cNode.mvar
let subgoal ← inferType mvar
pure m!"size: {cNode.size + answer.size}, {goal} <== {subgoal}"
consume { key := cNode.key, mvar := cNode.mvar, subgoals := rest, mctx := mctx, size := cNode.size + answer.size }
def step : SynthM Bool := do
checkMaxHeartbeats
let s ← get
if !s.resumeStack.isEmpty then
resume
pure true
else if !s.generatorStack.isEmpty then
generate
pure true
else
pure false
def getResult : SynthM (Option Expr) := do
pure (← get).result
partial def synth : SynthM (Option Expr) := do
if (← step) then
match (← getResult) with
| none => synth
| some result => pure result
else
trace[Meta.synthInstance] "failed"
pure none
def main (type : Expr) (maxResultSize : Nat) : MetaM (Option Expr) :=
withCurrHeartbeats <| traceCtx `Meta.synthInstance do
trace[Meta.synthInstance] "main goal {type}"
let mvar ← mkFreshExprMVar type
let mctx ← getMCtx
let key := mkTableKey mctx type
let action : SynthM (Option Expr) := do
newSubgoal mctx key mvar Waiter.root
synth
action.run { maxResultSize := maxResultSize, maxHeartbeats := getMaxHeartbeats (← getOptions) } |>.run' {}
end SynthInstance
/-
Type class parameters can be annotated with `outParam` annotations.
Given `C a_1 ... a_n`, we replace `a_i` with a fresh metavariable `?m_i` IF
`a_i` is an `outParam`.
The result is type correct because we reject type class declarations IF
it contains a regular parameter X that depends on an `out` parameter Y.
Then, we execute type class resolution as usual.
If it succeeds, and metavariables ?m_i have been assigned, we try to unify
the original type `C a_1 ... a_n` witht the normalized one.
-/
private def preprocess (type : Expr) : MetaM Expr :=
forallTelescopeReducing type fun xs type => do
let type ← whnf type
mkForallFVars xs type
private def preprocessLevels (us : List Level) : MetaM (List Level × Bool) := do
let mut r := #[]
let mut modified := false
for u in us do
let u ← instantiateLevelMVars u
if u.hasMVar then
r := r.push (← mkFreshLevelMVar)
modified := true
else
r := r.push u
return (r.toList, modified)
private partial def preprocessArgs (type : Expr) (i : Nat) (args : Array Expr) : MetaM (Array Expr) := do
if h : i < args.size then
let type ← whnf type
match type with
| Expr.forallE _ d b _ => do
let arg := args.get ⟨i, h⟩
let arg ← if isOutParam d then mkFreshExprMVar d else pure arg
let args := args.set ⟨i, h⟩ arg
preprocessArgs (b.instantiate1 arg) (i+1) args
| _ =>
throwError "type class resolution failed, insufficient number of arguments" -- TODO improve error message
else
return args
private def preprocessOutParam (type : Expr) : MetaM Expr :=
forallTelescope type fun xs typeBody => do
match typeBody.getAppFn with
| c@(Expr.const constName us _) =>
let env ← getEnv
if !hasOutParams env constName then
return type
else
let args := typeBody.getAppArgs
let cType ← inferType c
let args ← preprocessArgs cType 0 args
mkForallFVars xs (mkAppN c args)
| _ =>
return type
/-
Remark: when `maxResultSize? == none`, the configuration option `synthInstance.maxResultSize` is used.
Remark: we use a different option for controlling the maximum result size for coercions.
-/
def synthInstance? (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (Option Expr) := do profileitM Exception "typeclass inference" (← getOptions) do
let opts ← getOptions
let maxResultSize := maxResultSize?.getD (synthInstance.maxSize.get opts)
let inputConfig ← getConfig
withConfig (fun config => { config with isDefEqStuckEx := true, transparency := TransparencyMode.instances,
foApprox := true, ctxApprox := true, constApprox := false,
ignoreLevelMVarDepth := true }) do
let type ← instantiateMVars type
let type ← preprocess type
let s ← get
match s.cache.synthInstance.find? type with
| some result => pure result
| none =>
let result? ← withNewMCtxDepth do
let normType ← preprocessOutParam type
trace[Meta.synthInstance] "preprocess: {type} ==> {normType}"
match (← SynthInstance.main normType maxResultSize) with
| none => pure none
| some result =>
trace[Meta.synthInstance] "FOUND result {result}"
let result ← instantiateMVars result
if (← hasAssignableMVar result) then
trace[Meta.synthInstance] "Failed has assignable mvar {result.setOption `pp.all true}"
pure none
else
pure (some result)
let result? ← match result? with
| none => pure none
| some result => do
trace[Meta.synthInstance] "result {result}"
let resultType ← inferType result
if (← withConfig (fun _ => inputConfig) <| isDefEq type resultType) then
let result ← instantiateMVars result
pure (some result)
else
trace[Meta.synthInstance] "result type{indentExpr resultType}\nis not definitionally equal to{indentExpr type}"
pure none
if type.hasMVar then
pure result?
else do
modify fun s => { s with cache := { s.cache with synthInstance := s.cache.synthInstance.insert type result? } }
pure result?
/--
Return `LOption.some r` if succeeded, `LOption.none` if it failed, and `LOption.undef` if
instance cannot be synthesized right now because `type` contains metavariables. -/
def trySynthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (LOption Expr) := do
catchInternalId isDefEqStuckExceptionId
(toLOptionM <| synthInstance? type maxResultSize?)
(fun _ => pure LOption.undef)
def synthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM Expr :=
catchInternalId isDefEqStuckExceptionId
(do
let result? ← synthInstance? type maxResultSize?
match result? with
| some result => pure result
| none => throwError "failed to synthesize{indentExpr type}")
(fun _ => throwError "failed to synthesize{indentExpr type}")
@[export lean_synth_pending]
private def synthPendingImp (mvarId : MVarId) : MetaM Bool := withIncRecDepth <| withMVarContext mvarId do
let mvarDecl ← getMVarDecl mvarId
match mvarDecl.kind with
| MetavarKind.syntheticOpaque =>
return false
| _ =>
/- Check whether the type of the given metavariable is a class or not. If yes, then try to synthesize
it using type class resolution. We only do it for `synthetic` and `natural` metavariables. -/
match (← isClass? mvarDecl.type) with
| none =>
return false
| some _ =>
/- TODO: use a configuration option instead of the hard-coded limit `1`. -/
if (← read).synthPendingDepth > 1 then
trace[Meta.synthPending] "too many nested synthPending invocations"
return false
else
withReader (fun ctx => { ctx with synthPendingDepth := ctx.synthPendingDepth + 1 }) do
trace[Meta.synthPending] "synthPending {mkMVar mvarId}"
let val? ← catchInternalId isDefEqStuckExceptionId (synthInstance? mvarDecl.type (maxResultSize? := none)) (fun _ => pure none)
match val? with
| none =>
return false
| some val =>
if (← isExprMVarAssigned mvarId) then
return false
else
assignExprMVar mvarId val
return true
builtin_initialize
registerTraceClass `Meta.synthInstance
registerTraceClass `Meta.synthInstance.globalInstances
registerTraceClass `Meta.synthInstance.newSubgoal
registerTraceClass `Meta.synthInstance.tryResolve
registerTraceClass `Meta.synthInstance.resume
registerTraceClass `Meta.synthInstance.generate
registerTraceClass `Meta.synthPending
end Lean.Meta
|
349594f6c200bdd15d4fedf4ceea9ca9f62406b2 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/set/intervals/unordered_interval_auto.lean | 138ea9aa0f3087e96abecba4374cf63749a55d75 | [] | 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 | 10,491 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.order.bounds
import Mathlib.data.set.intervals.image_preimage
import Mathlib.PostPort
universes u
namespace Mathlib
/-!
# Intervals without endpoints ordering
In any decidable linear order `α`, we define the set of elements lying between two elements `a` and
`b` as `Icc (min a b) (max a b)`.
`Icc a b` requires the assumption `a ≤ b` to be meaningful, which is sometimes inconvenient. The
interval as defined in this file is always the set of things lying between `a` and `b`, regardless
of the relative order of `a` and `b`.
For real numbers, `Icc (min a b) (max a b)` is the same as `segment a b`.
## Notation
We use the localized notation `[a, b]` for `interval a b`. One can open the locale `interval` to
make the notation available.
-/
namespace set
/-- `interval a b` is the set of elements lying between `a` and `b`, with `a` and `b` included. -/
def interval {α : Type u} [linear_order α] (a : α) (b : α) : set α := Icc (min a b) (max a b)
@[simp] theorem interval_of_le {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) :
interval a b = Icc a b :=
eq.mpr (id (Eq._oldrec (Eq.refl (interval a b = Icc a b)) (interval.equations._eqn_1 a b)))
(eq.mpr (id (Eq._oldrec (Eq.refl (Icc (min a b) (max a b) = Icc a b)) (min_eq_left h)))
(eq.mpr (id (Eq._oldrec (Eq.refl (Icc a (max a b) = Icc a b)) (max_eq_right h)))
(Eq.refl (Icc a b))))
@[simp] theorem interval_of_ge {α : Type u} [linear_order α] {a : α} {b : α} (h : b ≤ a) :
interval a b = Icc b a :=
eq.mpr (id (Eq._oldrec (Eq.refl (interval a b = Icc b a)) (interval.equations._eqn_1 a b)))
(eq.mpr (id (Eq._oldrec (Eq.refl (Icc (min a b) (max a b) = Icc b a)) (min_eq_right h)))
(eq.mpr (id (Eq._oldrec (Eq.refl (Icc b (max a b) = Icc b a)) (max_eq_left h)))
(Eq.refl (Icc b a))))
theorem interval_swap {α : Type u} [linear_order α] (a : α) (b : α) : interval a b = interval b a :=
sorry
theorem interval_of_lt {α : Type u} [linear_order α] {a : α} {b : α} (h : a < b) :
interval a b = Icc a b :=
interval_of_le (le_of_lt h)
theorem interval_of_gt {α : Type u} [linear_order α] {a : α} {b : α} (h : b < a) :
interval a b = Icc b a :=
interval_of_ge (le_of_lt h)
theorem interval_of_not_le {α : Type u} [linear_order α] {a : α} {b : α} (h : ¬a ≤ b) :
interval a b = Icc b a :=
interval_of_gt (lt_of_not_ge h)
theorem interval_of_not_ge {α : Type u} [linear_order α] {a : α} {b : α} (h : ¬b ≤ a) :
interval a b = Icc a b :=
interval_of_lt (lt_of_not_ge h)
@[simp] theorem interval_self {α : Type u} [linear_order α] {a : α} : interval a a = singleton a :=
sorry
@[simp] theorem nonempty_interval {α : Type u} [linear_order α] {a : α} {b : α} :
set.nonempty (interval a b) :=
sorry
@[simp] theorem left_mem_interval {α : Type u} [linear_order α] {a : α} {b : α} :
a ∈ interval a b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ interval a b)) (interval.equations._eqn_1 a b)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ Icc (min a b) (max a b))) (propext mem_Icc)))
{ left := min_le_left a b, right := le_max_left a b })
@[simp] theorem right_mem_interval {α : Type u} [linear_order α] {a : α} {b : α} :
b ∈ interval a b :=
eq.mpr (id (Eq._oldrec (Eq.refl (b ∈ interval a b)) (interval_swap a b))) left_mem_interval
theorem Icc_subset_interval {α : Type u} [linear_order α] {a : α} {b : α} :
Icc a b ⊆ interval a b :=
id
fun (x : α) (h : x ∈ Icc a b) =>
eq.mpr
(id
(Eq._oldrec (Eq.refl (x ∈ interval a b))
(interval_of_le (le_trans (and.left h) (and.right h)))))
h
theorem Icc_subset_interval' {α : Type u} [linear_order α] {a : α} {b : α} :
Icc b a ⊆ interval a b :=
eq.mpr (id (Eq._oldrec (Eq.refl (Icc b a ⊆ interval a b)) (interval_swap a b)))
Icc_subset_interval
theorem mem_interval_of_le {α : Type u} [linear_order α] {a : α} {b : α} {x : α} (ha : a ≤ x)
(hb : x ≤ b) : x ∈ interval a b :=
Icc_subset_interval { left := ha, right := hb }
theorem mem_interval_of_ge {α : Type u} [linear_order α] {a : α} {b : α} {x : α} (hb : b ≤ x)
(ha : x ≤ a) : x ∈ interval a b :=
Icc_subset_interval' { left := hb, right := ha }
theorem interval_subset_interval {α : Type u} [linear_order α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(h₁ : a₁ ∈ interval a₂ b₂) (h₂ : b₁ ∈ interval a₂ b₂) : interval a₁ b₁ ⊆ interval a₂ b₂ :=
Icc_subset_Icc (le_min (and.left h₁) (and.left h₂)) (max_le (and.right h₁) (and.right h₂))
theorem interval_subset_interval_iff_mem {α : Type u} [linear_order α] {a₁ : α} {a₂ : α} {b₁ : α}
{b₂ : α} : interval a₁ b₁ ⊆ interval a₂ b₂ ↔ a₁ ∈ interval a₂ b₂ ∧ b₁ ∈ interval a₂ b₂ :=
{ mp :=
fun (h : interval a₁ b₁ ⊆ interval a₂ b₂) =>
{ left := h left_mem_interval, right := h right_mem_interval },
mpr :=
fun (h : a₁ ∈ interval a₂ b₂ ∧ b₁ ∈ interval a₂ b₂) =>
interval_subset_interval (and.left h) (and.right h) }
theorem interval_subset_interval_iff_le {α : Type u} [linear_order α] {a₁ : α} {a₂ : α} {b₁ : α}
{b₂ : α} : interval a₁ b₁ ⊆ interval a₂ b₂ ↔ min a₂ b₂ ≤ min a₁ b₁ ∧ max a₁ b₁ ≤ max a₂ b₂ :=
sorry
theorem interval_subset_interval_right {α : Type u} [linear_order α] {a : α} {b : α} {x : α}
(h : x ∈ interval a b) : interval x b ⊆ interval a b :=
interval_subset_interval h right_mem_interval
theorem interval_subset_interval_left {α : Type u} [linear_order α] {a : α} {b : α} {x : α}
(h : x ∈ interval a b) : interval a x ⊆ interval a b :=
interval_subset_interval left_mem_interval h
theorem bdd_below_bdd_above_iff_subset_interval {α : Type u} [linear_order α] (s : set α) :
bdd_below s ∧ bdd_above s ↔ ∃ (a : α), ∃ (b : α), s ⊆ interval a b :=
sorry
@[simp] theorem preimage_const_add_interval {α : Type u} [linear_ordered_add_comm_group α] (a : α)
(b : α) (c : α) : (fun (x : α) => a + x) ⁻¹' interval b c = interval (b - a) (c - a) :=
sorry
@[simp] theorem preimage_add_const_interval {α : Type u} [linear_ordered_add_comm_group α] (a : α)
(b : α) (c : α) : (fun (x : α) => x + a) ⁻¹' interval b c = interval (b - a) (c - a) :=
sorry
@[simp] theorem preimage_neg_interval {α : Type u} [linear_ordered_add_comm_group α] (a : α)
(b : α) : -interval a b = interval (-a) (-b) :=
sorry
@[simp] theorem preimage_sub_const_interval {α : Type u} [linear_ordered_add_comm_group α] (a : α)
(b : α) (c : α) : (fun (x : α) => x - a) ⁻¹' interval b c = interval (b + a) (c + a) :=
sorry
@[simp] theorem preimage_const_sub_interval {α : Type u} [linear_ordered_add_comm_group α] (a : α)
(b : α) (c : α) : (fun (x : α) => a - x) ⁻¹' interval b c = interval (a - b) (a - c) :=
sorry
@[simp] theorem image_const_add_interval {α : Type u} [linear_ordered_add_comm_group α] (a : α)
(b : α) (c : α) : (fun (x : α) => a + x) '' interval b c = interval (a + b) (a + c) :=
sorry
@[simp] theorem image_add_const_interval {α : Type u} [linear_ordered_add_comm_group α] (a : α)
(b : α) (c : α) : (fun (x : α) => x + a) '' interval b c = interval (b + a) (c + a) :=
sorry
@[simp] theorem image_const_sub_interval {α : Type u} [linear_ordered_add_comm_group α] (a : α)
(b : α) (c : α) : (fun (x : α) => a - x) '' interval b c = interval (a - b) (a - c) :=
sorry
@[simp] theorem image_sub_const_interval {α : Type u} [linear_ordered_add_comm_group α] (a : α)
(b : α) (c : α) : (fun (x : α) => x - a) '' interval b c = interval (b - a) (c - a) :=
sorry
theorem image_neg_interval {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) :
Neg.neg '' interval a b = interval (-a) (-b) :=
sorry
/-- If `[x, y]` is a subinterval of `[a, b]`, then the distance between `x` and `y`
is less than or equal to that of `a` and `b` -/
theorem abs_sub_le_of_subinterval {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α}
{x : α} {y : α} (h : interval x y ⊆ interval a b) : abs (y - x) ≤ abs (b - a) :=
sorry
/-- If `x ∈ [a, b]`, then the distance between `a` and `x` is less than or equal to
that of `a` and `b` -/
theorem abs_sub_left_of_mem_interval {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α}
{x : α} (h : x ∈ interval a b) : abs (x - a) ≤ abs (b - a) :=
abs_sub_le_of_subinterval (interval_subset_interval_left h)
/-- If `x ∈ [a, b]`, then the distance between `x` and `b` is less than or equal to
that of `a` and `b` -/
theorem abs_sub_right_of_mem_interval {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α}
{x : α} (h : x ∈ interval a b) : abs (b - x) ≤ abs (b - a) :=
abs_sub_le_of_subinterval (interval_subset_interval_right h)
@[simp] theorem preimage_mul_const_interval {k : Type u} [linear_ordered_field k] {a : k}
(ha : a ≠ 0) (b : k) (c : k) :
(fun (x : k) => x * a) ⁻¹' interval b c = interval (b / a) (c / a) :=
sorry
@[simp] theorem preimage_const_mul_interval {k : Type u} [linear_ordered_field k] {a : k}
(ha : a ≠ 0) (b : k) (c : k) :
(fun (x : k) => a * x) ⁻¹' interval b c = interval (b / a) (c / a) :=
sorry
@[simp] theorem preimage_div_const_interval {k : Type u} [linear_ordered_field k] {a : k}
(ha : a ≠ 0) (b : k) (c : k) :
(fun (x : k) => x / a) ⁻¹' interval b c = interval (b * a) (c * a) :=
sorry
@[simp] theorem image_mul_const_interval {k : Type u} [linear_ordered_field k] (a : k) (b : k)
(c : k) : (fun (x : k) => x * a) '' interval b c = interval (b * a) (c * a) :=
sorry
@[simp] theorem image_const_mul_interval {k : Type u} [linear_ordered_field k] (a : k) (b : k)
(c : k) : (fun (x : k) => a * x) '' interval b c = interval (a * b) (a * c) :=
sorry
@[simp] theorem image_div_const_interval {k : Type u} [linear_ordered_field k] (a : k) (b : k)
(c : k) : (fun (x : k) => x / a) '' interval b c = interval (b / a) (c / a) :=
image_mul_const_interval (a⁻¹) b c
end Mathlib |
9b3a86bd3874b7973aa323a21c9f94b670b75b3b | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /library/data/rat/order.lean | 0d534ca715780ce77f75baa28361a877bd38efc8 | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,927 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
Adds the ordering, and instantiates the rationals as an ordered field.
-/
import data.int algebra.ordered_field .basic
open quot eq.ops
/- the ordering on representations -/
namespace prerat
section int_notation
open int
variables {a b : prerat}
definition pos (a : prerat) : Prop := num a > 0
definition nonneg (a : prerat) : Prop := num a ≥ 0
theorem pos_of_int (a : ℤ) : pos (of_int a) ↔ (#int a > 0) :=
!iff.rfl
theorem nonneg_of_int (a : ℤ) : nonneg (of_int a) ↔ (#int a ≥ 0) :=
!iff.rfl
theorem pos_eq_pos_of_equiv {a b : prerat} (H1 : a ≡ b) : pos a = pos b :=
propext (iff.intro (num_pos_of_equiv H1) (num_pos_of_equiv H1⁻¹))
theorem nonneg_eq_nonneg_of_equiv (H : a ≡ b) : nonneg a = nonneg b :=
have H1 : (0 = num a) = (0 = num b),
from propext (iff.intro
(assume H2, eq.symm (num_eq_zero_of_equiv H H2⁻¹))
(assume H2, eq.symm (num_eq_zero_of_equiv H⁻¹ H2⁻¹))),
calc
nonneg a = (pos a ∨ 0 = num a) : propext !le_iff_lt_or_eq
... = (pos b ∨ 0 = num a) : pos_eq_pos_of_equiv H
... = (pos b ∨ 0 = num b) : H1
... = nonneg b : propext !le_iff_lt_or_eq
theorem nonneg_zero : nonneg zero := le.refl 0
theorem nonneg_add (H1 : nonneg a) (H2 : nonneg b) : nonneg (add a b) :=
show num a * denom b + num b * denom a ≥ 0,
from add_nonneg
(mul_nonneg H1 (le_of_lt (denom_pos b)))
(mul_nonneg H2 (le_of_lt (denom_pos a)))
theorem nonneg_antisymm (H1 : nonneg a) (H2 : nonneg (neg a)) : a ≡ zero :=
have H3 : num a = 0, from le.antisymm (nonpos_of_neg_nonneg H2) H1,
equiv_zero_of_num_eq_zero H3
theorem nonneg_total (a : prerat) : nonneg a ∨ nonneg (neg a) :=
or.elim (le.total 0 (num a))
(suppose 0 ≤ num a, or.inl this)
(suppose 0 ≥ num a, or.inr (neg_nonneg_of_nonpos this))
theorem nonneg_of_pos (H : pos a) : nonneg a := le_of_lt H
theorem ne_zero_of_pos (H : pos a) : ¬ a ≡ zero :=
assume H', ne_of_gt H (num_eq_zero_of_equiv_zero H')
theorem pos_of_nonneg_of_ne_zero (H1 : nonneg a) (H2 : ¬ a ≡ zero) : pos a :=
have num a ≠ 0, from suppose num a = 0, H2 (equiv_zero_of_num_eq_zero this),
lt_of_le_of_ne H1 (ne.symm this)
theorem nonneg_mul (H1 : nonneg a) (H2 : nonneg b) : nonneg (mul a b) :=
mul_nonneg H1 H2
theorem pos_mul (H1 : pos a) (H2 : pos b) : pos (mul a b) :=
mul_pos H1 H2
end int_notation
end prerat
local attribute prerat.setoid [instance]
/- The ordering on the rationals.
The definitions of pos and nonneg are kept private, because they are only meant for internal
use. Users should use a > 0 and a ≥ 0 instead of pos and nonneg.
-/
namespace rat
variables {a b c : ℚ}
/- transfer properties of pos and nonneg -/
private definition pos (a : ℚ) : Prop :=
quot.lift prerat.pos @prerat.pos_eq_pos_of_equiv a
private definition nonneg (a : ℚ) : Prop :=
quot.lift prerat.nonneg @prerat.nonneg_eq_nonneg_of_equiv a
private theorem pos_of_int (a : ℤ) : (#int a > 0) ↔ pos (of_int a) :=
prerat.pos_of_int a
private theorem nonneg_of_int (a : ℤ) : (#int a ≥ 0) ↔ nonneg (of_int a) :=
prerat.nonneg_of_int a
private theorem nonneg_zero : nonneg 0 := prerat.nonneg_zero
private theorem nonneg_add : nonneg a → nonneg b → nonneg (a + b) :=
quot.induction_on₂ a b @prerat.nonneg_add
private theorem nonneg_antisymm : nonneg a → nonneg (-a) → a = 0 :=
quot.induction_on a
(take u, assume H1 H2,
quot.sound (prerat.nonneg_antisymm H1 H2))
private theorem nonneg_total (a : ℚ) : nonneg a ∨ nonneg (-a) :=
quot.induction_on a @prerat.nonneg_total
private theorem nonneg_of_pos : pos a → nonneg a :=
quot.induction_on a @prerat.nonneg_of_pos
private theorem ne_zero_of_pos : pos a → a ≠ 0 :=
quot.induction_on a (take u, assume H1 H2, prerat.ne_zero_of_pos H1 (quot.exact H2))
private theorem pos_of_nonneg_of_ne_zero : nonneg a → ¬ a = 0 → pos a :=
quot.induction_on a
(take u,
assume h : nonneg ⟦u⟧,
suppose ⟦u⟧ ≠ (rat.of_num 0),
have ¬ (prerat.equiv u prerat.zero), from assume H, this (quot.sound H),
prerat.pos_of_nonneg_of_ne_zero h this)
private theorem nonneg_mul : nonneg a → nonneg b → nonneg (a * b) :=
quot.induction_on₂ a b @prerat.nonneg_mul
private theorem pos_mul : pos a → pos b → pos (a * b) :=
quot.induction_on₂ a b @prerat.pos_mul
private definition decidable_pos (a : ℚ) : decidable (pos a) :=
quot.rec_on_subsingleton a (take u, int.decidable_lt 0 (prerat.num u))
/- define order in terms of pos and nonneg -/
definition lt (a b : ℚ) : Prop := pos (b - a)
definition le (a b : ℚ) : Prop := nonneg (b - a)
definition gt [reducible] (a b : ℚ) := lt b a
definition ge [reducible] (a b : ℚ) := le b a
infix [priority rat.prio] < := rat.lt
infix [priority rat.prio] <= := rat.le
infix [priority rat.prio] ≤ := rat.le
infix [priority rat.prio] >= := rat.ge
infix [priority rat.prio] ≥ := rat.ge
infix [priority rat.prio] > := rat.gt
theorem of_int_lt_of_int_iff (a b : ℤ) : of_int a < of_int b ↔ (#int a < b) :=
iff.symm (calc
(#int a < b) ↔ (#int b - a > 0) : iff.symm !int.sub_pos_iff_lt
... ↔ pos (of_int (#int b - a)) : iff.symm !pos_of_int
... ↔ pos (of_int b - of_int a) : !of_int_sub ▸ iff.rfl
... ↔ of_int a < of_int b : iff.rfl)
theorem of_int_lt_of_int_of_lt {a b : ℤ} (H : (#int a < b)) : of_int a < of_int b :=
iff.mpr !of_int_lt_of_int_iff H
theorem lt_of_of_int_lt_of_int {a b : ℤ} (H : of_int a < of_int b) : (#int a < b) :=
iff.mp !of_int_lt_of_int_iff H
theorem of_int_le_of_int_iff (a b : ℤ) : of_int a ≤ of_int b ↔ (#int a ≤ b) :=
iff.symm (calc
(#int a ≤ b) ↔ (#int b - a ≥ 0) : iff.symm !int.sub_nonneg_iff_le
... ↔ nonneg (of_int (#int b - a)) : iff.symm !nonneg_of_int
... ↔ nonneg (of_int b - of_int a) : !of_int_sub ▸ iff.rfl
... ↔ of_int a ≤ of_int b : iff.rfl)
theorem of_int_le_of_int_of_le {a b : ℤ} (H : (#int a ≤ b)) : of_int a ≤ of_int b :=
iff.mpr !of_int_le_of_int_iff H
theorem le_of_of_int_le_of_int {a b : ℤ} (H : of_int a ≤ of_int b) : (#int a ≤ b) :=
iff.mp !of_int_le_of_int_iff H
theorem of_nat_lt_of_nat_iff (a b : ℕ) : of_nat a < of_nat b ↔ (#nat a < b) :=
by rewrite [*of_nat_eq, of_int_lt_of_int_iff, int.of_nat_lt_of_nat_iff]
theorem of_nat_lt_of_nat_of_lt {a b : ℕ} (H : (#nat a < b)) : of_nat a < of_nat b :=
iff.mpr !of_nat_lt_of_nat_iff H
theorem lt_of_of_nat_lt_of_nat {a b : ℕ} (H : of_nat a < of_nat b) : (#nat a < b) :=
iff.mp !of_nat_lt_of_nat_iff H
theorem of_nat_le_of_nat_iff (a b : ℕ) : of_nat a ≤ of_nat b ↔ (#nat a ≤ b) :=
by rewrite [*of_nat_eq, of_int_le_of_int_iff, int.of_nat_le_of_nat_iff]
theorem of_nat_le_of_nat_of_le {a b : ℕ} (H : (#nat a ≤ b)) : of_nat a ≤ of_nat b :=
iff.mpr !of_nat_le_of_nat_iff H
theorem le_of_of_nat_le_of_nat {a b : ℕ} (H : of_nat a ≤ of_nat b) : (#nat a ≤ b) :=
iff.mp !of_nat_le_of_nat_iff H
theorem of_nat_nonneg (a : ℕ) : (of_nat a ≥ 0) :=
of_nat_le_of_nat_of_le !nat.zero_le
theorem le.refl (a : ℚ) : a ≤ a :=
by rewrite [↑rat.le, sub_self]; apply nonneg_zero
theorem le.trans (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c :=
assert H3 : nonneg (c - b + (b - a)), from nonneg_add H2 H1,
begin
revert H3,
rewrite [↑rat.sub, add.assoc, neg_add_cancel_left],
intro H3, apply H3
end
theorem le.antisymm (H1 : a ≤ b) (H2 : b ≤ a) : a = b :=
have H3 : nonneg (-(a - b)), from !neg_sub⁻¹ ▸ H1,
have H4 : a - b = 0, from nonneg_antisymm H2 H3,
eq_of_sub_eq_zero H4
theorem le.total (a b : ℚ) : a ≤ b ∨ b ≤ a :=
or.elim (nonneg_total (b - a))
(assume H, or.inl H)
(assume H, or.inr (!neg_sub ▸ H))
theorem le.by_cases {P : Prop} (a b : ℚ) (H : a ≤ b → P) (H2 : b ≤ a → P) : P :=
or.elim (!rat.le.total) H H2
theorem lt_iff_le_and_ne (a b : ℚ) : a < b ↔ a ≤ b ∧ a ≠ b :=
iff.intro
(assume H : a < b,
have b - a ≠ 0, from ne_zero_of_pos H,
have a ≠ b, from ne.symm (assume H', this (H' ▸ !sub_self)),
and.intro (nonneg_of_pos H) this)
(assume H : a ≤ b ∧ a ≠ b,
obtain aleb aneb, from H,
have b - a ≠ 0, from (assume H', aneb (eq_of_sub_eq_zero H')⁻¹),
pos_of_nonneg_of_ne_zero aleb this)
theorem le_iff_lt_or_eq (a b : ℚ) : a ≤ b ↔ a < b ∨ a = b :=
iff.intro
(assume h : a ≤ b,
decidable.by_cases
(suppose a = b, or.inr this)
(suppose a ≠ b, or.inl (iff.mpr !lt_iff_le_and_ne (and.intro h this))))
(suppose a < b ∨ a = b,
or.elim this
(suppose a < b, and.left (iff.mp !lt_iff_le_and_ne this))
(suppose a = b, this ▸ !le.refl))
private theorem to_nonneg : a ≥ 0 → nonneg a :=
by intros; rewrite -sub_zero; eassumption
theorem add_le_add_left (H : a ≤ b) (c : ℚ) : c + a ≤ c + b :=
have c + b - (c + a) = b - a,
by rewrite [↑sub, neg_add, -add.assoc, add.comm c, add_neg_cancel_right],
show nonneg (c + b - (c + a)), from this⁻¹ ▸ H
theorem mul_nonneg (H1 : a ≥ (0 : ℚ)) (H2 : b ≥ (0 : ℚ)) : a * b ≥ (0 : ℚ) :=
have nonneg (a * b), from nonneg_mul (to_nonneg H1) (to_nonneg H2),
!sub_zero⁻¹ ▸ this
private theorem to_pos : a > 0 → pos a :=
by intros; rewrite -sub_zero; eassumption
theorem mul_pos (H1 : a > (0 : ℚ)) (H2 : b > (0 : ℚ)) : a * b > (0 : ℚ) :=
have pos (a * b), from pos_mul (to_pos H1) (to_pos H2),
!sub_zero⁻¹ ▸ this
definition decidable_lt [instance] : decidable_rel rat.lt :=
take a b, decidable_pos (b - a)
theorem le_of_lt (H : a < b) : a ≤ b := iff.mpr !le_iff_lt_or_eq (or.inl H)
theorem lt_irrefl (a : ℚ) : ¬ a < a :=
take Ha,
let Hand := (iff.mp !lt_iff_le_and_ne) Ha in
(and.right Hand) rfl
theorem not_le_of_gt (H : a < b) : ¬ b ≤ a :=
assume Hba,
let Heq := le.antisymm (le_of_lt H) Hba in
!lt_irrefl (Heq ▸ H)
theorem lt_of_lt_of_le (Hab : a < b) (Hbc : b ≤ c) : a < c :=
let Hab' := le_of_lt Hab in
let Hac := le.trans Hab' Hbc in
(iff.mpr !lt_iff_le_and_ne) (and.intro Hac
(assume Heq, not_le_of_gt (Heq ▸ Hab) Hbc))
theorem lt_of_le_of_lt (Hab : a ≤ b) (Hbc : b < c) : a < c :=
let Hbc' := le_of_lt Hbc in
let Hac := le.trans Hab Hbc' in
(iff.mpr !lt_iff_le_and_ne) (and.intro Hac
(assume Heq, not_le_of_gt (Heq⁻¹ ▸ Hbc) Hab))
theorem zero_lt_one : (0 : ℚ) < 1 := trivial
theorem add_lt_add_left (H : a < b) (c : ℚ) : c + a < c + b :=
let H' := le_of_lt H in
(iff.mpr (lt_iff_le_and_ne _ _)) (and.intro (add_le_add_left H' _)
(take Heq, let Heq' := add_left_cancel Heq in
!lt_irrefl (Heq' ▸ H)))
section migrate_algebra
open [classes] algebra
protected definition discrete_linear_ordered_field [reducible] :
algebra.discrete_linear_ordered_field rat :=
⦃algebra.discrete_linear_ordered_field,
rat.discrete_field,
le_refl := le.refl,
le_trans := @le.trans,
le_antisymm := @le.antisymm,
le_total := @le.total,
le_of_lt := @le_of_lt,
lt_irrefl := lt_irrefl,
lt_of_lt_of_le := @lt_of_lt_of_le,
lt_of_le_of_lt := @lt_of_le_of_lt,
le_iff_lt_or_eq := @le_iff_lt_or_eq,
add_le_add_left := @add_le_add_left,
mul_nonneg := @mul_nonneg,
mul_pos := @mul_pos,
decidable_lt := @decidable_lt,
zero_lt_one := zero_lt_one,
add_lt_add_left := @add_lt_add_left⦄
local attribute rat.discrete_linear_ordered_field [trans-instance]
local attribute rat.discrete_field [instance]
definition min : ℚ → ℚ → ℚ := algebra.min
definition max : ℚ → ℚ → ℚ := algebra.max
definition abs : ℚ → ℚ := algebra.abs
definition sign : ℚ → ℚ := algebra.sign
migrate from algebra with rat
hiding dvd, dvd.elim, dvd.elim_left, dvd.intro, dvd.intro_left, dvd.refl, dvd.trans,
dvd_mul_left, dvd_mul_of_dvd_left, dvd_mul_of_dvd_right, dvd_mul_right, dvd_neg_iff_dvd,
dvd_neg_of_dvd, dvd_of_dvd_neg, dvd_of_mul_left_dvd, dvd_of_mul_left_eq,
dvd_of_mul_right_dvd, dvd_of_mul_right_eq, dvd_of_neg_dvd, dvd_sub, dvd_zero
replacing sub → sub, has_le.ge → ge, has_lt.gt → gt,
divide → divide, max → max, min → min, abs → abs, sign → sign,
nmul → nmul, imul → imul
attribute le.trans lt.trans lt_of_lt_of_le lt_of_le_of_lt ge.trans gt.trans gt_of_gt_of_ge
gt_of_ge_of_gt [trans]
attribute decidable_le [instance]
end migrate_algebra
theorem of_nat_abs (a : ℤ) : abs (of_int a) = of_nat (int.nat_abs a) :=
assert ∀ n : ℕ, of_int (int.neg_succ_of_nat n) = - of_nat (nat.succ n), from λ n, rfl,
int.induction_on a
(take b, abs_of_nonneg !of_nat_nonneg)
(take b, by rewrite [this, abs_neg, abs_of_nonneg !of_nat_nonneg])
theorem eq_zero_of_nonneg_of_forall_lt {x : ℚ} (xnonneg : x ≥ 0) (H : ∀ ε, ε > 0 → x < ε) :
x = 0 :=
decidable.by_contradiction
(suppose x ≠ 0,
have x > 0, from lt_of_le_of_ne xnonneg (ne.symm this),
have x < x, from H x this,
show false, from !lt.irrefl this)
theorem eq_zero_of_nonneg_of_forall_le {x : ℚ} (xnonneg : x ≥ 0) (H : ∀ ε, ε > 0 → x ≤ ε) :
x = 0 :=
have H' : ∀ ε, ε > 0 → x < ε, from
take ε, suppose ε > 0,
have ε / 2 > 0, from div_pos_of_pos_of_pos this two_pos,
have x ≤ ε / 2, from H _ this,
show x < ε, from lt_of_le_of_lt this (rat.div_two_lt_of_pos `ε > 0`),
eq_zero_of_nonneg_of_forall_lt xnonneg H'
theorem eq_zero_of_forall_abs_le {x : ℚ} (H : ∀ ε, ε > 0 → abs x ≤ ε) :
x = 0 :=
decidable.by_contradiction
(suppose x ≠ 0,
have abs x = 0, from eq_zero_of_nonneg_of_forall_le !abs_nonneg H,
show false, from `x ≠ 0` (eq_zero_of_abs_eq_zero this))
theorem eq_of_forall_abs_sub_le {x y : ℚ} (H : ∀ ε, ε > 0 → abs (x - y) ≤ ε) :
x = y :=
have x - y = 0, from eq_zero_of_forall_abs_le H,
eq_of_sub_eq_zero this
section
open int
set_option pp.coercions true
theorem num_nonneg_of_nonneg {q : ℚ} (H : q ≥ 0) : num q ≥ 0 :=
have of_int (num q) ≥ of_int 0,
begin
rewrite [-mul_denom],
apply mul_nonneg H,
rewrite [of_int_le_of_int_iff],
exact int.le_of_lt !denom_pos
end,
show num q ≥ 0, from le_of_of_int_le_of_int this
theorem num_pos_of_pos {q : ℚ} (H : q > 0) : num q > 0 :=
have of_int (num q) > of_int 0,
begin
rewrite [-mul_denom],
apply mul_pos H,
rewrite [of_int_lt_of_int_iff],
exact !denom_pos
end,
show num q > 0, from lt_of_of_int_lt_of_int this
theorem num_neg_of_neg {q : ℚ} (H : q < 0) : num q < 0 :=
have of_int (num q) < of_int 0,
begin
rewrite [-mul_denom],
apply mul_neg_of_neg_of_pos H,
rewrite [of_int_lt_of_int_iff],
exact !denom_pos
end,
show num q < 0, from lt_of_of_int_lt_of_int this
theorem num_nonpos_of_nonpos {q : ℚ} (H : q ≤ 0) : num q ≤ 0 :=
have of_int (num q) ≤ of_int 0,
begin
rewrite [-mul_denom],
apply mul_nonpos_of_nonpos_of_nonneg H,
rewrite [of_int_le_of_int_iff],
exact int.le_of_lt !denom_pos
end,
show num q ≤ 0, from le_of_of_int_le_of_int this
end
definition ubound : ℚ → ℕ := λ a : ℚ, nat.succ (int.nat_abs (num a))
theorem ubound_ge (a : ℚ) : of_nat (ubound a) ≥ a :=
have h : abs a * abs (of_int (denom a)) = abs (of_int (num a)), from
!abs_mul ▸ !mul_denom ▸ rfl,
assert of_int (denom a) > 0, from of_int_lt_of_int_of_lt !denom_pos,
have 1 ≤ abs (of_int (denom a)), begin
rewrite (abs_of_pos this),
apply of_int_le_of_int_of_le,
apply denom_pos
end,
have abs a ≤ abs (of_int (num a)), from
le_of_mul_le_of_ge_one (h ▸ !le.refl) !abs_nonneg this,
calc
a ≤ abs a : le_abs_self
... ≤ abs (of_int (num a)) : this
... ≤ abs (of_int (num a)) + 1 : rat.le_add_of_nonneg_right trivial
... = of_nat (int.nat_abs (num a)) + 1 : of_nat_abs
... = of_nat (nat.succ (int.nat_abs (num a))) : of_nat_add
theorem ubound_pos (a : ℚ) : nat.gt (ubound a) nat.zero := !nat.succ_pos
theorem binary_nat_bound (a : ℕ) : of_nat a ≤ pow 2 a :=
nat.induction_on a (zero_le_one)
(take n, assume Hn,
calc
of_nat (nat.succ n) = (of_nat n) + 1 : of_nat_add
... ≤ pow 2 n + 1 : add_le_add_right Hn
... ≤ pow 2 n + rat.pow 2 n :
add_le_add_left (pow_ge_one_of_ge_one two_ge_one _)
... = pow 2 (nat.succ n) : pow_two_add)
theorem binary_bound (a : ℚ) : ∃ n : ℕ, a ≤ pow 2 n :=
exists.intro (ubound a) (calc
a ≤ of_nat (ubound a) : ubound_ge
... ≤ pow 2 (ubound a) : binary_nat_bound)
end rat
|
b4ab1573782168fba2ff22e8b06cc79d7495c450 | 6e8de6b43162bef473b4a0bd93b71db886df98ce | /src/tactics/macros.lean | 4491b13b6c1dd31ed57c3958b998c0a2d9e1b5e1 | [
"Unlicense"
] | permissive | adamtopaz/comb_geom | 38ec6fde8d2543f56227ec50cdfb86cac6ac33c1 | e16b629d6de3fbdea54a528755e7305dfb51e902 | refs/heads/master | 1,668,613,552,530 | 1,593,199,940,000 | 1,593,199,940,000 | 269,824,442 | 6 | 0 | Unlicense | 1,593,119,545,000 | 1,591,404,975,000 | Lean | UTF-8 | Lean | false | false | 119 | lean | import tactic
/-- A silly macro. -/
meta def tiny_hammer := `[
{finish} <|>
{tidy, done} <|>
{tidy, finish}
] |
a1f1379e8292aa280b8010a70d9fd7795c252651 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/ring_theory/witt_vector/is_poly.lean | 31464ae82f469604943bec476e259e88b09e5d96 | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 23,388 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Robert Y. Lewis
-/
import algebra.ring.ulift
import ring_theory.witt_vector.basic
import data.mv_polynomial.funext
/-!
# The `is_poly` predicate
`witt_vector.is_poly` is a (type-valued) predicate on functions `f : Π R, 𝕎 R → 𝕎 R`.
It asserts that there is a family of polynomials `φ : ℕ → mv_polynomial ℕ ℤ`,
such that the `n`th coefficient of `f x` is equal to `φ n` evaluated on the coefficients of `x`.
Many operations on Witt vectors satisfy this predicate (or an analogue for higher arity functions).
We say that such a function `f` is a *polynomial function*.
The power of satisfying this predicate comes from `is_poly.ext`.
It shows that if `φ` and `ψ` witness that `f` and `g` are polynomial functions,
then `f = g` not merely when `φ = ψ`, but in fact it suffices to prove
```
∀ n, bind₁ φ (witt_polynomial p _ n) = bind₁ ψ (witt_polynomial p _ n)
```
(in other words, when evaluating the Witt polynomials on `φ` and `ψ`, we get the same values)
which will then imply `φ = ψ` and hence `f = g`.
Even though this sufficient condition looks somewhat intimidating,
it is rather pleasant to check in practice;
more so than direct checking of `φ = ψ`.
In practice, we apply this technique to show that the composition of `witt_vector.frobenius`
and `witt_vector.verschiebung` is equal to multiplication by `p`.
## Main declarations
* `witt_vector.is_poly`, `witt_vector.is_poly₂`:
two predicates that assert that a unary/binary function on Witt vectors
is polynomial in the coefficients of the input values.
* `witt_vector.is_poly.ext`, `witt_vector.is_poly₂.ext`:
two polynomial functions are equal if their families of polynomials are equal
after evaluating the Witt polynmials on them.
* `witt_vector.is_poly.comp` (+ many variants) show that unary/binary compositions
of polynomial functions are polynomial.
* `witt_vector.id_is_poly`, `witt_vector.neg_is_poly`,
`witt_vector.add_is_poly₂`, `witt_vector.mul_is_poly₂`:
several well-known operations are polynomial functions
(for Verschiebung, Frobenius, and multiplication by `p`, see their respective files).
## On higher arity analogues
Ideally, there should be a predicate `is_polyₙ` for functions of higher arity,
together with `is_polyₙ.comp` that shows how such functions compose.
Since mathlib does not have a library on composition of higher arity functions,
we have only implemented the unary and binary variants so far.
Nullary functions (a.k.a. constants) are treated
as constant functions and fall under the unary case.
## Tactics
There are important metaprograms defined in this file:
the tactics `ghost_simp` and `ghost_calc` and the attributes `@[is_poly]` and `@[ghost_simps]`.
These are used in combination to discharge proofs of identities between polynomial functions.
Any atomic proof of `is_poly` or `is_poly₂` (i.e. not taking additional `is_poly` arguments)
should be tagged as `@[is_poly]`.
Any lemma doing "ring equation rewriting" with polynomial functions should be tagged
`@[ghost_simps]`, e.g.
```lean
@[ghost_simps]
lemma bind₁_frobenius_poly_witt_polynomial (n : ℕ) :
bind₁ (frobenius_poly p) (witt_polynomial p ℤ n) = (witt_polynomial p ℤ (n+1))
```
Proofs of identities between polynomial functions will often follow the pattern
```lean
begin
ghost_calc _,
<minor preprocessing>,
ghost_simp
end
```
## References
* [Hazewinkel, *Witt Vectors*][Haze09]
* [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21]
-/
/-
### Simplification tactics
`ghost_simp` is used later in the development for certain simplifications.
We define it here so it is a shared import.
-/
mk_simp_attribute ghost_simps
"Simplification rules for ghost equations"
namespace tactic
namespace interactive
setup_tactic_parser
/-- A macro for a common simplification when rewriting with ghost component equations. -/
meta def ghost_simp (lems : parse simp_arg_list) : tactic unit :=
do tactic.try tactic.intro1,
simp none none tt
(lems ++ [simp_arg_type.symm_expr ``(sub_eq_add_neg)])
[`ghost_simps] (loc.ns [none])
/--
`ghost_calc` is a tactic for proving identities between polynomial functions.
Typically, when faced with a goal like
```lean
∀ (x y : 𝕎 R), verschiebung (x * frobenius y) = verschiebung x * y
```
you can
1. call `ghost_calc`
2. do a small amount of manual work -- maybe nothing, maybe `rintro`, etc
3. call `ghost_simp`
and this will close the goal.
`ghost_calc` cannot detect whether you are dealing with unary or binary polynomial functions.
You must give it arguments to determine this.
If you are proving a universally quantified goal like the above,
call `ghost_calc _ _`.
If the variables are introduced already, call `ghost_calc x y`.
In the unary case, use `ghost_calc _` or `ghost_calc x`.
`ghost_calc` is a light wrapper around type class inference.
All it does is apply the appropriate extensionality lemma and try to infer the resulting goals.
This is subtle and Lean's elaborator doesn't like it because of the HO unification involved,
so it is easier (and prettier) to put it in a tactic script.
-/
meta def ghost_calc (ids' : parse ident_*) : tactic unit :=
do ids ← ids'.mmap $ λ n, get_local n <|> tactic.intro n,
`(@eq (witt_vector _ %%R) _ _) ← target,
match ids with
| [x] := refine ```(is_poly.ext _ _ _ _ %%x)
| [x, y] := refine ```(is_poly₂.ext _ _ _ _ %%x %%y)
| _ := fail "ghost_calc takes one or two arguments"
end,
nm ← match R with
| expr.local_const _ nm _ _ := return nm
| _ := get_unused_name `R
end,
iterate_exactly 2 apply_instance,
unfreezingI (tactic.clear' tt [R]),
introsI $ [nm, nm<.>"_inst"] ++ ids',
skip
end interactive
end tactic
namespace witt_vector
universe variable u
variables {p : ℕ} {R S : Type u} {σ idx : Type*} [hp : fact p.prime] [comm_ring R] [comm_ring S]
local notation `𝕎` := witt_vector p -- type as `\bbW`
local attribute [semireducible] witt_vector
open mv_polynomial
open function (uncurry)
include hp
variables (p)
noncomputable theory
/-!
### The `is_poly` predicate
-/
lemma poly_eq_of_witt_polynomial_bind_eq' (f g : ℕ → mv_polynomial (idx × ℕ) ℤ)
(h : ∀ n, bind₁ f (witt_polynomial p _ n) = bind₁ g (witt_polynomial p _ n)) :
f = g :=
begin
ext1 n,
apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective,
rw ← function.funext_iff at h,
replace h := congr_arg
(λ fam, bind₁ (mv_polynomial.map (int.cast_ring_hom ℚ) ∘ fam)
(X_in_terms_of_W p ℚ n)) h,
simpa only [function.comp, map_bind₁, map_witt_polynomial,
← bind₁_bind₁, bind₁_witt_polynomial_X_in_terms_of_W, bind₁_X_right] using h
end
lemma poly_eq_of_witt_polynomial_bind_eq (f g : ℕ → mv_polynomial ℕ ℤ)
(h : ∀ n, bind₁ f (witt_polynomial p _ n) = bind₁ g (witt_polynomial p _ n)) :
f = g :=
begin
ext1 n,
apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective,
rw ← function.funext_iff at h,
replace h := congr_arg
(λ fam, bind₁ (mv_polynomial.map (int.cast_ring_hom ℚ) ∘ fam)
(X_in_terms_of_W p ℚ n)) h,
simpa only [function.comp, map_bind₁, map_witt_polynomial,
← bind₁_bind₁, bind₁_witt_polynomial_X_in_terms_of_W, bind₁_X_right] using h
end
omit hp
-- Ideally, we would generalise this to n-ary functions
-- But we don't have a good theory of n-ary compositions in mathlib
/--
A function `f : Π R, 𝕎 R → 𝕎 R` that maps Witt vectors to Witt vectors over arbitrary base rings
is said to be *polynomial* if there is a family of polynomials `φₙ` over `ℤ` such that the `n`th
coefficient of `f x` is given by evaluating `φₙ` at the coefficients of `x`.
See also `witt_vector.is_poly₂` for the binary variant.
The `ghost_calc` tactic treats `is_poly` as a type class,
and the `@[is_poly]` attribute derives certain specialized composition instances
for declarations of type `is_poly f`.
For the most part, users are not expected to treat `is_poly` as a class.
-/
class is_poly (f : Π ⦃R⦄ [comm_ring R], witt_vector p R → 𝕎 R) : Prop :=
mk' :: (poly : ∃ φ : ℕ → mv_polynomial ℕ ℤ, ∀ ⦃R⦄ [comm_ring R] (x : 𝕎 R),
by exactI (f x).coeff = λ n, aeval x.coeff (φ n))
/-- The identity function on Witt vectors is a polynomial function. -/
instance id_is_poly : is_poly p (λ _ _, id) :=
⟨⟨X, by { introsI, simp only [aeval_X, id] }⟩⟩
instance id_is_poly_i' : is_poly p (λ _ _ a, a) :=
witt_vector.id_is_poly _
namespace is_poly
instance : inhabited (is_poly p (λ _ _, id)) :=
⟨witt_vector.id_is_poly p⟩
variables {p}
include hp
lemma ext {f g} (hf : is_poly p f) (hg : is_poly p g)
(h : ∀ (R : Type u) [_Rcr : comm_ring R] (x : 𝕎 R) (n : ℕ),
by exactI ghost_component n (f x) = ghost_component n (g x)) :
∀ (R : Type u) [_Rcr : comm_ring R] (x : 𝕎 R), by exactI f x = g x :=
begin
unfreezingI
{ obtain ⟨φ, hf⟩ := hf,
obtain ⟨ψ, hg⟩ := hg },
intros,
ext n,
rw [hf, hg, poly_eq_of_witt_polynomial_bind_eq p φ ψ],
intro k,
apply mv_polynomial.funext,
intro x,
simp only [hom_bind₁],
specialize h (ulift ℤ) (mk p $ λ i, ⟨x i⟩) k,
simp only [ghost_component_apply, aeval_eq_eval₂_hom] at h,
apply (ulift.ring_equiv.{0 u}).symm.injective,
simp only [map_eval₂_hom],
convert h,
all_goals {
funext i,
rw [← ring_equiv.coe_to_ring_hom],
simp only [hf, hg, mv_polynomial.eval, map_eval₂_hom],
apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
ext1,
apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
simp only [coeff_mk], refl }
end
omit hp
/-- The composition of polynomial functions is polynomial. -/
lemma comp {g f} (hg : is_poly p g) (hf : is_poly p f) :
is_poly p (λ R _Rcr, @g R _Rcr ∘ @f R _Rcr) :=
begin
unfreezingI
{ obtain ⟨φ, hf⟩ := hf,
obtain ⟨ψ, hg⟩ := hg },
use (λ n, bind₁ φ (ψ n)),
intros,
simp only [aeval_bind₁, function.comp, hg, hf]
end
end is_poly
/--
A binary function `f : Π R, 𝕎 R → 𝕎 R → 𝕎 R` on Witt vectors
is said to be *polynomial* if there is a family of polynomials `φₙ` over `ℤ` such that the `n`th
coefficient of `f x y` is given by evaluating `φₙ` at the coefficients of `x` and `y`.
See also `witt_vector.is_poly` for the unary variant.
The `ghost_calc` tactic treats `is_poly₂` as a type class,
and the `@[is_poly]` attribute derives certain specialized composition instances
for declarations of type `is_poly₂ f`.
For the most part, users are not expected to treat `is_poly₂` as a class.
-/
class is_poly₂ (f : Π ⦃R⦄ [comm_ring R], witt_vector p R → 𝕎 R → 𝕎 R) : Prop :=
mk' :: (poly : ∃ φ : ℕ → mv_polynomial (fin 2 × ℕ) ℤ, ∀ ⦃R⦄ [comm_ring R] (x y : 𝕎 R),
by exactI (f x y).coeff = λ n, peval (φ n) ![x.coeff, y.coeff])
variable {p}
/-- The composition of polynomial functions is polynomial. -/
lemma is_poly₂.comp {h f g} (hh : is_poly₂ p h) (hf : is_poly p f) (hg : is_poly p g) :
is_poly₂ p (λ R _Rcr x y, by exactI h (f x) (g y)) :=
begin
unfreezingI
{ obtain ⟨φ, hf⟩ := hf,
obtain ⟨ψ, hg⟩ := hg,
obtain ⟨χ, hh⟩ := hh },
refine ⟨⟨(λ n, bind₁ (uncurry $
![λ k, rename (prod.mk (0 : fin 2)) (φ k),
λ k, rename (prod.mk (1 : fin 2)) (ψ k)]) (χ n)), _⟩⟩,
intros,
funext n,
simp only [peval, aeval_bind₁, function.comp, hh, hf, hg, uncurry],
apply eval₂_hom_congr rfl _ rfl,
ext ⟨i, n⟩,
fin_cases i;
simp only [aeval_eq_eval₂_hom, eval₂_hom_rename, function.comp, matrix.cons_val_zero,
matrix.head_cons, matrix.cons_val_one],
end
/-- The composition of a polynomial function with a binary polynomial function is polynomial. -/
lemma is_poly.comp₂ {g f} (hg : is_poly p g) (hf : is_poly₂ p f) :
is_poly₂ p (λ R _Rcr x y, by exactI g (f x y)) :=
begin
unfreezingI
{ obtain ⟨φ, hf⟩ := hf,
obtain ⟨ψ, hg⟩ := hg },
use (λ n, bind₁ φ (ψ n)),
intros,
simp only [peval, aeval_bind₁, function.comp, hg, hf]
end
/-- The diagonal `λ x, f x x` of a polynomial function `f` is polynomial. -/
lemma is_poly₂.diag {f} (hf : is_poly₂ p f) :
is_poly p (λ R _Rcr x, by exactI f x x) :=
begin
unfreezingI {obtain ⟨φ, hf⟩ := hf},
refine ⟨⟨λ n, bind₁ (uncurry ![X, X]) (φ n), _⟩⟩,
intros, funext n,
simp only [hf, peval, uncurry, aeval_bind₁],
apply eval₂_hom_congr rfl _ rfl,
ext ⟨i, k⟩, fin_cases i;
simp only [matrix.head_cons, aeval_X, matrix.cons_val_zero, matrix.cons_val_one],
end
namespace tactic
open tactic
/-!
### The `@[is_poly]` attribute
This attribute is used to derive specialized composition instances
for `is_poly` and `is_poly₂` declarations.
-/
/--
If `n` is the name of a lemma with opened type `∀ vars, is_poly p _`,
`mk_poly_comp_lemmas n vars p` adds composition instances to the environment
`n.comp_i` and `n.comp₂_i`.
-/
meta def mk_poly_comp_lemmas (n : name) (vars : list expr) (p : expr) : tactic unit :=
do c ← mk_const n,
let appd := vars.foldl expr.app c,
tgt_bod ← to_expr ``(λ f [hf : is_poly %%p f], is_poly.comp %%appd hf) >>=
replace_univ_metas_with_univ_params,
tgt_bod ← lambdas vars tgt_bod,
tgt_tp ← infer_type tgt_bod,
let nm := n <.> "comp_i",
add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod,
set_attribute `instance nm,
tgt_bod ← to_expr ``(λ f [hf : is_poly₂ %%p f], is_poly.comp₂ %%appd hf) >>=
replace_univ_metas_with_univ_params,
tgt_bod ← lambdas vars tgt_bod,
tgt_tp ← infer_type tgt_bod,
let nm := n <.> "comp₂_i",
add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod,
set_attribute `instance nm
/--
If `n` is the name of a lemma with opened type `∀ vars, is_poly₂ p _`,
`mk_poly₂_comp_lemmas n vars p` adds composition instances to the environment
`n.comp₂_i` and `n.comp_diag`.
-/
meta def mk_poly₂_comp_lemmas (n : name) (vars : list expr) (p : expr) : tactic unit :=
do c ← mk_const n,
let appd := vars.foldl expr.app c,
tgt_bod ← to_expr ``(λ {f g} [hf : is_poly %%p f] [hg : is_poly %%p g],
is_poly₂.comp %%appd hf hg) >>= replace_univ_metas_with_univ_params,
tgt_bod ← lambdas vars tgt_bod,
tgt_tp ← infer_type tgt_bod >>= simp_lemmas.mk.dsimplify,
let nm := n <.> "comp₂_i",
add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod,
set_attribute `instance nm,
tgt_bod ← to_expr ``(λ {f g} [hf : is_poly %%p f] [hg : is_poly %%p g],
(is_poly₂.comp %%appd hf hg).diag) >>= replace_univ_metas_with_univ_params,
tgt_bod ← lambdas vars tgt_bod,
tgt_tp ← infer_type tgt_bod >>= simp_lemmas.mk.dsimplify,
let nm := n <.> "comp_diag",
add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod,
set_attribute `instance nm
/--
The `after_set` function for `@[is_poly]`. Calls `mk_poly(₂)_comp_lemmas`.
-/
meta def mk_comp_lemmas (n : name) : tactic unit :=
do d ← get_decl n,
(vars, tp) ← open_pis d.type,
match tp with
| `(is_poly %%p _) := mk_poly_comp_lemmas n vars p
| `(is_poly₂ %%p _) := mk_poly₂_comp_lemmas n vars p
| _ := fail "@[is_poly] should only be applied to terms of type `is_poly _ _` or `is_poly₂ _ _`"
end
/--
`@[is_poly]` is applied to lemmas of the form `is_poly f φ` or `is_poly₂ f φ`.
These lemmas should *not* be tagged as instances, and only atomic `is_poly` defs should be tagged:
composition lemmas should not. Roughly speaking, lemmas that take `is_poly` proofs as arguments
should not be tagged.
Type class inference struggles with function composition, and the higher order unification problems
involved in inferring `is_poly` proofs are complex. The standard style writing these proofs by hand
doesn't work very well. Instead, we construct the type class hierarchy "under the hood", with
limited forms of composition.
Applying `@[is_poly]` to a lemma creates a number of instances. Roughly, if the tagged lemma is a
proof of `is_poly f φ`, the instances added have the form
```lean
∀ g ψ, [is_poly g ψ] → is_poly (f ∘ g) _
```
Since `f` is fixed in this instance, it restricts the HO unification needed when the instance is
applied. Composition lemmas relating `is_poly` with `is_poly₂` are also added.
`id_is_poly` is an atomic instance.
The user-written lemmas are not instances. Users should be able to assemble `is_poly` proofs by hand
"as normal" if the tactic fails.
-/
@[user_attribute] meta def is_poly_attr : user_attribute :=
{ name := `is_poly,
descr := "Lemmas with this attribute describe the polynomial structure of functions",
after_set := some $ λ n _ _, mk_comp_lemmas n }
end tactic
include hp
/-!
### `is_poly` instances
These are not declared as instances at the top level,
but the `@[is_poly]` attribute adds instances based on each one.
Users are expected to use the non-instance versions manually.
-/
/-- The additive negation is a polynomial function on Witt vectors. -/
@[is_poly]
lemma neg_is_poly : is_poly p (λ R _, by exactI @has_neg.neg (𝕎 R) _) :=
⟨⟨λ n, rename prod.snd (witt_neg p n),
begin
introsI, funext n,
rw [neg_coeff, aeval_eq_eval₂_hom, eval₂_hom_rename],
apply eval₂_hom_congr rfl _ rfl,
ext ⟨i, k⟩, fin_cases i, refl,
end⟩⟩
section zero_one
/- To avoid a theory of 0-ary functions (a.k.a. constants)
we model them as constant unary functions. -/
/-- The function that is constantly zero on Witt vectors is a polynomial function. -/
instance zero_is_poly : is_poly p (λ _ _ _, by exactI 0) :=
⟨⟨0, by { introsI, funext n, simp only [pi.zero_apply, alg_hom.map_zero, zero_coeff] }⟩⟩
@[simp] lemma bind₁_zero_witt_polynomial (n : ℕ) :
bind₁ (0 : ℕ → mv_polynomial ℕ R) (witt_polynomial p R n) = 0 :=
by rw [← aeval_eq_bind₁, aeval_zero, constant_coeff_witt_polynomial, ring_hom.map_zero]
omit hp
/-- The coefficients of `1 : 𝕎 R` as polynomials. -/
def one_poly (n : ℕ) : mv_polynomial ℕ ℤ := if n = 0 then 1 else 0
include hp
@[simp] lemma bind₁_one_poly_witt_polynomial (n : ℕ) :
bind₁ one_poly (witt_polynomial p ℤ n) = 1 :=
begin
rw [witt_polynomial_eq_sum_C_mul_X_pow, alg_hom.map_sum, finset.sum_eq_single 0],
{ simp only [one_poly, one_pow, one_mul, alg_hom.map_pow, C_1, pow_zero, bind₁_X_right,
if_true, eq_self_iff_true], },
{ intros i hi hi0,
simp only [one_poly, if_neg hi0, zero_pow (pow_pos (nat.prime.pos hp) _), mul_zero,
alg_hom.map_pow, bind₁_X_right, alg_hom.map_mul], },
{ rw finset.mem_range, dec_trivial }
end
/-- The function that is constantly one on Witt vectors is a polynomial function. -/
instance one_is_poly : is_poly p (λ _ _ _, by exactI 1) :=
⟨⟨one_poly,
begin
introsI, funext n, cases n,
{ simp only [one_poly, if_true, eq_self_iff_true, one_coeff_zero, alg_hom.map_one], },
{ simp only [one_poly, nat.succ_pos', one_coeff_eq_of_pos,
if_neg n.succ_ne_zero, alg_hom.map_zero] }
end⟩⟩
end zero_one
omit hp
/-- Addition of Witt vectors is a polynomial function. -/
@[is_poly] lemma add_is_poly₂ [fact p.prime] : is_poly₂ p (λ _ _, by exactI (+)) :=
⟨⟨witt_add p, by { introsI, refl }⟩⟩
/-- Multiplication of Witt vectors is a polynomial function. -/
@[is_poly] lemma mul_is_poly₂ [fact p.prime] : is_poly₂ p (λ _ _, by exactI (*)) :=
⟨⟨witt_mul p, by { introsI, refl }⟩⟩
include hp
-- unfortunately this is not universe polymorphic, merely because `f` isn't
lemma is_poly.map {f} (hf : is_poly p f) (g : R →+* S) (x : 𝕎 R) :
map g (f x) = f (map g x) :=
begin
-- this could be turned into a tactic “macro” (taking `hf` as parameter)
-- so that applications do not have to worry about the universe issue
-- see `is_poly₂.map` for a slightly more general proof strategy
unfreezingI {obtain ⟨φ, hf⟩ := hf},
ext n,
simp only [map_coeff, hf, map_aeval],
apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
simp only [map_coeff]
end
namespace is_poly₂
omit hp
instance [fact p.prime] : inhabited (is_poly₂ p _) := ⟨add_is_poly₂⟩
variables {p}
/-- The composition of a binary polynomial function
with a unary polynomial function in the first argument is polynomial. -/
lemma comp_left {g f} (hg : is_poly₂ p g) (hf : is_poly p f) :
is_poly₂ p (λ R _Rcr x y, by exactI g (f x) y) :=
hg.comp hf (witt_vector.id_is_poly _)
/-- The composition of a binary polynomial function
with a unary polynomial function in the second argument is polynomial. -/
lemma comp_right {g f} (hg : is_poly₂ p g) (hf : is_poly p f) :
is_poly₂ p (λ R _Rcr x y, by exactI g x (f y)) :=
hg.comp (witt_vector.id_is_poly p) hf
include hp
lemma ext {f g} (hf : is_poly₂ p f) (hg : is_poly₂ p g)
(h : ∀ (R : Type u) [_Rcr : comm_ring R] (x y : 𝕎 R) (n : ℕ),
by exactI ghost_component n (f x y) = ghost_component n (g x y)) :
∀ (R) [_Rcr : comm_ring R] (x y : 𝕎 R), by exactI f x y = g x y :=
begin
unfreezingI
{ obtain ⟨φ, hf⟩ := hf,
obtain ⟨ψ, hg⟩ := hg },
intros,
ext n,
rw [hf, hg, poly_eq_of_witt_polynomial_bind_eq' p φ ψ],
clear x y,
intro k,
apply mv_polynomial.funext,
intro x,
simp only [hom_bind₁],
specialize h (ulift ℤ) (mk p $ λ i, ⟨x (0, i)⟩) (mk p $ λ i, ⟨x (1, i)⟩) k,
simp only [ghost_component_apply, aeval_eq_eval₂_hom] at h,
apply (ulift.ring_equiv.{0 u}).symm.injective,
simp only [map_eval₂_hom],
convert h; clear h,
all_goals {
funext i,
rw [← ring_equiv.coe_to_ring_hom],
simp only [hf, hg, mv_polynomial.eval, map_eval₂_hom],
apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
ext1,
apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
ext ⟨b, _⟩,
fin_cases b; simp only [coeff_mk, uncurry]; refl }
end
-- unfortunately this is not universe polymorphic, merely because `f` isn't
lemma map {f} (hf : is_poly₂ p f) (g : R →+* S) (x y : 𝕎 R) :
map g (f x y) = f (map g x) (map g y) :=
begin
-- this could be turned into a tactic “macro” (taking `hf` as parameter)
-- so that applications do not have to worry about the universe issue
unfreezingI {obtain ⟨φ, hf⟩ := hf},
ext n,
simp only [map_coeff, hf, map_aeval, peval, uncurry],
apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl,
try { ext ⟨i, k⟩, fin_cases i },
all_goals {
simp only [map_coeff, matrix.cons_val_zero, matrix.head_cons, matrix.cons_val_one] },
end
end is_poly₂
attribute [ghost_simps]
alg_hom.map_zero alg_hom.map_one alg_hom.map_add alg_hom.map_mul
alg_hom.map_sub alg_hom.map_neg alg_hom.id_apply alg_hom.map_nat_cast
ring_hom.map_zero ring_hom.map_one ring_hom.map_mul ring_hom.map_add
ring_hom.map_sub ring_hom.map_neg ring_hom.id_apply ring_hom.map_nat_cast
mul_add add_mul add_zero zero_add mul_one one_mul mul_zero zero_mul
nat.succ_ne_zero nat.add_sub_cancel nat.succ_eq_add_one
if_true eq_self_iff_true if_false forall_true_iff forall_2_true_iff forall_3_true_iff
end witt_vector
|
de79584642647cfd4934819fbece97ccf0030e23 | 88892181780ff536a81e794003fe058062f06758 | /src/knopp/ordered_aggregate.lean | 57b4b4d91e9490af201f8dc1baa24b99524f9c70 | [] | no_license | AtnNn/lean-sandbox | fe2c44280444e8bb8146ab8ac391c82b480c0a2e | 8c68afbdc09213173aef1be195da7a9a86060a97 | refs/heads/master | 1,623,004,395,876 | 1,579,969,507,000 | 1,579,969,507,000 | 146,666,368 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 726 | lean | import knopp.common
namespace knopp
class ordered_aggregate (system : Type) :=
(lt : system → system → Prop) (eq : system → system → Prop)
-- between any two, say a and b, one and only one of the three relations necessarily holds
(exclusive : ∀ a b, one_and_only_one [lt a b, eq a b, lt b a])
-- Fundamental laws of order
-- Invariably a = a
(refl : ∀ a, eq a a)
-- a = b always implies b = a
(comm_eq : ∀ a b, eq a b → eq b a)
-- a = b, b = c implies a = c
(trans_eq : ∀ a b c, eq a b → eq b c → eq a c)
-- a ≤ b, b < c, — or a < b, b ≤ c, — implies a < c
(trans_le_lt : ∀ a b c, ¬(lt b a) → lt b c → lt a c)
(trans_lt_le : ∀ a b c, lt a b → ¬(lt c b) → lt a c)
end knopp
|
21cfac2b889924691abc191fcb37f31d1ed9e367 | 193da933cf42f2f9188bb47e3c973205bc2abc5c | /AA_Algebras/00_intro.lean | 60d8df78df26b7f5c4dcb66ee6a6d73a7da7afb5 | [] | no_license | pandaman64/cs-dm | aa4e2621c7a19e2dae911bc237c33e02fcb0c7a3 | bfd2f5fd2612472e15bd970c7870b5d0dd73bd1c | refs/heads/master | 1,647,620,340,607 | 1,570,055,187,000 | 1,570,055,187,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 952 | lean | /-
An algebra is a set, A, of values of some type, along with a number of
functions, f_i, that are closed over A. By the phrase, closed over A,
we mean that each such functions takes values in A as its arguments and
returns values in A as its results.
In this unit, we make this concept clear through the study of two
important examples: Boolean algebra and the arithmetic of natural numbers.
We characterize each algebra by first defining its set, A, of values, and
by then defining a set of functions that are closed on that particular set.
In the course of studying these two simple algebras, for which you already
have strong intuition, we will encounter two of the most interesting and
useful ideas in all of computer science and discrete mathematics: the
inductive definition of sets of values, which we will call types, and the
recursive definition of functions taking and returning values of such types.
-/
|
0c684b663ac31f62a75a122ee395fef85d4069b9 | 367134ba5a65885e863bdc4507601606690974c1 | /src/order/bounded_lattice.lean | 1eeaf4b40933f95da76f186ac8e83482308fa6ff | [
"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 | 42,798 | 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
Defines bounded lattice type class hierarchy.
Includes the Prop and fun instances.
-/
import order.lattice
import data.option.basic
import tactic.pi_instances
import logic.nontrivial
set_option old_structure_cmd true
universes u v
variables {α : Type u} {β : Type v}
/-- Typeclass for the `⊤` (`\top`) notation -/
class has_top (α : Type u) := (top : α)
/-- Typeclass for the `⊥` (`\bot`) notation -/
class has_bot (α : Type u) := (bot : α)
notation `⊤` := has_top.top
notation `⊥` := has_bot.bot
attribute [pattern] has_bot.bot has_top.top
/-- An `order_top` is a partial order with a maximal element.
(We could state this on preorders, but then it wouldn't be unique
so distinguishing one would seem odd.) -/
class order_top (α : Type u) extends has_top α, partial_order α :=
(le_top : ∀ a : α, a ≤ ⊤)
section order_top
variables [order_top α] {a b : α}
@[simp] theorem le_top : a ≤ ⊤ :=
order_top.le_top a
theorem top_unique (h : ⊤ ≤ a) : a = ⊤ :=
le_antisymm le_top h
-- TODO: delete in favor of the next?
theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a :=
⟨assume eq, eq.symm ▸ le_refl ⊤, top_unique⟩
@[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ :=
⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩
@[simp] theorem not_top_lt : ¬ ⊤ < a :=
assume h, lt_irrefl a (lt_of_le_of_lt le_top h)
theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ :=
top_le_iff.1 $ h₂ ▸ h
lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ :=
begin
haveI := classical.dec_eq α,
haveI : decidable (⊤ ≤ a) := decidable_of_iff' _ top_le_iff,
by simp [-top_le_iff, lt_iff_le_not_le, not_iff_not.2 (@top_le_iff _ _ a)]
end
lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ :=
lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top
theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ :=
assume ha, hb $ top_unique $ ha ▸ hab
end order_top
lemma strict_mono.top_preimage_top' [linear_order α] [order_top β]
{f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) :
x ≤ a :=
H.top_preimage_top (λ p, by { rw h_top, exact le_top }) x
theorem order_top.ext_top {α} {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊤ : α) = ⊤ :=
top_unique $ by rw ← H; apply le_top
theorem order_top.ext {α} {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_top.ext_top H,
casesI A, casesI B,
injection this; congr'
end
/-- An `order_bot` is a partial order with a minimal element.
(We could state this on preorders, but then it wouldn't be unique
so distinguishing one would seem odd.) -/
class order_bot (α : Type u) extends has_bot α, partial_order α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
section order_bot
variables [order_bot α] {a b : α}
@[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a
theorem bot_unique (h : a ≤ ⊥) : a = ⊥ :=
le_antisymm h bot_le
-- TODO: delete?
theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ :=
⟨assume eq, eq.symm ▸ le_refl ⊥, bot_unique⟩
@[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ :=
⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩
@[simp] theorem not_lt_bot : ¬ a < ⊥ :=
assume h, lt_irrefl a (lt_of_lt_of_le h bot_le)
theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ :=
assume ha, hb $ bot_unique $ ha ▸ hab
theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ :=
le_bot_iff.1 $ h₂ ▸ h
lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ :=
begin
haveI := classical.dec_eq α,
haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff,
simp [-le_bot_iff, lt_iff_le_not_le, not_iff_not.2 (@le_bot_iff _ _ a)]
end
lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ :=
bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h
end order_bot
lemma strict_mono.bot_preimage_bot' [linear_order α] [order_bot β]
{f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) :
a ≤ x :=
H.bot_preimage_bot (λ p, by { rw h_bot, exact bot_le }) x
theorem order_bot.ext_bot {α} {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊥ : α) = ⊥ :=
bot_unique $ by rw ← H; apply bot_le
theorem order_bot.ext {α} {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_bot.ext_bot H,
casesI A, casesI B,
injection this; congr'
end
/-- A `semilattice_sup_top` is a semilattice with top and join. -/
class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α
section semilattice_sup_top
variables [semilattice_sup_top α] {a : α}
@[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ :=
sup_of_le_left le_top
@[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ :=
sup_of_le_right le_top
end semilattice_sup_top
/-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/
class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α
section semilattice_sup_bot
variables [semilattice_sup_bot α] {a b : α}
@[simp] theorem bot_sup_eq : ⊥ ⊔ a = a :=
sup_of_le_right bot_le
@[simp] theorem sup_bot_eq : a ⊔ ⊥ = a :=
sup_of_le_left bot_le
@[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) :=
by rw [eq_bot_iff, sup_le_iff]; simp
end semilattice_sup_bot
instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ :=
{ bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice }
/-- A `semilattice_inf_top` is a semilattice with top and meet. -/
class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α
section semilattice_inf_top
variables [semilattice_inf_top α] {a b : α}
@[simp] theorem top_inf_eq : ⊤ ⊓ a = a :=
inf_of_le_right le_top
@[simp] theorem inf_top_eq : a ⊓ ⊤ = a :=
inf_of_le_left le_top
@[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) :=
by rw [eq_top_iff, le_inf_iff]; simp
end semilattice_inf_top
/-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/
class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α
section semilattice_inf_bot
variables [semilattice_inf_bot α] {a : α}
@[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ :=
inf_of_le_left bot_le
@[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ :=
inf_of_le_right bot_le
end semilattice_inf_bot
/- Bounded lattices -/
/-- A bounded lattice is a lattice with a top and bottom element,
denoted `⊤` and `⊥` respectively. This allows for the interpretation
of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/
class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α :=
{ le_top := assume x, @le_top α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α :=
{ bot_le := assume x, @bot_le α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α :=
{ le_top := assume x, @le_top α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α :=
{ bot_le := assume x, @bot_le α _ x, ..bl }
theorem bounded_lattice.ext {α} {A B : bounded_lattice α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have H1 : @bounded_lattice.to_lattice α A =
@bounded_lattice.to_lattice α B := lattice.ext H,
have H2 := order_bot.ext H,
have H3 : @bounded_lattice.to_order_top α A =
@bounded_lattice.to_order_top α B := order_top.ext H,
have tt := order_bot.ext_bot H,
casesI A, casesI B,
injection H1; injection H2; injection H3; congr'
end
/-- A bounded distributive lattice is exactly what it sounds like. -/
class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α
lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α}
(h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c :=
⟨assume : a ⊓ b = ⊥,
calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁]
... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left]
... ≤ c : by simp [this, inf_le_right],
assume : a ≤ c,
bot_unique $
calc a ⊓ b ≤ b ⊓ c : by { rw [inf_comm], exact inf_le_inf_left _ this }
... = ⊥ : h₂⟩
/- Prop instance -/
instance bounded_distrib_lattice_Prop : bounded_distrib_lattice Prop :=
{ le := λa b, a → b,
le_refl := assume _, id,
le_trans := assume a b c f g, g ∘ f,
le_antisymm := assume a b Hab Hba, propext ⟨Hab, Hba⟩,
sup := or,
le_sup_left := @or.inl,
le_sup_right := @or.inr,
sup_le := assume a b c, or.rec,
inf := and,
inf_le_left := @and.left,
inf_le_right := @and.right,
le_inf := assume a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha),
le_sup_inf := assume a b c H, or_iff_not_imp_left.2 $
λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩,
top := true,
le_top := assume a Ha, true.intro,
bot := false,
bot_le := @false.elim }
noncomputable instance Prop.linear_order : linear_order Prop :=
{ le_total := by intros p q; change (p → q) ∨ (q → p); tauto!,
decidable_le := classical.dec_rel _,
.. (_ : partial_order Prop) }
@[simp]
lemma le_iff_imp {p q : Prop} : p ≤ q ↔ (p → q) := iff.rfl
section logic
variable [preorder α]
theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λx, p x ∧ q x) :=
assume a b h, and.imp (m_p h) (m_q h)
-- Note: by finish [monotone] doesn't work
theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λx, p x ∨ q x) :=
assume a b h, or.imp (m_p h) (m_q h)
end logic
instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) :=
{ bot := λ _, ⊥,
bot_le := λ x a, bot_le,
.. pi.partial_order }
/- Function lattices -/
instance pi.has_sup {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] : has_sup (Π i, α i) :=
⟨λ f g i, f i ⊔ g i⟩
@[simp] lemma sup_apply {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] (f g : Π i, α i) (i : ι) :
(f ⊔ g) i = f i ⊔ g i :=
rfl
instance pi.has_inf {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] : has_inf (Π i, α i) :=
⟨λ f g i, f i ⊓ g i⟩
@[simp] lemma inf_apply {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] (f g : Π i, α i) (i : ι) :
(f ⊓ g) i = f i ⊓ g i :=
rfl
instance pi.has_bot {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] : has_bot (Π i, α i) :=
⟨λ i, ⊥⟩
@[simp] lemma bot_apply {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] (i : ι) :
(⊥ : Π i, α i) i = ⊥ :=
rfl
instance pi.has_top {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] : has_top (Π i, α i) :=
⟨λ i, ⊤⟩
@[simp] lemma top_apply {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] (i : ι) :
(⊤ : Π i, α i) i = ⊤ :=
rfl
instance pi.semilattice_sup {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup (α i)] :
semilattice_sup (Π i, α i) :=
by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_inf {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf (α i)] :
semilattice_inf (Π i, α i) :=
by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_inf_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_bot (α i)] :
semilattice_inf_bot (Π i, α i) :=
by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_inf_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_top (α i)] :
semilattice_inf_top (Π i, α i) :=
by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_sup_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_bot (α i)] :
semilattice_sup_bot (Π i, α i) :=
by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_sup_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_top (α i)] :
semilattice_sup_top (Π i, α i) :=
by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.lattice {ι : Type*} {α : ι → Type*} [Π i, lattice (α i)] : lattice (Π i, α i) :=
{ .. pi.semilattice_sup, .. pi.semilattice_inf }
instance pi.bounded_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_lattice (α i)] :
bounded_lattice (Π i, α i) :=
{ .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot }
lemma eq_bot_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) :
x = (⊥ : α) :=
eq_bot_mono le_top (eq.symm hα)
lemma eq_top_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) :
x = (⊤ : α) :=
eq_top_mono bot_le hα
lemma subsingleton_of_top_le_bot {α : Type*} [bounded_lattice α] (h : (⊤ : α) ≤ (⊥ : α)) :
subsingleton α :=
⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩
lemma subsingleton_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = (⊤ : α)) :
subsingleton α :=
subsingleton_of_top_le_bot (ge_of_eq hα)
lemma subsingleton_iff_bot_eq_top {α : Type*} [bounded_lattice α] :
(⊥ : α) = (⊤ : α) ↔ subsingleton α :=
⟨subsingleton_of_bot_eq_top, λ h, by exactI subsingleton.elim ⊥ ⊤⟩
/-- Attach `⊥` to a type. -/
def with_bot (α : Type*) := option α
namespace with_bot
meta instance {α} [has_to_format α] : has_to_format (with_bot α) :=
{ to_format := λ x,
match x with
| none := "⊥"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_bot α) := ⟨some⟩
instance has_bot : has_bot (with_bot α) := ⟨none⟩
instance : inhabited (with_bot α) := ⟨⊥⟩
lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl
lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl
/-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/
@[elab_as_eliminator]
def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) :
Π (n : with_bot α), C n :=
option.rec h₁ h₂
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_bot α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a :=
⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩
lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a
instance [preorder α] : preorder (with_bot α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b,
lt := (<),
lt_iff_le_not_le := by intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<)];
split; refl,
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha,
let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in
⟨c, hc, le_trans ab bc⟩ }
instance partial_order [partial_order α] : partial_order (with_bot α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₁ with a,
{ cases o₂ with b, {refl},
rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩,
rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_bot.preorder }
instance order_bot [partial_order α] : order_bot (with_bot α) :=
{ bot_le := λ a a' h, option.no_confusion h,
..with_bot.partial_order, ..with_bot.has_bot }
@[simp, norm_cast] theorem coe_le_coe [preorder α] {a b : α} :
(a : with_bot α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩
@[simp] theorem some_le_some [preorder α] {a b : α} :
@has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe
theorem coe_le [partial_order α] {a b : α} :
∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b)
| _ rfl := coe_le_coe
@[norm_cast]
lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some
lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b
| (some a) b := le_refl a
| none b := λ _ h, option.no_confusion h
@[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl
lemma get_or_else_bot_le_iff [order_bot α] {a : with_bot α} {b : α} :
a.get_or_else ⊥ ≤ b ↔ a ≤ b :=
by cases a; simp [none_eq_bot, some_eq_coe]
instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤)
| none x := is_true $ λ a h, option.no_confusion h
| (some x) (some y) :=
if h : x ≤ y
then is_true (some_le_some.2 h)
else is_false $ by simp *
| (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<)
| none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩
| (some x) (some y) :=
if h : x < y
then is_true $ by simp *
else is_false $ by simp *
| x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩
instance linear_order [linear_order α] : linear_order (with_bot α) :=
{ le_total := λ o₁ o₂, begin
cases o₁ with a, {exact or.inl bot_le},
cases o₂ with b, {exact or.inr bot_le},
simp [le_total]
end,
decidable_le := with_bot.decidable_le,
decidable_lt := with_bot.decidable_lt,
..with_bot.partial_order }
instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) :=
{ sup := option.lift_or_get (⊔),
le_sup_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
le_sup_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₁ with b; cases o₂ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, sup_le h₁' h₂⟩ }
end,
..with_bot.order_bot }
instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) :=
{ inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)),
inf_le_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_left⟩
end,
inf_le_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_right⟩
end,
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, le_inf ab ac⟩
end,
..with_bot.order_bot }
instance lattice [lattice α] : lattice (with_bot α) :=
{ ..with_bot.semilattice_sup, ..with_bot.semilattice_inf }
theorem lattice_eq_DLO [linear_order α] :
lattice_of_linear_order = @with_bot.lattice α _ :=
lattice.ext $ λ x y, iff.rfl
theorem sup_eq_max [linear_order α] (x y : with_bot α) : x ⊔ y = max x y :=
by rw [← sup_eq_max, lattice_eq_DLO]
theorem inf_eq_min [linear_order α] (x y : with_bot α) : x ⊓ y = min x y :=
by rw [← inf_eq_min, lattice_eq_DLO]
instance order_top [order_top α] : order_top (with_bot α) :=
{ top := some ⊤,
le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩,
..with_bot.partial_order }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) :=
{ ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot }
lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_bot α → with_bot α → Prop) :=
have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ :=
acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim),
⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot)
(λ b, well_founded.induction h b
(show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) b,
from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot)
(λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] :
densely_ordered (with_bot α) :=
⟨ assume a b,
match a, b with
| a, none := assume h : a < ⊥, (not_lt_bot h).elim
| none, some b := assume h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩
| some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
end with_bot
--TODO(Mario): Construct using order dual on with_bot
/-- Attach `⊤` to a type. -/
def with_top (α : Type*) := option α
namespace with_top
meta instance {α} [has_to_format α] : has_to_format (with_top α) :=
{ to_format := λ x,
match x with
| none := "⊤"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_top α) := ⟨some⟩
instance has_top : has_top (with_top α) := ⟨none⟩
instance : inhabited (with_top α) := ⟨⊤⟩
lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl
lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl
/-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/
@[elab_as_eliminator]
def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) :
Π (n : with_top α), C n :=
option.rec h₁ h₂
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
@[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) .
@[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ .
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_top α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a }
@[priority 10]
instance has_le [has_le α] : has_le (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
@[simp] theorem some_le_some [has_le α] {a b : α} :
@has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b :=
by simp [(≤)]
@[simp] theorem le_none [has_le α] {a : with_top α} :
@has_le.le (with_top α) _ a none :=
by simp [(≤)]
@[simp] theorem some_lt_none [has_lt α] {a : α} :
@has_lt.lt (with_top α) _ (some a) none :=
by simp [(<)]; existsi a; refl
instance : can_lift (with_top α) α :=
{ coe := coe,
cond := λ r, r ≠ ⊤,
prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ }
instance [preorder α] : preorder (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a,
lt := (<),
lt_iff_le_not_le := by { intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<),(≤)] },
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc,
let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in
⟨a, ha, le_trans ab bc⟩,
}
instance partial_order [partial_order α] : partial_order (with_top α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₂ with b,
{ cases o₁ with a, {refl},
rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩,
rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_top.preorder }
instance order_top [partial_order α] : order_top (with_top α) :=
{ le_top := λ a a' h, option.no_confusion h,
..with_top.partial_order, .. with_top.has_top }
@[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} :
(a : with_top α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩
theorem le_coe [partial_order α] {a b : α} :
∀ {o : option α}, a ∈ o →
(@has_le.le (with_top α) _ o b ↔ a ≤ b)
| _ rfl := coe_le_coe
theorem le_coe_iff [partial_order α] {b : α} : ∀{x : with_top α}, x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b)
| (some a) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem coe_le_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b)
| (some b) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem lt_iff_exists_coe [partial_order α] : ∀{a b : with_top α}, a < b ↔ (∃p:α, a = p ∧ ↑p < b)
| (some a) b := by simp [some_eq_coe, coe_eq_coe]
| none b := by simp [none_eq_top]
@[norm_cast]
lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some
lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ := some_lt_none
theorem coe_lt_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a < x ↔ (∀b:α, x = ↑b → a < b)
| (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe]
| none := by simp [none_eq_top, coe_lt_top]
lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a :=
assume h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim
instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) :=
λ x y, @with_bot.decidable_le (order_dual α) _ _ y x
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) :=
λ x y, @with_bot.decidable_lt (order_dual α) _ _ y x
instance linear_order [linear_order α] : linear_order (with_top α) :=
{ le_total := λ o₁ o₂, begin
cases o₁ with a, {exact or.inr le_top},
cases o₂ with b, {exact or.inl le_top},
simp [le_total]
end,
decidable_le := with_top.decidable_le,
decidable_lt := with_top.decidable_lt,
..with_top.partial_order }
instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) :=
{ inf := option.lift_or_get (⊓),
inf_le_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
inf_le_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₂ with b; cases o₃ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, le_inf h₁' h₂⟩ }
end,
..with_top.order_top }
lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl
instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) :=
{ sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)),
le_sup_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_left⟩
end,
le_sup_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_right⟩
end,
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, sup_le ab ac⟩
end,
..with_top.order_top }
lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl
instance lattice [lattice α] : lattice (with_top α) :=
{ ..with_top.semilattice_sup, ..with_top.semilattice_inf }
theorem lattice_eq_DLO [linear_order α] :
lattice_of_linear_order = @with_top.lattice α _ :=
lattice.ext $ λ x y, iff.rfl
theorem sup_eq_max [linear_order α] (x y : with_top α) : x ⊔ y = max x y :=
by rw [← sup_eq_max, lattice_eq_DLO]
theorem inf_eq_min [linear_order α] (x y : with_top α) : x ⊓ y = min x y :=
by rw [← inf_eq_min, lattice_eq_DLO]
instance order_bot [order_bot α] : order_bot (with_top α) :=
{ bot := some ⊥,
bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩,
..with_top.partial_order }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) :=
{ ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot }
lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_top α → with_top α → Prop) :=
have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) :=
λ a, acc.intro _ (well_founded.induction h a
(show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) →
∀ y : with_top α, y < some b → acc (<) y,
from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim)
(λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))),
⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim)
(λ _ _, acc_some _))) acc_some⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] :
densely_ordered (with_top α) :=
⟨ assume a b,
match a, b with
| none, a := assume h : ⊤ < a, (not_top_lt h).elim
| some a, none := assume h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩
| some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α]
{a b : with_top α} :
(a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) :=
⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩,
λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩
end with_top
namespace subtype
/-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. -/
protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop}
(Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ x, @bot_le α _ x,
..subtype.semilattice_sup Psup }
/-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. -/
protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop}
(Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ x, @bot_le α _ x,
..subtype.semilattice_inf Pinf }
/-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. -/
protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop}
(Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} :=
{ top := ⟨⊤, Ptop⟩,
le_top := λ x, @le_top α _ x,
..subtype.semilattice_inf Pinf }
end subtype
namespace order_dual
variable (α)
instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩
instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩
instance [order_bot α] : order_top (order_dual α) :=
{ le_top := @bot_le α _,
.. order_dual.partial_order α, .. order_dual.has_top α }
instance [order_top α] : order_bot (order_dual α) :=
{ bot_le := @le_top α _,
.. order_dual.partial_order α, .. order_dual.has_bot α }
instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_top α }
instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_bot α }
instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_top α }
instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_bot α }
instance [bounded_lattice α] : bounded_lattice (order_dual α) :=
{ .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α }
instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) :=
{ .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α }
end order_dual
namespace prod
variables (α β)
instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩
instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩
instance [order_top α] [order_top β] : order_top (α × β) :=
{ le_top := assume a, ⟨le_top, le_top⟩,
.. prod.partial_order α β, .. prod.has_top α β }
instance [order_bot α] [order_bot β] : order_bot (α × β) :=
{ bot_le := assume a, ⟨bot_le, bot_le⟩,
.. prod.partial_order α β, .. prod.has_bot α β }
instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_top α β }
instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_top α β }
instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_bot α β }
instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_bot α β }
instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) :=
{ .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β }
instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] :
bounded_distrib_lattice (α × β) :=
{ .. prod.bounded_lattice α β, .. prod.distrib_lattice α β }
end prod
section disjoint
section semilattice_inf_bot
variable [semilattice_inf_bot α]
/-- Two elements of a lattice are disjoint if their inf is the bottom element.
(This generalizes disjoint sets, viewed as members of the subset lattice.) -/
def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥
theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ :=
eq_bot_iff.2 h
theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ :=
eq_bot_iff.symm
theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a :=
by rw [disjoint, disjoint, inf_comm]
@[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a :=
disjoint.comm.1
@[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := inf_le_left
@[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := inf_le_right
theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) :
disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂)
theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c :=
disjoint.mono h (le_refl _)
theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b :=
disjoint.mono (le_refl _) h
@[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ :=
by simp [disjoint]
lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b :=
by { intro h, rw [←h, disjoint_self] at hab, exact ha hab }
end semilattice_inf_bot
section bounded_lattice
variables [bounded_lattice α] {a : α}
@[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := by simp [disjoint_iff]
@[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := by simp [disjoint_iff]
end bounded_lattice
section bounded_distrib_lattice
variables [bounded_distrib_lattice α] {a b c : α}
@[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c :=
by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff]
@[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c :=
by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff]
lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c :=
disjoint_sup_left.2 ⟨ha, hb⟩
lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) :=
disjoint_sup_right.2 ⟨hb, hc⟩
lemma disjoint.left_le_of_le_sup_right {a b c : α} (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b :=
(λ x, le_of_inf_le_sup_le x (sup_le h le_sup_right)) ((disjoint_iff.mp hd).symm ▸ bot_le)
lemma disjoint.left_le_of_le_sup_left {a b c : α} (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b :=
@le_of_inf_le_sup_le _ _ a b c ((disjoint_iff.mp hd).symm ▸ bot_le)
((@sup_comm _ _ c b) ▸ (sup_le h le_sup_left))
end bounded_distrib_lattice
end disjoint
section is_compl
/-!
### `is_compl` predicate
-/
/-- Two elements `x` and `y` are complements of each other if
`x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/
structure is_compl [bounded_lattice α] (x y : α) : Prop :=
(inf_le_bot : x ⊓ y ≤ ⊥)
(top_le_sup : ⊤ ≤ x ⊔ y)
namespace is_compl
section bounded_lattice
variables [bounded_lattice α] {x y z : α}
protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1
@[symm] protected lemma symm (h : is_compl x y) : is_compl y x :=
⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩
lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y :=
⟨le_of_eq h₁, le_of_eq h₂.symm⟩
lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot
lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup
lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩
end bounded_lattice
variables [bounded_distrib_lattice α] {x y z : α}
lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y :=
⟨λ hz, h.disjoint.mono_left hz,
λ hz, le_of_inf_le_sup_le (le_trans hz bot_le) (le_trans le_top h.top_le_sup)⟩
lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x :=
h.symm.le_left_iff
lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y :=
h.to_order_dual.le_left_iff
lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x :=
h.symm.left_le_iff
lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') :
y' ≤ y :=
h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _)
lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) :
y = z :=
le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x)
lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) :
x = y :=
hxz.symm.right_unique hyz.symm
lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊔ x') (y ⊓ y') :=
of_eq
(by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm,
h'.inf_eq_bot, inf_bot_eq])
(by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq,
sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq])
lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊓ x') (y ⊔ y') :=
(h.symm.sup_inf h'.symm).symm
lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z :=
inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot
lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y :=
h.symm.inf_left_eq_bot_iff
lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z :=
disjoint_iff.trans h.inf_left_eq_bot_iff
lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y :=
h.symm.disjoint_left_iff
end is_compl
lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ :=
is_compl.of_eq bot_inf_eq sup_top_eq
lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ :=
is_compl.of_eq inf_bot_eq top_sup_eq
section
variables [bounded_lattice α] {x : α}
lemma eq_top_of_is_compl_bot (h : is_compl x ⊥) : x = ⊤ :=
sup_bot_eq.symm.trans h.sup_eq_top
lemma eq_top_of_bot_is_compl (h : is_compl ⊥ x) : x = ⊤ :=
eq_top_of_is_compl_bot h.symm
lemma eq_bot_of_is_compl_top (h : is_compl x ⊤) : x = ⊥ :=
eq_top_of_is_compl_bot h.to_order_dual
lemma eq_bot_of_top_is_compl (h : is_compl ⊤ x) : x = ⊥ :=
eq_top_of_bot_is_compl h.to_order_dual
end
/-- A complemented bounded lattice is one where every element has a
(not necessarily unique) complement. -/
class is_complemented (α) [bounded_lattice α] : Prop :=
(exists_is_compl : ∀ (a : α), ∃ (b : α), is_compl a b)
export is_complemented (exists_is_compl)
namespace is_complemented
variables [bounded_lattice α] [is_complemented α]
instance : is_complemented (order_dual α) :=
⟨λ a, ⟨classical.some (@exists_is_compl α _ _ a),
(classical.some_spec (@exists_is_compl α _ _ a)).to_order_dual⟩⟩
end is_complemented
end is_compl
section nontrivial
variables [bounded_lattice α] [nontrivial α]
lemma bot_ne_top : (⊥ : α) ≠ ⊤ :=
λ H, not_nontrivial_iff_subsingleton.mpr (subsingleton_of_bot_eq_top H) ‹_›
lemma top_ne_bot : (⊤ : α) ≠ ⊥ := ne.symm bot_ne_top
end nontrivial
namespace bool
instance : bounded_lattice bool :=
{ top := tt,
le_top := λ x, le_tt,
bot := ff,
bot_le := λ x, ff_le,
.. (infer_instance : lattice bool)}
end bool
section bool
@[simp] lemma top_eq_tt : ⊤ = tt := rfl
@[simp] lemma bot_eq_ff : ⊥ = ff := rfl
end bool
|
f528835f499e85da0b424d295da7f491f92fb5a1 | 36938939954e91f23dec66a02728db08a7acfcf9 | /lean/deps/galois_stdlib/src/galois/data/nat/repr_lemmas.lean | 1f8a6732e36cefce6743c28d7fb4ba31cf23ecc2 | [
"Apache-2.0"
] | permissive | pnwamk/reopt-vcg | f8b56dd0279392a5e1c6aee721be8138e6b558d3 | c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d | refs/heads/master | 1,631,145,017,772 | 1,593,549,019,000 | 1,593,549,143,000 | 254,191,418 | 0 | 0 | null | 1,586,377,077,000 | 1,586,377,077,000 | null | UTF-8 | Lean | false | false | 2,959 | lean | -- Lemmas
import galois.data.list.nth_le
namespace galois
namespace nat
open nat
/-- Show that nat.to_digits never returns empty list. -/
theorem to_digits_ne_nil (base:ℕ) (x:ℕ) : nat.to_digits base x ≠ list.nil :=
begin
cases x,
case nat.zero : { simp [nat.to_digits], },
case nat.succ : x {
simp [nat.to_digits],
cases (nat.to_digits base x),
{ simp [nat.digit_succ], },
{ simp [nat.digit_succ],
-- case split on ite condition, then use assumption to resovle goal.
apply (dite (hd + 1 = base)); { intro eq, simp [eq], },
},
},
end
/-- Prove each list entry returned by digit_succ is less than the base -/
theorem digit_succ_bound {base:ℕ} (basep : base ≥ 2)
{v : list ℕ}
{i:ℕ}
(i_lt_digit_succ : i < (digit_succ base v).length)
(v_read : Π(j_lt : i < v.length), list.nth_le v i j_lt < base)
: list.nth_le (digit_succ base v) i i_lt_digit_succ < base :=
begin
have base_is_pos : 0 < base := le_of_succ_le basep,
revert i,
induction v,
case list.nil {
intros i i_lt_digit_succ v_read,
simp [digit_succ, list.nth_le_singleton],
exact basep,
},
case list.cons : h r ind {
intros i i_lt_digit_succ v_read,
dsimp [digit_succ],
-- Split on whether h + 1 is base and simplify ite
apply dite (h + 1 = base); intro h_limit; simp [h_limit],
-- Case for h + 1 = base.
{ cases i; simp [list.nth_le],
case zero {
exact base_is_pos
},
case succ : i {
apply ind,
{ intros i_lt,
-- Rewrite i_lt in goal with meta variable to allow matching at q,
rw [proof_irrel i_lt _],
-- Use v_read
exact v_read (succ_lt_succ i_lt),
},
},
},
{ cases i,
case zero {
dsimp [list.nth_le],
dsimp [list.nth_le] at v_read,
have h_le : h + 1 ≤ base,
{ exact v_read (succ_le_succ (zero_le _)),
},
cases (lt_or_eq_of_le h_le),
case or.inl : is_lt { exact is_lt },
case or.inr : is_eq { exact (absurd is_eq h_limit), },
},
case succ : i {
simp [digit_succ, h_limit, succ_add] at i_lt_digit_succ,
apply v_read i_lt_digit_succ,
},
},
},
end
/-- Prove each list entry returned by to_digits is less than the base -/
theorem nth_to_digits_is_lt {base v : ℕ} (base_ok : base ≥ 2)
{i:ℕ} (p : i < (to_digits base v).length)
: list.nth_le (to_digits base v) i p < base :=
begin
have base_is_pos : 0 < base := nat.le_of_succ_le base_ok,
induction v,
case nat.zero {
simp [nat.to_digits] at p,
simp [nat.to_digits, list.nth_le []],
cases i,
case nat.zero {
simp [list.nth_le, *],
},
by_contradiction,
exact nat.not_succ_le_zero _ (nat.le_of_lt_succ p),
},
case nat.succ : v ind {
simp [nat.to_digits],
apply nat.digit_succ_bound base_ok,
{ intros i_lt,
exact ind i_lt,
},
},
end
end nat
end galois
|
55ba0b585371b8ce2813d25dda1c37f405ddda6e | df7bb3acd9623e489e95e85d0bc55590ab0bc393 | /lean/love02_backward_proofs_homework_sheet.lean | af6b08034924cba8111961c5e6fa5b8d04afa26d | [] | no_license | MaschavanderMarel/logical_verification_2020 | a41c210b9237c56cb35f6cd399e3ac2fe42e775d | 7d562ef174cc6578ca6013f74db336480470b708 | refs/heads/master | 1,692,144,223,196 | 1,634,661,675,000 | 1,634,661,675,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,313 | lean | import .love02_backward_proofs_exercise_sheet
/- # LoVe Homework 2: Backward Proofs
Homework must be done individually. -/
set_option pp.beta true
set_option pp.generalized_field_notation false
namespace LoVe
namespace backward_proofs
/- ## Question 1 (4 points): Connectives and Quantifiers
1.1 (3 points). Complete the following proofs using basic tactics such as
`intro`, `apply`, and `exact`.
Hint: Some strategies for carrying out such proofs are described at the end of
Section 2.3 in the Hitchhiker's Guide. -/
lemma B (a b c : Prop) :
(a → b) → (c → a) → c → b :=
sorry
lemma S (a b c : Prop) :
(a → b → c) → (a → b) → a → c :=
sorry
lemma more_nonsense (a b c : Prop) :
(c → (a → b) → a) → c → b → a :=
sorry
lemma even_more_nonsense (a b c : Prop) :
(a → a → b) → (b → c) → a → b → c :=
sorry
/- 1.2 (1 point). Prove the following lemma using basic tactics. -/
lemma weak_peirce (a b : Prop) :
((((a → b) → a) → a) → b) → b :=
sorry
/- ## Question 2 (5 points): Logical Connectives
2.1 (1 point). Prove the following property about implication using basic
tactics.
Hints:
* Keep in mind that `¬ a` is the same as `a → false`. You can start by invoking
`rw not_def` if this helps you.
* You will need to apply the elimination rules for `∨` and `false` at some
point. -/
lemma about_implication (a b : Prop) :
¬ a ∨ b → a → b :=
sorry
/- 2.2 (2 points). Prove the missing link in our chain of classical axiom
implications.
Hints:
* You can use `rw double_negation` to unfold the definition of
`double_negation`, and similarly for the other definitions.
* You will need to apply the double negation hypothesis for `a ∨ ¬ a`. You will
also need the left and right introduction rules for `∨` at some point. -/
#check excluded_middle
#check peirce
#check double_negation
lemma em_of_dn :
double_negation → excluded_middle :=
sorry
/- 2.3 (2 points). We have proved three of the six possible implications
between `excluded_middle`, `peirce`, and `double_negation`. State and prove the
three missing implications, exploiting the three theorems we already have. -/
#check peirce_of_em
#check dn_of_peirce
#check em_of_dn
-- enter your solution here
end backward_proofs
end LoVe
|
fbb65137280312eacb7f7d8203157ed223700213 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/direct_sum/finsupp.lean | e5ba9086e40089056ba2f39a4bfb52f8337c9e4c | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 1,580 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import algebra.direct_sum.module
import data.finsupp.to_dfinsupp
/-!
# Results on direct sums and finitely supported functions.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
1. The linear equivalence between finitely supported functions `ι →₀ M` and
the direct sum of copies of `M` indexed by `ι`.
-/
universes u v w
noncomputable theory
open_locale direct_sum
open linear_map submodule
variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M]
section finsupp_lequiv_direct_sum
variables (R M) (ι : Type*) [decidable_eq ι]
/-- The finitely supported functions `ι →₀ M` are in linear equivalence with the direct sum of
copies of M indexed by ι. -/
def finsupp_lequiv_direct_sum : (ι →₀ M) ≃ₗ[R] ⨁ i : ι, M :=
by haveI : Π m : M, decidable (m ≠ 0) := classical.dec_pred _; exact finsupp_lequiv_dfinsupp R
@[simp] theorem finsupp_lequiv_direct_sum_single (i : ι) (m : M) :
finsupp_lequiv_direct_sum R M ι (finsupp.single i m) = direct_sum.lof R ι _ i m :=
finsupp.to_dfinsupp_single i m
@[simp] theorem finsupp_lequiv_direct_sum_symm_lof (i : ι) (m : M) :
(finsupp_lequiv_direct_sum R M ι).symm (direct_sum.lof R ι _ i m) = finsupp.single i m :=
begin
letI : Π m : M, decidable (m ≠ 0) := classical.dec_pred _,
exact (dfinsupp.to_finsupp_single i m),
end
end finsupp_lequiv_direct_sum
|
8868cc800ff3c8cb79cdc841d71c6c064a7af98e | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/bench/binarytrees.lean | a2a57c5c62a9cfb6a518fe7d599d20535951cac8 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 1,696 | lean | inductive Tree
| Nil
| Node (l r : Tree) : Tree
open Tree
instance : Inhabited Tree := ⟨Nil⟩
-- This Function has an extra argument to suppress the
-- common sub-expression elimination optimization
partial def make' : UInt32 -> UInt32 -> Tree
| n, d =>
if d = 0 then Node Nil Nil
else Node (make' n (d - 1)) (make' (n + 1) (d - 1))
-- build a tree
def make (d : UInt32) := make' d d
def check : Tree → UInt32
| Nil => 0
| Node l r => 1 + check l + check r
def minN := 4
def out (s) (n : Nat) (t : UInt32) : IO Unit :=
IO.println (s ++ " of depth " ++ toString n ++ "\t check: " ++ toString t)
-- allocate and check lots of trees
partial def sumT : UInt32 -> UInt32 -> UInt32 -> UInt32
| d, i, t =>
if i = 0 then t
else
let a := check (make d);
sumT d (i-1) (t + a)
-- generate many trees
partial def depth : Nat -> Nat -> List (Nat × Nat × Task UInt32)
| d, m => if d ≤ m then
let n := 2 ^ (m - d + minN);
(n, d, Task.mk (fun _ => sumT (UInt32.ofNat d) (UInt32.ofNat n) 0)) :: depth (d+2) m
else []
def main : List String → IO UInt32
| [s] => do
let n := s.toNat!;
let maxN := Nat.max (minN + 2) n;
let stretchN := maxN + 1;
-- stretch memory tree
let c := check (make $ UInt32.ofNat stretchN);
out "stretch tree" stretchN c;
-- allocate a long lived tree
let long := make $ UInt32.ofNat maxN;
-- allocate, walk, and deallocate many bottom-up binary trees
let vs := (depth minN maxN); -- `using` (parList $ evalTuple3 r0 r0 rseq)
vs.mapM (fun ⟨m,d,i⟩ => out (toString m ++ "\t trees") d i.get);
-- confirm the the long-lived binary tree still exists
out "long lived tree" maxN (check long);
pure 0
| _ => pure 1
|
e6749a4908f14108510e38dd5905bb6f1b2a0cd6 | ea5678cc400c34ff95b661fa26d15024e27ea8cd | /test2.lean | aeafcc4a15e000dfbeb023cada3384178d4fae31 | [] | no_license | ChrisHughes24/leanstuff | dca0b5349c3ed893e8792ffbd98cbcadaff20411 | 9efa85f72efaccd1d540385952a6acc18fce8687 | refs/heads/master | 1,654,883,241,759 | 1,652,873,885,000 | 1,652,873,885,000 | 134,599,537 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 163 | lean | open classical
variables (α : Type) (p q : α → Prop)
variable a : α
variable r : Prop
theorem c4_1 : r→(∃ x:α,r):=
begin
rw[exists_],
end |
64d8b4f6d838e078f66be2914ec7147749a12544 | 649957717d58c43b5d8d200da34bf374293fe739 | /src/data/mv_polynomial.lean | df271477b50e19add6569bd956ac9c2d6137ea14 | [
"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 | 39,895 | 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, Johan Commelin, Mario Carneiro
Multivariate Polynomial
-/
import algebra.ring
import data.finsupp data.polynomial data.equiv.algebra
open set function finsupp lattice
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
/-- Multivariate polynomial, where `σ` is the index set of the variables and
`α` is the coefficient ring -/
def mv_polynomial (σ : Type*) (α : Type*) [comm_semiring α] := (σ →₀ ℕ) →₀ α
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : α} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
variables [decidable_eq σ] [decidable_eq α]
section comm_semiring
variables [comm_semiring α] {p q : mv_polynomial σ α}
instance : decidable_eq (mv_polynomial σ α) := finsupp.decidable_eq
instance : has_zero (mv_polynomial σ α) := finsupp.has_zero
instance : has_one (mv_polynomial σ α) := finsupp.has_one
instance : has_add (mv_polynomial σ α) := finsupp.has_add
instance : has_mul (mv_polynomial σ α) := finsupp.has_mul
instance : comm_semiring (mv_polynomial σ α) := finsupp.comm_semiring
/-- `monomial s a` is the monomial `a * X^s` -/
def monomial (s : σ →₀ ℕ) (a : α) : mv_polynomial σ α := single s a
/-- `C a` is the constant polynomial with value `a` -/
def C (a : α) : mv_polynomial σ α := monomial 0 a
/-- `X n` is the polynomial with value X_n -/
def X (n : σ) : mv_polynomial σ α := monomial (single n 1) 1
@[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ α) := by simp [C, monomial]; refl
@[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ α) := rfl
lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') :=
by simp [C, monomial, single_mul_single]
@[simp] lemma C_add : (C (a + a') : mv_polynomial σ α) = C a + C a' := single_add
@[simp] lemma C_mul : (C (a * a') : mv_polynomial σ α) = C a * C a' := C_mul_monomial.symm
@[simp] lemma C_pow (a : α) (n : ℕ) : (C (a^n) : mv_polynomial σ α) = (C a)^n :=
by induction n; simp [pow_succ, *]
instance : is_semiring_hom (C : α → mv_polynomial σ α) :=
{ map_zero := C_0,
map_one := C_1,
map_add := λ a a', C_add,
map_mul := λ a a', C_mul }
lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ α) = n :=
by induction n; simp [nat.succ_eq_add_one, *]
lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : α) :=
begin
induction e,
{ simp [X], refl },
{ simp [pow_succ, e_ih],
simp [X, monomial, single_mul_single, nat.succ_eq_add_one] }
end
lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) :=
by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp
lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) :=
by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp
lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ α) :=
begin
apply @finsupp.induction σ ℕ _ _ _ _ s,
{ simp [C, prod_zero_index]; exact (mul_one _).symm },
{ assume n e s hns he ih,
simp [prod_add_index, prod_single_index, pow_zero, pow_add, (mul_assoc _ _ _).symm, ih.symm,
monomial_add_single] }
end
@[recursor 7]
lemma induction_on {M : mv_polynomial σ α → Prop} (p : mv_polynomial σ α)
(h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) :
M p :=
have ∀s a, M (monomial s a),
begin
assume s a,
apply @finsupp.induction σ ℕ _ _ _ _ s,
{ show M (monomial 0 a), from h_C a, },
{ assume n e p hpn he ih,
have : ∀e:ℕ, M (monomial p a * X n ^ e),
{ intro e,
induction e,
{ simp [ih] },
{ simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } },
simp [monomial_add_single, this] }
end,
finsupp.induction p
(by have : M (C 0) := h_C 0; rwa [C_0] at this)
(assume s a p hsp ha hp, h_add _ _ (this s a) hp)
lemma hom_eq_hom [semiring γ]
(f g : mv_polynomial σ α → γ) (hf : is_semiring_hom f) (hg : is_semiring_hom g)
(hC : ∀a:α, f (C a) = g (C a)) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ α) :
f p = g p :=
mv_polynomial.induction_on p hC
begin assume p q hp hq, rw [is_semiring_hom.map_add f, is_semiring_hom.map_add g, hp, hq] end
begin assume p n hp, rw [is_semiring_hom.map_mul f, is_semiring_hom.map_mul g, hp, hX] end
lemma is_id (f : mv_polynomial σ α → mv_polynomial σ α) (hf : is_semiring_hom f)
(hC : ∀a:α, f (C a) = (C a)) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ α) :
f p = p :=
hom_eq_hom f id hf is_semiring_hom.id hC hX p
section coeff
def tmp.coe : has_coe_to_fun (mv_polynomial σ α) := by delta mv_polynomial; apply_instance
local attribute [instance] tmp.coe
def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ α) : α := p m
lemma ext (p q : mv_polynomial σ α) :
(∀ m, coeff m p = coeff m q) → p = q := ext
lemma ext_iff (p q : mv_polynomial σ α) :
(∀ m, coeff m p = coeff m q) ↔ p = q :=
⟨ext p q, λ h m, by rw h⟩
@[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ α) :
coeff m (p + q) = coeff m p + coeff m q := add_apply
@[simp] lemma coeff_zero (m : σ →₀ ℕ) :
coeff m (0 : mv_polynomial σ α) = 0 := rfl
@[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ α) = 0 := rfl
instance coeff.is_add_monoid_hom (m : σ →₀ ℕ) :
is_add_monoid_hom (coeff m : mv_polynomial σ α → α) :=
{ map_add := coeff_add m,
map_zero := coeff_zero m }
lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ α) (m : σ →₀ ℕ) :
coeff m (s.sum f) = s.sum (λ x, coeff m (f x)) :=
(finset.sum_hom _).symm
lemma monic_monomial_eq (m) : monomial m (1:α) = (m.prod $ λn e, X n ^ e : mv_polynomial σ α) :=
by simp [monomial_eq]
@[simp] lemma coeff_monomial (m n) (a) :
coeff m (monomial n a : mv_polynomial σ α) = if n = m then a else 0 :=
single_apply
@[simp] lemma coeff_C (m) (a) :
coeff m (C a : mv_polynomial σ α) = if 0 = m then a else 0 :=
single_apply
lemma coeff_X (i : σ) (m) (k : ℕ) :
coeff m (X i ^ k : mv_polynomial σ α) = if finsupp.single i k = m then 1 else 0 :=
begin
have := coeff_monomial m (finsupp.single i k) (1:α),
rwa [@monomial_eq _ _ (1:α) (finsupp.single i k) _ _ _,
C_1, one_mul, finsupp.prod_single_index] at this,
exact pow_zero _
end
@[simp] lemma coeff_C_mul (m) (a : α) (p : mv_polynomial σ α) : coeff m (C a * p) = a * coeff m p :=
begin
rw [mul_def, C, monomial],
simp only [sum_single_index, zero_mul, single_zero, zero_add, sum_zero],
convert sum_apply,
simp only [single_apply, finsupp.sum],
rw finset.sum_eq_single m,
{ rw if_pos rfl, refl },
{ intros m' hm' H, apply if_neg, exact H },
{ intros hm, rw if_pos rfl, rw not_mem_support_iff at hm, simp [hm] }
end
@[simp] lemma coeff_mul_X (m) (i : σ) (p : mv_polynomial σ α) :
coeff (m + single i 1) (p * X i) = coeff m p :=
begin
rw [mul_def, X, monomial],
simp only [sum_single_index, mul_one, single_zero, mul_zero],
convert sum_apply,
simp only [single_apply, finsupp.sum],
rw finset.sum_eq_single m,
{ rw if_pos rfl, refl },
{ intros m' hm' H, apply if_neg, intro h, apply H, ext j,
let c : (σ →₀ ℕ) → (σ → ℕ) := λ f, f, replace h := congr_arg c h, simpa [c] using congr_fun h j },
{ intros hm, rw if_pos rfl, rw not_mem_support_iff at hm, simp [hm] }
end
lemma coeff_mul_X' (m) (i : σ) (p : mv_polynomial σ α) :
coeff m (p * X i) = if i ∈ m.support then coeff (m - single i 1) p else 0 :=
begin
split_ifs with h h,
{ conv_rhs {rw ← coeff_mul_X _ i},
congr' 1, ext j,
by_cases hj : i = j,
{ subst j, simp only [nat_sub_apply, add_apply, single_eq_same],
refine (nat.sub_add_cancel _).symm, rw mem_support_iff at h,
exact nat.pos_of_ne_zero h },
{ simp [single_eq_of_ne hj] } },
{ delta coeff, rw ← not_mem_support_iff, intro hm, apply h,
have H := support_mul _ _ hm, simp only [finset.mem_bind] at H,
rcases H with ⟨j, hj, i', hi', H⟩,
delta X monomial at hi', rw mem_support_single at hi', cases hi',
simp * at * }
end
end coeff
section eval₂
variables [comm_semiring β]
variables (f : α → β) (g : σ → β)
/-- Evaluate a polynomial `p` given a valuation `g` of all the variables
and a ring hom `f` from the scalar ring to the target -/
def eval₂ (p : mv_polynomial σ α) : β :=
p.sum (λs a, f a * s.prod (λn e, g n ^ e))
@[simp] lemma eval₂_zero : (0 : mv_polynomial σ α).eval₂ f g = 0 :=
finsupp.sum_zero_index
variables [is_semiring_hom f]
@[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g :=
finsupp.sum_add_index
(by simp [is_semiring_hom.map_zero f])
(by simp [add_mul, is_semiring_hom.map_add f])
@[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) :=
finsupp.sum_single_index (by simp [is_semiring_hom.map_zero f])
@[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a :=
by simp [eval₂_monomial, C, prod_zero_index]
@[simp] lemma eval₂_one : (1 : mv_polynomial σ α).eval₂ f g = 1 :=
(eval₂_C _ _ _).trans (is_semiring_hom.map_one f)
@[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n :=
by simp [eval₂_monomial,
is_semiring_hom.map_one f, X, prod_single_index, pow_one]
lemma eval₂_mul_monomial :
∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) :=
begin
apply mv_polynomial.induction_on p,
{ assume a' s a,
simp [C_mul_monomial, eval₂_monomial, is_semiring_hom.map_mul f] },
{ assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] },
{ assume p n ih s a,
from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g :
by simp [monomial_single_add, -add_comm, pow_one, mul_assoc]
... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) :
by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm,
is_semiring_hom.map_one f, -add_comm] }
end
@[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g :=
begin
apply mv_polynomial.induction_on q,
{ simp [C, eval₂_monomial, eval₂_mul_monomial, prod_zero_index] },
{ simp [mul_add, eval₂_add] {contextual := tt} },
{ simp [X, eval₂_monomial, eval₂_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} }
end
@[simp] lemma eval₂_pow {p:mv_polynomial σ α} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n
| 0 := eval₂_one _ _
| (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow]
instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f g) :=
{ map_zero := eval₂_zero _ _,
map_one := eval₂_one _ _,
map_add := λ p q, eval₂_add _ _,
map_mul := λ p q, eval₂_mul _ _ }
lemma eval₂_comp_left {γ} [comm_semiring γ]
(k : β → γ) [is_semiring_hom k]
(f : α → β) [is_semiring_hom f] (g : σ → β)
(p) : k (eval₂ f g p) = eval₂ (k ∘ f) (k ∘ g) p :=
by apply mv_polynomial.induction_on p; simp [
eval₂_add, is_semiring_hom.map_add k,
eval₂_mul, is_semiring_hom.map_mul k] {contextual := tt}
@[simp] lemma eval₂_eta (p : mv_polynomial σ α) : eval₂ C X p = p :=
by apply mv_polynomial.induction_on p;
simp [eval₂_add, eval₂_mul] {contextual := tt}
lemma eval₂_congr (g₁ g₂ : σ → β)
(h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) :
p.eval₂ f g₁ = p.eval₂ f g₂ :=
begin
apply finset.sum_congr rfl,
intros c hc, dsimp, congr' 1,
apply finset.prod_congr rfl,
intros i hi, dsimp, congr' 1,
apply h hi,
rwa finsupp.mem_support_iff at hc
end
@[simp] lemma eval₂_prod [decidable_eq γ] (s : finset γ) (p : γ → mv_polynomial σ α) :
eval₂ f g (s.prod p) = s.prod (λ x, eval₂ f g $ p x) :=
(finset.prod_hom _).symm
@[simp] lemma eval₂_sum [decidable_eq γ] (s : finset γ) (p : γ → mv_polynomial σ α) :
eval₂ f g (s.sum p) = s.sum (λ x, eval₂ f g $ p x) :=
(finset.sum_hom _).symm
attribute [to_additive mv_polynomial.eval₂_sum] eval₂_prod
lemma eval₂_assoc [decidable_eq γ] (q : γ → mv_polynomial σ α) (p : mv_polynomial γ α) :
eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) :=
by { rw eval₂_comp_left (eval₂ f g), congr, funext, simp }
end eval₂
section eval
variables {f : σ → α}
/-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/
def eval (f : σ → α) : mv_polynomial σ α → α := eval₂ id f
@[simp] lemma eval_zero : (0 : mv_polynomial σ α).eval f = 0 := eval₂_zero _ _
@[simp] lemma eval_add : (p + q).eval f = p.eval f + q.eval f := eval₂_add _ _
lemma eval_monomial : (monomial s a).eval f = a * s.prod (λn e, f n ^ e) :=
eval₂_monomial _ _
@[simp] lemma eval_C : ∀ a, (C a).eval f = a := eval₂_C _ _
@[simp] lemma eval_X : ∀ n, (X n).eval f = f n := eval₂_X _ _
@[simp] lemma eval_mul : (p * q).eval f = p.eval f * q.eval f := eval₂_mul _ _
instance eval.is_semiring_hom : is_semiring_hom (eval f) :=
eval₂.is_semiring_hom _ _
theorem eval_assoc {τ} [decidable_eq τ]
(f : σ → mv_polynomial τ α) (g : τ → α)
(p : mv_polynomial σ α) :
p.eval (eval g ∘ f) = (eval₂ C f p).eval g :=
begin
rw eval₂_comp_left (eval g),
unfold eval, congr; funext a; simp
end
end eval
section map
variables [comm_semiring β] [decidable_eq β]
variables (f : α → β) [is_semiring_hom f]
/-- `map f p` maps a polynomial `p` across a ring hom `f` -/
def map : mv_polynomial σ α → mv_polynomial σ β := eval₂ (C ∘ f) X
@[simp] theorem map_monomial (s : σ →₀ ℕ) (a : α) : map f (monomial s a) = monomial s (f a) :=
(eval₂_monomial _ _).trans monomial_eq.symm
@[simp] theorem map_C : ∀ (a : α), map f (C a : mv_polynomial σ α) = C (f a) := map_monomial _ _
@[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ α) = X n := eval₂_X _ _
@[simp] theorem map_one : map f (1 : mv_polynomial σ α) = 1 := eval₂_one _ _
@[simp] theorem map_add (p q : mv_polynomial σ α) :
map f (p + q) = map f p + map f q := eval₂_add _ _
@[simp] theorem map_mul (p q : mv_polynomial σ α) :
map f (p * q) = map f p * map f q := eval₂_mul _ _
@[simp] lemma map_pow (p : mv_polynomial σ α) (n : ℕ) :
map f (p^n) = (map f p)^n := eval₂_pow _ _
instance map.is_semiring_hom :
is_semiring_hom (map f : mv_polynomial σ α → mv_polynomial σ β) :=
eval₂.is_semiring_hom _ _
theorem map_id : ∀ (p : mv_polynomial σ α), map id p = p := eval₂_eta
theorem map_map [comm_semiring γ] [decidable_eq γ]
(g : β → γ) [is_semiring_hom g]
(p : mv_polynomial σ α) :
map g (map f p) = map (g ∘ f) p :=
(eval₂_comp_left (map g) (C ∘ f) X p).trans $
by congr; funext a; simp
theorem eval₂_eq_eval_map (g : σ → β) (p : mv_polynomial σ α) :
p.eval₂ f g = (map f p).eval g :=
begin
unfold map eval,
rw eval₂_comp_left (eval₂ id g),
congr; funext a; simp
end
lemma eval₂_comp_right {γ} [comm_semiring γ]
(k : β → γ) [is_semiring_hom k]
(f : α → β) [is_semiring_hom f] (g : σ → β)
(p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, is_semiring_hom.map_add k, map_add, eval₂_add, hp, hq] },
{ intros p s hp,
rw [eval₂_mul, is_semiring_hom.map_mul k, map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] }
end
lemma map_eval₂ [decidable_eq γ] [decidable_eq δ]
(f : α → β) [is_semiring_hom f] (g : γ → mv_polynomial δ α) (p : mv_polynomial γ α) :
map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, map_add, hp, hq, map_add, eval₂_add] },
{ intros p s hp,
rw [eval₂_mul, map_mul, hp, map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] }
end
lemma coeff_map (p : mv_polynomial σ α) : ∀ (m : σ →₀ ℕ), coeff m (p.map f) = f (coeff m p) :=
begin
apply mv_polynomial.induction_on p; clear p,
{ intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw is_semiring_hom.map_zero f },
{ intros p q hp hq m, simp only [hp, hq, map_add, coeff_add], rw is_semiring_hom.map_add f },
{ intros p i hp m, simp only [hp, map_mul, map_X],
simp only [hp, mem_support_iff, coeff_mul_X'],
split_ifs, {refl},
rw is_semiring_hom.map_zero f }
end
lemma map_injective (hf : function.injective f) :
function.injective (map f : mv_polynomial σ α → mv_polynomial σ β) :=
λ p q h, ext _ _ $ λ m, hf $
begin
rw ← ext_iff at h,
specialize h m,
rw [coeff_map, coeff_map] at h,
exact h
end
end map
section degrees
section comm_semiring
def degrees (p : mv_polynomial σ α) : multiset σ :=
p.support.sup (λs:σ →₀ ℕ, s.to_multiset)
lemma degrees_monomial (s : σ →₀ ℕ) (a : α) : degrees (monomial s a) ≤ s.to_multiset :=
finset.sup_le $ assume t h,
begin
have := finsupp.support_single_subset h,
rw [finset.singleton_eq_singleton, finset.mem_singleton] at this,
rw this
end
lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : α) (ha : a ≠ 0) :
degrees (monomial s a) = s.to_multiset :=
le_antisymm (degrees_monomial s a) $ finset.le_sup $
by rw [monomial, finsupp.support_single_ne_zero ha,
finset.singleton_eq_singleton, finset.mem_singleton]
lemma degrees_C (a : α) : degrees (C a : mv_polynomial σ α) = 0 :=
multiset.le_zero.1 $ degrees_monomial _ _
lemma degrees_X (n : σ) : degrees (X n : mv_polynomial σ α) ≤ {n} :=
le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _
lemma degrees_zero : degrees (0 : mv_polynomial σ α) = 0 := degrees_C 0
lemma degrees_one : degrees (1 : mv_polynomial σ α) = 0 := degrees_C 1
lemma degrees_add (p q : mv_polynomial σ α) : (p + q).degrees ≤ p.degrees ⊔ q.degrees :=
begin
refine finset.sup_le (assume b hb, _),
cases finset.mem_union.1 (finsupp.support_add hb),
{ exact le_sup_left_of_le (finset.le_sup h) },
{ exact le_sup_right_of_le (finset.le_sup h) },
end
lemma degrees_sum {ι : Type*} [decidable_eq ι] (s : finset ι) (f : ι → mv_polynomial σ α) :
(s.sum f).degrees ≤ s.sup (λi, (f i).degrees) :=
begin
refine s.induction _ _,
{ simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_refl _ },
{ assume i s his ih,
rw [finset.sup_insert, finset.sum_insert his],
exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) }
end
lemma degrees_mul (p q : mv_polynomial σ α) : (p * q).degrees ≤ p.degrees + q.degrees :=
begin
refine finset.sup_le (assume b hb, _),
have := support_mul p q hb,
simp only [finset.mem_bind, finset.singleton_eq_singleton, finset.mem_singleton] at this,
rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩,
rw [finsupp.to_multiset_add],
exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂)
end
lemma degrees_prod {ι : Type*} [decidable_eq ι] (s : finset ι) (f : ι → mv_polynomial σ α) :
(s.prod f).degrees ≤ s.sum (λi, (f i).degrees) :=
begin
refine s.induction _ _,
{ simp only [finset.prod_empty, finset.sum_empty, degrees_one] },
{ assume i s his ih,
rw [finset.prod_insert his, finset.sum_insert his],
exact le_trans (degrees_mul _ _) (add_le_add_left ih _) }
end
lemma degrees_pow (p : mv_polynomial σ α) :
∀(n : ℕ), (p^n).degrees ≤ add_monoid.smul n p.degrees
| 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end
| (n + 1) := le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _)
end comm_semiring
end degrees
section vars
/-- `vars p` is the set of variables appearing in the polynomial `p` -/
def vars (p : mv_polynomial σ α) : finset σ := p.degrees.to_finset
@[simp] lemma vars_0 : (0 : mv_polynomial σ α).vars = ∅ :=
by rw [vars, degrees_zero, multiset.to_finset_zero]
@[simp] lemma vars_monomial (h : a ≠ 0) : (monomial s a).vars = s.support :=
by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset]
@[simp] lemma vars_C : (C a : mv_polynomial σ α).vars = ∅ :=
by rw [vars, degrees_C, multiset.to_finset_zero]
@[simp] lemma vars_X (h : 0 ≠ (1 : α)) : (X n : mv_polynomial σ α).vars = {n} :=
by rw [X, vars_monomial h.symm, finsupp.support_single_ne_zero zero_ne_one.symm]
end vars
section degree_of
/-- `degree_of n p` gives the highest power of X_n that appears in `p` -/
def degree_of (n : σ) (p : mv_polynomial σ α) : ℕ := p.degrees.count n
end degree_of
section total_degree
/-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/
def total_degree (p : mv_polynomial σ α) : ℕ := p.support.sup (λs, s.sum $ λn e, e)
lemma total_degree_eq (p : mv_polynomial σ α) :
p.total_degree = p.support.sup (λm, m.to_multiset.card) :=
begin
rw [total_degree],
congr, funext m,
exact (finsupp.card_to_multiset _).symm
end
lemma total_degree_le_degrees_card (p : mv_polynomial σ α) :
p.total_degree ≤ p.degrees.card :=
begin
rw [total_degree_eq],
exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs)
end
lemma total_degree_C (a : α) : (C a : mv_polynomial σ α).total_degree = 0 :=
nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn,
have _ := finsupp.support_single_subset hn,
begin
rw [finset.singleton_eq_singleton, finset.mem_singleton] at this,
subst this,
exact le_refl _
end
lemma total_degree_zero : (0 : mv_polynomial σ α).total_degree = 0 :=
by rw [← C_0]; exact total_degree_C (0 : α)
lemma total_degree_one : (1 : mv_polynomial σ α).total_degree = 0 :=
total_degree_C (1 : α)
lemma total_degree_add (a b : mv_polynomial σ α) :
(a + b).total_degree ≤ max a.total_degree b.total_degree :=
finset.sup_le $ assume n hn,
have _ := finsupp.support_add hn,
begin
rcases finset.mem_union.1 this,
{ exact le_max_left_of_le (finset.le_sup h) },
{ exact le_max_right_of_le (finset.le_sup h) }
end
lemma total_degree_mul (a b : mv_polynomial σ α) :
(a * b).total_degree ≤ a.total_degree + b.total_degree :=
finset.sup_le $ assume n hn,
have _ := finsupp.support_mul a b hn,
begin
simp only [finset.mem_bind, finset.mem_singleton, finset.singleton_eq_singleton] at this,
rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩,
rw [finsupp.sum_add_index],
{ exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) },
{ assume a, refl },
{ assume a b₁ b₂, refl }
end
lemma total_degree_list_prod :
∀(s : list (mv_polynomial σ α)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum
| [] := by rw [@list.prod_nil (mv_polynomial σ α) _, total_degree_one]; refl
| (p :: ps) :=
begin
rw [@list.prod_cons (mv_polynomial σ α) _, list.map, list.sum_cons],
exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _)
end
lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ α)) :
s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum :=
begin
refine quotient.induction_on s (assume l, _),
rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum],
exact total_degree_list_prod l
end
lemma total_degree_finset_prod {ι : Type*}
(s : finset ι) (f : ι → mv_polynomial σ α) :
(s.prod f).total_degree ≤ s.sum (λi, (f i).total_degree) :=
begin
refine le_trans (total_degree_multiset_prod _) _,
rw [multiset.map_map],
refl
end
end total_degree
end comm_semiring
section comm_ring
variable [comm_ring α]
variables {p q : mv_polynomial σ α}
instance : ring (mv_polynomial σ α) := finsupp.ring
instance : comm_ring (mv_polynomial σ α) := finsupp.comm_ring
instance : has_scalar α (mv_polynomial σ α) := finsupp.has_scalar
instance : module α (mv_polynomial σ α) := finsupp.module _ α
instance C.is_ring_hom : is_ring_hom (C : α → mv_polynomial σ α) :=
by apply is_ring_hom.of_semiring
variables (σ a a')
lemma C_sub : (C (a - a') : mv_polynomial σ α) = C a - C a' := is_ring_hom.map_sub _
@[simp] lemma C_neg : (C (-a) : mv_polynomial σ α) = -C a := is_ring_hom.map_neg _
@[simp] lemma coeff_sub (m : σ →₀ ℕ) (p q : mv_polynomial σ α) :
coeff m (p - q) = coeff m p - coeff m q := finsupp.sub_apply
instance coeff.is_add_group_hom (m : σ →₀ ℕ) :
is_add_group_hom (coeff m : mv_polynomial σ α → α) :=
⟨coeff_add m⟩
variables {σ} (p)
theorem C_mul' : mv_polynomial.C a * p = a • p :=
begin
apply finsupp.induction p,
{ exact (mul_zero $ mv_polynomial.C a).trans (@smul_zero α (mv_polynomial σ α) _ _ _ a).symm },
intros p b f haf hb0 ih,
rw [mul_add, ih, @smul_add α (mv_polynomial σ α) _ _ _ a], congr' 1,
rw [finsupp.mul_def, finsupp.smul_single, mv_polynomial.C, mv_polynomial.monomial],
rw [finsupp.sum_single_index, finsupp.sum_single_index, zero_add, smul_eq_mul],
{ rw [mul_zero, finsupp.single_zero] },
{ rw finsupp.sum_single_index,
all_goals { rw [zero_mul, finsupp.single_zero] } }
end
lemma smul_eq_C_mul (p : mv_polynomial σ α) (a : α) : a • p = C a * p :=
begin
rw [← finsupp.sum_single p, @finsupp.smul_sum (σ →₀ ℕ) α α, finsupp.mul_sum],
refine finset.sum_congr rfl (assume n _, _),
simp only [finsupp.smul_single],
exact C_mul_monomial.symm
end
@[simp] lemma smul_eval (x) (p : mv_polynomial σ α) (s) : (s • p).eval x = s * p.eval x :=
by rw [smul_eq_C_mul, eval_mul, eval_C]
section degrees
lemma degrees_neg [comm_ring α] (p : mv_polynomial σ α) : (- p).degrees = p.degrees :=
by rw [degrees, finsupp.support_neg]; refl
lemma degrees_sub [comm_ring α] (p q : mv_polynomial σ α) :
(p - q).degrees ≤ p.degrees ⊔ q.degrees :=
le_trans (degrees_add p (-q)) $ by rw [degrees_neg]
end degrees
section eval₂
variables [comm_ring β]
variables (f : α → β) [is_ring_hom f] (g : σ → β)
instance eval₂.is_ring_hom : is_ring_hom (eval₂ f g) :=
by apply is_ring_hom.of_semiring
lemma eval₂_sub : (p - q).eval₂ f g = p.eval₂ f g - q.eval₂ f g := is_ring_hom.map_sub _
@[simp] lemma eval₂_neg : (-p).eval₂ f g = -(p.eval₂ f g) := is_ring_hom.map_neg _
lemma hom_C (f : mv_polynomial σ ℤ → β) [is_ring_hom f] (n : ℤ) : f (C n) = (n : β) :=
congr_fun (int.eq_cast' (f ∘ C)) n
/-- A ring homomorphism f : Z[X_1, X_2, ...] -> R
is determined by the evaluations f(X_1), f(X_2), ... -/
@[simp] lemma eval₂_hom_X {α : Type u} [decidable_eq α] (c : ℤ → β) [is_ring_hom c]
(f : mv_polynomial α ℤ → β) [is_ring_hom f] (x : mv_polynomial α ℤ) :
eval₂ c (f ∘ X) x = f x :=
mv_polynomial.induction_on x
(λ n, by { rw [hom_C f, eval₂_C, int.eq_cast' c], refl })
(λ p q hp hq, by { rw [eval₂_add, hp, hq], exact (is_ring_hom.map_add f).symm })
(λ p n hp, by { rw [eval₂_mul, eval₂_X, hp], exact (is_ring_hom.map_mul f).symm })
end eval₂
section eval
variables (f : σ → α)
instance eval.is_ring_hom : is_ring_hom (eval f) := eval₂.is_ring_hom _ _
lemma eval_sub : (p - q).eval f = p.eval f - q.eval f := is_ring_hom.map_sub _
@[simp] lemma eval_neg : (-p).eval f = -(p.eval f) := is_ring_hom.map_neg _
end eval
section map
variables [decidable_eq β] [comm_ring β]
variables (f : α → β) [is_ring_hom f]
instance map.is_ring_hom : is_ring_hom (map f : mv_polynomial σ α → mv_polynomial σ β) :=
eval₂.is_ring_hom _ _
lemma map_sub : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _
@[simp] lemma map_neg : (-p).map f = -(p.map f) := is_ring_hom.map_neg _
end map
end comm_ring
section rename
variables {α} [comm_semiring α] [decidable_eq α] [decidable_eq β] [decidable_eq γ] [decidable_eq δ]
def rename (f : β → γ) : mv_polynomial β α → mv_polynomial γ α :=
eval₂ C (X ∘ f)
instance rename.is_semiring_hom (f : β → γ) :
is_semiring_hom (rename f : mv_polynomial β α → mv_polynomial γ α) :=
by unfold rename; apply_instance
@[simp] lemma rename_C (f : β → γ) (a : α) : rename f (C a) = C a :=
eval₂_C _ _ _
@[simp] lemma rename_X (f : β → γ) (b : β) : rename f (X b : mv_polynomial β α) = X (f b) :=
eval₂_X _ _ _
@[simp] lemma rename_zero (f : β → γ) :
rename f (0 : mv_polynomial β α) = 0 :=
eval₂_zero _ _
@[simp] lemma rename_one (f : β → γ) :
rename f (1 : mv_polynomial β α) = 1 :=
eval₂_one _ _
@[simp] lemma rename_add (f : β → γ) (p q : mv_polynomial β α) :
rename f (p + q) = rename f p + rename f q :=
eval₂_add _ _
@[simp] lemma rename_sub {α} [comm_ring α] [decidable_eq α]
(f : β → γ) (p q : mv_polynomial β α) :
rename f (p - q) = rename f p - rename f q :=
eval₂_sub _ _ _
@[simp] lemma rename_mul (f : β → γ) (p q : mv_polynomial β α) :
rename f (p * q) = rename f p * rename f q :=
eval₂_mul _ _
@[simp] lemma rename_pow (f : β → γ) (p : mv_polynomial β α) (n : ℕ) :
rename f (p^n) = (rename f p)^n :=
eval₂_pow _ _
lemma map_rename [comm_semiring β] (f : α → β) [is_semiring_hom f]
(g : γ → δ) (p : mv_polynomial γ α) :
map f (rename g p) = rename g (map f p) :=
mv_polynomial.induction_on p
(λ a, by simp)
(λ p q hp hq, by simp [hp, hq])
(λ p n hp, by simp [hp])
@[simp] lemma rename_rename (f : β → γ) (g : γ → δ) (p : mv_polynomial β α) :
rename g (rename f p) = rename (g ∘ f) p :=
show rename g (eval₂ C (X ∘ f) p) = _,
by simp only [eval₂_comp_left (rename g) C (X ∘ f) p, (∘), rename_C, rename_X]; refl
@[simp] lemma rename_id (p : mv_polynomial β α) : rename id p = p :=
eval₂_eta p
lemma rename_monomial (f : β → γ) (p : β →₀ ℕ) (a : α) :
rename f (monomial p a) = monomial (p.map_domain f) a :=
begin
rw [rename, eval₂_monomial, monomial_eq, finsupp.prod_map_domain_index],
{ exact assume n, pow_zero _ },
{ exact assume n i₁ i₂, pow_add _ _ _ }
end
lemma rename_eq (f : β → γ) (p : mv_polynomial β α) :
rename f p = finsupp.map_domain (finsupp.map_domain f) p :=
begin
simp only [rename, eval₂, finsupp.map_domain],
congr, ext s a : 2,
rw [← monomial, monomial_eq, finsupp.prod_sum_index],
congr, ext n i : 2,
rw [finsupp.prod_single_index],
exact pow_zero _,
exact assume a, pow_zero _,
exact assume a b c, pow_add _ _ _
end
lemma injective_rename (f : β → γ) (hf : function.injective f) :
function.injective (rename f : mv_polynomial β α → mv_polynomial γ α) :=
have (rename f : mv_polynomial β α → mv_polynomial γ α) =
finsupp.map_domain (finsupp.map_domain f) := funext (rename_eq f),
begin
rw this,
exact finsupp.injective_map_domain (finsupp.injective_map_domain hf)
end
lemma total_degree_rename_le (f : β → γ) (p : mv_polynomial β α) :
(p.rename f).total_degree ≤ p.total_degree :=
finset.sup_le $ assume b,
begin
assume h,
rw rename_eq at h,
have h' := finsupp.map_domain_support h,
rcases finset.mem_image.1 h' with ⟨s, hs, rfl⟩,
rw finsupp.sum_map_domain_index,
exact le_trans (le_refl _) (finset.le_sup hs),
exact assume _, rfl,
exact assume _ _ _, rfl
end
section
variables [comm_semiring β] (f : α → β) [is_semiring_hom f]
variables (k : γ → δ) (g : δ → β) (p : mv_polynomial γ α)
lemma eval₂_rename : (p.rename k).eval₂ f g = p.eval₂ f (g ∘ k) :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma rename_eval₂ (g : δ → mv_polynomial γ α) :
(p.eval₂ C (g ∘ k)).rename k = (p.rename k).eval₂ C (rename k ∘ g) :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma rename_prodmk_eval₂ (d : δ) (g : γ → mv_polynomial γ α) :
(p.eval₂ C g).rename (prod.mk d) = p.eval₂ C (λ x, (g x).rename (prod.mk d)) :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma eval₂_rename_prodmk (g : δ × γ → β) (d : δ) :
(rename (prod.mk d) p).eval₂ f g = eval₂ f (λ i, g (d, i)) p :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma eval_rename_prodmk (g : δ × γ → α) (d : δ) :
(rename (prod.mk d) p).eval g = eval (λ i, g (d, i)) p :=
eval₂_rename_prodmk id _ _ _
end
end rename
lemma eval₂_cast_comp {β : Type u} {γ : Type v} [decidable_eq β] [decidable_eq γ] (f : γ → β)
{α : Type w} [comm_ring α] (c : ℤ → α) [is_ring_hom c] (g : β → α) (x : mv_polynomial γ ℤ) :
eval₂ c (g ∘ f) x = eval₂ c g (rename f x) :=
mv_polynomial.induction_on x
(λ n, by simp only [eval₂_C, rename_C])
(λ p q hp hq, by simp only [hp, hq, rename, eval₂_add])
(λ p n hp, by simp only [hp, rename, eval₂_X, eval₂_mul])
instance rename.is_ring_hom
{α} [comm_ring α] [decidable_eq α] [decidable_eq β] [decidable_eq γ] (f : β → γ) :
is_ring_hom (rename f : mv_polynomial β α → mv_polynomial γ α) :=
@is_ring_hom.of_semiring (mv_polynomial β α) (mv_polynomial γ α) _ _ (rename f)
(rename.is_semiring_hom f)
section equiv
variables (α) [comm_ring α]
variables [decidable_eq β] [decidable_eq γ] [decidable_eq δ]
set_option class.instance_max_depth 40
def pempty_ring_equiv : mv_polynomial pempty α ≃r α :=
{ to_fun := mv_polynomial.eval₂ id $ pempty.elim,
inv_fun := C,
left_inv := is_id _ (by apply_instance) (assume a, by rw [eval₂_C]; refl) (assume a, a.elim),
right_inv := λ r, eval₂_C _ _ _,
hom := eval₂.is_ring_hom _ _ }
def punit_ring_equiv : mv_polynomial punit α ≃r polynomial α :=
{ to_fun := eval₂ polynomial.C (λu:punit, polynomial.X),
inv_fun := polynomial.eval₂ mv_polynomial.C (X punit.star),
left_inv :=
begin
refine is_id _ _ _ _,
apply is_semiring_hom.comp (eval₂ polynomial.C (λu:punit, polynomial.X)) _; apply_instance,
{ assume a, rw [eval₂_C, polynomial.eval₂_C] },
{ rintros ⟨⟩, rw [eval₂_X, polynomial.eval₂_X] }
end,
right_inv := assume p, polynomial.induction_on p
(assume a, by rw [polynomial.eval₂_C, mv_polynomial.eval₂_C])
(assume p q hp hq, by rw [polynomial.eval₂_add, mv_polynomial.eval₂_add, hp, hq])
(assume p n hp,
by rw [polynomial.eval₂_mul, polynomial.eval₂_pow, polynomial.eval₂_X, polynomial.eval₂_C,
eval₂_mul, eval₂_C, eval₂_pow, eval₂_X]),
hom := eval₂.is_ring_hom _ _ }
def ring_equiv_of_equiv (e : β ≃ γ) : mv_polynomial β α ≃r mv_polynomial γ α :=
{ to_fun := rename e,
inv_fun := rename e.symm,
left_inv := λ p, by simp only [rename_rename, (∘), e.symm_apply_apply]; exact rename_id p,
right_inv := λ p, by simp only [rename_rename, (∘), e.apply_symm_apply]; exact rename_id p,
hom := rename.is_ring_hom e }
def ring_equiv_congr [comm_ring γ] (e : α ≃r γ) : mv_polynomial β α ≃r mv_polynomial β γ :=
{ to_fun := map e.to_fun,
inv_fun := map e.symm.to_fun,
left_inv := assume p,
have (e.symm.to_equiv.to_fun ∘ e.to_equiv.to_fun) = id,
{ ext a, exact e.to_equiv.symm_apply_apply a },
by simp only [map_map, this, map_id],
right_inv := assume p,
have (e.to_equiv.to_fun ∘ e.symm.to_equiv.to_fun) = id,
{ ext a, exact e.to_equiv.apply_symm_apply a },
by simp only [map_map, this, map_id],
hom := map.is_ring_hom e.to_fun }
section
variables (β γ δ)
instance ring_on_sum : ring (mv_polynomial (β ⊕ γ) α) := by apply_instance
instance ring_on_iter : ring (mv_polynomial β (mv_polynomial γ α)) := by apply_instance
def sum_to_iter : mv_polynomial (β ⊕ γ) α → mv_polynomial β (mv_polynomial γ α) :=
eval₂ (C ∘ C) (λbc, sum.rec_on bc X (C ∘ X))
instance is_semiring_hom_C_C :
is_semiring_hom (C ∘ C : α → mv_polynomial β (mv_polynomial γ α)) :=
@is_semiring_hom.comp _ _ _ _ C mv_polynomial.is_semiring_hom _ _ C mv_polynomial.is_semiring_hom
instance is_semiring_hom_sum_to_iter : is_semiring_hom (sum_to_iter α β γ) :=
eval₂.is_semiring_hom _ _
lemma sum_to_iter_C (a : α) : sum_to_iter α β γ (C a) = C (C a) :=
eval₂_C _ _ a
lemma sum_to_iter_Xl (b : β) : sum_to_iter α β γ (X (sum.inl b)) = X b :=
eval₂_X _ _ (sum.inl b)
lemma sum_to_iter_Xr (c : γ) : sum_to_iter α β γ (X (sum.inr c)) = C (X c) :=
eval₂_X _ _ (sum.inr c)
def iter_to_sum : mv_polynomial β (mv_polynomial γ α) → mv_polynomial (β ⊕ γ) α :=
eval₂ (eval₂ C (X ∘ sum.inr)) (X ∘ sum.inl)
section
instance is_semiring_hom_iter_to_sum : is_semiring_hom (iter_to_sum α β γ) :=
eval₂.is_semiring_hom _ _
end
lemma iter_to_sum_C_C (a : α) : iter_to_sum α β γ (C (C a)) = C a :=
eq.trans (eval₂_C _ _ (C a)) (eval₂_C _ _ _)
lemma iter_to_sum_X (b : β) : iter_to_sum α β γ (X b) = X (sum.inl b) :=
eval₂_X _ _ _
lemma iter_to_sum_C_X (c : γ) : iter_to_sum α β γ (C (X c)) = X (sum.inr c) :=
eq.trans (eval₂_C _ _ (X c)) (eval₂_X _ _ _)
def mv_polynomial_equiv_mv_polynomial [comm_ring δ]
(f : mv_polynomial β α → mv_polynomial γ δ) (hf : is_semiring_hom f)
(g : mv_polynomial γ δ → mv_polynomial β α) (hg : is_semiring_hom g)
(hfgC : ∀a, f (g (C a)) = C a)
(hfgX : ∀n, f (g (X n)) = X n)
(hgfC : ∀a, g (f (C a)) = C a)
(hgfX : ∀n, g (f (X n)) = X n) :
mv_polynomial β α ≃r mv_polynomial γ δ :=
{ to_fun := f, inv_fun := g,
left_inv := is_id _ (is_semiring_hom.comp _ _) hgfC hgfX,
right_inv := is_id _ (is_semiring_hom.comp _ _) hfgC hfgX,
hom := is_ring_hom.of_semiring f }
def sum_ring_equiv : mv_polynomial (β ⊕ γ) α ≃r mv_polynomial β (mv_polynomial γ α) :=
begin
apply @mv_polynomial_equiv_mv_polynomial α (β ⊕ γ) _ _ _ _ _ _ _ _
(sum_to_iter α β γ) _ (iter_to_sum α β γ) _,
{ assume p,
apply @hom_eq_hom _ _ _ _ _ _ _ _ _ _ _ _ _ p,
apply_instance,
{ apply @is_semiring_hom.comp _ _ _ _ _ _ _ _ _ _,
apply_instance,
apply @is_semiring_hom.comp _ _ _ _ _ _ _ _ _ _,
apply_instance,
{ apply @mv_polynomial.is_semiring_hom },
{ apply mv_polynomial.is_semiring_hom_iter_to_sum α β γ },
{ apply mv_polynomial.is_semiring_hom_sum_to_iter α β γ } },
{ apply mv_polynomial.is_semiring_hom },
{ assume a, rw [iter_to_sum_C_C α β γ, sum_to_iter_C α β γ] },
{ assume c, rw [iter_to_sum_C_X α β γ, sum_to_iter_Xr α β γ] } },
{ assume b, rw [iter_to_sum_X α β γ, sum_to_iter_Xl α β γ] },
{ assume a, rw [sum_to_iter_C α β γ, iter_to_sum_C_C α β γ] },
{ assume n, cases n with b c,
{ rw [sum_to_iter_Xl, iter_to_sum_X] },
{ rw [sum_to_iter_Xr, iter_to_sum_C_X] } },
{ apply mv_polynomial.is_semiring_hom_sum_to_iter α β γ },
{ apply mv_polynomial.is_semiring_hom_iter_to_sum α β γ }
end
instance option_ring : ring (mv_polynomial (option β) α) :=
mv_polynomial.ring
instance polynomial_ring : ring (polynomial (mv_polynomial β α)) :=
@comm_ring.to_ring _ polynomial.comm_ring
instance polynomial_ring2 : ring (mv_polynomial β (polynomial α)) :=
by apply_instance
def option_equiv_left : mv_polynomial (option β) α ≃r polynomial (mv_polynomial β α) :=
(ring_equiv_of_equiv α $ (equiv.option_equiv_sum_punit β).trans (equiv.sum_comm _ _)).trans $
(sum_ring_equiv α _ _).trans $
punit_ring_equiv _
def option_equiv_right : mv_polynomial (option β) α ≃r mv_polynomial β (polynomial α) :=
(ring_equiv_of_equiv α $ equiv.option_equiv_sum_punit.{0} β).trans $
(sum_ring_equiv α β unit).trans $
ring_equiv_congr (mv_polynomial unit α) (punit_ring_equiv α)
end
end equiv
end mv_polynomial
|
986d4ab31058a5f66d0b9e784e36486423802ada | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/data/real/cau_seq.lean | 97c8efd3a1839586cc065089c353bbb7ca0b24b6 | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 25,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 algebra.big_operators.order
/-!
# Cauchy sequences
A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where
applicable, lemmas that will be reused in other contexts have been stated in extra generality.
There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology.
This is a concrete implementation that is useful for simplicity and computability reasons.
## Important definitions
* `is_absolute_value`: a type class stating that `f : β → α` satisfies the axioms of an abs val
* `is_cau_seq`: a predicate that says `f : ℕ → β` is Cauchy.
* `cau_seq`: the type of Cauchy sequences valued in type `β` with respect to an absolute value
function `abv`.
## Tags
sequence, cauchy, abs val, absolute value
-/
open_locale big_operators
/-- A function `f` is an absolute value if it is nonnegative, zero only at 0, additive, and
multiplicative. -/
class is_absolute_value {α} [linear_ordered_field α]
{β} [ring β] (f : β → α) : Prop :=
(abv_nonneg [] : ∀ x, 0 ≤ f x)
(abv_eq_zero [] : ∀ {x}, f x = 0 ↔ x = 0)
(abv_add [] : ∀ x y, f (x + y) ≤ f x + f y)
(abv_mul [] : ∀ x y, f (x * y) = f x * f y)
namespace is_absolute_value
variables {α : Type*} [linear_ordered_field α]
{β : Type*} [ring β] (abv : β → α) [is_absolute_value abv]
theorem abv_zero : abv 0 = 0 := (abv_eq_zero abv).2 rfl
theorem abv_one' (h : (1:β) ≠ 0) : abv 1 = 1 :=
(mul_right_inj' $ mt (abv_eq_zero abv).1 h).1 $
by rw [← abv_mul abv, mul_one, mul_one]
theorem abv_one
{β : Type*} [domain β] (abv : β → α) [is_absolute_value abv] :
abv 1 = 1 := abv_one' abv one_ne_zero
theorem abv_pos {a : β} : 0 < abv a ↔ a ≠ 0 :=
by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [abv_eq_zero abv, abv_nonneg abv]
theorem abv_neg (a : β) : abv (-a) = abv a :=
by rw [← mul_self_inj_of_nonneg (abv_nonneg abv _) (abv_nonneg abv _),
← abv_mul abv, ← abv_mul abv]; simp
theorem abv_sub (a b : β) : abv (a - b) = abv (b - a) :=
by rw [← neg_sub, abv_neg abv]
theorem abv_inv
{β : Type*} [field β] (abv : β → α) [is_absolute_value abv]
(a : β) : abv a⁻¹ = (abv a)⁻¹ :=
classical.by_cases
(λ h : a = 0, by simp [h, abv_zero abv])
(λ h, mul_right_cancel' (mt (abv_eq_zero abv).1 h) $
by rw [← abv_mul abv]; simp [h, mt (abv_eq_zero abv).1 h, abv_one abv])
theorem abv_div
{β : Type*} [field β] (abv : β → α) [is_absolute_value abv]
(a b : β) : abv (a / b) = abv a / abv b :=
by rw [division_def, abv_mul abv, abv_inv abv]; refl
lemma abv_sub_le (a b c : β) : abv (a - c) ≤ abv (a - b) + abv (b - c) :=
by simpa [sub_eq_add_neg, add_assoc] using abv_add abv (a - b) (b - c)
lemma sub_abv_le_abv_sub (a b : β) : abv a - abv b ≤ abv (a - b) :=
sub_le_iff_le_add.2 $ by simpa using abv_add abv (a - b) b
lemma abs_abv_sub_le_abv_sub (a b : β) :
abs (abv a - abv b) ≤ abv (a - b) :=
abs_sub_le_iff.2 ⟨sub_abv_le_abv_sub abv _ _,
by rw abv_sub abv; apply sub_abv_le_abv_sub abv⟩
lemma abv_pow {β : Type*} [domain β] (abv : β → α) [is_absolute_value abv]
(a : β) (n : ℕ) : abv (a ^ n) = abv a ^ n :=
by induction n; simp [abv_mul abv, pow_succ, abv_one abv, *]
end is_absolute_value
instance abs_is_absolute_value {α} [linear_ordered_field α] :
is_absolute_value (abs : α → α) :=
{ abv_nonneg := abs_nonneg,
abv_eq_zero := λ _, abs_eq_zero,
abv_add := abs_add,
abv_mul := abs_mul }
open is_absolute_value
theorem exists_forall_ge_and {α} [linear_order α] {P Q : α → Prop} :
(∃ i, ∀ j ≥ i, P j) → (∃ i, ∀ j ≥ i, Q j) →
∃ i, ∀ j ≥ i, P j ∧ Q j
| ⟨a, h₁⟩ ⟨b, h₂⟩ := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in
⟨c, λ j hj, ⟨h₁ _ (le_trans ac hj), h₂ _ (le_trans bc hj)⟩⟩
section
variables {α : Type*} [linear_ordered_field α]
{β : Type*} [ring β] (abv : β → α) [is_absolute_value abv]
theorem rat_add_continuous_lemma
{ε : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β},
abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ + a₂ - (b₁ + b₂)) < ε :=
⟨ε / 2, half_pos ε0, λ a₁ a₂ b₁ b₂ h₁ h₂,
by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]
using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ h₂)⟩
theorem rat_mul_continuous_lemma
{ε K₁ K₂ : α} (ε0 : 0 < ε) :
∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv a₁ < K₁ → abv b₂ < K₂ →
abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ * a₂ - b₁ * b₂) < ε :=
begin
have K0 : (0 : α) < max 1 (max K₁ K₂) := lt_of_lt_of_le zero_lt_one (le_max_left _ _),
have εK := div_pos (half_pos ε0) K0,
refine ⟨_, εK, λ a₁ a₂ b₁ b₂ ha₁ hb₂ h₁ h₂, _⟩,
replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ K₂) (le_max_right 1 _)),
replace hb₂ := lt_of_lt_of_le hb₂ (le_trans (le_max_right K₁ _) (le_max_right 1 _)),
have := add_lt_add
(mul_lt_mul' (le_of_lt h₁) hb₂ (abv_nonneg abv _) εK)
(mul_lt_mul' (le_of_lt h₂) ha₁ (abv_nonneg abv _) εK),
rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this,
simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm]
using lt_of_le_of_lt (abv_add abv _ _) this
end
theorem rat_inv_continuous_lemma
{β : Type*} [field β] (abv : β → α) [is_absolute_value abv]
{ε K : α} (ε0 : 0 < ε) (K0 : 0 < K) :
∃ δ > 0, ∀ {a b : β}, K ≤ abv a → K ≤ abv b →
abv (a - b) < δ → abv (a⁻¹ - b⁻¹) < ε :=
begin
have KK := mul_pos K0 K0,
have εK := mul_pos ε0 KK,
refine ⟨_, εK, λ a b ha hb h, _⟩,
have a0 := lt_of_lt_of_le K0 ha,
have b0 := lt_of_lt_of_le K0 hb,
rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0),
abv_div abv, abv_mul abv, mul_comm, abv_sub abv,
← mul_div_cancel ε (ne_of_gt KK)],
exact div_lt_div h
(mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _))
(le_of_lt $ mul_pos ε0 KK) KK
end
end
/-- A sequence is Cauchy if the distance between its entries tends to zero. -/
def is_cau_seq {α : Type*} [linear_ordered_field α]
{β : Type*} [ring β] (abv : β → α) (f : ℕ → β) : Prop :=
∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - f i) < ε
namespace is_cau_seq
variables {α : Type*} [linear_ordered_field α]
{β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] {f : ℕ → β}
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem cauchy₂ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) :
∃ i, ∀ j k ≥ i, abv (f j - f k) < ε :=
begin
refine (hf _ (half_pos ε0)).imp (λ i hi j k ij ik, _),
rw ← add_halves ε,
refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _),
rw abv_sub abv, exact hi _ ik
end
theorem cauchy₃ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) :
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε :=
let ⟨i, H⟩ := hf.cauchy₂ ε0 in ⟨i, λ j ij k jk, H _ _ (le_trans ij jk) ij⟩
end is_cau_seq
/-- `cau_seq β abv` is the type of `β`-valued Cauchy sequences, with respect to the absolute value
function `abv`. -/
def cau_seq {α : Type*} [linear_ordered_field α]
(β : Type*) [ring β] (abv : β → α) : Type* :=
{f : ℕ → β // is_cau_seq abv f}
namespace cau_seq
variables {α : Type*} [linear_ordered_field α]
section ring
variables {β : Type*} [ring β] {abv : β → α}
instance : has_coe_to_fun (cau_seq β abv) := ⟨_, subtype.val⟩
@[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) :
@coe_fn (cau_seq β abv) _ ⟨f, hf⟩ = f := rfl
theorem ext {f g : cau_seq β abv} (h : ∀ i, f i = g i) : f = g :=
subtype.eq (funext h)
theorem is_cau (f : cau_seq β abv) : is_cau_seq abv f := f.2
theorem cauchy (f : cau_seq β abv) :
∀ {ε}, 0 < ε → ∃ i, ∀ j ≥ i, abv (f j - f i) < ε := f.2
/-- Given a Cauchy sequence `f`, create a Cauchy sequence from a sequence `g` with
the same values as `f`. -/
def of_eq (f : cau_seq β abv) (g : ℕ → β) (e : ∀ i, f i = g i) : cau_seq β abv :=
⟨g, λ ε, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩
variable [is_absolute_value abv]
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem cauchy₂ (f : cau_seq β abv) {ε} : 0 < ε →
∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := f.2.cauchy₂
theorem cauchy₃ (f : cau_seq β abv) {ε} : 0 < ε →
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := f.2.cauchy₃
theorem bounded (f : cau_seq β abv) : ∃ r, ∀ i, abv (f i) < r :=
begin
cases f.cauchy zero_lt_one with i h,
let R := ∑ j in finset.range (i+1), abv (f j),
have : ∀ j ≤ i, abv (f j) ≤ R,
{ intros j ij, change (λ j, abv (f j)) j ≤ R,
apply finset.single_le_sum,
{ intros, apply abv_nonneg abv },
{ rwa [finset.mem_range, nat.lt_succ_iff] } },
refine ⟨R + 1, λ j, _⟩,
cases lt_or_le j i with ij ij,
{ exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) },
{ have := lt_of_le_of_lt (abv_add abv _ _)
(add_lt_add_of_le_of_lt (this _ (le_refl _)) (h _ ij)),
rw [add_sub, add_comm] at this, simpa }
end
theorem bounded' (f : cau_seq β abv) (x : α) : ∃ r > x, ∀ i, abv (f i) < r :=
let ⟨r, h⟩ := f.bounded in
⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _),
λ i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩
instance : has_add (cau_seq β abv) :=
⟨λ f g, ⟨λ i, (f i + g i : β), λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abv ε0,
⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (H₁ _ ij) (H₂ _ ij)⟩⟩⟩
@[simp] theorem add_apply (f g : cau_seq β abv) (i : ℕ) : (f + g) i = f i + g i := rfl
variable (abv)
/-- The constant Cauchy sequence. -/
def const (x : β) : cau_seq β abv :=
⟨λ i, x, λ ε ε0, ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩⟩
variable {abv}
local notation `const` := const abv
@[simp] theorem const_apply (x : β) (i : ℕ) : (const x : ℕ → β) i = x := rfl
theorem const_inj {x y : β} : (const x : cau_seq β abv) = const y ↔ x = y :=
⟨λ h, congr_arg (λ f:cau_seq β abv, (f:ℕ→β) 0) h, congr_arg _⟩
instance : has_zero (cau_seq β abv) := ⟨const 0⟩
instance : has_one (cau_seq β abv) := ⟨const 1⟩
instance : inhabited (cau_seq β abv) := ⟨0⟩
@[simp] theorem zero_apply (i) : (0 : cau_seq β abv) i = 0 := rfl
@[simp] theorem one_apply (i) : (1 : cau_seq β abv) i = 1 := rfl
theorem const_add (x y : β) : const (x + y) = const x + const y :=
ext $ λ i, rfl
instance : has_mul (cau_seq β abv) :=
⟨λ f g, ⟨λ i, (f i * g i : β), λ ε ε0,
let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0,
⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abv ε0,
⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in
Hδ (hF j) (hG i) (H₁ _ ij) (H₂ _ ij)⟩⟩⟩
@[simp] theorem mul_apply (f g : cau_seq β abv) (i : ℕ) : (f * g) i = f i * g i := rfl
theorem const_mul (x y : β) : const (x * y) = const x * const y :=
ext $ λ i, rfl
instance : has_neg (cau_seq β abv) :=
⟨λ f, of_eq (const (-1) * f) (λ x, -f x) (λ i, by simp)⟩
@[simp] theorem neg_apply (f : cau_seq β abv) (i) : (-f) i = -f i := rfl
theorem const_neg (x : β) : const (-x) = -const x :=
ext $ λ i, rfl
instance : ring (cau_seq β abv) :=
by refine {neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, ..};
{ intros, apply ext, simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm] }
instance {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] :
comm_ring (cau_seq β abv) :=
{ mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm],
..cau_seq.ring }
theorem const_sub (x y : β) : const (x - y) = const x - const y :=
by rw [sub_eq_add_neg, const_add, const_neg, sub_eq_add_neg]
@[simp] theorem sub_apply (f g : cau_seq β abv) (i : ℕ) : (f - g) i = f i - g i := rfl
/-- `lim_zero f` holds when `f` approaches 0. -/
def lim_zero {abv : β → α} (f : cau_seq β abv) : Prop := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j) < ε
theorem add_lim_zero {f g : cau_seq β abv}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g)
| ε ε0 := (exists_forall_ge_and
(hf _ $ half_pos ε0) (hg _ $ half_pos ε0)).imp $
λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in
by simpa [add_halves ε] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ H₂)
theorem mul_lim_zero_right (f : cau_seq β abv) {g}
(hg : lim_zero g) : lim_zero (f * g)
| ε ε0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in
(hg _ $ div_pos ε0 F0).imp $ λ i H j ij,
by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0;
rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this
theorem mul_lim_zero_left {f} (g : cau_seq β abv)
(hg : lim_zero f) : lim_zero (f * g)
| ε ε0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in
(hg _ $ div_pos ε0 G0).imp $ λ i H j ij,
by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _);
rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this
theorem neg_lim_zero {f : cau_seq β abv} (hf : lim_zero f) : lim_zero (-f) :=
by rw ← neg_one_mul; exact mul_lim_zero_right _ hf
theorem sub_lim_zero {f g : cau_seq β abv}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) :=
by simpa only [sub_eq_add_neg] using add_lim_zero hf (neg_lim_zero hg)
theorem lim_zero_sub_rev {f g : cau_seq β abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) :=
by simpa using neg_lim_zero hfg
theorem zero_lim_zero : lim_zero (0 : cau_seq β abv)
| ε ε0 := ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩
theorem const_lim_zero {x : β} : lim_zero (const x) ↔ x = 0 :=
⟨λ H, (abv_eq_zero abv).1 $
eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $
λ ε ε0, let ⟨i, hi⟩ := H _ ε0 in le_of_lt $ hi _ (le_refl _),
λ e, e.symm ▸ zero_lim_zero⟩
instance equiv : setoid (cau_seq β abv) :=
⟨λ f g, lim_zero (f - g),
⟨λ f, by simp [zero_lim_zero],
λ f g h, by simpa using neg_lim_zero h,
λ f g h fg gh, by simpa [sub_eq_add_neg, add_assoc] using add_lim_zero fg gh⟩⟩
lemma add_equiv_add {f1 f2 g1 g2 : cau_seq β abv} (hf : f1 ≈ f2) (hg : g1 ≈ g2) :
f1 + g1 ≈ f2 + g2 :=
begin
change lim_zero ((f1 + g1) - _),
convert add_lim_zero hf hg using 1,
simp only [sub_eq_add_neg, add_assoc],
rw add_comm (-f2), simp only [add_assoc],
congr' 2, simp
end
lemma neg_equiv_neg {f g : cau_seq β abv} (hf : f ≈ g) : -f ≈ -g :=
begin
have hf : lim_zero _ := neg_lim_zero hf,
show lim_zero (-f - -g),
convert hf using 1, simp
end
theorem equiv_def₃ {f g : cau_seq β abv} (h : f ≈ g) {ε : α} (ε0 : 0 < ε) :
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - g j) < ε :=
(exists_forall_ge_and (h _ $ half_pos ε0) (f.cauchy₃ $ half_pos ε0)).imp $
λ i H j ij k jk, let ⟨h₁, h₂⟩ := H _ ij in
by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (h₂ _ jk));
rwa [sub_add_sub_cancel', add_halves] at this
theorem lim_zero_congr {f g : cau_seq β abv} (h : f ≈ g) : lim_zero f ↔ lim_zero g :=
⟨λ l, by simpa using add_lim_zero (setoid.symm h) l,
λ l, by simpa using add_lim_zero h l⟩
theorem abv_pos_of_not_lim_zero {f : cau_seq β abv} (hf : ¬ lim_zero f) :
∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ abv (f j) :=
begin
haveI := classical.prop_decidable,
by_contra nk,
refine hf (λ ε ε0, _),
simp [not_forall] at nk,
cases f.cauchy₃ (half_pos ε0) with i hi,
rcases nk _ (half_pos ε0) i with ⟨j, ij, hj⟩,
refine ⟨j, λ k jk, _⟩,
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj),
rwa [sub_add_cancel, add_halves] at this
end
theorem of_near (f : ℕ → β) (g : cau_seq β abv)
(h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - g j) < ε) : is_cau_seq abv f
| ε ε0 :=
let ⟨i, hi⟩ := exists_forall_ge_and
(h _ (half_pos $ half_pos ε0)) (g.cauchy₃ $ half_pos ε0) in
⟨i, λ j ij, begin
cases hi _ (le_refl _) with h₁ h₂, rw abv_sub abv at h₁,
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁),
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (h₂ _ ij)),
rwa [add_halves, add_halves, add_right_comm,
sub_add_sub_cancel, sub_add_sub_cancel] at this
end⟩
lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : ¬ f ≈ 0) : ¬ lim_zero f :=
assume : lim_zero f,
have lim_zero (f - 0), by simpa,
hf this
lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : g * f ≈ 0 :=
have lim_zero (f - 0), from hf,
have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa,
show lim_zero (g*f - 0), by simpa
lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : ¬ (f * g) ≈ 0 :=
assume : lim_zero (f*g - 0),
have hlz : lim_zero (f*g), by simpa,
have hf' : ¬ lim_zero f, by simpa using (show ¬ lim_zero (f - 0), from hf),
have hg' : ¬ lim_zero g, by simpa using (show ¬ lim_zero (g - 0), from hg),
begin
rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩,
rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩,
have : 0 < a1 * a2, from mul_pos ha1 ha2,
cases hlz _ this with N hN,
let i := max N (max N1 N2),
have hN' := hN i (le_max_left _ _),
have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)),
have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)),
apply not_le_of_lt hN',
change _ ≤ abv (_ * _),
rw is_absolute_value.abv_mul abv,
apply mul_le_mul; try { assumption },
{ apply le_of_lt ha2 },
{ apply is_absolute_value.abv_nonneg abv }
end
theorem const_equiv {x y : β} : const x ≈ const y ↔ x = y :=
show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero]
end ring
section comm_ring
variables {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv]
lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : f * g ≈ 0 :=
by rw mul_comm; apply mul_equiv_zero _ hf
end comm_ring
section integral_domain
variables {β : Type*} [integral_domain β] (abv : β → α) [is_absolute_value abv]
lemma one_not_equiv_zero : ¬ (const abv 1) ≈ (const abv 0) :=
assume h,
have ∀ ε > 0, ∃ i, ∀ k, i ≤ k → abv (1 - 0) < ε, from h,
have h1 : abv 1 ≤ 0, from le_of_not_gt $
assume h2 : 0 < abv 1,
exists.elim (this _ h2) $ λ i hi,
lt_irrefl (abv 1) $ by simpa using hi _ (le_refl _),
have h2 : 0 ≤ abv 1, from is_absolute_value.abv_nonneg _ _,
have abv 1 = 0, from le_antisymm h1 h2,
have (1 : β) = 0, from (is_absolute_value.abv_eq_zero abv).1 this,
absurd this one_ne_zero
end integral_domain
section field
variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv]
theorem inv_aux {f : cau_seq β abv} (hf : ¬ lim_zero f) :
∀ ε > 0, ∃ i, ∀ j ≥ i, abv ((f j)⁻¹ - (f i)⁻¹) < ε | ε ε0 :=
let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf,
⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abv ε0 K0,
⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨iK, H'⟩ := H _ (le_refl _) in Hδ (H _ ij).1 iK (H' _ ij)⟩
/-- Given a Cauchy sequence `f` with nonzero limit, create a Cauchy sequence with values equal to
the inverses of the values of `f`. -/
def inv (f : cau_seq β abv) (hf : ¬ lim_zero f) : cau_seq β abv := ⟨_, inv_aux hf⟩
@[simp] theorem inv_apply {f : cau_seq β abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl
theorem inv_mul_cancel {f : cau_seq β abv} (hf) : inv f hf * f ≈ 1 :=
λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in
⟨i, λ j ij,
by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)),
abv_zero abv] using ε0⟩
theorem const_inv {x : β} (hx : x ≠ 0) :
const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) :=
ext (assume n, by simp[inv_apply, const_apply])
end field
section abs
local notation `const` := const abs
/-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/
def pos (f : cau_seq α abs) : Prop := ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ f j
theorem not_lim_zero_of_pos {f : cau_seq α abs} : pos f → ¬ lim_zero f
| ⟨F, F0, hF⟩ H :=
let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0),
⟨h₁, h₂⟩ := h _ (le_refl _) in
not_lt_of_le h₁ (abs_lt.1 h₂).2
theorem const_pos {x : α} : pos (const x) ↔ 0 < x :=
⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ (le_refl _)),
λ h, ⟨x, h, 0, λ j _, le_refl _⟩⟩
theorem add_pos {f g : cau_seq α abs} : pos f → pos g → pos (f + g)
| ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ :=
let ⟨i, h⟩ := exists_forall_ge_and hF hG in
⟨_, _root_.add_pos F0 G0, i,
λ j ij, let ⟨h₁, h₂⟩ := h _ ij in add_le_add h₁ h₂⟩
theorem pos_add_lim_zero {f g : cau_seq α abs} : pos f → lim_zero g → pos (f + g)
| ⟨F, F0, hF⟩ H :=
let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in
⟨_, half_pos F0, i, λ j ij, begin
cases h j ij with h₁ h₂,
have := add_le_add h₁ (le_of_lt (abs_lt.1 h₂).1),
rwa [← sub_eq_add_neg, sub_self_div_two] at this
end⟩
protected theorem mul_pos {f g : cau_seq α abs} : pos f → pos g → pos (f * g)
| ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ :=
let ⟨i, h⟩ := exists_forall_ge_and hF hG in
⟨_, _root_.mul_pos F0 G0, i,
λ j ij, let ⟨h₁, h₂⟩ := h _ ij in
mul_le_mul h₁ h₂ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩
theorem trichotomy (f : cau_seq α abs) : pos f ∨ lim_zero f ∨ pos (-f) :=
begin
cases classical.em (lim_zero f); simp *,
rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩,
rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩,
refine (le_total 0 (f i)).imp _ _;
refine (λ h, ⟨K, K0, i, λ j ij, _⟩);
have := (hi _ ij).1;
cases hi _ (le_refl _) with h₁ h₂,
{ rwa abs_of_nonneg at this,
rw abs_of_nonneg h at h₁,
exact (le_add_iff_nonneg_right _).1
(le_trans h₁ $ neg_le_sub_iff_le_add'.1 $
le_of_lt (abs_lt.1 $ h₂ _ ij).1) },
{ rwa abs_of_nonpos at this,
rw abs_of_nonpos h at h₁,
rw [← sub_le_sub_iff_right, zero_sub],
exact le_trans (le_of_lt (abs_lt.1 $ h₂ _ ij).2) h₁ }
end
instance : has_lt (cau_seq α abs) := ⟨λ f g, pos (g - f)⟩
instance : has_le (cau_seq α abs) := ⟨λ f g, f < g ∨ f ≈ g⟩
theorem lt_of_lt_of_eq {f g h : cau_seq α abs}
(fg : f < g) (gh : g ≈ h) : f < h :=
show pos (h - f),
by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh)
theorem lt_of_eq_of_lt {f g h : cau_seq α abs}
(fg : f ≈ g) (gh : g < h) : f < h :=
by have := pos_add_lim_zero gh (neg_lim_zero fg);
rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this
theorem lt_trans {f g h : cau_seq α abs} (fg : f < g) (gh : g < h) : f < h :=
show pos (h - f),
by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh
theorem lt_irrefl {f : cau_seq α abs} : ¬ f < f
| h := not_lim_zero_of_pos h (by simp [zero_lim_zero])
lemma le_of_eq_of_le {f g h : cau_seq α abs}
(hfg : f ≈ g) (hgh : g ≤ h) : f ≤ h :=
hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg)
(or.inr ∘ setoid.trans hfg)
lemma le_of_le_of_eq {f g h : cau_seq α abs}
(hfg : f ≤ g) (hgh : g ≈ h) : f ≤ h :=
hfg.elim (λ h, or.inl (cau_seq.lt_of_lt_of_eq h hgh))
(λ h, or.inr (setoid.trans h hgh))
instance : preorder (cau_seq α abs) :=
{ lt := (<),
le := λ f g, f < g ∨ f ≈ g,
le_refl := λ f, or.inr (setoid.refl _),
le_trans := λ f g h fg, match fg with
| or.inl fg, or.inl gh := or.inl $ lt_trans fg gh
| or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh
| or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh
| or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh
end,
lt_iff_le_not_le := λ f g,
⟨λ h, ⟨or.inl h,
not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩,
λ ⟨h₁, h₂⟩, h₁.resolve_right
(mt (λ h, or.inr (setoid.symm h)) h₂)⟩ }
theorem le_antisymm {f g : cau_seq α abs} (fg : f ≤ g) (gf : g ≤ f) : f ≈ g :=
fg.resolve_left (not_lt_of_le gf)
theorem lt_total (f g : cau_seq α abs) : f < g ∨ f ≈ g ∨ g < f :=
(trichotomy (g - f)).imp_right
(λ h, h.imp (λ h, setoid.symm h) (λ h, by rwa neg_sub at h))
theorem le_total (f g : cau_seq α abs) : f ≤ g ∨ g ≤ f :=
(or.assoc.2 (lt_total f g)).imp_right or.inl
theorem const_lt {x y : α} : const x < const y ↔ x < y :=
show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos]
theorem const_le {x y : α} : const x ≤ const y ↔ x ≤ y :=
by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv
lemma le_of_exists {f g : cau_seq α abs}
(h : ∃ i, ∀ j ≥ i, f j ≤ g j) : f ≤ g :=
let ⟨i, hi⟩ := h in
(or.assoc.2 (cau_seq.lt_total f g)).elim
id
(λ hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in
not_lt_of_ge (hi (max i j) (le_max_left _ _))
(sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _))))))
theorem exists_gt (f : cau_seq α abs) : ∃ a : α, f < const a :=
let ⟨K, H⟩ := f.bounded in
⟨K + 1, 1, zero_lt_one, 0, λ i _, begin
rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right],
exact le_of_lt (abs_lt.1 (H _)).2
end⟩
theorem exists_lt (f : cau_seq α abs) : ∃ a : α, const a < f :=
let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _,
by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩
end abs
end cau_seq
|
39b2f04349fb895d2e7f779417df1bb8e6a9353c | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/field_theory/finite/basic.lean | 7379bd1146d94a7e8bf63c82e48425bd6173abe4 | [
"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 | 12,499 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Joey van Langen, Casper Putz
-/
import tactic.apply_fun
import data.equiv.ring
import data.zmod.basic
import linear_algebra.basis
import ring_theory.integral_domain
import field_theory.separable
/-!
# Finite fields
This file contains basic results about finite fields.
Throughout most of this file, `K` denotes a finite field
and `q` is notation for the cardinality of `K`.
See `ring_theory.integral_domain` for the fact that the unit group of a finite field is a
cyclic group, as well as the fact that every finite integral domain is a field
(`field_of_integral_domain`).
## Main results
1. `card_units`: The unit group of a finite field is has cardinality `q - 1`.
2. `sum_pow_units`: The sum of `x^i`, where `x` ranges over the units of `K`, is
- `q-1` if `q-1 ∣ i`
- `0` otherwise
3. `finite_field.card`: The cardinality `q` is a power of the characteristic of `K`.
See `card'` for a variant.
## Notation
Throughout most of this file, `K` denotes a finite field
and `q` is notation for the cardinality of `K`.
-/
variables {K : Type*} [field K] [fintype K]
variables {R : Type*} [integral_domain R]
local notation `q` := fintype.card K
open_locale big_operators
namespace finite_field
open finset function
section polynomial
open polynomial
/-- The cardinality of a field is at most `n` times the cardinality of the image of a degree `n`
polynomial -/
lemma card_image_polynomial_eval [decidable_eq R] [fintype R] {p : polynomial R}
(hp : 0 < p.degree) : fintype.card R ≤ nat_degree p * (univ.image (λ x, eval x p)).card :=
finset.card_le_mul_card_image _ _
(λ a _, calc _ = (p - C a).roots.to_finset.card : congr_arg card
(by simp [finset.ext_iff, mem_roots_sub_C hp])
... ≤ (p - C a).roots.card : multiset.to_finset_card_le _
... ≤ _ : card_roots_sub_C' hp)
/-- If `f` and `g` are quadratic polynomials, then the `f.eval a + g.eval b = 0` has a solution. -/
lemma exists_root_sum_quadratic [fintype R] {f g : polynomial R} (hf2 : degree f = 2)
(hg2 : degree g = 2) (hR : fintype.card R % 2 = 1) : ∃ a b, f.eval a + g.eval b = 0 :=
by letI := classical.dec_eq R; exact
suffices ¬ disjoint (univ.image (λ x : R, eval x f)) (univ.image (λ x : R, eval x (-g))),
begin
simp only [disjoint_left, mem_image] at this,
push_neg at this,
rcases this with ⟨x, ⟨a, _, ha⟩, ⟨b, _, hb⟩⟩,
exact ⟨a, b, by rw [ha, ← hb, eval_neg, neg_add_self]⟩
end,
assume hd : disjoint _ _,
lt_irrefl (2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card) $
calc 2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card
≤ 2 * fintype.card R : nat.mul_le_mul_left _ (finset.card_le_univ _)
... = fintype.card R + fintype.card R : two_mul _
... < nat_degree f * (univ.image (λ x : R, eval x f)).card +
nat_degree (-g) * (univ.image (λ x : R, eval x (-g))).card :
add_lt_add_of_lt_of_le
(lt_of_le_of_ne
(card_image_polynomial_eval (by rw hf2; exact dec_trivial))
(mt (congr_arg (%2)) (by simp [nat_degree_eq_of_degree_eq_some hf2, hR])))
(card_image_polynomial_eval (by rw [degree_neg, hg2]; exact dec_trivial))
... = 2 * (univ.image (λ x : R, eval x f) ∪ univ.image (λ x : R, eval x (-g))).card :
by rw [card_disjoint_union hd]; simp [nat_degree_eq_of_degree_eq_some hf2,
nat_degree_eq_of_degree_eq_some hg2, bit0, mul_add]
end polynomial
lemma card_units : fintype.card (units K) = fintype.card K - 1 :=
begin
classical,
rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : K)⟩)],
haveI := set_fintype {a : K | a ≠ 0},
haveI := set_fintype (@set.univ K),
rw [fintype.card_congr (equiv.units_equiv_ne_zero _),
← @set.card_insert _ _ {a : K | a ≠ 0} _ (not_not.2 (eq.refl (0 : K)))
(set.fintype_insert _ _), fintype.card_congr (equiv.set.univ K).symm],
congr; simp [set.ext_iff, classical.em]
end
lemma prod_univ_units_id_eq_neg_one :
(∏ x : units K, x) = (-1 : units K) :=
begin
classical,
have : (∏ x in (@univ (units K) _).erase (-1), x) = 1,
from prod_involution (λ x _, x⁻¹) (by simp)
(λ a, by simp [units.inv_eq_self_iff] {contextual := tt})
(λ a, by simp [@inv_eq_iff_inv_eq _ _ a, eq_comm] {contextual := tt})
(by simp),
rw [← insert_erase (mem_univ (-1 : units K)), prod_insert (not_mem_erase _ _),
this, mul_one]
end
lemma pow_card_sub_one_eq_one (a : K) (ha : a ≠ 0) : a ^ (q - 1) = 1 :=
calc a ^ (fintype.card K - 1) = (units.mk0 a ha ^ (fintype.card K - 1) : units K) :
by rw [units.coe_pow, units.coe_mk0]
... = 1 : by { classical, rw [← card_units, pow_card_eq_one], refl }
lemma pow_card (a : K) : a ^ q = a :=
begin
have hp : fintype.card K > 0 := fintype.card_pos_iff.2 (by apply_instance),
by_cases h : a = 0, { rw h, apply zero_pow hp },
rw [← nat.succ_pred_eq_of_pos hp, pow_succ, nat.pred_eq_sub_one,
pow_card_sub_one_eq_one a h, mul_one],
end
variable (K)
theorem card (p : ℕ) [char_p K p] : ∃ (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) :=
begin
haveI hp : fact p.prime := ⟨char_p.char_is_prime K p⟩,
letI : module (zmod p) K := { .. (zmod.cast_hom (dvd_refl _) K).to_module },
obtain ⟨n, h⟩ := vector_space.card_fintype (zmod p) K,
rw zmod.card at h,
refine ⟨⟨n, _⟩, hp.1, h⟩,
apply or.resolve_left (nat.eq_zero_or_pos n),
rintro rfl,
rw pow_zero at h,
have : (0 : K) = 1, { apply fintype.card_le_one_iff.mp (le_of_eq h) },
exact absurd this zero_ne_one,
end
theorem card' : ∃ (p : ℕ) (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) :=
let ⟨p, hc⟩ := char_p.exists K in ⟨p, @finite_field.card K _ _ p hc⟩
@[simp] lemma cast_card_eq_zero : (q : K) = 0 :=
begin
rcases char_p.exists K with ⟨p, _char_p⟩, resetI,
rcases card K p with ⟨n, hp, hn⟩,
simp only [char_p.cast_eq_zero_iff K p, hn],
conv { congr, rw [← pow_one p] },
exact pow_dvd_pow _ n.2,
end
lemma forall_pow_eq_one_iff (i : ℕ) :
(∀ x : units K, x ^ i = 1) ↔ q - 1 ∣ i :=
begin
obtain ⟨x, hx⟩ := is_cyclic.exists_generator (units K),
classical,
rw [← card_units, ← order_of_eq_card_of_forall_mem_gpowers hx, order_of_dvd_iff_pow_eq_one],
split,
{ intro h, apply h },
{ intros h y,
simp_rw ← mem_powers_iff_mem_gpowers at hx,
rcases hx y with ⟨j, rfl⟩,
rw [← pow_mul, mul_comm, pow_mul, h, one_pow], }
end
/-- The sum of `x ^ i` as `x` ranges over the units of a finite field of cardinality `q`
is equal to `0` unless `(q - 1) ∣ i`, in which case the sum is `q - 1`. -/
lemma sum_pow_units (i : ℕ) :
∑ x : units K, (x ^ i : K) = if (q - 1) ∣ i then -1 else 0 :=
begin
let φ : units K →* K :=
{ to_fun := λ x, x ^ i,
map_one' := by rw [units.coe_one, one_pow],
map_mul' := by { intros, rw [units.coe_mul, mul_pow] } },
haveI : decidable (φ = 1) := by { classical, apply_instance },
calc ∑ x : units K, φ x = if φ = 1 then fintype.card (units K) else 0 : sum_hom_units φ
... = if (q - 1) ∣ i then -1 else 0 : _,
suffices : (q - 1) ∣ i ↔ φ = 1,
{ simp only [this],
split_ifs with h h, swap, refl,
rw [card_units, nat.cast_sub, cast_card_eq_zero, nat.cast_one, zero_sub],
show 1 ≤ q, from fintype.card_pos_iff.mpr ⟨0⟩ },
rw [← forall_pow_eq_one_iff, monoid_hom.ext_iff],
apply forall_congr, intro x,
rw [units.ext_iff, units.coe_pow, units.coe_one, monoid_hom.one_apply],
refl,
end
/-- The sum of `x ^ i` as `x` ranges over a finite field of cardinality `q`
is equal to `0` if `i < q - 1`. -/
lemma sum_pow_lt_card_sub_one (i : ℕ) (h : i < q - 1) :
∑ x : K, x ^ i = 0 :=
begin
by_cases hi : i = 0,
{ simp only [hi, nsmul_one, sum_const, pow_zero, card_univ, cast_card_eq_zero], },
classical,
have hiq : ¬ (q - 1) ∣ i, { contrapose! h, exact nat.le_of_dvd (nat.pos_of_ne_zero hi) h },
let φ : units K ↪ K := ⟨coe, units.ext⟩,
have : univ.map φ = univ \ {0},
{ ext x,
simp only [true_and, embedding.coe_fn_mk, mem_sdiff, units.exists_iff_ne_zero,
mem_univ, mem_map, exists_prop_of_true, mem_singleton] },
calc ∑ x : K, x ^ i = ∑ x in univ \ {(0 : K)}, x ^ i :
by rw [← sum_sdiff ({0} : finset K).subset_univ, sum_singleton,
zero_pow (nat.pos_of_ne_zero hi), add_zero]
... = ∑ x : units K, x ^ i : by { rw [← this, univ.sum_map φ], refl }
... = 0 : by { rw [sum_pow_units K i, if_neg], exact hiq, }
end
variables {K}
theorem frobenius_pow {p : ℕ} [fact p.prime] [char_p K p] {n : ℕ} (hcard : q = p^n) :
(frobenius K p) ^ n = 1 :=
begin
ext, conv_rhs { rw [ring_hom.one_def, ring_hom.id_apply, ← pow_card x, hcard], }, clear hcard,
induction n, {simp},
rw [pow_succ, pow_succ', pow_mul, ring_hom.mul_def, ring_hom.comp_apply, frobenius_def, n_ih]
end
open polynomial
lemma expand_card (f : polynomial K) :
expand K q f = f ^ q :=
begin
cases char_p.exists K with p hp, letI := hp,
rcases finite_field.card K p with ⟨⟨n, npos⟩, ⟨hp, hn⟩⟩, haveI : fact p.prime := ⟨hp⟩,
dsimp at hn, rw hn at *,
rw ← map_expand_pow_char,
rw [frobenius_pow hn, ring_hom.one_def, map_id],
end
end finite_field
namespace zmod
open finite_field polynomial
lemma sq_add_sq (p : ℕ) [hp : fact p.prime] (x : zmod p) :
∃ a b : zmod p, a^2 + b^2 = x :=
begin
cases hp.1.eq_two_or_odd with hp2 hp_odd,
{ substI p, change fin 2 at x, fin_cases x, { use 0, simp }, { use [0, 1], simp } },
let f : polynomial (zmod p) := X^2,
let g : polynomial (zmod p) := X^2 - C x,
obtain ⟨a, b, hab⟩ : ∃ a b, f.eval a + g.eval b = 0 :=
@exists_root_sum_quadratic _ _ _ f g
(degree_X_pow 2) (degree_X_pow_sub_C dec_trivial _) (by rw [zmod.card, hp_odd]),
refine ⟨a, b, _⟩,
rw ← sub_eq_zero,
simpa only [eval_C, eval_X, eval_pow, eval_sub, ← add_sub_assoc] using hab,
end
end zmod
namespace char_p
lemma sq_add_sq (R : Type*) [integral_domain R] (p : ℕ) [fact (0 < p)] [char_p R p] (x : ℤ) :
∃ a b : ℕ, (a^2 + b^2 : R) = x :=
begin
haveI := char_is_prime_of_pos R p,
obtain ⟨a, b, hab⟩ := zmod.sq_add_sq p x,
refine ⟨a.val, b.val, _⟩,
simpa using congr_arg (zmod.cast_hom (dvd_refl _) R) hab
end
end char_p
open_locale nat
open zmod
/-- The Fermat-Euler totient theorem. `nat.modeq.pow_totient` is an alternative statement
of the same theorem. -/
@[simp] lemma zmod.pow_totient {n : ℕ} [fact (0 < n)] (x : units (zmod n)) : x ^ φ n = 1 :=
by rw [← card_units_eq_totient, pow_card_eq_one]
/-- The Fermat-Euler totient theorem. `zmod.pow_totient` is an alternative statement
of the same theorem. -/
lemma nat.modeq.pow_totient {x n : ℕ} (h : nat.coprime x n) : x ^ φ n ≡ 1 [MOD n] :=
begin
cases n, {simp},
rw ← zmod.eq_iff_modeq_nat,
let x' : units (zmod (n+1)) := zmod.unit_of_coprime _ h,
have := zmod.pow_totient x',
apply_fun (coe : units (zmod (n+1)) → zmod (n+1)) at this,
simpa only [-zmod.pow_totient, nat.succ_eq_add_one, nat.cast_pow, units.coe_one,
nat.cast_one, coe_unit_of_coprime, units.coe_pow],
end
open finite_field
namespace zmod
/-- A variation on Fermat's little theorem. See `zmod.pow_card_sub_one_eq_one` -/
@[simp] lemma pow_card {p : ℕ} [fact p.prime] (x : zmod p) : x ^ p = x :=
by { have h := finite_field.pow_card x, rwa zmod.card p at h }
@[simp] lemma frobenius_zmod (p : ℕ) [fact p.prime] :
frobenius (zmod p) p = ring_hom.id _ :=
by { ext a, rw [frobenius_def, zmod.pow_card, ring_hom.id_apply] }
@[simp] lemma card_units (p : ℕ) [fact p.prime] : fintype.card (units (zmod p)) = p - 1 :=
by rw [card_units, card]
/-- Fermat's Little Theorem: for every unit `a` of `zmod p`, we have `a ^ (p - 1) = 1`. -/
theorem units_pow_card_sub_one_eq_one (p : ℕ) [fact p.prime] (a : units (zmod p)) :
a ^ (p - 1) = 1 :=
by rw [← card_units p, pow_card_eq_one]
/-- Fermat's Little Theorem: for all nonzero `a : zmod p`, we have `a ^ (p - 1) = 1`. -/
theorem pow_card_sub_one_eq_one {p : ℕ} [fact p.prime] {a : zmod p} (ha : a ≠ 0) :
a ^ (p - 1) = 1 :=
by { have h := pow_card_sub_one_eq_one a ha, rwa zmod.card p at h }
open polynomial
lemma expand_card {p : ℕ} [fact p.prime] (f : polynomial (zmod p)) :
expand (zmod p) p f = f ^ p :=
by { have h := finite_field.expand_card f, rwa zmod.card p at h }
end zmod
|
1d8ca3d06383a93a7b764b7cca9ac41d4fc893da | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/matrix/transvection.lean | 8c0daac3129b65cd83aae1d1135332aa238e6740 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 32,974 | lean | /-
Copyright (c) 2021 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.matrix.basis
import data.matrix.dmatrix
import linear_algebra.matrix.determinant
import linear_algebra.matrix.reindex
import tactic.field_simp
/-!
# Transvections
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Transvections are matrices of the form `1 + std_basis_matrix i j c`, where `std_basis_matrix i j c`
is the basic matrix with a `c` at position `(i, j)`. Multiplying by such a transvection on the left
(resp. on the right) amounts to adding `c` times the `j`-th row to to the `i`-th row
(resp `c` times the `i`-th column to the `j`-th column). Therefore, they are useful to present
algorithms operating on rows and columns.
Transvections are a special case of *elementary matrices* (according to most references, these also
contain the matrices exchanging rows, and the matrices multiplying a row by a constant).
We show that, over a field, any matrix can be written as `L ⬝ D ⬝ L'`, where `L` and `L'` are
products of transvections and `D` is diagonal. In other words, one can reduce a matrix to diagonal
form by operations on its rows and columns, a variant of Gauss' pivot algorithm.
## Main definitions and results
* `transvection i j c` is the matrix equal to `1 + std_basis_matrix i j c`.
* `transvection_struct n R` is a structure containing the data of `i, j, c` and a proof that
`i ≠ j`. These are often easier to manipulate than straight matrices, especially in inductive
arguments.
* `exists_list_transvec_mul_diagonal_mul_list_transvec` states that any matrix `M` over a field can
be written in the form `t_1 ⬝ ... ⬝ t_k ⬝ D ⬝ t'_1 ⬝ ... ⬝ t'_l`, where `D` is diagonal and
the `t_i`, `t'_j` are transvections.
* `diagonal_transvection_induction` shows that a property which is true for diagonal matrices and
transvections, and invariant under product, is true for all matrices.
* `diagonal_transvection_induction_of_det_ne_zero` is the same statement over invertible matrices.
## Implementation details
The proof of the reduction results is done inductively on the size of the matrices, reducing an
`(r + 1) × (r + 1)` matrix to a matrix whose last row and column are zeroes, except possibly for
the last diagonal entry. This step is done as follows.
If all the coefficients on the last row and column are zero, there is nothing to do. Otherwise,
one can put a nonzero coefficient in the last diagonal entry by a row or column operation, and then
subtract this last diagonal entry from the other entries in the last row and column to make them
vanish.
This step is done in the type `fin r ⊕ unit`, where `fin r` is useful to choose arbitrarily some
order in which we cancel the coefficients, and the sum structure is useful to use the formalism of
block matrices.
To proceed with the induction, we reindex our matrices to reduce to the above situation.
-/
universes u₁ u₂
namespace matrix
open_locale matrix
variables (n p : Type*) (R : Type u₂) {𝕜 : Type*} [field 𝕜]
variables [decidable_eq n] [decidable_eq p]
variables [comm_ring R]
section transvection
variables {R n} (i j : n)
/-- The transvection matrix `transvection i j c` is equal to the identity plus `c` at position
`(i, j)`. Multiplying by it on the left (as in `transvection i j c ⬝ M`) corresponds to adding
`c` times the `j`-th line of `M` to its `i`-th line. Multiplying by it on the right corresponds
to adding `c` times the `i`-th column to the `j`-th column. -/
def transvection (c : R) : matrix n n R := 1 + matrix.std_basis_matrix i j c
@[simp] lemma transvection_zero : transvection i j (0 : R) = 1 :=
by simp [transvection]
section
/-- A transvection matrix is obtained from the identity by adding `c` times the `j`-th row to
the `i`-th row. -/
lemma update_row_eq_transvection [finite n] (c : R) :
update_row (1 : matrix n n R) i (((1 : matrix n n R)) i + c • (1 : matrix n n R) j) =
transvection i j c :=
begin
casesI nonempty_fintype n,
ext a b,
by_cases ha : i = a, by_cases hb : j = b,
{ simp only [update_row_self, transvection, ha, hb, pi.add_apply,
std_basis_matrix.apply_same, one_apply_eq, pi.smul_apply, mul_one, algebra.id.smul_eq_mul], },
{ simp only [update_row_self, transvection, ha, hb, std_basis_matrix.apply_of_ne, pi.add_apply,
ne.def, not_false_iff, pi.smul_apply, and_false, one_apply_ne,
algebra.id.smul_eq_mul, mul_zero] },
{ simp only [update_row_ne, transvection, ha, ne.symm ha, std_basis_matrix.apply_of_ne, add_zero,
algebra.id.smul_eq_mul, ne.def, not_false_iff, dmatrix.add_apply,
pi.smul_apply, mul_zero, false_and] },
end
variables [fintype n]
lemma transvection_mul_transvection_same (h : i ≠ j) (c d : R) :
transvection i j c ⬝ transvection i j d = transvection i j (c + d) :=
by simp [transvection, matrix.add_mul, matrix.mul_add, h, h.symm, add_smul, add_assoc,
std_basis_matrix_add]
@[simp] lemma transvection_mul_apply_same (b : n) (c : R) (M : matrix n n R) :
(transvection i j c ⬝ M) i b = M i b + c * M j b :=
by simp [transvection, matrix.add_mul]
@[simp] lemma mul_transvection_apply_same (a : n) (c : R) (M : matrix n n R) :
(M ⬝ transvection i j c) a j = M a j + c * M a i :=
by simp [transvection, matrix.mul_add, mul_comm]
@[simp] lemma transvection_mul_apply_of_ne (a b : n) (ha : a ≠ i) (c : R) (M : matrix n n R) :
(transvection i j c ⬝ M) a b = M a b :=
by simp [transvection, matrix.add_mul, ha]
@[simp] lemma mul_transvection_apply_of_ne (a b : n) (hb : b ≠ j) (c : R) (M : matrix n n R) :
(M ⬝ transvection i j c) a b = M a b :=
by simp [transvection, matrix.mul_add, hb]
@[simp] lemma det_transvection_of_ne (h : i ≠ j) (c : R) : det (transvection i j c) = 1 :=
by rw [← update_row_eq_transvection i j, det_update_row_add_smul_self _ h, det_one]
end
variables (R n)
/-- A structure containing all the information from which one can build a nontrivial transvection.
This structure is easier to manipulate than transvections as one has a direct access to all the
relevant fields. -/
@[nolint has_nonempty_instance]
structure transvection_struct :=
(i j : n)
(hij : i ≠ j)
(c : R)
instance [nontrivial n] : nonempty (transvection_struct n R) :=
by { choose x y hxy using exists_pair_ne n, exact ⟨⟨x, y, hxy, 0⟩⟩ }
namespace transvection_struct
variables {R n}
/-- Associating to a `transvection_struct` the corresponding transvection matrix. -/
def to_matrix (t : transvection_struct n R) : matrix n n R :=
transvection t.i t.j t.c
@[simp] lemma to_matrix_mk (i j : n) (hij : i ≠ j) (c : R) :
transvection_struct.to_matrix ⟨i, j, hij, c⟩ = transvection i j c := rfl
@[simp] protected lemma det [fintype n] (t : transvection_struct n R) : det t.to_matrix = 1 :=
det_transvection_of_ne _ _ t.hij _
@[simp] lemma det_to_matrix_prod [fintype n] (L : list (transvection_struct n 𝕜)) :
det ((L.map to_matrix).prod) = 1 :=
begin
induction L with t L IH,
{ simp },
{ simp [IH], }
end
/-- The inverse of a `transvection_struct`, designed so that `t.inv.to_matrix` is the inverse of
`t.to_matrix`. -/
@[simps] protected def inv (t : transvection_struct n R) : transvection_struct n R :=
{ i := t.i,
j := t.j,
hij := t.hij,
c := - t.c }
section
variable [fintype n]
lemma inv_mul (t : transvection_struct n R) :
t.inv.to_matrix ⬝ t.to_matrix = 1 :=
by { rcases t, simp [to_matrix, transvection_mul_transvection_same, t_hij] }
lemma mul_inv (t : transvection_struct n R) :
t.to_matrix ⬝ t.inv.to_matrix = 1 :=
by { rcases t, simp [to_matrix, transvection_mul_transvection_same, t_hij] }
lemma reverse_inv_prod_mul_prod (L : list (transvection_struct n R)) :
(L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod ⬝ (L.map to_matrix).prod = 1 :=
begin
induction L with t L IH,
{ simp },
{ suffices : (L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod ⬝
(t.inv.to_matrix ⬝ t.to_matrix) ⬝ (L.map to_matrix).prod = 1, by simpa [matrix.mul_assoc],
simpa [inv_mul] using IH, }
end
lemma prod_mul_reverse_inv_prod (L : list (transvection_struct n R)) :
(L.map to_matrix).prod ⬝ (L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod = 1 :=
begin
induction L with t L IH,
{ simp },
{ suffices : t.to_matrix ⬝ ((L.map to_matrix).prod ⬝
(L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod) ⬝ t.inv.to_matrix = 1,
by simpa [matrix.mul_assoc],
simp_rw [IH, matrix.mul_one, t.mul_inv], }
end
end
variables (p)
open sum
/-- Given a `transvection_struct` on `n`, define the corresponding `transvection_struct` on `n ⊕ p`
using the identity on `p`. -/
def sum_inl (t : transvection_struct n R) : transvection_struct (n ⊕ p) R :=
{ i := inl t.i,
j := inl t.j,
hij := by simp [t.hij],
c := t.c }
lemma to_matrix_sum_inl (t : transvection_struct n R) :
(t.sum_inl p).to_matrix = from_blocks t.to_matrix 0 0 1 :=
begin
cases t,
ext a b,
cases a; cases b,
{ by_cases h : a = b;
simp [transvection_struct.sum_inl, transvection, h, std_basis_matrix], },
{ simp [transvection_struct.sum_inl, transvection] },
{ simp [transvection_struct.sum_inl, transvection] },
{ by_cases h : a = b;
simp [transvection_struct.sum_inl, transvection, h] },
end
@[simp] lemma sum_inl_to_matrix_prod_mul [fintype n] [fintype p]
(M : matrix n n R) (L : list (transvection_struct n R)) (N : matrix p p R) :
(L.map (to_matrix ∘ sum_inl p)).prod ⬝ from_blocks M 0 0 N
= from_blocks ((L.map to_matrix).prod ⬝ M) 0 0 N :=
begin
induction L with t L IH,
{ simp },
{ simp [matrix.mul_assoc, IH, to_matrix_sum_inl, from_blocks_multiply], },
end
@[simp] lemma mul_sum_inl_to_matrix_prod [fintype n] [fintype p]
(M : matrix n n R) (L : list (transvection_struct n R)) (N : matrix p p R) :
(from_blocks M 0 0 N) ⬝ (L.map (to_matrix ∘ sum_inl p)).prod
= from_blocks (M ⬝ (L.map to_matrix).prod) 0 0 N :=
begin
induction L with t L IH generalizing M N,
{ simp },
{ simp [IH, to_matrix_sum_inl, from_blocks_multiply], },
end
variable {p}
/-- Given a `transvection_struct` on `n` and an equivalence between `n` and `p`, define the
corresponding `transvection_struct` on `p`. -/
def reindex_equiv (e : n ≃ p) (t : transvection_struct n R) : transvection_struct p R :=
{ i := e t.i,
j := e t.j,
hij := by simp [t.hij],
c := t.c }
variables [fintype n] [fintype p]
lemma to_matrix_reindex_equiv (e : n ≃ p) (t : transvection_struct n R) :
(t.reindex_equiv e).to_matrix = reindex_alg_equiv R e t.to_matrix :=
begin
cases t,
ext a b,
simp only [reindex_equiv, transvection, mul_boole, algebra.id.smul_eq_mul, to_matrix_mk,
submatrix_apply, reindex_apply, dmatrix.add_apply, pi.smul_apply, reindex_alg_equiv_apply],
by_cases ha : e t_i = a; by_cases hb : e t_j = b; by_cases hab : a = b;
simp [ha, hb, hab, ← e.apply_eq_iff_eq_symm_apply, std_basis_matrix]
end
lemma to_matrix_reindex_equiv_prod (e : n ≃ p) (L : list (transvection_struct n R)) :
(L.map (to_matrix ∘ (reindex_equiv e))).prod = reindex_alg_equiv R e (L.map to_matrix).prod :=
begin
induction L with t L IH,
{ simp },
{ simp only [to_matrix_reindex_equiv, IH, function.comp_app, list.prod_cons, mul_eq_mul,
reindex_alg_equiv_apply, list.map],
exact (reindex_alg_equiv_mul _ _ _ _).symm }
end
end transvection_struct
end transvection
/-!
# Reducing matrices by left and right multiplication by transvections
In this section, we show that any matrix can be reduced to diagonal form by left and right
multiplication by transvections (or, equivalently, by elementary operations on lines and columns).
The main step is to kill the last row and column of a matrix in `fin r ⊕ unit` with nonzero last
coefficient, by subtracting this coefficient from the other ones. The list of these operations is
recorded in `list_transvec_col M` and `list_transvec_row M`. We have to analyze inductively how
these operations affect the coefficients in the last row and the last column to conclude that they
have the desired effect.
Once this is done, one concludes the reduction by induction on the size
of the matrices, through a suitable reindexing to identify any fintype with `fin r ⊕ unit`.
-/
namespace pivot
variables {R} {r : ℕ} (M : matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜)
open sum unit fin transvection_struct
/-- A list of transvections such that multiplying on the left with these transvections will replace
the last column with zeroes. -/
def list_transvec_col : list (matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) :=
list.of_fn $ λ i : fin r, transvection (inl i) (inr star) $
-M (inl i) (inr star) / M (inr star) (inr star)
/-- A list of transvections such that multiplying on the right with these transvections will replace
the last row with zeroes. -/
def list_transvec_row : list (matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) :=
list.of_fn $ λ i : fin r, transvection (inr star) (inl i) $
-M (inr star) (inl i) / M (inr star) (inr star)
/-- Multiplying by some of the matrices in `list_transvec_col M` does not change the last row. -/
lemma list_transvec_col_mul_last_row_drop (i : fin r ⊕ unit) {k : ℕ} (hk : k ≤ r) :
(((list_transvec_col M).drop k).prod ⬝ M) (inr star) i = M (inr star) i :=
begin
apply nat.decreasing_induction' _ hk,
{ simp only [list_transvec_col, list.length_of_fn, matrix.one_mul, list.drop_eq_nil_of_le,
list.prod_nil], },
{ assume n hn hk IH,
have hn' : n < (list_transvec_col M).length, by simpa [list_transvec_col] using hn,
rw ← list.cons_nth_le_drop_succ hn',
simpa [list_transvec_col, matrix.mul_assoc] }
end
/-- Multiplying by all the matrices in `list_transvec_col M` does not change the last row. -/
lemma list_transvec_col_mul_last_row (i : fin r ⊕ unit) :
((list_transvec_col M).prod ⬝ M) (inr star) i = M (inr star) i :=
by simpa using list_transvec_col_mul_last_row_drop M i (zero_le _)
/-- Multiplying by all the matrices in `list_transvec_col M` kills all the coefficients in the
last column but the last one. -/
lemma list_transvec_col_mul_last_col (hM : M (inr star) (inr star) ≠ 0) (i : fin r) :
((list_transvec_col M).prod ⬝ M) (inl i) (inr star) = 0 :=
begin
suffices H : ∀ (k : ℕ), k ≤ r → (((list_transvec_col M).drop k).prod ⬝ M) (inl i) (inr star) =
if k ≤ i then 0 else M (inl i) (inr star),
by simpa only [if_true, list.drop.equations._eqn_1] using H 0 (zero_le _),
assume k hk,
apply nat.decreasing_induction' _ hk,
{ simp only [list_transvec_col, list.length_of_fn, matrix.one_mul, list.drop_eq_nil_of_le,
list.prod_nil],
rw if_neg,
simpa only [not_le] using i.2 },
{ assume n hn hk IH,
have hn' : n < (list_transvec_col M).length, by simpa [list_transvec_col] using hn,
let n' : fin r := ⟨n, hn⟩,
rw ← list.cons_nth_le_drop_succ hn',
have A : (list_transvec_col M).nth_le n hn' = transvection (inl n') (inr star)
(-M (inl n') (inr star) / M (inr star) (inr star)), by simp [list_transvec_col],
simp only [matrix.mul_assoc, A, matrix.mul_eq_mul, list.prod_cons],
by_cases h : n' = i,
{ have hni : n = i,
{ cases i, simp only [fin.mk_eq_mk] at h, simp [h] },
rw [h, transvection_mul_apply_same, IH, list_transvec_col_mul_last_row_drop _ _ hn, ← hni],
field_simp [hM] },
{ have hni : n ≠ i,
{ rintros rfl, cases i, simpa using h },
simp only [transvection_mul_apply_of_ne, ne.def, not_false_iff, ne.symm h],
rw IH,
rcases le_or_lt (n+1) i with hi|hi,
{ simp only [hi, n.le_succ.trans hi, if_true] },
{ rw [if_neg, if_neg],
{ simpa only [hni.symm, not_le, or_false] using nat.lt_succ_iff_lt_or_eq.1 hi },
{ simpa only [not_le] using hi } } } }
end
/-- Multiplying by some of the matrices in `list_transvec_row M` does not change the last column. -/
lemma mul_list_transvec_row_last_col_take (i : fin r ⊕ unit) {k : ℕ} (hk : k ≤ r) :
(M ⬝ ((list_transvec_row M).take k).prod) i (inr star) = M i (inr star) :=
begin
induction k with k IH,
{ simp only [matrix.mul_one, list.take_zero, list.prod_nil], },
{ have hkr : k < r := hk,
let k' : fin r := ⟨k, hkr⟩,
have : (list_transvec_row M).nth k = ↑(transvection (inr unit.star) (inl k')
(-M (inr unit.star) (inl k') / M (inr unit.star) (inr unit.star))),
{ simp only [list_transvec_row, list.of_fn_nth_val, hkr, dif_pos, list.nth_of_fn], refl },
simp only [list.take_succ, ← matrix.mul_assoc, this, list.prod_append, matrix.mul_one,
matrix.mul_eq_mul, list.prod_cons, list.prod_nil, option.to_list_some],
rw [mul_transvection_apply_of_ne, IH hkr.le],
simp only [ne.def, not_false_iff], }
end
/-- Multiplying by all the matrices in `list_transvec_row M` does not change the last column. -/
lemma mul_list_transvec_row_last_col (i : fin r ⊕ unit) :
(M ⬝ (list_transvec_row M).prod) i (inr star) = M i (inr star) :=
begin
have A : (list_transvec_row M).length = r, by simp [list_transvec_row],
rw [← list.take_length (list_transvec_row M), A],
simpa using mul_list_transvec_row_last_col_take M i le_rfl,
end
/-- Multiplying by all the matrices in `list_transvec_row M` kills all the coefficients in the
last row but the last one. -/
lemma mul_list_transvec_row_last_row (hM : M (inr star) (inr star) ≠ 0) (i : fin r) :
(M ⬝ (list_transvec_row M).prod) (inr star) (inl i) = 0 :=
begin
suffices H : ∀ (k : ℕ), k ≤ r → (M ⬝ ((list_transvec_row M).take k).prod) (inr star) (inl i) =
if k ≤ i then M (inr star) (inl i) else 0,
{ have A : (list_transvec_row M).length = r, by simp [list_transvec_row],
rw [← list.take_length (list_transvec_row M), A],
have : ¬ (r ≤ i), by simp,
simpa only [this, ite_eq_right_iff] using H r le_rfl },
assume k hk,
induction k with n IH,
{ simp only [if_true, matrix.mul_one, list.take_zero, zero_le', list.prod_nil] },
{ have hnr : n < r := hk,
let n' : fin r := ⟨n, hnr⟩,
have A : (list_transvec_row M).nth n = ↑(transvection (inr unit.star) (inl n')
(-M (inr unit.star) (inl n') / M (inr unit.star) (inr unit.star))),
{ simp only [list_transvec_row, list.of_fn_nth_val, hnr, dif_pos, list.nth_of_fn], refl },
simp only [list.take_succ, A, ← matrix.mul_assoc, list.prod_append, matrix.mul_one,
matrix.mul_eq_mul, list.prod_cons, list.prod_nil, option.to_list_some],
by_cases h : n' = i,
{ have hni : n = i,
{ cases i, simp only [fin.mk_eq_mk] at h, simp only [h, coe_mk] },
have : ¬ (n.succ ≤ i), by simp only [← hni, n.lt_succ_self, not_le],
simp only [h, mul_transvection_apply_same, list.take, if_false,
mul_list_transvec_row_last_col_take _ _ hnr.le, hni.le, this, if_true, IH hnr.le],
field_simp [hM] },
{ have hni : n ≠ i,
{ rintros rfl, cases i, simpa using h },
simp only [IH hnr.le, ne.def, mul_transvection_apply_of_ne, not_false_iff, ne.symm h],
rcases le_or_lt (n+1) i with hi|hi,
{ simp [hi, n.le_succ.trans hi, if_true], },
{ rw [if_neg, if_neg],
{ simpa only [not_le] using hi },
{ simpa only [hni.symm, not_le, or_false] using nat.lt_succ_iff_lt_or_eq.1 hi } } } }
end
/-- Multiplying by all the matrices either in `list_transvec_col M` and `list_transvec_row M` kills
all the coefficients in the last row but the last one. -/
lemma list_transvec_col_mul_mul_list_transvec_row_last_col
(hM : M (inr star) (inr star) ≠ 0) (i : fin r) :
((list_transvec_col M).prod ⬝ M ⬝ (list_transvec_row M).prod) (inr star) (inl i) = 0 :=
begin
have : list_transvec_row M = list_transvec_row ((list_transvec_col M).prod ⬝ M),
by simp [list_transvec_row, list_transvec_col_mul_last_row],
rw this,
apply mul_list_transvec_row_last_row,
simpa [list_transvec_col_mul_last_row] using hM
end
/-- Multiplying by all the matrices either in `list_transvec_col M` and `list_transvec_row M` kills
all the coefficients in the last column but the last one. -/
lemma list_transvec_col_mul_mul_list_transvec_row_last_row
(hM : M (inr star) (inr star) ≠ 0) (i : fin r) :
((list_transvec_col M).prod ⬝ M ⬝ (list_transvec_row M).prod) (inl i) (inr star) = 0 :=
begin
have : list_transvec_col M = list_transvec_col (M ⬝ (list_transvec_row M).prod),
by simp [list_transvec_col, mul_list_transvec_row_last_col],
rw [this, matrix.mul_assoc],
apply list_transvec_col_mul_last_col,
simpa [mul_list_transvec_row_last_col] using hM
end
/-- Multiplying by all the matrices either in `list_transvec_col M` and `list_transvec_row M` turns
the matrix in block-diagonal form. -/
lemma is_two_block_diagonal_list_transvec_col_mul_mul_list_transvec_row
(hM : M (inr star) (inr star) ≠ 0) :
is_two_block_diagonal ((list_transvec_col M).prod ⬝ M ⬝ (list_transvec_row M).prod) :=
begin
split,
{ ext i j,
have : j = star, by simp only [eq_iff_true_of_subsingleton],
simp [to_blocks₁₂, this, list_transvec_col_mul_mul_list_transvec_row_last_row M hM] },
{ ext i j,
have : i = star, by simp only [eq_iff_true_of_subsingleton],
simp [to_blocks₂₁, this, list_transvec_col_mul_mul_list_transvec_row_last_col M hM] },
end
/-- There exist two lists of `transvection_struct` such that multiplying by them on the left and
on the right makes a matrix block-diagonal, when the last coefficient is nonzero. -/
lemma exists_is_two_block_diagonal_of_ne_zero (hM : M (inr star) (inr star) ≠ 0) :
∃ (L L' : list (transvection_struct (fin r ⊕ unit) 𝕜)),
is_two_block_diagonal ((L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod) :=
begin
let L : list (transvection_struct (fin r ⊕ unit) 𝕜) :=
list.of_fn (λ i : fin r, ⟨inl i, inr star, by simp,
-M (inl i) (inr star) / M (inr star) (inr star)⟩),
let L' : list (transvection_struct (fin r ⊕ unit) 𝕜) :=
list.of_fn (λ i : fin r, ⟨inr star, inl i, by simp,
-M (inr star) (inl i) / M (inr star) (inr star)⟩),
refine ⟨L, L', _⟩,
have A : L.map to_matrix = list_transvec_col M, by simp [L, list_transvec_col, (∘)],
have B : L'.map to_matrix = list_transvec_row M, by simp [L, list_transvec_row, (∘)],
rw [A, B],
exact is_two_block_diagonal_list_transvec_col_mul_mul_list_transvec_row M hM
end
/-- There exist two lists of `transvection_struct` such that multiplying by them on the left and
on the right makes a matrix block-diagonal. -/
lemma exists_is_two_block_diagonal_list_transvec_mul_mul_list_transvec
(M : matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) :
∃ (L L' : list (transvection_struct (fin r ⊕ unit) 𝕜)),
is_two_block_diagonal ((L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod) :=
begin
by_cases H : is_two_block_diagonal M, { refine ⟨list.nil, list.nil, by simpa using H⟩ },
-- we have already proved this when the last coefficient is nonzero
by_cases hM : M (inr star) (inr star) ≠ 0,
{ exact exists_is_two_block_diagonal_of_ne_zero M hM },
-- when the last coefficient is zero but there is a nonzero coefficient on the last row or the
-- last column, we will first put this nonzero coefficient in last position, and then argue as
-- above.
push_neg at hM,
simp [not_and_distrib, is_two_block_diagonal, to_blocks₁₂, to_blocks₂₁, ←matrix.ext_iff] at H,
have : ∃ (i : fin r), M (inl i) (inr star) ≠ 0 ∨ M (inr star) (inl i) ≠ 0,
{ cases H,
{ contrapose! H,
rintros i ⟨⟩,
exact (H i).1 },
{ contrapose! H,
rintros ⟨⟩ j,
exact (H j).2, } },
rcases this with ⟨i, h|h⟩,
{ let M' := transvection (inr unit.star) (inl i) 1 ⬝ M,
have hM' : M' (inr star) (inr star) ≠ 0, by simpa [M', hM],
rcases exists_is_two_block_diagonal_of_ne_zero M' hM' with ⟨L, L', hLL'⟩,
rw matrix.mul_assoc at hLL',
refine ⟨L ++ [⟨inr star, inl i, by simp, 1⟩], L', _⟩,
simp only [list.map_append, list.prod_append, matrix.mul_one, to_matrix_mk, list.prod_cons,
list.prod_nil, mul_eq_mul, list.map, matrix.mul_assoc (L.map to_matrix).prod],
exact hLL' },
{ let M' := M ⬝ transvection (inl i) (inr star) 1,
have hM' : M' (inr star) (inr star) ≠ 0, by simpa [M', hM],
rcases exists_is_two_block_diagonal_of_ne_zero M' hM' with ⟨L, L', hLL'⟩,
refine ⟨L, ⟨inl i, inr star, by simp, 1⟩ :: L', _⟩,
simp only [←matrix.mul_assoc, to_matrix_mk, list.prod_cons, mul_eq_mul, list.map],
rw [matrix.mul_assoc (L.map to_matrix).prod],
exact hLL' }
end
/-- Inductive step for the reduction: if one knows that any size `r` matrix can be reduced to
diagonal form by elementary operations, then one deduces it for matrices over `fin r ⊕ unit`. -/
lemma exists_list_transvec_mul_mul_list_transvec_eq_diagonal_induction
(IH : ∀ (M : matrix (fin r) (fin r) 𝕜),
∃ (L₀ L₀' : list (transvection_struct (fin r) 𝕜)) (D₀ : (fin r) → 𝕜),
(L₀.map to_matrix).prod ⬝ M ⬝ (L₀'.map to_matrix).prod = diagonal D₀)
(M : matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) :
∃ (L L' : list (transvection_struct (fin r ⊕ unit) 𝕜)) (D : fin r ⊕ unit → 𝕜),
(L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod = diagonal D :=
begin
rcases exists_is_two_block_diagonal_list_transvec_mul_mul_list_transvec M with ⟨L₁, L₁', hM⟩,
let M' := (L₁.map to_matrix).prod ⬝ M ⬝ (L₁'.map to_matrix).prod,
let M'' := to_blocks₁₁ M',
rcases IH M'' with ⟨L₀, L₀', D₀, h₀⟩,
set c := M' (inr star) (inr star) with hc,
refine ⟨L₀.map (sum_inl unit) ++ L₁, L₁' ++ L₀'.map (sum_inl unit),
sum.elim D₀ (λ _, M' (inr star) (inr star)), _⟩,
suffices :
(L₀.map (to_matrix ∘ sum_inl unit)).prod ⬝ M' ⬝ (L₀'.map (to_matrix ∘ sum_inl unit)).prod =
diagonal (sum.elim D₀ (λ _, c)), by simpa [M', matrix.mul_assoc, c],
have : M' = from_blocks M'' 0 0 (diagonal (λ _, c)),
{ rw ← from_blocks_to_blocks M',
congr,
{ exact hM.1 },
{ exact hM.2 },
{ ext ⟨⟩ ⟨⟩, rw [hc, to_blocks₂₂, of_apply], refl, } },
rw this,
simp [h₀],
end
variables {n p} [fintype n] [fintype p]
/-- Reduction to diagonal form by elementary operations is invariant under reindexing. -/
lemma reindex_exists_list_transvec_mul_mul_list_transvec_eq_diagonal (M : matrix p p 𝕜) (e : p ≃ n)
(H : ∃ (L L' : list (transvection_struct n 𝕜)) (D : n → 𝕜),
(L.map to_matrix).prod ⬝ (matrix.reindex_alg_equiv 𝕜 e M) ⬝ (L'.map to_matrix).prod
= diagonal D) :
∃ (L L' : list (transvection_struct p 𝕜)) (D : p → 𝕜),
(L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod = diagonal D :=
begin
rcases H with ⟨L₀, L₀', D₀, h₀⟩,
refine ⟨L₀.map (reindex_equiv e.symm), L₀'.map (reindex_equiv e.symm), D₀ ∘ e, _⟩,
have : M = reindex_alg_equiv 𝕜 e.symm (reindex_alg_equiv 𝕜 e M),
by simp only [equiv.symm_symm, submatrix_submatrix, reindex_apply, submatrix_id_id,
equiv.symm_comp_self, reindex_alg_equiv_apply],
rw this,
simp only [to_matrix_reindex_equiv_prod, list.map_map, reindex_alg_equiv_apply],
simp only [← reindex_alg_equiv_apply, ← reindex_alg_equiv_mul, h₀],
simp only [equiv.symm_symm, reindex_apply, submatrix_diagonal_equiv, reindex_alg_equiv_apply],
end
/-- Any matrix can be reduced to diagonal form by elementary operations. Formulated here on `Type 0`
because we will make an induction using `fin r`.
See `exists_list_transvec_mul_mul_list_transvec_eq_diagonal` for the general version (which follows
from this one and reindexing). -/
lemma exists_list_transvec_mul_mul_list_transvec_eq_diagonal_aux
(n : Type) [fintype n] [decidable_eq n]
(M : matrix n n 𝕜) : ∃ (L L' : list (transvection_struct n 𝕜)) (D : n → 𝕜),
(L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod = diagonal D :=
begin
unfreezingI { induction hn : fintype.card n with r IH generalizing n M },
{ refine ⟨list.nil, list.nil, λ _, 1, _⟩,
ext i j,
rw fintype.card_eq_zero_iff at hn,
exact hn.elim' i },
{ have e : n ≃ fin r ⊕ unit,
{ refine fintype.equiv_of_card_eq _,
rw hn,
convert (@fintype.card_sum (fin r) unit _ _).symm,
simp },
apply reindex_exists_list_transvec_mul_mul_list_transvec_eq_diagonal M e,
apply exists_list_transvec_mul_mul_list_transvec_eq_diagonal_induction
(λ N, IH (fin r) N (by simp)) }
end
/-- Any matrix can be reduced to diagonal form by elementary operations. -/
theorem exists_list_transvec_mul_mul_list_transvec_eq_diagonal
(M : matrix n n 𝕜) : ∃ (L L' : list (transvection_struct n 𝕜)) (D : n → 𝕜),
(L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod = diagonal D :=
begin
have e : n ≃ fin (fintype.card n) := fintype.equiv_of_card_eq (by simp),
apply reindex_exists_list_transvec_mul_mul_list_transvec_eq_diagonal M e,
apply exists_list_transvec_mul_mul_list_transvec_eq_diagonal_aux
end
/-- Any matrix can be written as the product of transvections, a diagonal matrix, and
transvections.-/
theorem exists_list_transvec_mul_diagonal_mul_list_transvec
(M : matrix n n 𝕜) : ∃ (L L' : list (transvection_struct n 𝕜)) (D : n → 𝕜),
M = (L.map to_matrix).prod ⬝ diagonal D ⬝ (L'.map to_matrix).prod :=
begin
rcases exists_list_transvec_mul_mul_list_transvec_eq_diagonal M with ⟨L, L', D, h⟩,
refine ⟨L.reverse.map transvection_struct.inv, L'.reverse.map transvection_struct.inv, D, _⟩,
suffices : M =
((L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod ⬝ (L.map to_matrix).prod) ⬝ M ⬝
((L'.map to_matrix).prod ⬝ (L'.reverse.map (to_matrix ∘ transvection_struct.inv)).prod),
by simpa [← h, matrix.mul_assoc],
rw [reverse_inv_prod_mul_prod, prod_mul_reverse_inv_prod, matrix.one_mul, matrix.mul_one],
end
end pivot
open pivot transvection_struct
variables {n} [fintype n]
/-- Induction principle for matrices based on transvections: if a property is true for all diagonal
matrices, all transvections, and is stable under product, then it is true for all matrices. This is
the useful way to say that matrices are generated by diagonal matrices and transvections.
We state a slightly more general version: to prove a property for a matrix `M`, it suffices to
assume that the diagonal matrices we consider have the same determinant as `M`. This is useful to
obtain similar principles for `SLₙ` or `GLₙ`. -/
lemma diagonal_transvection_induction (P : matrix n n 𝕜 → Prop) (M : matrix n n 𝕜)
(hdiag : ∀ D : n → 𝕜, det (diagonal D) = det M → P (diagonal D))
(htransvec : ∀ (t : transvection_struct n 𝕜), P t.to_matrix)
(hmul : ∀ A B, P A → P B → P (A ⬝ B)) :
P M :=
begin
rcases exists_list_transvec_mul_diagonal_mul_list_transvec M with ⟨L, L', D, h⟩,
have PD : P (diagonal D) := hdiag D (by simp [h]),
suffices H : ∀ (L₁ L₂ : list (transvection_struct n 𝕜)) (E : matrix n n 𝕜),
P E → P ((L₁.map to_matrix).prod ⬝ E ⬝ (L₂.map to_matrix).prod),
by { rw h, apply H L L', exact PD },
assume L₁ L₂ E PE,
induction L₁ with t L₁ IH,
{ simp only [matrix.one_mul, list.prod_nil, list.map],
induction L₂ with t L₂ IH generalizing E,
{ simpa },
{ simp only [←matrix.mul_assoc, list.prod_cons, mul_eq_mul, list.map],
apply IH,
exact hmul _ _ PE (htransvec _) } },
{ simp only [matrix.mul_assoc, list.prod_cons, mul_eq_mul, list.map] at ⊢ IH,
exact hmul _ _ (htransvec _) IH }
end
/-- Induction principle for invertible matrices based on transvections: if a property is true for
all invertible diagonal matrices, all transvections, and is stable under product of invertible
matrices, then it is true for all invertible matrices. This is the useful way to say that
invertible matrices are generated by invertible diagonal matrices and transvections. -/
lemma diagonal_transvection_induction_of_det_ne_zero (P : matrix n n 𝕜 → Prop)
(M : matrix n n 𝕜) (hMdet : det M ≠ 0)
(hdiag : ∀ D : n → 𝕜, det (diagonal D) ≠ 0 → P (diagonal D))
(htransvec : ∀ (t : transvection_struct n 𝕜), P t.to_matrix)
(hmul : ∀ A B, det A ≠ 0 → det B ≠ 0 → P A → P B → P (A ⬝ B)) :
P M :=
begin
let Q : matrix n n 𝕜 → Prop := λ N, det N ≠ 0 ∧ P N,
have : Q M,
{ apply diagonal_transvection_induction Q M,
{ assume D hD,
have detD : det (diagonal D) ≠ 0, by { rw hD, exact hMdet },
exact ⟨detD, hdiag _ detD⟩ },
{ assume t,
exact ⟨by simp, htransvec t⟩ },
{ assume A B QA QB,
exact ⟨by simp [QA.1, QB.1], hmul A B QA.1 QB.1 QA.2 QB.2⟩ } },
exact this.2
end
end matrix
|
4a608cfbea4f6d5380c914d33cabbd3d6aa17554 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/rewrite_search/discovery.lean | fbafb926be26bbb64008c927ae76a6ef21ccdfcf | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 3,442 | lean | /-
Copyright (c) 2020 Kevin Lacker, Keeley Hoek, Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Lacker, Keeley Hoek, Scott Morrison
-/
import tactic.nth_rewrite
import tactic.rewrite_search.types
/-!
# Generating a list of rewrites to use as steps in rewrite search.
-/
namespace tactic.rewrite_search
open tactic tactic.interactive tactic.rewrite_search
/--
Convert a list of expressions into a list of rules. The difference is that a rule
includes a flag for direction, so this simply includes each expression twice,
once in each direction.
-/
private meta def rules_from_exprs (l : list expr) : list (expr × bool) :=
l.map (λ e, (e, ff)) ++ l.map (λ e, (e, tt))
/-- Returns true if expression is an equation or iff. -/
private meta def is_acceptable_rewrite : expr → bool
| (expr.pi n bi d b) := is_acceptable_rewrite b
| `(%%a = %%b) := tt
| `(%%a ↔ %%b) := tt
| _ := ff
/-- Returns true if the expression is an equation or iff and has no metavariables. -/
private meta def is_acceptable_hyp (r : expr) : tactic bool :=
do t ← infer_type r >>= whnf, return $ is_acceptable_rewrite t ∧ ¬t.has_meta_var
/-- Collect all hypotheses in the local context that are usable as rewrite rules. -/
private meta def rules_from_hyps : tactic (list (expr × bool)) :=
do hyps ← local_context,
rules_from_exprs <$> hyps.mfilter is_acceptable_hyp
/-- Use this attribute to make `rewrite_search` use this definition during search. -/
@[user_attribute]
meta def rewrite_search_attr : user_attribute :=
{ name := `rewrite,
descr := "declare that this definition should be considered by `rewrite_search`" }
/-- Gather rewrite rules from lemmas explicitly tagged with `rewrite. -/
private meta def rules_from_rewrite_attr : tactic (list (expr × bool)) :=
do names ← attribute.get_instances `rewrite,
rules_from_exprs <$> names.mmap mk_const
/--
Collect rewrite rules to use from the environment.
-/
meta def collect_rules : tactic (list (expr × bool)) :=
do from_attr ← rules_from_rewrite_attr,
from_hyps ← rules_from_hyps,
return $ from_attr ++ from_hyps
open tactic.nth_rewrite tactic.nth_rewrite.congr
/--
Constructing our rewrite structure from the `tracked_rewrite` provided by `nth_rewrite`.
rule_index is the index of the rule used from the rules provided.
tracked is an (index, tracked_rewrite) pair for the element of `all_rewrites exp rule` we used.
-/
private meta def from_tracked (rule_index : ℕ) (tracked : ℕ × tracked_rewrite) : rewrite :=
do let (rw_index, rw) := tracked,
let h : how := ⟨rule_index, rw_index, rw.addr⟩,
⟨rw.exp, rw.proof, h⟩
/--
Get all rewrites that start at the given expression and use the given rewrite rule.
-/
private meta def rewrites_for_rule (exp : expr) (cfg : config) (numbered_rule: ℕ × expr × bool) :
tactic (list rewrite) :=
do let (rule_index, rule) := numbered_rule,
tracked ← all_rewrites exp rule cfg.to_cfg,
return (list.map (from_tracked rule_index) tracked.enum)
/--
Get all rewrites that start at the given expression and use one of the given rewrite rules.
-/
meta def get_rewrites (rules : list (expr × bool)) (exp : expr) (cfg : config) :
tactic (buffer rewrite) :=
do lists ← list.mmap (rewrites_for_rule exp cfg) rules.enum,
return (list.foldl buffer.append_list buffer.nil lists)
end tactic.rewrite_search
|
1e4d11ba907ff2b063e1b5684db8a82ee313b98f | 76ce87faa6bc3c2aa9af5962009e01e04f2a074a | /HW/HW3.lean | 23ed20ae28b4a0ccd6e38919511df662e5e54406 | [] | no_license | Mnormansell/Discrete-Notes | db423dd9206bbe7080aecb84b4c2d275b758af97 | 61f13b98be590269fc4822be7b47924a6ddc1261 | refs/heads/master | 1,585,412,435,424 | 1,540,919,483,000 | 1,540,919,483,000 | 148,684,638 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,627 | lean | /-
Produce a proof, pf1, of the proposition
that 0 = 0 ∧ (1 = 1 ∧ 2 = 2).
-/
lemma pf1 : 0 = 0 ∧ (1 = 1 ∧ 2 = 2) :=
and.intro rfl (and.intro rfl rfl)
/-
Produce a proof, pf2, of the proposition
that (0 = 0 ∧ 1 = 1) ∧ 2 = 2
-/
lemma pf2 : (0 = 0 ∧ 1 = 1) ∧ 2 = 2 :=
and.intro (and.intro rfl rfl) rfl
/-
Produce a proof, pf3, of the proposition
that 0 = 0 ∧ 1 = 1 ∧ 2 = 2. Hint, one of
the two preceding proofs can be used to
prove this proposition; there's no need
to type out a whole new proof.
-/
lemma pf3 : 0 = 0 ∧ 1 = 1 ∧ 2 = 2 :=
pf1
/-
An operator, *, is "right associative"
if X * Y * Z means X * (Y * Z), and is
"left associative" if X * Y * Z means
(X * Y) * Y. Is the logical connective,
∧, left or right associative? Explain.
-/
-- It's right associative as we just proved
-- pf3 with pf1, and pf1 is in the form
-- X * (Y * Z).
/-
Use Lean to produce a proof, pf4, that
0 = 0 ∧ 1 = 1 ∧ 2 = 2 is exactly the
same proposition as one of the two
parenthesized forms. It will be a
proof that two propositions are equal.
Put parentheses around each of the
propositions.
-/
lemma pf4 :
(0 = 0 ∧ 1 = 1 ∧ 2 = 2) =
(0 = 0 ∧ (1 = 1 ∧ 2 = 2)) :=
rfl
/-
Given arbitrary propositions, P, Q and
R it should be possible to produce a
proof, pf5, showing that if P ∧ (Q ∧ R)
is true then so is (P ∧ Q) ∧ R. Written
in inference rule form, this would say
the following:
{ P Q R: Prop }, p_qr : P ∧ (Q ∧ R)
---------------------------------- ∧.assoc_1
pq_r : (P ∧ Q) ∧ R
Proving that this is a valid rule
can be done by defining a function,
let's call it and_assoc_l, that when
given any propositions, P, Q, and R
(implicitly), and when given a proof
of P ∧ (Q ∧ R), constructs and returns
a proof of (P ∧ Q) ∧ R.
Here we give you this function, and
we explain each part in comments.
You will then apply what you learn
by studying this example to solve
the same problem but going in the
other direction. Here's the solution.
-/
-- define the function name
def and_assoc_l
-- specify the arguments and their types
{P Q R: Prop}
(pf: P ∧ (Q ∧ R)) : -- note colon
-- the return type
(P ∧ Q) ∧ R
/-
What we've given so far is what we call
the function signature: its name, the
names and types of the arguments that it
takes, and the type of the return value.
In this case, the return value is of
type (P ∧ Q) ∧ R, and will thus serve
as a proof of this proposition. This is
a function that takes a proof and returns
a (different) proof. It thus provides a
general recipe for turning any proof of
P ∧ (Q ∧ R) into a proof of (P ∧ Q) ∧ R.
-/
:= -- now give function body
/-
Usually we'd expect to see an expression
here, involving multiple, nested and.elim
and and.intro expressions. We could write
the function body that way, but it's a bit
tricky to get all the nested expressions
right. Here's a revelation: We can use a
tactic script to produce the same result.
Open your Messages window, put your cursor
on begin, study carefully the tactic state,
notice that the arguments are given in the
context to the left of the turnstile and
the goal remaining to be proved is to the
right. You can use the context values as
arguments to tactics.
Now click through each line of the script
and study very carefully how it changes the
context. By the end of the script, you
should see how we've been able to use
elimination rules take apart the proof
that was given as an argument, giving names
to the parts, and how we can then further
take apart those parts, giving names to the
subparts, and finally how we can intro
rules to put all these pieces together
again into the proof we need.
-/
begin
have pfP := and.elim_left pf,
have pfQR := and.elim_right pf,
have pfQ := and.elim_left pfQR,
have pfR := and.elim_right pfQR,
have pfPQ := and.intro pfP pfQ,
have pfPQ_R := and.intro pfPQ pfR,
exact pfPQ_R
end
/-
Define another function, and_assoc_r,
that goes the other direction: given
a proof of (P ∧ Q) ∧ R it derives and
returns a proof of P ∧ (Q ∧ R). Write
the entire solution yourself.
-/
def and_assoc_r
{P Q R: Prop}
(pf: (P ∧ Q) ∧ R) :
P ∧ (Q ∧ R) :=
begin
have pfPQ := and.elim_left pf,
have pfR := and.elim_right pf,
have pfP := and.elim_left pfPQ,
have pfQ := and.elim_right pfPQ,
have pfQR := and.intro pfQ pfR,
have pfP_QR := and.intro pfP pfQR,
exact pfP_QR
end
/-
It's important to learn how you would
give such proofs in natural langage.
Let's take our first example. Here is
a natural language version.
"Given arbitrary propositions, P, Q, and
R, and the assumption that P ∧ (Q ∧ R) is
true, we are to show that (P ∧ Q) ∧ R is
true.
Given that P ∧ (Q ∧ R) is true, it must
be that P is true and that Q ∧ R is also
true. Given that Q ∧ R is true, it must
be that Q is true, and R is also true.
So we have that P, Q, and R are all true.
From these conclusions we can in turn
deduce that P ∧ Q must be true. And so
we now have that P ∧ Q is true and so is
R, from which, finally we can deduce
that (P ∧ Q) ∧ R must be true as well.
QED."
Now it's your turn: write an English
language proof for the theorem in the
other direction.
-/
/-
"Given arbitrary propositions, P, Q, and
R, and the assumption that (P ∧ Q) ∧ R is
true, we are to show that P ∧ (Q ∧ R) is
true.
Given that (P ∧ Q) ∧ R, it must be that
(P ∧ Q) is true and also that R is true.
Given that (P ∧ Q) is true, then P must
be true, and Q must be true. Therefore
P, Q, and R are all true.
From this conclusion we can deduce that
Q ∧ R must be true. Since P is true and
(Q ∧ R) is true, it follows that P ∧ (Q ∧ R)
must be true as well.
QED."
-/
/-
Use Lean to produce a proof, tnott, of
the proposition that truth isn't truth.
I.e., true is not true. We'll write this
is Lean like this:
theorem tnott: true ≠ true := _.
To make it a little easier to solve
this otherwise difficult problem, we
allow you to stipulate one "axiom" of
your choice, which you can then use
to produce the required proof.
-/
-- You can introduce an axiom here
axiom f: false
-- Now prove the theorem
theorem tnott : true ≠ true := false.elim f
/-
What did you have to accept to be able
to prove that truth isn't truth?
-/
/- We had to accept that there was an axiom
for false, which is an absurdity, which
then allows us to create a proof for a
proposition for which there is not proof
-/ |
ed0058eb6f2c9dac48cff6f3e598c9eca15c9f76 | fe25de614feb5587799621c41487aaee0d083b08 | /src/Lean/MetavarContext.lean | dd56ce836dbda2526f2f9e96605ccffcb0e039e1 | [
"Apache-2.0"
] | permissive | pollend/lean4 | e8469c2f5fb8779b773618c3267883cf21fb9fac | c913886938c4b3b83238a3f99673c6c5a9cec270 | refs/heads/master | 1,687,973,251,481 | 1,628,039,739,000 | 1,628,039,739,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 53,598 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.MonadCache
import Lean.LocalContext
namespace Lean
/-
The metavariable context stores metavariable declarations and their
assignments. It is used in the elaborator, tactic framework, unifier
(aka `isDefEq`), and type class resolution (TC). First, we list all
the requirements imposed by these modules.
- We may invoke TC while executing `isDefEq`. We need this feature to
be able to solve unification problems such as:
```
f ?a (ringAdd ?s) ?x ?y =?= f Int intAdd n m
```
where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)`
During `isDefEq` (i.e., unification), it will need to solve the constrain
```
ringAdd ?s =?= intAdd
```
We say `ringAdd ?s` is stuck because it cannot be reduced until we
synthesize the term `?s : Ring ?a` using TC. This can be done since we
have assigned `?a := Int` when solving `?a =?= Int`.
- TC uses `isDefEq`, and `isDefEq` may create TC problems as shown
above. Thus, we may have nested TC problems.
- `isDefEq` extends the local context when going inside binders. Thus,
the local context for nested TC may be an extension of the local
context for outer TC.
- TC should not assign metavariables created by the elaborator, simp,
tactic framework, and outer TC problems. Reason: TC commits to the
first solution it finds. Consider the TC problem `Coe Nat ?x`,
where `?x` is a metavariable created by the caller. There are many
solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...),
and it doesn’t make sense to commit to the first one since TC does
not know the constraints the caller may impose on `?x` after the
TC problem is solved.
Remark: we claim it is not feasible to make the whole system backtrackable,
and allow the caller to backtrack back to TC and ask it for another solution
if the first one found did not work. We claim it would be too inefficient.
- TC metavariables should not leak outside of TC. Reason: we want to
get rid of them after we synthesize the instance.
- `simp` invokes `isDefEq` for matching the left-hand-side of
equations to terms in our goal. Thus, it may invoke TC indirectly.
- In Lean3, we didn’t have to create a fresh pattern for trying to
match the left-hand-side of equations when executing `simp`. We had a
mechanism called "tmp" metavariables. It avoided this overhead, but it
created many problems since `simp` may indirectly call TC which may
recursively call TC. Moreover, we may want to allow TC to invoke
tactics in the future. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke
a tactic and `simp` itself. The Lean3 approach assumed that
metavariables were short-lived, this is not true in Lean4, and to some
extent was also not true in Lean3 since `simp`, in principle, could
trigger an arbitrary number of nested TC problems.
- Here are some possible call stack traces we could have in Lean3 (and Lean4).
```
Elaborator (-> TC -> isDefEq)+
Elaborator -> isDefEq (-> TC -> isDefEq)*
Elaborator -> simp -> isDefEq (-> TC -> isDefEq)*
```
In Lean4, TC may also invoke tactics in the future.
- In Lean3 and Lean4, TC metavariables are not really short-lived. We
solve an arbitrary number of unification problems, and we may have
nested TC invocations.
- TC metavariables do not share the same local context even in the
same invocation. In the C++ and Lean implementations we use a trick to
ensure they do:
https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594
- Metavariables may be natural, synthetic or syntheticOpaque.
a) Natural metavariables may be assigned by unification (i.e., `isDefEq`).
b) Synthetic metavariables may still be assigned by unification,
but whenever possible `isDefEq` will avoid the assignment. For example,
if we have the unification constaint `?m =?= ?n`, where `?m` is synthetic,
but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`.
We use synthetic metavariables for type class resolution.
Any module that creates synthetic metavariables, must also check
whether they have been assigned by `isDefEq`, and then still synthesize
them, and check whether the sythesized result is compatible with the one
assigned by `isDefEq`.
c) SyntheticOpaque metavariables are never assigned by `isDefEq`.
That is, the constraint `?n =?= Nat.succ Nat.zero` always fail
if `?n` is a syntheticOpaque metavariable. This kind of metavariable
is created by tactics such as `intro`. Reason: in the tactic framework,
subgoals as represented as metavariables, and a subgoal `?n` is considered
as solved whenever the metavariable is assigned.
This distinction was not precise in Lean3 and produced
counterintuitive behavior. For example, the following hack was added
in Lean3 to work around one of these issues:
https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751
- When creating lambda/forall expressions, we need to convert/abstract
free variables and convert them to bound variables. Now, suppose we a
trying to create a lambda/forall expression by abstracting free
variable `xs` and a term `t[?m]` which contains a metavariable `?m`,
and the local context of `?m` contains `xs`. The term
```
fun xs => t[?m]
```
will be ill-formed if we later assign a term `s` to `?m`, and
`s` contains free variables in `xs`. We address this issue by changing
the free variable abstraction procedure. We consider two cases: `?m`
is natural, `?m` is synthetic. Assume the type of `?m` is
`A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with
type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`.
In both cases, we produce the term `fun xs => t[?n xs]`
1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce
the term `fun xs => t[?n xs]`
2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable.
However, `?n` is managed by the metavariable context itself.
We say we have a "delayed assignment" `?n xs := ?m`.
That is, after a term `s` is assigned to `?m`, and `s`
does not contain metavariables, we replace any occurrence
`?n ts` with `s[xs := ts]`.
Gruesome details:
- When we create the type `forall xs => A` for `?n`, we may
encounter the same issue if `A` contains metavariables. So, the
process above is recursive. We claim it terminates because we keep
creating new metavariables with smaller local contexts.
- Suppose, we have `t[?m]` and we want to create a let-expression by
abstracting a let-decl free variable `x`, and the local context of
`?m` contatins `x`. Similarly to the previous case
```
let x : T := v; t[?m]
```
will be ill-formed if we later assign a term `s` to `?m`, and
`s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`.
1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with
and local context := local context of `?m` - `x`, we assign `?m := ?n`,
and produce the term `let x : T := v; t[?n]`. That is, we are just making
sure `?n` must never be assigned to a term containing `x`.
2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n`
with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`,
create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`.
Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since
`fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r`
with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic
may have reduced `let x : T := v; t[?n x]` into `t[?n v]`.
We are essentially using the pair "delayed assignment + application" to implement a delayed
substitution.
- We use TC for implementing coercions. Both Joe Hendrix and Reid Barton
reported a nasty limitation. In Lean3, TC will not be used if there are
metavariables in the TC problem. For example, the elaborator will not try
to synthesize `Coe Nat ?x`. This is good, but this constraint is too
strict for problems such as `Coe (Vector Bool ?n) (BV ?n)`. The coercion
exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw
an exception instead of return `false` whenever it tries to assign
a metavariable owned by its caller. The idea is to sign to the caller that
it cannot solve the TC problem at this point, and more information is needed.
That is, the caller must make progress an assign its metavariables before
trying to invoke TC again.
In Lean4, we are using a simpler design for the `MetavarContext`.
- No distinction betwen temporary and regular metavariables.
- Metavariables have a `depth` Nat field.
- MetavarContext also has a `depth` field.
- We bump the `MetavarContext` depth when we create a nested problem.
Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ...
- When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`.
- Metavariables from depth N+1 must be fully assigned before we return to level N.
- New design even allows us to invoke tactics from TC.
* Main concern
We don't have tmp metavariables anymore in Lean4. Thus, before trying to match
the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`,
create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with
these metavariables. We are hoping to minimize this overhead by
- Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`.
- Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`.
It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables,
and a new pattern.
- Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set.
- Adding support for AC-rewriting. In Lean3, users use AC lemmas as
rewriting rules for "sorting" terms. This is inefficient, requires
a quadratic number of rewrite steps, and does not preserve the
structure of the goal.
The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses
`isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3,
all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using
very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars,
we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars.
-/
structure LocalInstance where
className : Name
fvar : Expr
deriving Inhabited
abbrev LocalInstances := Array LocalInstance
instance : BEq LocalInstance where
beq i₁ i₂ := i₁.fvar == i₂.fvar
/-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/
def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances :=
match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with
| some idx => localInsts.eraseIdx idx
| _ => localInsts
inductive MetavarKind where
| natural
| synthetic
| syntheticOpaque
deriving Inhabited
def MetavarKind.isSyntheticOpaque : MetavarKind → Bool
| MetavarKind.syntheticOpaque => true
| _ => false
def MetavarKind.isNatural : MetavarKind → Bool
| MetavarKind.natural => true
| _ => false
structure MetavarDecl where
userName : Name := Name.anonymous
lctx : LocalContext
type : Expr
depth : Nat
localInstances : LocalInstances
kind : MetavarKind
numScopeArgs : Nat := 0 -- See comment at `CheckAssignment` `Meta/ExprDefEq.lean`
index : Nat -- We use this field to track how old a metavariable is. It is set using a counter at `MetavarContext`
deriving Inhabited
/--
A delayed assignment for a metavariable `?m`. It represents an assignment of the form
`?m := (fun fvars => val)`. The local context `lctx` provides the declarations for `fvars`.
Note that `fvars` may not be defined in the local context for `?m`.
- TODO: after we delete the old frontend, we can remove the field `lctx`.
This field is only used in old C++ implementation. -/
structure DelayedMetavarAssignment where
lctx : LocalContext
fvars : Array Expr
val : Expr
open Std (HashMap PersistentHashMap)
structure MetavarContext where
depth : Nat := 0
mvarCounter : Nat := 0 -- Counter for setting the field `index` at `MetavarDecl`
lDepth : PersistentHashMap MVarId Nat := {}
decls : PersistentHashMap MVarId MetavarDecl := {}
lAssignment : PersistentHashMap MVarId Level := {}
eAssignment : PersistentHashMap MVarId Expr := {}
dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {}
class MonadMCtx (m : Type → Type) where
getMCtx : m MetavarContext
modifyMCtx : (MetavarContext → MetavarContext) → m Unit
export MonadMCtx (getMCtx modifyMCtx)
instance (m n) [MonadLift m n] [MonadMCtx m] : MonadMCtx n where
getMCtx := liftM (getMCtx : m _)
modifyMCtx := fun f => liftM (modifyMCtx f : m _)
namespace MetavarContext
instance : Inhabited MetavarContext := ⟨{}⟩
@[export lean_mk_metavar_ctx]
def mkMetavarContext : Unit → MetavarContext := fun _ => {}
/- Low level API for adding/declaring metavariable declarations.
It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`.
It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/
def addExprMVarDecl (mctx : MetavarContext)
(mvarId : MVarId)
(userName : Name)
(lctx : LocalContext)
(localInstances : LocalInstances)
(type : Expr)
(kind : MetavarKind := MetavarKind.natural)
(numScopeArgs : Nat := 0) : MetavarContext :=
{ mctx with
mvarCounter := mctx.mvarCounter + 1
decls := mctx.decls.insert mvarId {
depth := mctx.depth
index := mctx.mvarCounter
userName
lctx
localInstances
type
kind
numScopeArgs } }
def addExprMVarDeclExp (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances)
(type : Expr) (kind : MetavarKind) : MetavarContext :=
addExprMVarDecl mctx mvarId userName lctx localInstances type kind
/- Low level API for adding/declaring universe level metavariable declarations.
It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`.
It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/
def addLevelMVarDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext :=
{ mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth }
def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl :=
mctx.decls.find? mvarId
def getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl :=
match mctx.decls.find? mvarId with
| some decl => decl
| none => panic! "unknown metavariable"
def findUserName? (mctx : MetavarContext) (userName : Name) : Option MVarId :=
let search : Except MVarId Unit := mctx.decls.forM fun mvarId decl =>
if decl.userName == userName then throw mvarId else pure ()
match search with
| Except.ok _ => none
| Except.error mvarId => some mvarId
def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext :=
let decl := mctx.getDecl mvarId
{ mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } }
def setMVarUserName (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext :=
let decl := mctx.getDecl mvarId
{ mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } }
/- Update the type of the given metavariable. This function assumes the new type is
definitionally equal to the current one -/
def setMVarType (mctx : MetavarContext) (mvarId : MVarId) (type : Expr) : MetavarContext :=
let decl := mctx.getDecl mvarId
{ mctx with decls := mctx.decls.insert mvarId { decl with type := type } }
def findLevelDepth? (mctx : MetavarContext) (mvarId : MVarId) : Option Nat :=
mctx.lDepth.find? mvarId
def getLevelDepth (mctx : MetavarContext) (mvarId : MVarId) : Nat :=
match mctx.findLevelDepth? mvarId with
| some d => d
| none => panic! "unknown metavariable"
def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool :=
match mctx.findDecl? mvarId with
| none => false
| some mvarDecl => mvarDecl.userName.isAnonymous
def renameMVar (mctx : MetavarContext) (mvarId : MVarId) (newUserName : Name) : MetavarContext :=
match mctx.findDecl? mvarId with
| none => panic! "unknown metavariable"
| some mvarDecl => { mctx with decls := mctx.decls.insert mvarId { mvarDecl with userName := newUserName } }
def assignLevel (m : MetavarContext) (mvarId : MVarId) (val : Level) : MetavarContext :=
{ m with lAssignment := m.lAssignment.insert mvarId val }
def assignExpr (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext :=
{ m with eAssignment := m.eAssignment.insert mvarId val }
def assignDelayed (m : MetavarContext) (mvarId : MVarId) (lctx : LocalContext) (fvars : Array Expr) (val : Expr) : MetavarContext :=
{ m with dAssignment := m.dAssignment.insert mvarId { lctx := lctx, fvars := fvars, val := val } }
def getLevelAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Level :=
m.lAssignment.find? mvarId
def getExprAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Expr :=
m.eAssignment.find? mvarId
def getDelayedAssignment? (m : MetavarContext) (mvarId : MVarId) : Option DelayedMetavarAssignment :=
m.dAssignment.find? mvarId
def isLevelAssigned (m : MetavarContext) (mvarId : MVarId) : Bool :=
m.lAssignment.contains mvarId
def isExprAssigned (m : MetavarContext) (mvarId : MVarId) : Bool :=
m.eAssignment.contains mvarId
def isDelayedAssigned (m : MetavarContext) (mvarId : MVarId) : Bool :=
m.dAssignment.contains mvarId
def eraseDelayed (m : MetavarContext) (mvarId : MVarId) : MetavarContext :=
{ m with dAssignment := m.dAssignment.erase mvarId }
/- Given a sequence of delayed assignments
```
mvarId₁ := mvarId₂ ...;
...
mvarIdₙ := mvarId_root ... -- where `mvarId_root` is not delayed assigned
```
in `mctx`, `getDelayedRoot mctx mvarId₁` return `mvarId_root`.
If `mvarId₁` is not delayed assigned then return `mvarId₁` -/
partial def getDelayedRoot (m : MetavarContext) : MVarId → MVarId
| mvarId => match getDelayedAssignment? m mvarId with
| some d => match d.val.getAppFn with
| Expr.mvar mvarId _ => getDelayedRoot m mvarId
| _ => mvarId
| none => mvarId
def isLevelAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool :=
match mctx.lDepth.find? mvarId with
| some d => d == mctx.depth
| _ => panic! "unknown universe metavariable"
def isExprAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool :=
let decl := mctx.getDecl mvarId
decl.depth == mctx.depth
def incDepth (mctx : MetavarContext) : MetavarContext :=
{ mctx with depth := mctx.depth + 1 }
/-- Return true iff the given level contains an assigned metavariable. -/
def hasAssignedLevelMVar (mctx : MetavarContext) : Level → Bool
| Level.succ lvl _ => lvl.hasMVar && hasAssignedLevelMVar mctx lvl
| Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂)
| Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂)
| Level.mvar mvarId _ => mctx.isLevelAssigned mvarId
| Level.zero _ => false
| Level.param _ _ => false
/-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/
def hasAssignedMVar (mctx : MetavarContext) : Expr → Bool
| Expr.const _ lvls _ => lvls.any (hasAssignedLevelMVar mctx)
| Expr.sort lvl _ => hasAssignedLevelMVar mctx lvl
| Expr.app f a _ => (f.hasMVar && hasAssignedMVar mctx f) || (a.hasMVar && hasAssignedMVar mctx a)
| Expr.letE _ t v b _ => (t.hasMVar && hasAssignedMVar mctx t) || (v.hasMVar && hasAssignedMVar mctx v) || (b.hasMVar && hasAssignedMVar mctx b)
| Expr.forallE _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b)
| Expr.lam _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b)
| Expr.fvar _ _ => false
| Expr.bvar _ _ => false
| Expr.lit _ _ => false
| Expr.mdata _ e _ => e.hasMVar && hasAssignedMVar mctx e
| Expr.proj _ _ e _ => e.hasMVar && hasAssignedMVar mctx e
| Expr.mvar mvarId _ => mctx.isExprAssigned mvarId || mctx.isDelayedAssigned mvarId
/-- Return true iff the given level contains a metavariable that can be assigned. -/
def hasAssignableLevelMVar (mctx : MetavarContext) : Level → Bool
| Level.succ lvl _ => lvl.hasMVar && hasAssignableLevelMVar mctx lvl
| Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂)
| Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂)
| Level.mvar mvarId _ => mctx.isLevelAssignable mvarId
| Level.zero _ => false
| Level.param _ _ => false
/-- Return `true` iff expression contains a metavariable that can be assigned. -/
def hasAssignableMVar (mctx : MetavarContext) : Expr → Bool
| Expr.const _ lvls _ => lvls.any (hasAssignableLevelMVar mctx)
| Expr.sort lvl _ => hasAssignableLevelMVar mctx lvl
| Expr.app f a _ => (f.hasMVar && hasAssignableMVar mctx f) || (a.hasMVar && hasAssignableMVar mctx a)
| Expr.letE _ t v b _ => (t.hasMVar && hasAssignableMVar mctx t) || (v.hasMVar && hasAssignableMVar mctx v) || (b.hasMVar && hasAssignableMVar mctx b)
| Expr.forallE _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b)
| Expr.lam _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b)
| Expr.fvar _ _ => false
| Expr.bvar _ _ => false
| Expr.lit _ _ => false
| Expr.mdata _ e _ => e.hasMVar && hasAssignableMVar mctx e
| Expr.proj _ _ e _ => e.hasMVar && hasAssignableMVar mctx e
| Expr.mvar mvarId _ => mctx.isExprAssignable mvarId
/-
Notes on artificial eta-expanded terms due to metavariables.
We try avoid synthetic terms such as `((fun x y => t) a b)` in the output produced by the elaborator.
This kind of term may be generated when instantiating metavariable assignments.
This module tries to avoid their generation because they often introduce unnecessary dependencies and
may affect automation.
When elaborating terms, we use metavariables to represent "holes". Each hole has a context which includes
all free variables that may be used to "fill" the hole. Suppose, we create a metavariable (hole) `?m : Nat` in a context
containing `(x : Nat) (y : Nat) (b : Bool)`, then we can assign terms such as `x + y` to `?m` since `x` and `y`
are in the context used to create `?m`. Now, suppose we have the term `?m + 1` and we want to create the lambda expression
`fun x => ?m + 1`. This term is not correct since we may assign to `?m` a term containing `x`.
We address this issue by create a synthetic metavariable `?n : Nat → Nat` and adding the delayed assignment
`?n #[x] := ?m`, and the term `fun x => ?n x + 1`. When we later assign a term `t[x]` to `?m`, `fun x => t[x]` is assigned to
`?n`, and if we substitute it at `fun x => ?n x + 1`, we produce `fun x => ((fun x => t[x]) x) + 1`.
To avoid this term eta-expanded term, we apply beta-reduction when instantiating metavariable assignments in this module.
This operation is performed at `instantiateExprMVars`, `elimMVarDeps`, and `levelMVarToParam`.
-/
partial def instantiateLevelMVars [Monad m] [MonadMCtx m] : Level → m Level
| lvl@(Level.succ lvl₁ _) => return Level.updateSucc! lvl (← instantiateLevelMVars lvl₁)
| lvl@(Level.max lvl₁ lvl₂ _) => return Level.updateMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂)
| lvl@(Level.imax lvl₁ lvl₂ _) => return Level.updateIMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂)
| lvl@(Level.mvar mvarId _) => do
match getLevelAssignment? (← getMCtx) mvarId with
| some newLvl =>
if !newLvl.hasMVar then pure newLvl
else do
let newLvl' ← instantiateLevelMVars newLvl
modifyMCtx fun mctx => mctx.assignLevel mvarId newLvl'
pure newLvl'
| none => pure lvl
| lvl => pure lvl
/-- instantiateExprMVars main function -/
partial def instantiateExprMVars [Monad m] [MonadMCtx m] [STWorld ω m] [MonadLiftT (ST ω) m] (e : Expr) : MonadCacheT ExprStructEq Expr m Expr :=
if !e.hasMVar then
pure e
else checkCache { val := e : ExprStructEq } fun _ => do match e with
| Expr.proj _ _ s _ => return e.updateProj! (← instantiateExprMVars s)
| Expr.forallE _ d b _ => return e.updateForallE! (← instantiateExprMVars d) (← instantiateExprMVars b)
| Expr.lam _ d b _ => return e.updateLambdaE! (← instantiateExprMVars d) (← instantiateExprMVars b)
| Expr.letE _ t v b _ => return e.updateLet! (← instantiateExprMVars t) (← instantiateExprMVars v) (← instantiateExprMVars b)
| Expr.const _ lvls _ => return e.updateConst! (← lvls.mapM instantiateLevelMVars)
| Expr.sort lvl _ => return e.updateSort! (← instantiateLevelMVars lvl)
| Expr.mdata _ b _ => return e.updateMData! (← instantiateExprMVars b)
| Expr.app .. => e.withApp fun f args => do
let instArgs (f : Expr) : MonadCacheT ExprStructEq Expr m Expr := do
let args ← args.mapM instantiateExprMVars
pure (mkAppN f args)
let instApp : MonadCacheT ExprStructEq Expr m Expr := do
let wasMVar := f.isMVar
let f ← instantiateExprMVars f
if wasMVar && f.isLambda then
/- Some of the arguments in args are irrelevant after we beta reduce. -/
instantiateExprMVars (f.betaRev args.reverse)
else
instArgs f
match f with
| Expr.mvar mvarId _ =>
let mctx ← getMCtx
match mctx.getDelayedAssignment? mvarId with
| none => instApp
| some { fvars := fvars, val := val, .. } =>
/-
Apply "delayed substitution" (i.e., delayed assignment + application).
That is, `f` is some metavariable `?m`, that is delayed assigned to `val`.
If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain
metavariables, we replace the free variables `fvars` in `newVal` with the first
`fvars.size` elements of `args`. -/
if fvars.size > args.size then
/- We don't have sufficient arguments for instantiating the free variables `fvars`.
This can only happy if a tactic or elaboration function is not implemented correctly.
We decided to not use `panic!` here and report it as an error in the frontend
when we are checking for unassigned metavariables in an elaborated term. -/
instArgs f
else
let newVal ← instantiateExprMVars val
if newVal.hasExprMVar then
instArgs f
else do
let args ← args.mapM instantiateExprMVars
/-
Example: suppose we have
`?m t1 t2 t3`
That is, `f := ?m` and `args := #[t1, t2, t3]`
Morever, `?m` is delayed assigned
`?m #[x, y] := f x y`
where, `fvars := #[x, y]` and `newVal := f x y`.
After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`.
After `instantiaterRevRange 0 2 args`, we have `f t1 t2`.
After `mkAppRange 2 3`, we have `f t1 t2 t3` -/
let newVal := newVal.abstract fvars
let result := newVal.instantiateRevRange 0 fvars.size args
let result := mkAppRange result fvars.size args.size args
pure result
| _ => instApp
| e@(Expr.mvar mvarId _) => checkCache { val := e : ExprStructEq } fun _ => do
let mctx ← getMCtx
match mctx.getExprAssignment? mvarId with
| some newE => do
let newE' ← instantiateExprMVars newE
modifyMCtx fun mctx => mctx.assignExpr mvarId newE'
pure newE'
| none => pure e
| e => pure e
instance : MonadMCtx (StateRefT MetavarContext (ST ω)) where
getMCtx := get
modifyMCtx := modify
def instantiateMVars (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext :=
if !e.hasMVar then
(e, mctx)
else
let instantiate {ω} (e : Expr) : (MonadCacheT ExprStructEq Expr $ StateRefT MetavarContext $ ST ω) Expr :=
instantiateExprMVars e
runST fun _ => instantiate e |>.run |>.run mctx
def instantiateLCtxMVars (mctx : MetavarContext) (lctx : LocalContext) : LocalContext × MetavarContext :=
lctx.foldl (init := ({}, mctx)) fun (lctx, mctx) ldecl =>
match ldecl with
| LocalDecl.cdecl _ fvarId userName type bi =>
let (type, mctx) := mctx.instantiateMVars type
(lctx.mkLocalDecl fvarId userName type bi, mctx)
| LocalDecl.ldecl _ fvarId userName type value nonDep =>
let (type, mctx) := mctx.instantiateMVars type
let (value, mctx) := mctx.instantiateMVars value
(lctx.mkLetDecl fvarId userName type value nonDep, mctx)
def instantiateMVarDeclMVars (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext :=
let mvarDecl := mctx.getDecl mvarId
let (lctx, mctx) := mctx.instantiateLCtxMVars mvarDecl.lctx
let (type, mctx) := mctx.instantiateMVars mvarDecl.type
{ mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx := lctx, type := type } }
namespace DependsOn
private abbrev M := StateM ExprSet
private def shouldVisit (e : Expr) : M Bool := do
if !e.hasMVar && !e.hasFVar then
return false
else if (← get).contains e then
return false
else
modify fun s => s.insert e
return true
@[specialize] private partial def dep (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool :=
let rec
visit (e : Expr) : M Bool := do
if !(← shouldVisit e) then
pure false
else
visitMain e,
visitMain : Expr → M Bool
| Expr.proj _ _ s _ => visit s
| Expr.forallE _ d b _ => visit d <||> visit b
| Expr.lam _ d b _ => visit d <||> visit b
| Expr.letE _ t v b _ => visit t <||> visit v <||> visit b
| Expr.mdata _ b _ => visit b
| Expr.app f a _ => visit a <||> if f.isApp then visitMain f else visit f
| Expr.mvar mvarId _ =>
match mctx.getExprAssignment? mvarId with
| some a => visit a
| none =>
let lctx := (mctx.getDecl mvarId).lctx
return lctx.any fun decl => p decl.fvarId
| Expr.fvar fvarId _ => return p fvarId
| e => pure false
visit e
@[inline] partial def main (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool :=
if !e.hasFVar && !e.hasMVar then pure false else dep mctx p e
end DependsOn
/--
Return `true` iff `e` depends on a free variable `x` s.t. `p x` is `true`.
For each metavariable `?m` occurring in `x`
1- If `?m := t`, then we visit `t` looking for `x`
2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`.
This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/
@[inline] def findExprDependsOn (mctx : MetavarContext) (e : Expr) (p : FVarId → Bool) : Bool :=
DependsOn.main mctx p e |>.run' {}
/--
Similar to `findExprDependsOn`, but checks the expressions in the given local declaration
depends on a free variable `x` s.t. `p x` is `true`. -/
@[inline] def findLocalDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (p : FVarId → Bool) : Bool :=
match localDecl with
| LocalDecl.cdecl (type := t) .. => findExprDependsOn mctx t p
| LocalDecl.ldecl (type := t) (value := v) .. => (DependsOn.main mctx p t <||> DependsOn.main mctx p v).run' {}
def exprDependsOn (mctx : MetavarContext) (e : Expr) (fvarId : FVarId) : Bool :=
findExprDependsOn mctx e fun fvarId' => fvarId == fvarId'
def localDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (fvarId : FVarId) : Bool :=
findLocalDeclDependsOn mctx localDecl fun fvarId' => fvarId == fvarId'
namespace MkBinding
inductive Exception where
| revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (decl : LocalDecl)
instance : ToString Exception where
toString
| Exception.revertFailure _ lctx toRevert decl =>
"failed to revert "
++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'"))
++ ", '" ++ toString decl.userName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator"
++ " (possible solution: use tactic 'clear' to remove '" ++ toString decl.userName ++ "' from local context)"
/--
`MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`.
We use a single state object for convenience.
We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/
structure State where
mctx : MetavarContext
ngen : NameGenerator
cache : HashMap ExprStructEq Expr := {}
abbrev MCore := EStateM Exception State
abbrev M := ReaderT Bool (EStateM Exception State)
def preserveOrder : M Bool := read
instance : MonadHashMapCacheAdapter ExprStructEq Expr M where
getCache := do let s ← get; pure s.cache
modifyCache := fun f => modify fun s => { s with cache := f s.cache }
/-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/
private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl := do
let mut d : LocalDecl := lctx.getFVar! xs[0]
for i in [1:xs.size] do
let curr := lctx.getFVar! xs[i]
if curr.index < d.index then
d := curr
return d
/--
Given `toRevert` an array of free variables s.t. `lctx` contains their declarations,
return a new array of free variables that contains `toRevert` and all free variables
in `lctx` that may depend on `toRevert`.
Remark: the result is sorted by `LocalDecl` indices.
Remark: We used to throw an `Exception.revertFailure` exception when an auxiliary declaration
had to be reversed. Recall that auxiliary declarations are created when compiling (mutually)
recursive definitions. The `revertFailure` due to auxiliary declaration dependency was originally
introduced in Lean3 to address issue https://github.com/leanprover/lean/issues/1258.
In Lean4, this solution is not satisfactory because all definitions/theorems are potentially
recursive. So, even an simple (incomplete) definition such as
```
variables {α : Type} in
def f (a : α) : List α :=
_
```
would trigger the `Exception.revertFailure` exception. In the definition above,
the elaborator creates the auxiliary definition `f : {α : Type} → List α`.
The `_` is elaborated as a new fresh variable `?m` that contains `α : Type`, `a : α`, and `f : α → List α` in its context,
When we try to create the lambda `fun {α : Type} (a : α) => ?m`, we first need to create
an auxiliary `?n` which do not contain `α` and `a` in its context. That is,
we create the metavariable `?n : {α : Type} → (a : α) → (f : α → List α) → List α`,
add the delayed assignment `?n #[α, a, f] := ?m α a f`, and create the lambda
`fun {α : Type} (a : α) => ?n α a f`.
See `elimMVarDeps` for more information.
If we kept using the Lean3 approach, we would get the `Exception.revertFailure` exception because we are
reverting the auxiliary definition `f`.
Note that https://github.com/leanprover/lean/issues/1258 is not an issue in Lean4 because
we have changed how we compile recursive definitions.
-/
def collectDeps (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (preserveOrder : Bool) : Except Exception (Array Expr) := do
if toRevert.size == 0 then
pure toRevert
else
if preserveOrder then
-- Make sure none of `toRevert` is an AuxDecl
-- Make sure toRevert[j] does not depend on toRevert[i] for j > i
toRevert.size.forM fun i => do
let fvar := toRevert[i]
let decl := lctx.getFVar! fvar
i.forM fun j => do
let prevFVar := toRevert[j]
let prevDecl := lctx.getFVar! prevFVar
if localDeclDependsOn mctx prevDecl fvar.fvarId! then
throw (Exception.revertFailure mctx lctx toRevert prevDecl)
let newToRevert := if preserveOrder then toRevert else Array.mkEmpty toRevert.size
let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert
let initSize := newToRevert.size
lctx.foldlM (init := newToRevert) (start := firstDeclToVisit.index) fun (newToRevert : Array Expr) decl =>
if initSize.any fun i => decl.fvarId == (newToRevert.get! i).fvarId! then pure newToRevert
else if toRevert.any fun x => decl.fvarId == x.fvarId! then
pure (newToRevert.push decl.toExpr)
else if findLocalDeclDependsOn mctx decl (fun fvarId => newToRevert.any fun x => x.fvarId! == fvarId) then
pure (newToRevert.push decl.toExpr)
else
pure newToRevert
/-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`.
We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/
def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext :=
toRevert.foldr (init := lctx) fun x lctx =>
lctx.erase x.fvarId!
@[inline] private def getMCtx : M MetavarContext :=
return (← get).mctx
/-- Return free variables in `xs` that are in the local context `lctx` -/
private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr :=
xs.foldl (init := #[]) fun scope x =>
if lctx.contains x.fvarId! then
scope.push x
else
scope
/-- Execute `x` with an empty cache, and then restore the original cache. -/
@[inline] private def withFreshCache (x : M α) : M α := do
let cache ← modifyGet fun s => (s.cache, { s with cache := {} })
let a ← x
modify fun s => { s with cache := cache }
pure a
/--
Create an application `mvar ys` where `ys` are the free variables.
See "Gruesome details" in the beginning of the file for understanding
how let-decl free variables are handled. -/
private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr :=
xs.foldl (init := mvar) fun e x =>
match kind with
| MetavarKind.syntheticOpaque => mkApp e x
| _ => if (lctx.getFVar! x).isLet then e else mkApp e x
/-- Return true iff some `e` in `es` depends on `fvarId` -/
private def anyDependsOn (mctx : MetavarContext) (es : Array Expr) (fvarId : FVarId) : Bool :=
es.any fun e => exprDependsOn mctx e fvarId
mutual
private partial def visit (xs : Array Expr) (e : Expr) : M Expr :=
if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => elim xs e
private partial def elim (xs : Array Expr) (e : Expr) : M Expr :=
match e with
| Expr.proj _ _ s _ => return e.updateProj! (← visit xs s)
| Expr.forallE _ d b _ => return e.updateForallE! (← visit xs d) (← visit xs b)
| Expr.lam _ d b _ => return e.updateLambdaE! (← visit xs d) (← visit xs b)
| Expr.letE _ t v b _ => return e.updateLet! (← visit xs t) (← visit xs v) (← visit xs b)
| Expr.mdata _ b _ => return e.updateMData! (← visit xs b)
| Expr.app _ _ _ => e.withApp fun f args => elimApp xs f args
| Expr.mvar mvarId _ => elimApp xs e #[]
| e => return e
private partial def mkAuxMVarType (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do
let e ← abstractRangeAux xs xs.size e
xs.size.foldRevM (init := e) fun i e =>
let x := xs[i]
match lctx.getFVar! x with
| LocalDecl.cdecl _ _ n type bi => do
let type := type.headBeta
let type ← abstractRangeAux xs i type
pure <| Lean.mkForall n bi type e
| LocalDecl.ldecl _ _ n type value nonDep => do
let type := type.headBeta
let type ← abstractRangeAux xs i type
let value ← abstractRangeAux xs i value
let e := mkLet n type value e nonDep
match kind with
| MetavarKind.syntheticOpaque =>
-- See "Gruesome details" section in the beginning of the file
let e := e.liftLooseBVars 0 1
pure <| mkForall n BinderInfo.default type e
| _ => pure e
where
abstractRangeAux (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do
let e ← elim xs e
pure (e.abstractRange i xs)
private partial def elimMVar (xs : Array Expr) (mvarId : MVarId) (args : Array Expr) : M (Expr × Array Expr) := do
let mctx ← getMCtx
let mvarDecl := mctx.getDecl mvarId
let mvarLCtx := mvarDecl.lctx
let toRevert := getInScope mvarLCtx xs
if toRevert.size == 0 then
let args ← args.mapM (visit xs)
return (mkAppN (mkMVar mvarId) args, #[])
else
let newMVarKind := if !mctx.isExprAssignable mvarId then MetavarKind.syntheticOpaque else mvarDecl.kind
/- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := val`,
then `nestedFVars` is `#[x_1, ..., x_n]`.
In this case, we produce a new `syntheticOpaque` metavariable `?n` and a delayed assignment
```
?n #[y_1, ..., y_m, x_1, ... x_n] := ?m x_1 ... x_n
```
where `#[y_1, ..., y_m]` is `toRevert` after `collectDeps`.
Remark: `newMVarKind != MetavarKind.syntheticOpaque ==> nestedFVars == #[]`
-/
let rec cont (nestedFVars : Array Expr) (nestedLCtx : LocalContext) : M (Expr × Array Expr) := do
let args ← args.mapM (visit xs)
let preserve ← preserveOrder
match collectDeps mctx mvarLCtx toRevert preserve with
| Except.error ex => throw ex
| Except.ok toRevert =>
let newMVarLCtx := reduceLocalContext mvarLCtx toRevert
let newLocalInsts := mvarDecl.localInstances.filter fun inst => toRevert.all fun x => inst.fvar != x
-- Remark: we must reset the before processing `mkAuxMVarType` because `toRevert` may not be equal to `xs`
let newMVarType ← withFreshCache do mkAuxMVarType mvarLCtx toRevert newMVarKind mvarDecl.type
let newMVarId := (← get).ngen.curr
let newMVar := mkMVar newMVarId
let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind
let numScopeArgs := mvarDecl.numScopeArgs + result.getAppNumArgs
modify fun s => { s with
mctx := s.mctx.addExprMVarDecl newMVarId Name.anonymous newMVarLCtx newLocalInsts newMVarType newMVarKind numScopeArgs,
ngen := s.ngen.next
}
match newMVarKind with
| MetavarKind.syntheticOpaque =>
modify fun s => { s with mctx := assignDelayed s.mctx newMVarId nestedLCtx (toRevert ++ nestedFVars) (mkAppN (mkMVar mvarId) nestedFVars) }
| _ =>
modify fun s => { s with mctx := assignExpr s.mctx mvarId result }
return (mkAppN result args, toRevert)
if !mvarDecl.kind.isSyntheticOpaque then
cont #[] mvarLCtx
else match mctx.getDelayedAssignment? mvarId with
| none => cont #[] mvarLCtx
| some { fvars := fvars, lctx := nestedLCtx, .. } => cont fvars nestedLCtx -- Remark: nestedLCtx is bigger than mvarLCtx
private partial def elimApp (xs : Array Expr) (f : Expr) (args : Array Expr) : M Expr := do
match f with
| Expr.mvar mvarId _ =>
match (← getMCtx).getExprAssignment? mvarId with
| some newF =>
if newF.isLambda then
let args ← args.mapM (visit xs)
elim xs <| newF.betaRev args.reverse
else
elimApp xs newF args
| none => return (← elimMVar xs mvarId args).1
| _ =>
return mkAppN (← visit xs f) (← args.mapM (visit xs))
end
partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr :=
if !e.hasMVar then
pure e
else
withFreshCache do
elim xs e
partial def revert (xs : Array Expr) (mvarId : MVarId) : M (Expr × Array Expr) :=
withFreshCache do
elimMVar xs mvarId #[]
/--
Similar to `Expr.abstractRange`, but handles metavariables correctly.
It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not
contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`.
`elimMVarDeps` is defined later in this file. -/
@[inline] private def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do
let e ← elimMVarDeps xs e
pure (e.abstractRange i xs)
/--
Similar to `LocalContext.mkBinding`, but handles metavariables correctly.
If `usedOnly == false` then `forall` and `lambda` expressions are created only for used variables.
If `usedLetOnly == false` then `let` expressions are created only for used (let-) variables. -/
@[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool) (usedLetOnly : Bool) : M (Expr × Nat) := do
let e ← abstractRange xs xs.size e
xs.size.foldRevM
(fun i (p : Expr × Nat) => do
let (e, num) := p;
let x := xs[i]
match lctx.getFVar! x with
| LocalDecl.cdecl _ _ n type bi =>
if !usedOnly || e.hasLooseBVar 0 then
let type := type.headBeta;
let type ← abstractRange xs i type
if isLambda then
pure (Lean.mkLambda n bi type e, num + 1)
else
pure (Lean.mkForall n bi type e, num + 1)
else
pure (e.lowerLooseBVars 1 1, num)
| LocalDecl.ldecl _ _ n type value nonDep =>
if !usedLetOnly || e.hasLooseBVar 0 then
let type ← abstractRange xs i type
let value ← abstractRange xs i value
pure (mkLet n type value e nonDep, num + 1)
else
pure (e.lowerLooseBVars 1 1, num))
(e, 0)
end MkBinding
abbrev MkBindingM := ReaderT LocalContext MkBinding.MCore
def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr := fun _ =>
MkBinding.elimMVarDeps xs e preserveOrder
def revert (xs : Array Expr) (mvarId : MVarId) (preserveOrder : Bool) : MkBindingM (Expr × Array Expr) := fun _ =>
MkBinding.revert xs mvarId preserveOrder
def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM (Expr × Nat) := fun lctx =>
MkBinding.mkBinding isLambda lctx xs e usedOnly usedLetOnly false
@[inline] def mkLambda (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM Expr := do
let (e, _) ← mkBinding (isLambda := true) xs e usedOnly usedLetOnly
pure e
@[inline] def mkForall (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM Expr := do
let (e, _) ← mkBinding (isLambda := false) xs e usedOnly usedLetOnly
pure e
/--
`isWellFormed mctx lctx e` return true if
- All locals in `e` are declared in `lctx`
- All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/
partial def isWellFormed (mctx : MetavarContext) (lctx : LocalContext) : Expr → Bool
| Expr.mdata _ e _ => isWellFormed mctx lctx e
| Expr.proj _ _ e _ => isWellFormed mctx lctx e
| e@(Expr.app f a _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx f && isWellFormed mctx lctx a)
| e@(Expr.lam _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b)
| e@(Expr.forallE _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b)
| e@(Expr.letE _ t v b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx t && isWellFormed mctx lctx v && isWellFormed mctx lctx b)
| Expr.const .. => true
| Expr.bvar .. => true
| Expr.sort .. => true
| Expr.lit .. => true
| Expr.mvar mvarId _ =>
let mvarDecl := mctx.getDecl mvarId;
if mvarDecl.lctx.isSubPrefixOf lctx then true
else match mctx.getExprAssignment? mvarId with
| none => false
| some v => isWellFormed mctx lctx v
| Expr.fvar fvarId _ => lctx.contains fvarId
namespace LevelMVarToParam
structure Context where
paramNamePrefix : Name
alreadyUsedPred : Name → Bool
structure State where
mctx : MetavarContext
paramNames : Array Name := #[]
nextParamIdx : Nat
cache : HashMap ExprStructEq Expr := {}
abbrev M := ReaderT Context $ StateM State
instance : MonadCache ExprStructEq Expr M where
findCached? e := return (← get).cache.find? e
cache e v := modify fun s => { s with cache := s.cache.insert e v }
partial def mkParamName : M Name := do
let ctx ← read
let s ← get
let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx
if ctx.alreadyUsedPred newParamName then
modify fun s => { s with nextParamIdx := s.nextParamIdx + 1 }
mkParamName
else do
modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName }
pure newParamName
partial def visitLevel (u : Level) : M Level := do
match u with
| Level.succ v _ => return u.updateSucc! (← visitLevel v)
| Level.max v₁ v₂ _ => return u.updateMax! (← visitLevel v₁) (← visitLevel v₂)
| Level.imax v₁ v₂ _ => return u.updateIMax! (← visitLevel v₁) (← visitLevel v₂)
| Level.zero _ => pure u
| Level.param .. => pure u
| Level.mvar mvarId _ =>
let s ← get
match s.mctx.getLevelAssignment? mvarId with
| some v => visitLevel v
| none =>
let p ← mkParamName
let p := mkLevelParam p
modify fun s => { s with mctx := s.mctx.assignLevel mvarId p }
pure p
partial def main (e : Expr) : M Expr :=
if !e.hasMVar then
return e
else
checkCache { val := e : ExprStructEq } fun _ => do
match e with
| Expr.proj _ _ s _ => return e.updateProj! (← main s)
| Expr.forallE _ d b _ => return e.updateForallE! (← main d) (← main b)
| Expr.lam _ d b _ => return e.updateLambdaE! (← main d) (← main b)
| Expr.letE _ t v b _ => return e.updateLet! (← main t) (← main v) (← main b)
| Expr.app .. => e.withApp fun f args => visitApp f args
| Expr.mdata _ b _ => return e.updateMData! (← main b)
| Expr.const _ us _ => return e.updateConst! (← us.mapM visitLevel)
| Expr.sort u _ => return e.updateSort! (← visitLevel u)
| Expr.mvar .. => visitApp e #[]
| e => return e
where
visitApp (f : Expr) (args : Array Expr) : M Expr := do
match f with
| Expr.mvar mvarId .. =>
match (← get).mctx.getExprAssignment? mvarId with
| some v => return (← visitApp v args).headBeta
| none => return mkAppN f (← args.mapM main)
| _ => return mkAppN (← main f) (← args.mapM main)
end LevelMVarToParam
structure UnivMVarParamResult where
mctx : MetavarContext
newParamNames : Array Name
nextParamIdx : Nat
expr : Expr
def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1)
: UnivMVarParamResult :=
let (e, s) := LevelMVarToParam.main e { paramNamePrefix := paramNamePrefix, alreadyUsedPred := alreadyUsedPred } { mctx := mctx, nextParamIdx := nextParamIdx }
{ mctx := s.mctx,
newParamNames := s.paramNames,
nextParamIdx := s.nextParamIdx,
expr := e }
def getExprAssignmentDomain (mctx : MetavarContext) : Array MVarId :=
mctx.eAssignment.foldl (init := #[]) fun a mvarId _ => Array.push a mvarId
end MetavarContext
end Lean
|
cb6a1c39fb15bf72a65378e7e7534e65095fa0b9 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/ring_exp.lean | 8ee73b46356a9cd8a2943560afa574ee239ffacb | [
"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 | 57,386 | lean | /-
Copyright (c) 2019 Tim Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baanen
-/
import tactic.norm_num
import control.traversable.basic
/-!
# `ring_exp` tactic
A tactic for solving equations in commutative (semi)rings,
where the exponents can also contain variables.
More precisely, expressions of the following form are supported:
- constants (non-negative integers)
- variables
- coefficients (any rational number, embedded into the (semi)ring)
- addition of expressions
- multiplication of expressions
- exponentiation of expressions (the exponent must have type `ℕ`)
- subtraction and negation of expressions (if the base is a full ring)
The motivating example is proving `2 * 2^n * b = b * 2^(n+1)`,
something that the `ring` tactic cannot do, but `ring_exp` can.
## Implementation notes
The basic approach to prove equalities is to normalise both sides and check for equality.
The normalisation is guided by building a value in the type `ex` at the meta level,
together with a proof (at the base level) that the original value is equal to
the normalised version.
The normalised version and normalisation proofs are also stored in the `ex` type.
The outline of the file:
- Define an inductive family of types `ex`, parametrised over `ex_type`,
which can represent expressions with `+`, `*`, `^` and rational numerals.
The parametrisation over `ex_type` ensures that associativity and distributivity are applied,
by restricting which kinds of subexpressions appear as arguments to the various operators.
- Represent addition, multiplication and exponentiation in the `ex` type,
thus allowing us to map expressions to `ex` (the `eval` function drives this).
We apply associativity and distributivity of the operators here (helped by `ex_type`)
and commutativity as well (by sorting the subterms; unfortunately not helped by anything).
Any expression not of the above formats is treated as an atom (the same as a variable).
There are some details we glossed over which make the plan more complicated:
- The order on atoms is not initially obvious.
We construct a list containing them in order of initial appearance in the expression,
then use the index into the list as a key to order on.
- In the tactic, a normalized expression `ps : ex` lives in the meta-world,
but the normalization proofs live in the real world.
Thus, we cannot directly say `ps.orig = ps.pretty` anywhere,
but we have to carefully construct the proof when we compute `ps`.
This was a major source of bugs in development!
- For `pow`, the exponent must be a natural number, while the base can be any semiring `α`.
We swap out operations for the base ring `α` with those for the exponent ring `ℕ`
as soon as we deal with exponents.
This is accomplished by the `in_exponent` function and is relatively painless since
we work in a `reader` monad.
- The normalized form of an expression is the one that is useful for the tactic,
but not as nice to read. To remedy this, the user-facing normalization calls `ex.simp`.
## Caveats and future work
Subtraction cancels out identical terms, but division does not.
That is: `a - a = 0 := by ring_exp` solves the goal,
but `a / a := 1 by ring_exp` doesn't.
Note that `0 / 0` is generally defined to be `0`,
so division cancelling out is not true in general.
Multiplication of powers can be simplified a little bit further:
`2 ^ n * 2 ^ n = 4 ^ n := by ring_exp` could be implemented
in a similar way that `2 * a + 2 * a = 4 * a := by ring_exp` already works.
This feature wasn't needed yet, so it's not implemented yet.
## Tags
ring, semiring, exponent, power
-/
-- The base ring `α` will have a universe level `u`.
-- We do not introduce `α` as a variable yet,
-- in order to make it explicit or implicit as required.
universes u
namespace tactic.ring_exp
open nat
/--
The `atom` structure is used to represent atomic expressions:
those which `ring_exp` cannot parse any further.
For instance, `a + (a % b)` has `a` and `(a % b)` as atoms.
The `ring_exp_eq` tactic does not normalize the subexpressions in atoms,
but `ring_exp` does if `ring_exp_eq` was not sufficient.
Atoms in fact represent equivalence classes of expressions,
modulo definitional equality.
The field `index : ℕ` should be a unique number for each class,
while `value : expr` contains a representative of this class.
The function `resolve_atom` determines the appropriate atom
for a given expression.
-/
meta structure atom : Type := (value : expr) (index : ℕ)
namespace atom
/--
The `eq` operation on `atom`s works modulo definitional equality,
ignoring their `value`s.
The invariants on `atom` ensure indices are unique per value.
Thus, `eq` indicates equality as long as the `atom`s come from the same context.
-/
meta def eq (a b : atom) : bool := a.index = b.index
/--
We order `atom`s on the order of appearance in the main expression.
-/
meta def lt (a b : atom) : bool := a.index < b.index
meta instance : has_repr atom := ⟨λ x, "(atom " ++ repr x.2 ++ ")"⟩
end atom
section expression
/-!
### `expression` section
In this section, we define the `ex` type and its basic operations.
First, we introduce the supporting types `coeff`, `ex_type` and `ex_info`.
For understanding the code, it's easier to check out `ex` itself first,
then refer back to the supporting types.
The arithmetic operations on `ex` need additional definitions,
so they are defined in a later section.
-/
/--
Coefficients in the expression are stored in a wrapper structure,
allowing for easier modification of the data structures.
The modifications might be caching of the result of `expr.of_rat`,
or using a different meta representation of numerals.
-/
@[derive decidable_eq, derive inhabited]
structure coeff : Type := (value : ℚ)
/-- The values in `ex_type` are used as parameters to `ex` to control the expression's structure. -/
@[derive decidable_eq, derive inhabited]
inductive ex_type : Type
| base : ex_type
| sum : ex_type
| prod : ex_type
| exp : ex_type
open ex_type
/--
Each `ex` stores information for its normalization proof.
The `orig` expression is the expression that was passed to `eval`.
The `pretty` expression is the normalised form that the `ex` represents.
(I didn't call this something like `norm`, because there are already
too many things called `norm` in mathematics!)
The field `proof` contains an optional proof term of type `%%orig = %%pretty`.
The value `none` for the proof indicates that everything reduces to reflexivity.
(Which saves space in quite a lot of cases.)
-/
meta structure ex_info : Type :=
(orig : expr) (pretty : expr) (proof : option expr)
/--
The `ex` type is an abstract representation of an expression with `+`, `*` and `^`.
Those operators are mapped to the `sum`, `prod` and `exp` constructors respectively.
The `zero` constructor is the base case for `ex sum`, e.g. `1 + 2` is represented
by (something along the lines of) `sum 1 (sum 2 zero)`.
The `coeff` constructor is the base case for `ex prod`, and is used for numerals.
The code maintains the invariant that the coefficient is never `0`.
The `var` constructor is the base case for `ex exp`, and is used for atoms.
The `sum_b` constructor allows for addition in the base of an exponentiation;
it serves a similar purpose as the parentheses in `(a + b)^c`.
The code maintains the invariant that the argument to `sum_b` is not `zero`
or `sum _ zero`.
All of the constructors contain an `ex_info` field,
used to carry around (arguments to) proof terms.
While the `ex_type` parameter enforces some simplification invariants,
the following ones must be manually maintained at the risk of insufficient power:
- the argument to `coeff` must be nonzero (to ensure `0 = 0 * 1`)
- the argument to `sum_b` must be of the form `sum a (sum b bs)` (to ensure `(a + 0)^n = a^n`)
- normalisation proofs of subexpressions must be `refl ps.pretty`
- if we replace `sum` with `cons` and `zero` with `nil`, the resulting list is sorted
according to the `lt` relation defined further down; similarly for `prod` and `coeff`
(to ensure `a + b = b + a`).
The first two invariants could be encoded in a subtype of `ex`,
but aren't (yet) to spare some implementation burden.
The other invariants cannot be encoded because we need the `tactic` monad to check them.
(For example, the correct equality check of `expr` is `is_def_eq : expr → expr → tactic unit`.)
-/
meta inductive ex : ex_type → Type
| zero (info : ex_info) : ex sum
| sum (info : ex_info) : ex prod → ex sum → ex sum
| coeff (info : ex_info) : coeff → ex prod
| prod (info : ex_info) : ex exp → ex prod → ex prod
| var (info : ex_info) : atom → ex base
| sum_b (info : ex_info) : ex sum → ex base
| exp (info : ex_info) : ex base → ex prod → ex exp
/--
Return the proof information associated to the `ex`.
-/
meta def ex.info : Π {et : ex_type} (ps : ex et), ex_info
| sum (ex.zero i) := i
| sum (ex.sum i _ _) := i
| prod (ex.coeff i _) := i
| prod (ex.prod i _ _) := i
| base (ex.var i _) := i
| base (ex.sum_b i _) := i
| exp (ex.exp i _ _) := i
/--
Return the original, non-normalized version of this `ex`.
Note that arguments to another `ex` are always "pre-normalized":
their `orig` and `pretty` are equal, and their `proof` is reflexivity.
-/
meta def ex.orig {et : ex_type} (ps : ex et) : expr := ps.info.orig
/--
Return the normalized version of this `ex`.
-/
meta def ex.pretty {et : ex_type} (ps : ex et) : expr := ps.info.pretty
/--
Return the normalisation proof of the given expression.
If the proof is `refl`, we give `none` instead,
which helps to control the size of proof terms.
To get an actual term, use `ex.proof_term`,
or use `mk_proof` with the correct set of arguments.
-/
meta def ex.proof {et : ex_type} (ps : ex et) : option expr := ps.info.proof
/--
Update the `orig` and `proof` fields of the `ex_info`.
Intended for use in `ex.set_info`.
-/
meta def ex_info.set (i : ex_info) (o : option expr) (pf : option expr) : ex_info :=
{orig := o.get_or_else i.pretty, proof := pf, .. i}
/--
Update the `ex_info` of the given expression.
We use this to combine intermediate normalisation proofs.
Since `pretty` only depends on the subexpressions,
which do not change, we do not set `pretty`.
-/
meta def ex.set_info : Π {et : ex_type} (ps : ex et), option expr → option expr → ex et
| sum (ex.zero i) o pf := ex.zero (i.set o pf)
| sum (ex.sum i p ps) o pf := ex.sum (i.set o pf) p ps
| prod (ex.coeff i x) o pf := ex.coeff (i.set o pf) x
| prod (ex.prod i p ps) o pf := ex.prod (i.set o pf) p ps
| base (ex.var i x) o pf := ex.var (i.set o pf) x
| base (ex.sum_b i ps) o pf := ex.sum_b (i.set o pf) ps
| exp (ex.exp i p ps) o pf := ex.exp (i.set o pf) p ps
instance coeff_has_repr : has_repr coeff := ⟨λ x, repr x.1⟩
/-- Convert an `ex` to a `string`. -/
meta def ex.repr : Π {et : ex_type}, ex et → string
| sum (ex.zero _) := "0"
| sum (ex.sum _ p ps) := ex.repr p ++ " + " ++ ex.repr ps
| prod (ex.coeff _ x) := repr x
| prod (ex.prod _ p ps) := ex.repr p ++ " * " ++ ex.repr ps
| base (ex.var _ x) := repr x
| base (ex.sum_b _ ps) := "(" ++ ex.repr ps ++ ")"
| exp (ex.exp _ p ps) := ex.repr p ++ " ^ " ++ ex.repr ps
meta instance {et : ex_type} : has_repr (ex et) := ⟨ex.repr⟩
/--
Equality test for expressions.
Since equivalence of `atom`s is not the same as equality,
we cannot make a true `(=)` operator for `ex` either.
-/
meta def ex.eq : Π {et : ex_type}, ex et → ex et → bool
| sum (ex.zero _) (ex.zero _) := tt
| sum (ex.zero _) (ex.sum _ _ _) := ff
| sum (ex.sum _ _ _) (ex.zero _) := ff
| sum (ex.sum _ p ps) (ex.sum _ q qs) := p.eq q && ps.eq qs
| prod (ex.coeff _ x) (ex.coeff _ y) := x = y
| prod (ex.coeff _ _) (ex.prod _ _ _) := ff
| prod (ex.prod _ _ _) (ex.coeff _ _) := ff
| prod (ex.prod _ p ps) (ex.prod _ q qs) := p.eq q && ps.eq qs
| base (ex.var _ x) (ex.var _ y) := x.eq y
| base (ex.var _ _) (ex.sum_b _ _) := ff
| base (ex.sum_b _ _) (ex.var _ _) := ff
| base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.eq qs
| exp (ex.exp _ p ps) (ex.exp _ q qs) := p.eq q && ps.eq qs
/--
The ordering on expressions.
As for `ex.eq`, this is a linear order only in one context.
-/
meta def ex.lt : Π {et : ex_type}, ex et → ex et → bool
| sum _ (ex.zero _) := ff
| sum (ex.zero _) _ := tt
| sum (ex.sum _ p ps) (ex.sum _ q qs) := p.lt q || (p.eq q && ps.lt qs)
| prod (ex.coeff _ x) (ex.coeff _ y) := x.1 < y.1
| prod (ex.coeff _ _) _ := tt
| prod _ (ex.coeff _ _) := ff
| prod (ex.prod _ p ps) (ex.prod _ q qs) := p.lt q || (p.eq q && ps.lt qs)
| base (ex.var _ x) (ex.var _ y) := x.lt y
| base (ex.var _ _) (ex.sum_b _ _) := tt
| base (ex.sum_b _ _) (ex.var _ _) := ff
| base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.lt qs
| exp (ex.exp _ p ps) (ex.exp _ q qs) := p.lt q || (p.eq q && ps.lt qs)
end expression
section operations
/-!
### `operations` section
This section defines the operations (on `ex`) that use tactics.
They live in the `ring_exp_m` monad,
which adds a cache and a list of encountered atoms to the `tactic` monad.
Throughout this section, we will be constructing proof terms.
The lemmas used in the construction are all defined over a commutative semiring α.
-/
variables {α : Type u} [comm_semiring α]
open tactic
open ex_type
/--
Stores the information needed in the `eval` function and its dependencies,
so they can (re)construct expressions.
The `eval_info` structure stores this information for one type,
and the `context` combines the two types, one for bases and one for exponents.
-/
meta structure eval_info :=
(α : expr) (univ : level)
-- Cache the instances for optimization and consistency
(csr_instance : expr) (ha_instance : expr) (hm_instance : expr) (hp_instance : expr)
-- Optional instances (only required for (-) and (/) respectively)
(ring_instance : option expr) (dr_instance : option expr)
-- Cache common constants.
(zero : expr) (one : expr)
/--
The `context` contains the full set of information needed for the `eval` function.
This structure has two copies of `eval_info`:
one is for the base (typically some semiring `α`) and another for the exponent (always `ℕ`).
When evaluating an exponent, we put `info_e` in `info_b`.
-/
meta structure context :=
(info_b : eval_info) (info_e : eval_info) (transp : transparency)
/--
The `ring_exp_m` monad is used instead of `tactic` to store the context.
-/
@[derive [monad, alternative]]
meta def ring_exp_m (α : Type) : Type := reader_t context (state_t (list atom) tactic) α
/--
Access the instance cache.
-/
meta def get_context : ring_exp_m context := reader_t.read
/--
Lift an operation in the `tactic` monad to the `ring_exp_m` monad.
This operation will not access the cache.
-/
meta def lift {α} (m : tactic α) : ring_exp_m α := reader_t.lift (state_t.lift m)
/--
Change the context of the given computation,
so that expressions are evaluated in the exponent ring,
instead of the base ring.
-/
meta def in_exponent {α} (mx : ring_exp_m α) : ring_exp_m α := do
ctx ← get_context,
reader_t.lift $ mx.run ⟨ctx.info_e, ctx.info_e, ctx.transp⟩
/--
Specialized version of `mk_app` where the first two arguments are `{α}` `[some_class α]`.
Should be faster because it can use the cached instances.
-/
meta def mk_app_class (f : name) (inst : expr) (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
pure $ (@expr.const tt f [ctx.info_b.univ] ctx.info_b.α inst).mk_app args
/--
Specialized version of `mk_app` where the first two arguments are `{α}` `[comm_semiring α]`.
Should be faster because it can use the cached instances.
-/
meta def mk_app_csr (f : name) (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class f (ctx.info_b.csr_instance) args
/--
Specialized version of `mk_app ``has_add.add`.
Should be faster because it can use the cached instances.
-/
meta def mk_add (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class ``has_add.add ctx.info_b.ha_instance args
/--
Specialized version of `mk_app ``has_mul.mul`.
Should be faster because it can use the cached instances.
-/
meta def mk_mul (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class ``has_mul.mul ctx.info_b.hm_instance args
/--
Specialized version of `mk_app ``has_pow.pow`.
Should be faster because it can use the cached instances.
-/
meta def mk_pow (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
pure $ (@expr.const tt ``has_pow.pow
[ctx.info_b.univ, ctx.info_e.univ]
ctx.info_b.α ctx.info_e.α
ctx.info_b.hp_instance).mk_app args
/-- Construct a normalization proof term or return the cached one. -/
meta def ex_info.proof_term (ps : ex_info) : ring_exp_m expr :=
match ps.proof with
| none := lift $ tactic.mk_eq_refl ps.pretty
| (some p) := pure p
end
/-- Construct a normalization proof term or return the cached one. -/
meta def ex.proof_term {et : ex_type} (ps : ex et) : ring_exp_m expr := ps.info.proof_term
/--
If all `ex_info` have trivial proofs, return a trivial proof.
Otherwise, construct all proof terms.
Useful in applications where trivial proofs combine to another trivial proof,
most importantly to pass to `mk_proof_or_refl`.
-/
meta def none_or_proof_term : list ex_info → ring_exp_m (option (list expr))
| [] := pure none
| (x :: xs) := do
xs_pfs ← none_or_proof_term xs,
match (x.proof, xs_pfs) with
| (none, none) := pure none
| (some x_pf, none) := do
xs_pfs ← traverse ex_info.proof_term xs,
pure (some (x_pf :: xs_pfs))
| (_, some xs_pfs) := do
x_pf ← x.proof_term,
pure (some (x_pf :: xs_pfs))
end
/--
Use the proof terms as arguments to the given lemma.
If the lemma could reduce to reflexivity, consider using `mk_proof_or_refl.`
-/
meta def mk_proof (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do
hs' ← traverse ex_info.proof_term hs,
mk_app_csr lem (args ++ hs')
/--
Use the proof terms as arguments to the given lemma.
Often, we construct a proof term using congruence where reflexivity suffices.
To solve this, the following function tries to get away with reflexivity.
-/
meta def mk_proof_or_refl (term : expr) (lem : name) (args : list expr) (hs : list ex_info) :
ring_exp_m expr := do
hs_full ← none_or_proof_term hs,
match hs_full with
| none := lift $ mk_eq_refl term
| (some hs') := mk_app_csr lem (args ++ hs')
end
/-- A shortcut for adding the original terms of two expressions. -/
meta def add_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_add [ps.orig, qs.orig]
/-- A shortcut for multiplying the original terms of two expressions. -/
meta def mul_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_mul [ps.orig, qs.orig]
/-- A shortcut for exponentiating the original terms of two expressions. -/
meta def pow_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_pow [ps.orig, qs.orig]
/-- Congruence lemma for constructing `ex.sum`. -/
lemma sum_congr {p p' ps ps' : α} : p = p' → ps = ps' → p + ps = p' + ps' := by cc
/-- Congruence lemma for constructing `ex.prod`. -/
lemma prod_congr {p p' ps ps' : α} : p = p' → ps = ps' → p * ps = p' * ps' := by cc
/-- Congruence lemma for constructing `ex.exp`. -/
lemma exp_congr {p p' : α} {ps ps' : ℕ} : p = p' → ps = ps' → p ^ ps = p' ^ ps' := by cc
/-- Constructs `ex.zero` with the correct arguments. -/
meta def ex_zero : ring_exp_m (ex sum) := do
ctx ← get_context,
pure $ ex.zero ⟨ctx.info_b.zero, ctx.info_b.zero, none⟩
/-- Constructs `ex.sum` with the correct arguments. -/
meta def ex_sum (p : ex prod) (ps : ex sum) : ring_exp_m (ex sum) := do
pps_o ← add_orig p ps,
pps_p ← mk_add [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``sum_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.sum ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
/--
Constructs `ex.coeff` with the correct arguments.
There are more efficient constructors for specific numerals:
if `x = 0`, you should use `ex_zero`; if `x = 1`, use `ex_one`.
-/
meta def ex_coeff (x : rat) : ring_exp_m (ex prod) := do
ctx ← get_context,
x_p ← lift $ expr.of_rat ctx.info_b.α x,
pure (ex.coeff ⟨x_p, x_p, none⟩ ⟨x⟩)
/--
Constructs `ex.coeff 1` with the correct arguments.
This is a special case for optimization purposes.
-/
meta def ex_one : ring_exp_m (ex prod) := do
ctx ← get_context,
pure $ ex.coeff ⟨ctx.info_b.one, ctx.info_b.one, none⟩ ⟨1⟩
/-- Constructs `ex.prod` with the correct arguments. -/
meta def ex_prod (p : ex exp) (ps : ex prod) : ring_exp_m (ex prod) := do
pps_o ← mul_orig p ps,
pps_p ← mk_mul [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``prod_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.prod ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
/-- Constructs `ex.var` with the correct arguments. -/
meta def ex_var (p : atom) : ring_exp_m (ex base) := pure (ex.var ⟨p.1, p.1, none⟩ p)
/-- Constructs `ex.sum_b` with the correct arguments. -/
meta def ex_sum_b (ps : ex sum) : ring_exp_m (ex base) :=
pure (ex.sum_b ps.info (ps.set_info none none))
/-- Constructs `ex.exp` with the correct arguments. -/
meta def ex_exp (p : ex base) (ps : ex prod) : ring_exp_m (ex exp) := do
ctx ← get_context,
pps_o ← pow_orig p ps,
pps_p ← mk_pow [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``exp_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.exp ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
lemma base_to_exp_pf {p p' : α} : p = p' → p = p' ^ 1 := by simp
/-- Conversion from `ex base` to `ex exp`. -/
meta def base_to_exp (p : ex base) : ring_exp_m (ex exp) := do
o ← in_exponent $ ex_one,
ps ← ex_exp p o,
pf ← mk_proof ``base_to_exp_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma exp_to_prod_pf {p p' : α} : p = p' → p = p' * 1 := by simp
/-- Conversion from `ex exp` to `ex prod`. -/
meta def exp_to_prod (p : ex exp) : ring_exp_m (ex prod) := do
o ← ex_one,
ps ← ex_prod p o,
pf ← mk_proof ``exp_to_prod_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma prod_to_sum_pf {p p' : α} : p = p' → p = p' + 0 := by simp
/-- Conversion from `ex prod` to `ex sum`. -/
meta def prod_to_sum (p : ex prod) : ring_exp_m (ex sum) := do
z ← ex_zero,
ps ← ex_sum p z,
pf ← mk_proof ``prod_to_sum_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma atom_to_sum_pf (p : α) : p = p ^ 1 * 1 + 0 := by simp
/--
A more efficient conversion from `atom` to `ex sum`.
The result should be the same as `ex_var p >>= base_to_exp >>= exp_to_prod >>= prod_to_sum`,
except we need to calculate less intermediate steps.
-/
meta def atom_to_sum (p : atom) : ring_exp_m (ex sum) := do
p' ← ex_var p,
o ← in_exponent $ ex_one,
p' ← ex_exp p' o,
o ← ex_one,
p' ← ex_prod p' o,
z ← ex_zero,
p' ← ex_sum p' z,
pf ← mk_proof ``atom_to_sum_pf [p.1] [],
pure $ p'.set_info p.1 pf
/--
Compute the sum of two coefficients.
Note that the result might not be a valid expression:
if `p = -q`, then the result should be `ex.zero : ex sum` instead.
The caller must detect when this happens!
The returned value is of the form `ex.coeff _ (p + q)`,
with the proof of `expr.of_rat p + expr.of_rat q = expr.of_rat (p + q)`.
-/
meta def add_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do
ctx ← get_context,
pq_o ← mk_add [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_field pq_o,
pure $ ex.coeff ⟨pq_o, pq_p, pq_pf⟩ ⟨p.1 + q.1⟩
lemma mul_coeff_pf_one_mul (q : α) : 1 * q = q := one_mul q
lemma mul_coeff_pf_mul_one (p : α) : p * 1 = p := mul_one p
/--
Compute the product of two coefficients.
The returned value is of the form `ex.coeff _ (p * q)`,
with the proof of `expr.of_rat p * expr.of_rat q = expr.of_rat (p * q)`.
-/
meta def mul_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) :=
match p.1, q.1 with -- Special case to speed up multiplication with 1.
| ⟨1, 1, _, _⟩, _ := do
ctx ← get_context,
pq_o ← mk_mul [p_p, q_p],
pf ← mk_app_csr ``mul_coeff_pf_one_mul [q_p],
pure $ ex.coeff ⟨pq_o, q_p, pf⟩ ⟨q.1⟩
| _, ⟨1, 1, _, _⟩ := do
ctx ← get_context,
pq_o ← mk_mul [p_p, q_p],
pf ← mk_app_csr ``mul_coeff_pf_mul_one [p_p],
pure $ ex.coeff ⟨pq_o, p_p, pf⟩ ⟨p.1⟩
| _, _ := do
ctx ← get_context,
pq' ← mk_mul [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_field pq',
pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩
end
section rewrite
/-! ### `rewrite` section
In this section we deal with rewriting terms to fit in the basic grammar of `eval`.
For example, `nat.succ n` is rewritten to `n + 1` before it is evaluated further.
-/
/-- Given a proof that the expressions `ps_o` and `ps'.orig` are equal,
show that `ps_o` and `ps'.pretty` are equal.
Useful to deal with aliases in `eval`. For instance, `nat.succ p` can be handled
as an alias of `p + 1` as follows:
```
| ps_o@`(nat.succ %%p_o) := do
ps' ← eval `(%%p_o + 1),
pf ← lift $ mk_app ``nat.succ_eq_add_one [p_o],
rewrite ps_o ps' pf
```
-/
meta def rewrite (ps_o : expr) (ps' : ex sum) (pf : expr) : ring_exp_m (ex sum) :=
do
ps'_pf ← ps'.info.proof_term,
pf ← lift $ mk_eq_trans pf ps'_pf,
pure $ ps'.set_info ps_o pf
end rewrite
/--
Represents the way in which two products are equal except coefficient.
This type is used in the function `add_overlap`.
In order to deal with equations of the form `a * 2 + a = 3 * a`,
the `add` function will add up overlapping products,
turning `a * 2 + a` into `a * 3`.
We need to distinguish `a * 2 + a` from `a * 2 + b` in order to do this,
and the `overlap` type carries the information on how it overlaps.
The case `none` corresponds to non-overlapping products, e.g. `a * 2 + b`;
the case `nonzero` to overlapping products adding to non-zero, e.g. `a * 2 + a`
(the `ex prod` field will then look like `a * 3` with a proof that `a * 2 + a = a * 3`);
the case `zero` to overlapping products adding to zero, e.g. `a * 2 + a * -2`.
We distinguish those two cases because in the second, the whole product reduces to `0`.
A potential extension to the tactic would also do this for the base of exponents,
e.g. to show `2^n * 2^n = 4^n`.
-/
meta inductive overlap : Type
| none : overlap
| nonzero : ex prod → overlap
| zero : ex sum → overlap
lemma add_overlap_pf {ps qs pq} (p : α) : ps + qs = pq → p * ps + p * qs = p * pq := λ pq_pf, calc
p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _)
... = p * pq : by rw pq_pf
lemma add_overlap_pf_zero {ps qs} (p : α) : ps + qs = 0 → p * ps + p * qs = 0 := λ pq_pf, calc
p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _)
... = p * 0 : by rw pq_pf
... = 0 : mul_zero _
/--
Given arguments `ps`, `qs` of the form `ps' * x` and `ps' * y` respectively
return `ps + qs = ps' * (x + y)` (with `x` and `y` arbitrary coefficients).
For other arguments, return `overlap.none`.
-/
meta def add_overlap : ex prod → ex prod → ring_exp_m overlap
| (ex.coeff x_i x) (ex.coeff y_i y) := do
xy@(ex.coeff _ xy_c) ← add_coeff x_i.pretty y_i.pretty x y
| lift $ fail "internal error: add_coeff should return ex.coeff",
if xy_c.1 = 0
then do
z ← ex_zero,
pure $ overlap.zero (z.set_info xy.orig xy.proof)
else pure $ overlap.nonzero xy
| (ex.prod _ _ _) (ex.coeff _ _) := pure overlap.none
| (ex.coeff _ _) (ex.prod _ _ _) := pure overlap.none
| pps@(ex.prod _ p ps) qqs@(ex.prod _ q qs) := if p.eq q
then do
pq_ol ← add_overlap ps qs,
pqs_o ← add_orig pps qqs,
match pq_ol with
| overlap.none := pure overlap.none
| (overlap.nonzero pq) := do
pqs ← ex_prod p pq,
pf ← mk_proof ``add_overlap_pf
[ps.pretty, qs.pretty, pq.pretty, p.pretty]
[pq.info],
pure $ overlap.nonzero (pqs.set_info pqs_o pf)
| (overlap.zero pq) := do
z ← ex_zero,
pf ← mk_proof ``add_overlap_pf_zero
[ps.pretty, qs.pretty, p.pretty]
[pq.info],
pure $ overlap.zero (z.set_info pqs_o pf)
end
else pure overlap.none
section addition
lemma add_pf_z_sum {ps qs qs' : α} : ps = 0 → qs = qs' → ps + qs = qs' := λ ps_pf qs_pf, calc
ps + qs = 0 + qs' : by rw [ps_pf, qs_pf]
... = qs' : zero_add _
lemma add_pf_sum_z {ps ps' qs : α} : ps = ps' → qs = 0 → ps + qs = ps' := λ ps_pf qs_pf, calc
ps + qs = ps' + 0 : by rw [ps_pf, qs_pf]
... = ps' : add_zero _
lemma add_pf_sum_overlap {pps p ps qqs q qs pq pqs : α} :
pps = p + ps → qqs = q + qs → p + q = pq → ps + qs = pqs → pps + qqs = pq + pqs := by cc
lemma add_pf_sum_overlap_zero {pps p ps qqs q qs pqs : α} :
pps = p + ps → qqs = q + qs → p + q = 0 → ps + qs = pqs → pps + qqs = pqs :=
λ pps_pf qqs_pf pq_pf pqs_pf, calc
pps + qqs = (p + ps) + (q + qs) : by rw [pps_pf, qqs_pf]
... = (p + q) + (ps + qs) : by cc
... = 0 + pqs : by rw [pq_pf, pqs_pf]
... = pqs : zero_add _
lemma add_pf_sum_lt {pps p ps qqs pqs : α} :
pps = p + ps → ps + qqs = pqs → pps + qqs = p + pqs := by cc
lemma add_pf_sum_gt {pps qqs q qs pqs : α} :
qqs = q + qs → pps + qs = pqs → pps + qqs = q + pqs := by cc
/--
Add two expressions.
* `0 + qs = 0`
* `ps + 0 = 0`
* `ps * x + ps * y = ps * (x + y)` (for `x`, `y` coefficients; uses `add_overlap`)
* `(p + ps) + (q + qs) = p + (ps + (q + qs))` (if `p.lt q`)
* `(p + ps) + (q + qs) = q + ((p + ps) + qs)` (if not `p.lt q`)
-/
meta def add : ex sum → ex sum → ring_exp_m (ex sum)
| ps@(ex.zero ps_i) qs := do
pf ← mk_proof ``add_pf_z_sum [ps.orig, qs.orig, qs.pretty] [ps.info, qs.info],
pqs_o ← add_orig ps qs,
pure $ qs.set_info pqs_o pf
| ps qs@(ex.zero qs_i) := do
pf ← mk_proof ``add_pf_sum_z [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info],
pqs_o ← add_orig ps qs,
pure $ ps.set_info pqs_o pf
| pps@(ex.sum pps_i p ps) qqs@(ex.sum qqs_i q qs) := do
ol ← add_overlap p q,
ppqqs_o ← add_orig pps qqs,
match ol with
| (overlap.nonzero pq) := do
pqs ← add ps qs,
pqqs ← ex_sum pq pqs,
qqs_pf ← qqs.proof_term,
pf ← mk_proof ``add_pf_sum_overlap
[pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pq.pretty, pqs.pretty]
[pps.info, qqs.info, pq.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
| (overlap.zero pq) := do
pqs ← add ps qs,
pf ← mk_proof ``add_pf_sum_overlap_zero
[pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[pps.info, qqs.info, pq.info, pqs.info],
pure $ pqs.set_info ppqqs_o pf
| overlap.none := if p.lt q
then do
pqs ← add ps qqs,
ppqs ← ex_sum p pqs,
pf ← mk_proof ``add_pf_sum_lt
[pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqqs_o pf
else do
pqs ← add pps qs,
pqqs ← ex_sum q pqs,
pf ← mk_proof ``add_pf_sum_gt
[pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
end
end addition
section multiplication
lemma mul_pf_c_c {ps ps' qs qs' pq : α} :
ps = ps' → qs = qs' → ps' * qs' = pq → ps * qs = pq := by cc
lemma mul_pf_c_prod {ps qqs q qs pqs : α} :
qqs = q * qs → ps * qs = pqs → ps * qqs = q * pqs := by cc
lemma mul_pf_prod_c {pps p ps qs pqs : α} :
pps = p * ps → ps * qs = pqs → pps * qs = p * pqs := by cc
lemma mul_pp_pf_overlap {pps p_b ps qqs qs psqs : α} {p_e q_e : ℕ} :
pps = p_b ^ p_e * ps → qqs = p_b ^ q_e * qs →
p_b ^ (p_e + q_e) * (ps * qs) = psqs → pps * qqs = psqs
:= λ ps_pf qs_pf psqs_pf, by simp [symm psqs_pf, pow_add, ps_pf, qs_pf]; ac_refl
lemma mul_pp_pf_prod_lt {pps p ps qqs pqs : α} :
pps = p * ps → ps * qqs = pqs → pps * qqs = p * pqs := by cc
lemma mul_pp_pf_prod_gt {pps qqs q qs pqs : α} :
qqs = q * qs → pps * qs = pqs → pps * qqs = q * pqs := by cc
/--
Multiply two expressions.
* `x * y = (x * y)` (for `x`, `y` coefficients)
* `x * (q * qs) = q * (qs * x)` (for `x` coefficient)
* `(p * ps) * y = p * (ps * y)` (for `y` coefficient)
* `(p_b^p_e * ps) * (p_b^q_e * qs) = p_b^(p_e + q_e) * (ps * qs)`
(if `p_e` and `q_e` are identical except coefficient)
* `(p * ps) * (q * qs) = p * (ps * (q * qs))` (if `p.lt q`)
* `(p * ps) * (q * qs) = q * ((p * ps) * qs)` (if not `p.lt q`)
-/
meta def mul_pp : ex prod → ex prod → ring_exp_m (ex prod)
| ps@(ex.coeff _ x) qs@(ex.coeff _ y) := do
pq ← mul_coeff ps.pretty qs.pretty x y,
pq_o ← mul_orig ps qs,
pf ← mk_proof_or_refl pq.pretty ``mul_pf_c_c
[ps.orig, ps.pretty, qs.orig, qs.pretty, pq.pretty]
[ps.info, qs.info, pq.info],
pure $ pq.set_info pq_o pf
| ps@(ex.coeff _ x) qqs@(ex.prod _ q qs) := do
pqs ← mul_pp ps qs,
pqqs ← ex_prod q pqs,
pqqs_o ← mul_orig ps qqs,
pf ← mk_proof ``mul_pf_c_prod
[ps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info pqqs_o pf
| pps@(ex.prod _ p ps) qs@(ex.coeff _ y) := do
pqs ← mul_pp ps qs,
ppqs ← ex_prod p pqs,
ppqs_o ← mul_orig pps qs,
pf ← mk_proof ``mul_pf_prod_c
[pps.orig, p.pretty, ps.pretty, qs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqs_o pf
| pps@(ex.prod _ p@(ex.exp _ p_b p_e) ps) qqs@(ex.prod _ q@(ex.exp _ q_b q_e) qs) := do
ppqqs_o ← mul_orig pps qqs,
pq_ol ← in_exponent $ add_overlap p_e q_e,
match pq_ol, p_b.eq q_b with
| (overlap.nonzero pq_e), tt := do
psqs ← mul_pp ps qs,
pq ← ex_exp p_b pq_e,
ppsqqs ← ex_prod pq psqs,
pf ← mk_proof ``mul_pp_pf_overlap
[pps.orig, p_b.pretty, ps.pretty, qqs.orig, qs.pretty, ppsqqs.pretty, p_e.pretty, q_e.pretty]
[pps.info, qqs.info, ppsqqs.info],
pure $ ppsqqs.set_info ppqqs_o pf
| _, _ := if p.lt q then do
pqs ← mul_pp ps qqs,
ppqs ← ex_prod p pqs,
pf ← mk_proof ``mul_pp_pf_prod_lt
[pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqqs_o pf
else do
pqs ← mul_pp pps qs,
pqqs ← ex_prod q pqs,
pf ← mk_proof ``mul_pp_pf_prod_gt
[pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
end
lemma mul_p_pf_zero {ps qs : α} : ps = 0 → ps * qs = 0 :=
λ ps_pf, by rw [ps_pf, zero_mul]
lemma mul_p_pf_sum {pps p ps qs ppsqs : α} : pps = p + ps →
p * qs + ps * qs = ppsqs → pps * qs = ppsqs := λ pps_pf ppsqs_pf, calc
pps * qs = (p + ps) * qs : by rw [pps_pf]
... = p * qs + ps * qs : add_mul _ _ _
... = ppsqs : ppsqs_pf
/--
Multiply two expressions.
* `0 * qs = 0`
* `(p + ps) * qs = (p * qs) + (ps * qs)`
-/
meta def mul_p : ex sum → ex prod → ring_exp_m (ex sum)
| ps@(ex.zero ps_i) qs := do
z ← ex_zero,
z_o ← mul_orig ps qs,
pf ← mk_proof ``mul_p_pf_zero [ps.orig, qs.orig] [ps.info],
pure $ z.set_info z_o pf
| pps@(ex.sum pps_i p ps) qs := do
pqs ← mul_pp p qs >>= prod_to_sum,
psqs ← mul_p ps qs,
ppsqs ← add pqs psqs,
pps_pf ← pps.proof_term,
ppsqs_o ← mul_orig pps qs,
ppsqs_pf ← ppsqs.proof_term,
pf ← mk_proof ``mul_p_pf_sum
[pps.orig, p.pretty, ps.pretty, qs.orig, ppsqs.pretty]
[pps.info, ppsqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma mul_pf_zero {ps qs : α} : qs = 0 → ps * qs = 0 :=
λ qs_pf, by rw [qs_pf, mul_zero]
lemma mul_pf_sum {ps qqs q qs psqqs : α} : qqs = q + qs → ps * q + ps * qs = psqqs →
ps * qqs = psqqs := λ qs_pf psqqs_pf, calc
ps * qqs = ps * (q + qs) : by rw [qs_pf]
... = ps * q + ps * qs : mul_add _ _ _
... = psqqs : psqqs_pf
/--
Multiply two expressions.
* `ps * 0 = 0`
* `ps * (q + qs) = (ps * q) + (ps * qs)`
-/
meta def mul : ex sum → ex sum → ring_exp_m (ex sum)
| ps qs@(ex.zero qs_i) := do
z ← ex_zero,
z_o ← mul_orig ps qs,
pf ← mk_proof ``mul_pf_zero [ps.orig, qs.orig] [qs.info],
pure $ z.set_info z_o pf
| ps qqs@(ex.sum qqs_i q qs) := do
psq ← mul_p ps q,
psqs ← mul ps qs,
psqqs ← add psq psqs,
psqqs_o ← mul_orig ps qqs,
pf ← mk_proof ``mul_pf_sum
[ps.orig, qqs.orig, q.orig, qs.orig, psqqs.pretty]
[qqs.info, psqqs.info],
pure $ psqqs.set_info psqqs_o pf
end multiplication
section exponentiation
lemma pow_e_pf_exp {pps p : α} {ps qs psqs : ℕ} :
pps = p ^ ps → ps * qs = psqs → pps ^ qs = p ^ psqs :=
λ pps_pf psqs_pf, calc
pps ^ qs = (p ^ ps) ^ qs : by rw [pps_pf]
... = p ^ (ps * qs) : symm (pow_mul _ _ _)
... = p ^ psqs : by rw [psqs_pf]
/--
Compute the exponentiation of two coefficients.
The returned value is of the form `ex.coeff _ (p ^ q)`,
with the proof of `expr.of_rat p ^ expr.of_rat q = expr.of_rat (p ^ q)`.
-/
meta def pow_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do
ctx ← get_context,
pq' ← mk_pow [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_pow pq',
if q.value.denom ≠ 1 then lift $ fail!"Only integer powers are supported, not {q.value}."
else pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 ^ q.value.num⟩
/--
Exponentiate two expressions.
* `(p ^ ps) ^ qs = p ^ (ps * qs)`
-/
meta def pow_e : ex exp → ex prod → ring_exp_m (ex exp)
| pps@(ex.exp pps_i p ps) qs := do
psqs ← in_exponent $ mul_pp ps qs,
ppsqs ← ex_exp p psqs,
ppsqs_o ← pow_orig pps qs,
pf ← mk_proof ``pow_e_pf_exp
[pps.orig, p.pretty, ps.pretty, qs.orig, psqs.pretty]
[pps.info, psqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma pow_pp_pf_one {ps : α} {qs : ℕ} : ps = 1 → ps ^ qs = 1 :=
λ ps_pf, by rw [ps_pf, one_pow]
lemma pow_pf_c_c {ps ps' pq : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps' ^ qs' = pq → ps ^ qs = pq := by cc
lemma pow_pp_pf_c {ps ps' pqs : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps' ^ qs' = pqs → ps ^ qs = pqs * 1 :=
by simp; cc
lemma pow_pp_pf_prod {pps p ps pqs psqs : α} {qs : ℕ} : pps = p * ps →
p ^ qs = pqs → ps ^ qs = psqs → pps ^ qs = pqs * psqs :=
λ pps_pf pqs_pf psqs_pf, calc
pps ^ qs = (p * ps) ^ qs : by rw [pps_pf]
... = p ^ qs * ps ^ qs : mul_pow _ _ _
... = pqs * psqs : by rw [pqs_pf, psqs_pf]
/--
Exponentiate two expressions.
* `1 ^ qs = 1`
* `x ^ qs = x ^ qs` (for `x` coefficient)
* `(p * ps) ^ qs = p ^ qs + ps ^ qs`
-/
meta def pow_pp : ex prod → ex prod → ring_exp_m (ex prod)
| ps@(ex.coeff ps_i ⟨⟨1, 1, _, _⟩⟩) qs := do
o ← ex_one,
o_o ← pow_orig ps qs,
pf ← mk_proof ``pow_pp_pf_one [ps.orig, qs.orig] [ps.info],
pure $ o.set_info o_o pf
| ps@(ex.coeff ps_i x) qs@(ex.coeff qs_i y) := do
pq ← pow_coeff ps.pretty qs.pretty x y,
pq_o ← pow_orig ps qs,
pf ← mk_proof_or_refl pq.pretty ``pow_pf_c_c
[ps.orig, ps.pretty, pq.pretty, qs.orig, qs.pretty]
[ps.info, qs.info, pq.info],
pure $ pq.set_info pq_o pf
| ps@(ex.coeff ps_i x) qs := do
ps'' ← pure ps >>= prod_to_sum >>= ex_sum_b,
pqs ← ex_exp ps'' qs,
pqs_o ← pow_orig ps qs,
pf ← mk_proof_or_refl pqs.pretty ``pow_pp_pf_c
[ps.orig, ps.pretty, pqs.pretty, qs.orig, qs.pretty]
[ps.info, qs.info, pqs.info],
pqs' ← exp_to_prod pqs,
pure $ pqs'.set_info pqs_o pf
| pps@(ex.prod pps_i p ps) qs := do
pqs ← pow_e p qs,
psqs ← pow_pp ps qs,
ppsqs ← ex_prod pqs psqs,
ppsqs_o ← pow_orig pps qs,
pf ← mk_proof ``pow_pp_pf_prod
[pps.orig, p.pretty, ps.pretty, pqs.pretty, psqs.pretty, qs.orig]
[pps.info, pqs.info, psqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma pow_p_pf_one {ps ps' : α} {qs : ℕ} : ps = ps' → qs = succ zero → ps ^ qs = ps' :=
λ ps_pf qs_pf, calc
ps ^ qs = ps' ^ 1 : by rw [ps_pf, qs_pf]
... = ps' : pow_one _
lemma pow_p_pf_zero {ps : α} {qs qs' : ℕ} : ps = 0 → qs = succ qs' → ps ^ qs = 0 :=
λ ps_pf qs_pf, calc
ps ^ qs = 0 ^ (succ qs') : by rw [ps_pf, qs_pf]
... = 0 : zero_pow (succ_pos qs')
lemma pow_p_pf_succ {ps pqqs : α} {qs qs' : ℕ} :
qs = succ qs' → ps * ps ^ qs' = pqqs → ps ^ qs = pqqs :=
λ qs_pf pqqs_pf, calc
ps ^ qs = ps ^ succ qs' : by rw [qs_pf]
... = ps * ps ^ qs' : pow_succ _ _
... = pqqs : by rw [pqqs_pf]
lemma pow_p_pf_singleton {pps p pqs : α} {qs : ℕ} :
pps = p + 0 → p ^ qs = pqs → pps ^ qs = pqs :=
λ pps_pf pqs_pf, by rw [pps_pf, add_zero, pqs_pf]
lemma pow_p_pf_cons {ps ps' : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps ^ qs = ps' ^ qs' := by cc
/--
Exponentiate two expressions.
* `ps ^ 1 = ps`
* `0 ^ qs = 0` (note that this is handled *after* `ps ^ 0 = 1`)
* `(p + 0) ^ qs = p ^ qs`
* `ps ^ (qs + 1) = ps * ps ^ qs` (note that this is handled *after* `p + 0 ^ qs = p ^ qs`)
* `ps ^ qs = ps ^ qs` (otherwise)
-/
meta def pow_p : ex sum → ex prod → ring_exp_m (ex sum)
| ps qs@(ex.coeff qs_i ⟨⟨1, 1, _, _⟩⟩) := do
ps_o ← pow_orig ps qs,
pf ← mk_proof ``pow_p_pf_one [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info],
pure $ ps.set_info ps_o pf
| ps@(ex.zero ps_i) qs@(ex.coeff qs_i ⟨⟨succ y, 1, _, _⟩⟩) := do
ctx ← get_context,
z ← ex_zero,
qs_pred ← lift $ expr.of_nat ctx.info_e.α y,
pf ← mk_proof ``pow_p_pf_zero [ps.orig, qs.orig, qs_pred] [ps.info, qs.info],
z_o ← pow_orig ps qs,
pure $ z.set_info z_o pf
| pps@(ex.sum pps_i p (ex.zero _)) qqs := do
pqs ← pow_pp p qqs,
pqs_o ← pow_orig pps qqs,
pf ← mk_proof ``pow_p_pf_singleton
[pps.orig, p.pretty, pqs.pretty, qqs.orig]
[pps.info, pqs.info],
prod_to_sum $ pqs.set_info pqs_o pf
| ps qs@(ex.coeff qs_i ⟨⟨int.of_nat (succ n), 1, den_pos, _⟩⟩) := do
qs' ← in_exponent $ ex_coeff ⟨int.of_nat n, 1, den_pos, coprime_one_right _⟩,
pqs ← pow_p ps qs',
pqqs ← mul ps pqs,
pqqs_o ← pow_orig ps qs,
pf ← mk_proof ``pow_p_pf_succ
[ps.orig, pqqs.pretty, qs.orig, qs'.pretty]
[qs.info, pqqs.info],
pure $ pqqs.set_info pqqs_o pf
| pps qqs := do -- fallback: treat them as atoms
pps' ← ex_sum_b pps,
psqs ← ex_exp pps' qqs,
psqs_o ← pow_orig pps qqs,
pf ← mk_proof_or_refl psqs.pretty ``pow_p_pf_cons
[pps.orig, pps.pretty, qqs.orig, qqs.pretty]
[pps.info, qqs.info],
exp_to_prod (psqs.set_info psqs_o pf) >>= prod_to_sum
lemma pow_pf_zero {ps : α} {qs : ℕ} : qs = 0 → ps ^ qs = 1 := λ qs_pf, calc
ps ^ qs = ps ^ 0 : by rw [qs_pf]
... = 1 : pow_zero _
lemma pow_pf_sum {ps psqqs : α} {qqs q qs : ℕ} : qqs = q + qs →
ps ^ q * ps ^ qs = psqqs → ps ^ qqs = psqqs := λ qqs_pf psqqs_pf, calc
ps ^ qqs = ps ^ (q + qs) : by rw [qqs_pf]
... = ps ^ q * ps ^ qs : pow_add _ _ _
... = psqqs : psqqs_pf
/--
Exponentiate two expressions.
* `ps ^ 0 = 1`
* `ps ^ (q + qs) = ps ^ q * ps ^ qs`
-/
meta def pow : ex sum → ex sum → ring_exp_m (ex sum)
| ps qs@(ex.zero qs_i) := do
o ← ex_one,
o_o ← pow_orig ps qs,
pf ← mk_proof ``pow_pf_zero [ps.orig, qs.orig] [qs.info],
prod_to_sum $ o.set_info o_o pf
| ps qqs@(ex.sum qqs_i q qs) := do
psq ← pow_p ps q,
psqs ← pow ps qs,
psqqs ← mul psq psqs,
psqqs_o ← pow_orig ps qqs,
pf ← mk_proof ``pow_pf_sum
[ps.orig, psqqs.pretty, qqs.orig, q.pretty, qs.pretty]
[qqs.info, psqqs.info],
pure $ psqqs.set_info psqqs_o pf
end exponentiation
lemma simple_pf_sum_zero {p p' : α} : p = p' → p + 0 = p' := by simp
lemma simple_pf_prod_one {p p' : α} : p = p' → p * 1 = p' := by simp
lemma simple_pf_prod_neg_one {α} [ring α] {p p' : α} : p = p' → p * -1 = - p' := by simp
lemma simple_pf_var_one (p : α) : p ^ 1 = p := by simp
lemma simple_pf_exp_one {p p' : α} : p = p' → p ^ 1 = p' := by simp
/--
Give a simpler, more human-readable representation of the normalized expression.
Normalized expressions might have the form `a^1 * 1 + 0`,
since the dummy operations reduce special cases in pattern-matching.
Humans prefer to read `a` instead.
This tactic gets rid of the dummy additions, multiplications and exponentiations.
Returns a normalized expression `e'` and a proof that `e.pretty = e'`.
-/
meta def ex.simple : Π {et : ex_type}, ex et → ring_exp_m (expr × expr)
| sum pps@(ex.sum pps_i p (ex.zero _)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_sum_zero [p.pretty, p_p, p_pf]
| sum (ex.sum pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← ps.simple,
prod.mk
<$> mk_add [p_p, ps_p]
<*> mk_app_csr ``sum_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| prod (ex.prod pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_prod_one [p.pretty, p_p, p_pf]
| prod pps@(ex.prod pps_i p (ex.coeff _ ⟨⟨-1, 1, _, _⟩⟩)) := do
ctx ← get_context,
match ctx.info_b.ring_instance with
| none := prod.mk pps.pretty <$> lift (mk_eq_refl pps.pretty)
| (some ringi) := do
(p_p, p_pf) ← p.simple,
prod.mk
<$> lift (mk_app ``has_neg.neg [p_p])
<*> mk_app_class ``simple_pf_prod_neg_one ringi [p.pretty, p_p, p_pf]
end
| prod (ex.prod pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← ps.simple,
prod.mk
<$> mk_mul [p_p, ps_p]
<*> mk_app_csr ``prod_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| base (ex.sum_b pps_i ps) := ps.simple
| exp (ex.exp pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_exp_one [p.pretty, p_p, p_pf]
| exp (ex.exp pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← in_exponent $ ps.simple,
prod.mk
<$> mk_pow [p_p, ps_p]
<*> mk_app_csr ``exp_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| et ps := prod.mk ps.pretty <$> lift (mk_eq_refl ps.pretty)
/--
Performs a lookup of the atom `a` in the list of known atoms,
or allocates a new one.
If `a` is not definitionally equal to any of the list's entries,
a new atom is appended to the list and returned.
The index of this atom is kept track of in the second inductive argument.
This function is mostly useful in `resolve_atom`,
which updates the state with the new list of atoms.
-/
meta def resolve_atom_aux (a : expr) : list atom → ℕ → ring_exp_m (atom × list atom)
| [] n := let atm : atom := ⟨a, n⟩ in pure (atm, [atm])
| bas@(b :: as) n := do
ctx ← get_context,
(lift $ is_def_eq a b.value ctx.transp >> pure (b , bas)) <|> do
(atm, as') ← resolve_atom_aux as (succ n),
pure (atm, b :: as')
/--
Convert the expression to an atom:
either look up a definitionally equal atom,
or allocate it as a new atom.
You probably want to use `eval_base` if `eval` doesn't work
instead of directly calling `resolve_atom`,
since `eval_base` can also handle numerals.
-/
meta def resolve_atom (a : expr) : ring_exp_m atom := do
atoms ← reader_t.lift $ state_t.get,
(atm, atoms') ← resolve_atom_aux a atoms 0,
reader_t.lift $ state_t.put atoms',
pure atm
/--
Treat the expression atomically: as a coefficient or atom.
Handles cases where `eval` cannot treat the expression as a known operation
because it is just a number or single variable.
-/
meta def eval_base (ps : expr) : ring_exp_m (ex sum) :=
match ps.to_rat with
| some ⟨0, 1, _, _⟩ := ex_zero
| some x := ex_coeff x >>= prod_to_sum
| none := do
a ← resolve_atom ps,
atom_to_sum a
end
lemma negate_pf {α} [ring α] {ps ps' : α} : (-1) * ps = ps' → -ps = ps' := by simp
/--
Negate an expression by multiplying with `-1`.
Only works if there is a `ring` instance; otherwise it will `fail`.
-/
meta def negate (ps : ex sum) : ring_exp_m (ex sum) := do
ctx ← get_context,
match ctx.info_b.ring_instance with
| none := lift $ fail "internal error: negate called in semiring"
| (some ring_instance) := do
minus_one ← ex_coeff (-1) >>= prod_to_sum,
ps' ← mul minus_one ps,
ps_pf ← ps'.proof_term,
pf ← mk_app_class ``negate_pf ring_instance [ps.orig, ps'.pretty, ps_pf],
ps'_o ← lift $ mk_app ``has_neg.neg [ps.orig],
pure $ ps'.set_info ps'_o pf
end
lemma inverse_pf {α} [division_ring α] {ps ps_u ps_p e' e'' : α} :
ps = ps_u → ps_u = ps_p → ps_p ⁻¹ = e' → e' = e'' → ps ⁻¹ = e'' :=
by cc
/--
Invert an expression by simplifying, applying `has_inv.inv` and treating the result as an atom.
Only works if there is a `division_ring` instance; otherwise it will `fail`.
-/
meta def inverse (ps : ex sum) : ring_exp_m (ex sum) := do
ctx ← get_context,
dri ← match ctx.info_b.dr_instance with
| none := lift $ fail "division is only supported in a division ring"
| (some dri) := pure dri
end,
(ps_simple, ps_simple_pf) ← ps.simple,
e ← lift $ mk_app ``has_inv.inv [ps_simple],
(e', e_pf) ← lift (norm_num.derive e) <|> ((λ e_pf, (e, e_pf)) <$> lift (mk_eq_refl e)),
e'' ← eval_base e',
ps_pf ← ps.proof_term,
e''_pf ← e''.proof_term,
pf ← mk_app_class ``inverse_pf dri
[ ps.orig, ps.pretty, ps_simple, e', e''.pretty,
ps_pf, ps_simple_pf, e_pf, e''_pf],
e''_o ← lift $ mk_app ``has_inv.inv [ps.orig],
pure $ e''.set_info e''_o pf
lemma sub_pf {α} [ring α] {ps qs psqs : α} (h : ps + -qs = psqs) : ps - qs = psqs :=
by rwa sub_eq_add_neg
lemma div_pf {α} [division_ring α] {ps qs psqs : α} (h : ps * qs⁻¹ = psqs) : ps / qs = psqs :=
by rwa div_eq_mul_inv
end operations
section wiring
/-!
### `wiring` section
This section deals with going from `expr` to `ex` and back.
The main attraction is `eval`, which uses `add`, `mul`, etc.
to calculate an `ex` from a given `expr`.
Other functions use `ex`es to produce `expr`s together with a proof,
or produce the context to run `ring_exp_m` from an `expr`.
-/
open tactic
open ex_type
/--
Compute a normalized form (of type `ex`) from an expression (of type `expr`).
This is the main driver of the `ring_exp` tactic,
calling out to `add`, `mul`, `pow`, etc. to parse the `expr`.
-/
meta def eval : expr → ring_exp_m (ex sum)
| e@`(%%ps + %%qs) := do
ps' ← eval ps,
qs' ← eval qs,
add ps' qs'
| ps_o@`(nat.succ %%p_o) := do
ps' ← eval `(%%p_o + 1),
pf ← lift $ mk_app ``nat.succ_eq_add_one [p_o],
rewrite ps_o ps' pf
| e@`(%%ps - %%qs) := (do
ctx ← get_context,
ri ← match ctx.info_b.ring_instance with
| none := lift $ fail "subtraction is not directly supported in a semiring"
| (some ri) := pure ri
end,
ps' ← eval ps,
qs' ← eval qs >>= negate,
psqs ← add ps' qs',
psqs_pf ← psqs.proof_term,
pf ← mk_app_class ``sub_pf ri [ps, qs, psqs.pretty, psqs_pf],
pure (psqs.set_info e pf)) <|> eval_base e
| e@`(- %%ps) := do
ps' ← eval ps,
negate ps' <|> eval_base e
| e@`(%%ps * %%qs) := do
ps' ← eval ps,
qs' ← eval qs,
mul ps' qs'
| e@`(has_inv.inv %%ps) := do
ps' ← eval ps,
inverse ps' <|> eval_base e
| e@`(%%ps / %%qs) := do
ctx ← get_context,
dri ← match ctx.info_b.dr_instance with
| none := lift $ fail "division is only directly supported in a division ring"
| (some dri) := pure dri
end,
ps' ← eval ps,
qs' ← eval qs,
(do qs'' ← inverse qs',
psqs ← mul ps' qs'',
psqs_pf ← psqs.proof_term,
pf ← mk_app_class ``div_pf dri [ps, qs, psqs.pretty, psqs_pf],
pure (psqs.set_info e pf)) <|> eval_base e
| e@`(@has_pow.pow _ _ %%hp_instance %%ps %%qs) := do
ctx ← get_context,
ps' ← eval ps,
qs' ← in_exponent $ eval qs,
psqs ← pow ps' qs',
psqs_pf ← psqs.proof_term,
(do
lift (is_def_eq hp_instance ctx.info_b.hp_instance
<|> fail "has_pow instance must be nat.has_pow or monoid.has_pow"),
has_pow_pf ← lift $ mk_eq_refl e,
pf ← lift $ mk_eq_trans has_pow_pf psqs_pf,
pure $ psqs.set_info e pf) <|> eval_base e
| ps := eval_base ps
/--
Run `eval` on the expression and return the result together with normalization proof.
See also `eval_simple` if you want something that behaves like `norm_num`.
-/
meta def eval_with_proof (e : expr) : ring_exp_m (ex sum × expr) := do
e' ← eval e,
prod.mk e' <$> e'.proof_term
/--
Run `eval` on the expression and simplify the result.
Returns a simplified normalized expression, together with an equality proof.
See also `eval_with_proof` if you just want to check the equality of two expressions.
-/
meta def eval_simple (e : expr) : ring_exp_m (expr × expr) := do
(complicated, complicated_pf) ← eval_with_proof e,
(simple, simple_pf) ← complicated.simple,
prod.mk simple <$> lift (mk_eq_trans complicated_pf simple_pf)
/-- Compute the `eval_info` for a given type `α`. -/
meta def make_eval_info (α : expr) : tactic eval_info := do
u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
csr_instance ← mk_app ``comm_semiring [α] >>= mk_instance,
ring_instance ← (some <$> (mk_app ``ring [α] >>= mk_instance) <|> pure none),
dr_instance ← (some <$> (mk_app ``division_ring [α] >>= mk_instance) <|> pure none),
ha_instance ← mk_app ``has_add [α] >>= mk_instance,
hm_instance ← mk_app ``has_mul [α] >>= mk_instance,
hp_instance ← mk_mapp ``monoid.has_pow [some α, none],
z ← mk_mapp ``has_zero.zero [α, none],
o ← mk_mapp ``has_one.one [α, none],
pure ⟨α, u, csr_instance, ha_instance, hm_instance, hp_instance, ring_instance, dr_instance, z, o⟩
/-- Use `e` to build the context for running `mx`. -/
meta def run_ring_exp {α} (transp : transparency) (e : expr) (mx : ring_exp_m α) : tactic α := do
info_b ← infer_type e >>= make_eval_info,
info_e ← mk_const ``nat >>= make_eval_info,
(λ x : (_ × _), x.1) <$> (state_t.run (reader_t.run mx ⟨info_b, info_e, transp⟩) [])
/-- Repeatedly apply `eval_simple` on (sub)expressions. -/
meta def normalize (transp : transparency) (e : expr) : tactic (expr × expr) := do
(_, e', pf') ← ext_simplify_core () {}
simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do
(e'', pf) ← run_ring_exp transp e $ eval_simple e,
guard (¬ e'' =ₐ e),
return ((), e'', some pf, ff))
(λ _ _ _ _ _, failed) `eq e,
pure (e', pf')
end wiring
end tactic.ring_exp
namespace tactic.interactive
open interactive interactive.types lean.parser tactic tactic.ring_exp
local postfix (name := parser.optional) `?`:9001 := optional
/--
Tactic for solving equations of *commutative* (semi)rings,
allowing variables in the exponent.
This version of `ring_exp` fails if the target is not an equality.
The variant `ring_exp_eq!` will use a more aggressive reducibility setting
to determine equality of atoms.
-/
meta def ring_exp_eq (red : parse (tk "!")?) : tactic unit := do
`(eq %%ps %%qs) ← target >>= whnf,
let transp := if red.is_some then semireducible else reducible,
((ps', ps_pf), (qs', qs_pf)) ← run_ring_exp transp ps $
prod.mk <$> eval_with_proof ps <*> eval_with_proof qs,
if ps'.eq qs'
then do
qs_pf_inv ← mk_eq_symm qs_pf,
pf ← mk_eq_trans ps_pf qs_pf_inv,
tactic.interactive.exact ``(%%pf)
else fail "ring_exp failed to prove equality"
/--
Tactic for evaluating expressions in *commutative* (semi)rings, allowing for variables in the
exponent.
This tactic extends `ring`: it should solve every goal that `ring` can solve.
Additionally, it knows how to evaluate expressions with complicated exponents
(where `ring` only understands constant exponents).
The variants `ring_exp!` and `ring_exp_eq!` use a more aggessive reducibility setting to determine
equality of atoms.
For example:
```lean
example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp
example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp
example (x y : ℕ) : x + id y = y + id x := by ring_exp!
```
-/
meta def ring_exp (red : parse (tk "!")?) (loc : parse location) : tactic unit :=
match loc with
| interactive.loc.ns [none] := ring_exp_eq red
| _ := failed
end <|>
do ns ← loc.get_locals,
let transp := if red.is_some then semireducible else reducible,
tt ← tactic.replace_at (normalize transp) ns loc.include_goal
| fail "ring_exp failed to simplify",
when loc.include_goal $ try tactic.reflexivity
add_tactic_doc
{ name := "ring_exp",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ring_exp],
tags := ["arithmetic", "simplification", "decision procedure"] }
end tactic.interactive
namespace conv.interactive
open conv interactive
open tactic tactic.interactive (ring_exp_eq)
open tactic.ring_exp (normalize)
local postfix (name := parser.optional) `?`:9001 := optional
/--
Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic
`ring_exp`.
-/
meta def ring_exp (red : parse (lean.parser.tk "!")?) : conv unit :=
let transp := if red.is_some then semireducible else reducible in
discharge_eq_lhs (ring_exp_eq red)
<|> replace_lhs (normalize transp)
<|> fail "ring_exp failed to simplify"
end conv.interactive
|
3da677317e6ff6bc311f328d9c1787551e92134c | 618003631150032a5676f229d13a079ac875ff77 | /src/order/filter/extr.lean | 316554a0082d49f169a9f0b44419cd8cd54c46c8 | [
"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 | 18,647 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import order.filter.basic
/-!
# Minimum and maximum w.r.t. a filter and on a aet
## Main Definitions
This file defines six predicates of the form `is_A_B`, where `A` is `min`, `max`, or `extr`,
and `B` is `filter` or `on`.
* `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a`;
* `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a`;
* `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a`.
Similar predicates with `_on` suffix are particular cases for `l = principal s`.
## Main statements
### Change of the filter (set) argument
* `is_*_filter.filter_mono` : replace the filter with a smaller one;
* `is_*_filter.filter_inf` : replace a filter `l` with `l ⊓ l'`;
* `is_*_on.on_subset` : restrict to a smaller set;
* `is_*_on.inter` : replace a set `s` wtih `s ∩ t`.
### Composition
* `is_*_*.comp_mono` : if `x` is an extremum for `f` and `g` is a monotone function,
then `x` is an extremum for `g ∘ f`;
* `is_*_*.comp_antimono` : similarly for the case of monotonically decreasing `g`;
* `is_*_*.bicomp_mono` : if `x` is an extremum of the same type for `f` and `g`
and a binary operation `op` is monotone in both arguments, then `x` is an extremum
of the same type for `λ x, op (f x) (g x)`.
* `is_*_filter.comp_tendsto` : if `g x` is an extremum for `f` w.r.t. `l'` and `tendsto g l l'`,
then `x` is an extremum for `f ∘ g` w.r.t. `l`.
* `is_*_on.on_preimage` : if `g x` is an extremum for `f` on `s`, then `x` is an extremum
for `f ∘ g` on `g ⁻¹' s`.
### Algebraic operations
* `is_*_*.add` : if `x` is an extremum of the same type for two functions,
then it is an extremum of the same type for their sum;
* `is_*_*.neg` : if `x` is an extremum for `f`, then it is an extremum
of the opposite type for `-f`;
* `is_*_*.sub` : if `x` is an a minimum for `f` and a maximum for `g`,
then it is a minimum for `f - g` and a maximum for `g - f`;
* `is_*_*.max`, `is_*_*.min`, `is_*_*.sup`, `is_*_*.inf` : similarly for `is_*_*.add`
for pointwise `max`, `min`, `sup`, `inf`, respectively.
### Miscellaneous definitions
* `is_*_*_const` : any point is both a minimum and maximum for a constant function;
* `is_min/max_*.is_ext` : any minimum/maximum point is an extremum;
* `is_*_*.dual`, `is_*_*.undual`: conversion between codomains `α` and `dual α`;
## Missing features (TODO)
* Multiplication and division;
* `is_*_*.bicompl` : if `x` is a minimum for `f`, `y` is a minimum for `g`, and `op` is a monotone
binary operation, then `(x, y)` is a minimum for `uncurry (bicompl op f g)`. From this point of view,
`is_*_*.bicomp` is a composition
* It would be nice to have a tactic that specializes `comp_(anti)mono` or `bicomp_mono`
based on a proof of monotonicity of a given (binary) function. The tactic should maintain a `meta`
list of known (anti)monotone (binary) functions with their names, as well as a list of special
types of filters, and define the missing lemmas once one of these two lists grows.
-/
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
open set filter
section preorder
variables [preorder β] [preorder γ]
variables (f : α → β) (s : set α) (l : filter α) (a : α)
/-! ### Definitions -/
/-- `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a` -/
def is_min_filter : Prop := ∀ᶠ x in l, f a ≤ f x
/-- `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a` -/
def is_max_filter : Prop := ∀ᶠ x in l, f x ≤ f a
/-- `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a` -/
def is_extr_filter : Prop := is_min_filter f l a ∨ is_max_filter f l a
/-- `is_min_on f s a` means that `f a ≤ f x` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/
def is_min_on := is_min_filter f (principal s) a
/-- `is_max_on f s a` means that `f x ≤ f a` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/
def is_max_on := is_max_filter f (principal s) a
/-- `is_extr_on f s a` means `is_min_on f s a` or `is_max_on f s a` -/
def is_extr_on : Prop := is_extr_filter f (principal s) a
variables {f s a l} {t : set α} {l' : filter α}
lemma is_extr_on.elim {p : Prop} :
is_extr_on f s a → (is_min_on f s a → p) → (is_max_on f s a → p) → p :=
or.elim
lemma is_min_on_iff : is_min_on f s a ↔ ∀ x ∈ s, f a ≤ f x := iff.rfl
lemma is_max_on_iff : is_max_on f s a ↔ ∀ x ∈ s, f x ≤ f a := iff.rfl
lemma is_min_on_univ_iff : is_min_on f univ a ↔ ∀ x, f a ≤ f x :=
univ_subset_iff.trans eq_univ_iff_forall
lemma is_max_on_univ_iff : is_max_on f univ a ↔ ∀ x, f x ≤ f a :=
univ_subset_iff.trans eq_univ_iff_forall
/-! ### Conversion to `is_extr_*` -/
lemma is_min_filter.is_extr : is_min_filter f l a → is_extr_filter f l a := or.inl
lemma is_max_filter.is_extr : is_max_filter f l a → is_extr_filter f l a := or.inr
lemma is_min_on.is_extr (h : is_min_on f s a) : is_extr_on f s a := h.is_extr
lemma is_max_on.is_extr (h : is_max_on f s a) : is_extr_on f s a := h.is_extr
/-! ### Constant function -/
lemma is_min_filter_const {b : β} : is_min_filter (λ _, b) l a :=
univ_mem_sets' $ λ _, le_refl _
lemma is_max_filter_const {b : β} : is_max_filter (λ _, b) l a :=
univ_mem_sets' $ λ _, le_refl _
lemma is_extr_filter_const {b : β} : is_extr_filter (λ _, b) l a := is_min_filter_const.is_extr
lemma is_min_on_const {b : β} : is_min_on (λ _, b) s a := is_min_filter_const
lemma is_max_on_const {b : β} : is_max_on (λ _, b) s a := is_max_filter_const
lemma is_extr_on_const {b : β} : is_extr_on (λ _, b) s a := is_extr_filter_const
/-! ### Order dual -/
lemma is_min_filter_dual_iff : @is_min_filter α (order_dual β) _ f l a ↔ is_max_filter f l a :=
iff.rfl
lemma is_max_filter_dual_iff : @is_max_filter α (order_dual β) _ f l a ↔ is_min_filter f l a :=
iff.rfl
lemma is_extr_filter_dual_iff : @is_extr_filter α (order_dual β) _ f l a ↔ is_extr_filter f l a :=
or_comm _ _
alias is_min_filter_dual_iff ↔ is_min_filter.undual is_max_filter.dual
alias is_max_filter_dual_iff ↔ is_max_filter.undual is_min_filter.dual
alias is_extr_filter_dual_iff ↔ is_extr_filter.undual is_extr_filter.dual
lemma is_min_on_dual_iff : @is_min_on α (order_dual β) _ f s a ↔ is_max_on f s a := iff.rfl
lemma is_max_on_dual_iff : @is_max_on α (order_dual β) _ f s a ↔ is_min_on f s a := iff.rfl
lemma is_extr_on_dual_iff : @is_extr_on α (order_dual β) _ f s a ↔ is_extr_on f s a := or_comm _ _
alias is_min_on_dual_iff ↔ is_min_on.undual is_max_on.dual
alias is_max_on_dual_iff ↔ is_max_on.undual is_min_on.dual
alias is_extr_on_dual_iff ↔ is_extr_on.undual is_extr_on.dual
/-! ### Operations on the filter/set -/
lemma is_min_filter.filter_mono (h : is_min_filter f l a) (hl : l' ≤ l) :
is_min_filter f l' a := hl h
lemma is_max_filter.filter_mono (h : is_max_filter f l a) (hl : l' ≤ l) :
is_max_filter f l' a := hl h
lemma is_extr_filter.filter_mono (h : is_extr_filter f l a) (hl : l' ≤ l) :
is_extr_filter f l' a :=
h.elim (λ h, (h.filter_mono hl).is_extr) (λ h, (h.filter_mono hl).is_extr)
lemma is_min_filter.filter_inf (h : is_min_filter f l a) (l') : is_min_filter f (l ⊓ l') a :=
h.filter_mono inf_le_left
lemma is_max_filter.filter_inf (h : is_max_filter f l a) (l') : is_max_filter f (l ⊓ l') a :=
h.filter_mono inf_le_left
lemma is_extr_filter.filter_inf (h : is_extr_filter f l a) (l') : is_extr_filter f (l ⊓ l') a :=
h.filter_mono inf_le_left
lemma is_min_on.on_subset (hf : is_min_on f t a) (h : s ⊆ t) : is_min_on f s a :=
hf.filter_mono $ principal_mono.2 h
lemma is_max_on.on_subset (hf : is_max_on f t a) (h : s ⊆ t) : is_max_on f s a :=
hf.filter_mono $ principal_mono.2 h
lemma is_extr_on.on_subset (hf : is_extr_on f t a) (h : s ⊆ t) : is_extr_on f s a :=
hf.filter_mono $ principal_mono.2 h
lemma is_min_on.inter (hf : is_min_on f s a) (t) : is_min_on f (s ∩ t) a :=
hf.on_subset (inter_subset_left s t)
lemma is_max_on.inter (hf : is_max_on f s a) (t) : is_max_on f (s ∩ t) a :=
hf.on_subset (inter_subset_left s t)
lemma is_extr_on.inter (hf : is_extr_on f s a) (t) : is_extr_on f (s ∩ t) a :=
hf.on_subset (inter_subset_left s t)
/-! ### Composition with (anti)monotone functions -/
lemma is_min_filter.comp_mono (hf : is_min_filter f l a) {g : β → γ} (hg : monotone g) :
is_min_filter (g ∘ f) l a :=
mem_sets_of_superset hf $ λ x hx, hg hx
lemma is_max_filter.comp_mono (hf : is_max_filter f l a) {g : β → γ} (hg : monotone g) :
is_max_filter (g ∘ f) l a :=
mem_sets_of_superset hf $ λ x hx, hg hx
lemma is_extr_filter.comp_mono (hf : is_extr_filter f l a) {g : β → γ} (hg : monotone g) :
is_extr_filter (g ∘ f) l a :=
hf.elim (λ hf, (hf.comp_mono hg).is_extr) (λ hf, (hf.comp_mono hg).is_extr)
lemma is_min_filter.comp_antimono (hf : is_min_filter f l a) {g : β → γ}
(hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) :
is_max_filter (g ∘ f) l a :=
hf.dual.comp_mono (λ x y h, hg h)
lemma is_max_filter.comp_antimono (hf : is_max_filter f l a) {g : β → γ}
(hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) :
is_min_filter (g ∘ f) l a :=
hf.dual.comp_mono (λ x y h, hg h)
lemma is_extr_filter.comp_antimono (hf : is_extr_filter f l a) {g : β → γ}
(hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) :
is_extr_filter (g ∘ f) l a :=
hf.dual.comp_mono (λ x y h, hg h)
lemma is_min_on.comp_mono (hf : is_min_on f s a) {g : β → γ} (hg : monotone g) :
is_min_on (g ∘ f) s a :=
hf.comp_mono hg
lemma is_max_on.comp_mono (hf : is_max_on f s a) {g : β → γ} (hg : monotone g) :
is_max_on (g ∘ f) s a :=
hf.comp_mono hg
lemma is_extr_on.comp_mono (hf : is_extr_on f s a) {g : β → γ} (hg : monotone g) :
is_extr_on (g ∘ f) s a :=
hf.comp_mono hg
lemma is_min_on.comp_antimono (hf : is_min_on f s a) {g : β → γ}
(hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) :
is_max_on (g ∘ f) s a :=
hf.comp_antimono hg
lemma is_max_on.comp_antimono (hf : is_max_on f s a) {g : β → γ}
(hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) :
is_min_on (g ∘ f) s a :=
hf.comp_antimono hg
lemma is_extr_on.comp_antimono (hf : is_extr_on f s a) {g : β → γ}
(hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) :
is_extr_on (g ∘ f) s a :=
hf.comp_antimono hg
lemma is_min_filter.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op)
(hf : is_min_filter f l a) {g : α → γ} (hg : is_min_filter g l a) :
is_min_filter (λ x, op (f x) (g x)) l a :=
mem_sets_of_superset (inter_mem_sets hf hg) $ λ x ⟨hfx, hgx⟩, hop hfx hgx
lemma is_max_filter.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op)
(hf : is_max_filter f l a) {g : α → γ} (hg : is_max_filter g l a) :
is_max_filter (λ x, op (f x) (g x)) l a :=
mem_sets_of_superset (inter_mem_sets hf hg) $ λ x ⟨hfx, hgx⟩, hop hfx hgx
-- No `extr` version because we need `hf` and `hg` to be of the same kind
lemma is_min_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op)
(hf : is_min_on f s a) {g : α → γ} (hg : is_min_on g s a) :
is_min_on (λ x, op (f x) (g x)) s a :=
hf.bicomp_mono hop hg
lemma is_max_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op)
(hf : is_max_on f s a) {g : α → γ} (hg : is_max_on g s a) :
is_max_on (λ x, op (f x) (g x)) s a :=
hf.bicomp_mono hop hg
/-! ### Composition with `tendsto` -/
lemma is_min_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_min_filter f l (g b))
(hg : tendsto g l' l) :
is_min_filter (f ∘ g) l' b :=
hg hf
lemma is_max_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_max_filter f l (g b))
(hg : tendsto g l' l) :
is_max_filter (f ∘ g) l' b :=
hg hf
lemma is_extr_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_extr_filter f l (g b))
(hg : tendsto g l' l) :
is_extr_filter (f ∘ g) l' b :=
hf.elim (λ hf, (hf.comp_tendsto hg).is_extr) (λ hf, (hf.comp_tendsto hg).is_extr)
lemma is_min_on.on_preimage (g : δ → α) {b : δ} (hf : is_min_on f s (g b)) :
is_min_on (f ∘ g) (g ⁻¹' s) b :=
hf.comp_tendsto (tendsto_principal_principal.mpr $ subset.refl _)
lemma is_max_on.on_preimage (g : δ → α) {b : δ} (hf : is_max_on f s (g b)) :
is_max_on (f ∘ g) (g ⁻¹' s) b :=
hf.comp_tendsto (tendsto_principal_principal.mpr $ subset.refl _)
lemma is_extr_on.on_preimage (g : δ → α) {b : δ} (hf : is_extr_on f s (g b)) :
is_extr_on (f ∘ g) (g ⁻¹' s) b :=
hf.elim (λ hf, (hf.on_preimage g).is_extr) (λ hf, (hf.on_preimage g).is_extr)
end preorder
/-! ### Pointwise addition -/
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.add (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, f x + g x) l a :=
show is_min_filter (λ x, f x + g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, add_le_add' hx hy) hg
lemma is_max_filter.add (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, f x + g x) l a :=
show is_max_filter (λ x, f x + g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, add_le_add' hx hy) hg
lemma is_min_on.add (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, f x + g x) s a :=
hf.add hg
lemma is_max_on.add (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, f x + g x) s a :=
hf.add hg
end ordered_add_comm_monoid
/-! ### Pointwise negation and subtraction -/
section ordered_add_comm_group
variables [ordered_add_comm_group β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.neg (hf : is_min_filter f l a) : is_max_filter (λ x, -f x) l a :=
hf.comp_antimono (λ x y hx, neg_le_neg hx)
lemma is_max_filter.neg (hf : is_max_filter f l a) : is_min_filter (λ x, -f x) l a :=
hf.comp_antimono (λ x y hx, neg_le_neg hx)
lemma is_extr_filter.neg (hf : is_extr_filter f l a) : is_extr_filter (λ x, -f x) l a :=
hf.elim (λ hf, hf.neg.is_extr) (λ hf, hf.neg.is_extr)
lemma is_min_on.neg (hf : is_min_on f s a) : is_max_on (λ x, -f x) s a :=
hf.comp_antimono (λ x y hx, neg_le_neg hx)
lemma is_max_on.neg (hf : is_max_on f s a) : is_min_on (λ x, -f x) s a :=
hf.comp_antimono (λ x y hx, neg_le_neg hx)
lemma is_extr_on.neg (hf : is_extr_on f s a) : is_extr_on (λ x, -f x) s a :=
hf.elim (λ hf, hf.neg.is_extr) (λ hf, hf.neg.is_extr)
lemma is_min_filter.sub (hf : is_min_filter f l a) (hg : is_max_filter g l a) :
is_min_filter (λ x, f x - g x) l a :=
hf.add hg.neg
lemma is_max_filter.sub (hf : is_max_filter f l a) (hg : is_min_filter g l a) :
is_max_filter (λ x, f x - g x) l a :=
hf.add hg.neg
lemma is_min_on.sub (hf : is_min_on f s a) (hg : is_max_on g s a) :
is_min_on (λ x, f x - g x) s a :=
hf.add hg.neg
lemma is_max_on.sub (hf : is_max_on f s a) (hg : is_min_on g s a) :
is_max_on (λ x, f x - g x) s a :=
hf.add hg.neg
end ordered_add_comm_group
/-! ### Pointwise `sup`/`inf` -/
section semilattice_sup
variables [semilattice_sup β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.sup (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, f x ⊔ g x) l a :=
show is_min_filter (λ x, f x ⊔ g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, sup_le_sup hx hy) hg
lemma is_max_filter.sup (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, f x ⊔ g x) l a :=
show is_max_filter (λ x, f x ⊔ g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, sup_le_sup hx hy) hg
lemma is_min_on.sup (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, f x ⊔ g x) s a :=
hf.sup hg
lemma is_max_on.sup (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, f x ⊔ g x) s a :=
hf.sup hg
end semilattice_sup
section semilattice_inf
variables [semilattice_inf β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.inf (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, f x ⊓ g x) l a :=
show is_min_filter (λ x, f x ⊓ g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, inf_le_inf hx hy) hg
lemma is_max_filter.inf (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, f x ⊓ g x) l a :=
show is_max_filter (λ x, f x ⊓ g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, inf_le_inf hx hy) hg
lemma is_min_on.inf (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, f x ⊓ g x) s a :=
hf.inf hg
lemma is_max_on.inf (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, f x ⊓ g x) s a :=
hf.inf hg
end semilattice_inf
/-! ### Pointwise `min`/`max` -/
section decidable_linear_order
variables [decidable_linear_order β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.min (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, min (f x) (g x)) l a :=
show is_min_filter (λ x, min (f x) (g x)) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, min_le_min hx hy) hg
lemma is_max_filter.min (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, min (f x) (g x)) l a :=
show is_max_filter (λ x, min (f x) (g x)) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, min_le_min hx hy) hg
lemma is_min_on.min (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, min (f x) (g x)) s a :=
hf.min hg
lemma is_max_on.min (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, min (f x) (g x)) s a :=
hf.min hg
lemma is_min_filter.max (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, max (f x) (g x)) l a :=
show is_min_filter (λ x, max (f x) (g x)) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, max_le_max hx hy) hg
lemma is_max_filter.max (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, max (f x) (g x)) l a :=
show is_max_filter (λ x, max (f x) (g x)) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, max_le_max hx hy) hg
lemma is_min_on.max (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, max (f x) (g x)) s a :=
hf.max hg
lemma is_max_on.max (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, max (f x) (g x)) s a :=
hf.max hg
end decidable_linear_order
|
5cf989312a6275440919f61af24d4b41b5815cad | 94e33a31faa76775069b071adea97e86e218a8ee | /counterexamples/seminorm_lattice_not_distrib.lean | ca4c5798c29fb796c8ee1e12088b840e5984614f | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 3,284 | lean | /-
Copyright (c) 2022 Pierre-Alexandre Bazin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Pierre-Alexandre Bazin
-/
import analysis.seminorm
/-!
# The lattice of seminorms is not distributive
We provide an example of three seminorms over the ℝ-vector space ℝ×ℝ which don't satisfy the lattice
distributivity property `(p ⊔ q1) ⊓ (p ⊔ q2) ≤ p ⊔ (q1 ⊓ q2)`.
This proves the lattice `seminorm ℝ (ℝ × ℝ)` is not distributive.
## References
* https://en.wikipedia.org/wiki/Seminorm#Examples
-/
namespace seminorm_not_distrib
open_locale nnreal
private lemma bdd_below_range_add {𝕜 E : Type*} [normed_field 𝕜] [add_comm_group E] [module 𝕜 E]
(x : E) (p q : seminorm 𝕜 E) :
bdd_below (set.range (λ (u : E), p u + q (x - u))) :=
by { use 0, rintro _ ⟨x, rfl⟩, exact add_nonneg (p.nonneg _) (q.nonneg _) }
@[simps] noncomputable def p : seminorm ℝ (ℝ×ℝ) :=
(norm_seminorm ℝ ℝ).comp (linear_map.fst _ _ _) ⊔ (norm_seminorm ℝ ℝ).comp (linear_map.snd _ _ _)
@[simps] noncomputable def q1 : seminorm ℝ (ℝ×ℝ) :=
(4 : ℝ≥0) • (norm_seminorm ℝ ℝ).comp (linear_map.fst _ _ _)
@[simps] noncomputable def q2 : seminorm ℝ (ℝ×ℝ) :=
(4 : ℝ≥0) • (norm_seminorm ℝ ℝ).comp (linear_map.snd _ _ _)
lemma eq_one : (p ⊔ (q1 ⊓ q2)) (1, 1) = 1 :=
begin
suffices : (⨅ x : ℝ × ℝ, q1 x + q2 (1 - x)) ≤ 1, by simpa,
apply cinfi_le_of_le (bdd_below_range_add _ _ _) ((0, 1) : ℝ×ℝ), dsimp [q1, q2],
simp only [abs_zero, smul_zero, sub_self, add_zero, zero_le_one],
end
/-- This is a counterexample to the distributivity of the lattice `seminorm ℝ (ℝ × ℝ)`. -/
lemma not_distrib : ¬((p ⊔ q1) ⊓ (p ⊔ q2) ≤ p ⊔ (q1 ⊓ q2)) :=
begin
intro le_sup_inf,
have c : ¬(4/3 ≤ (1:ℝ)) := by norm_num,
apply c, nth_rewrite 2 ← eq_one,
apply le_trans _ (le_sup_inf _),
apply le_cinfi, intro x,
cases le_or_lt x.fst (1/3) with h1 h1,
{ cases le_or_lt x.snd (2/3) with h2 h2,
{ calc 4/3 = 4 * (1 - 2/3) : by norm_num
... ≤ 4 * (1 - x.snd) : (mul_le_mul_left zero_lt_four).mpr (sub_le_sub_left h2 _)
... ≤ 4 * |1 - x.snd| : (mul_le_mul_left zero_lt_four).mpr (le_abs_self _)
... = q2 ((1, 1) - x) : rfl
... ≤ (p ⊔ q2) ((1, 1) - x) : le_sup_right
... ≤ (p ⊔ q1) x + (p ⊔ q2) ((1, 1) - x) : le_add_of_nonneg_left ((p ⊔ q1).nonneg _) },
{ calc 4/3 = 2/3 + (1 - 1/3) : by norm_num
... ≤ x.snd + (1 - x.fst) : add_le_add (le_of_lt h2) (sub_le_sub_left h1 _)
... ≤ |x.snd| + |1 - x.fst| : add_le_add (le_abs_self _) (le_abs_self _)
... ≤ p x + p ((1, 1) - x) : add_le_add le_sup_right le_sup_left
... ≤ (p ⊔ q1) x + (p ⊔ q2) ((1, 1) - x) : add_le_add le_sup_left le_sup_left } },
{ calc 4/3 = 4 * (1/3) : by norm_num
... ≤ 4 * x.fst : (mul_le_mul_left zero_lt_four).mpr (le_of_lt h1)
... ≤ 4 * |x.fst| : (mul_le_mul_left zero_lt_four).mpr (le_abs_self _)
... = q1 x : rfl
... ≤ (p ⊔ q1) x : le_sup_right
... ≤ (p ⊔ q1) x + (p ⊔ q2) ((1, 1) - x) : le_add_of_nonneg_right ((p ⊔ q2).nonneg _) }
end
end seminorm_not_distrib
|
017d5b8c24c656dc53502859353ef93600576c5c | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /hott/algebra/category/iso.hlean | 247e0fc6d1c35595585cab555602df7c24dc55eb | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,780 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn, Jakob von Raumer
-/
import .precategory types.sigma arity
open eq category prod equiv is_equiv sigma sigma.ops is_trunc
namespace iso
structure split_mono [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) :=
{retraction_of : b ⟶ a}
(retraction_comp : retraction_of ∘ f = id)
structure split_epi [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) :=
{section_of : b ⟶ a}
(comp_section : f ∘ section_of = id)
structure is_iso [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) :=
{inverse : b ⟶ a}
(left_inverse : inverse ∘ f = id)
(right_inverse : f ∘ inverse = id)
attribute is_iso.inverse [quasireducible]
attribute is_iso [multiple-instances]
open split_mono split_epi is_iso
abbreviation retraction_of [unfold 6] := @split_mono.retraction_of
abbreviation retraction_comp [unfold 6] := @split_mono.retraction_comp
abbreviation section_of [unfold 6] := @split_epi.section_of
abbreviation comp_section [unfold 6] := @split_epi.comp_section
abbreviation inverse [unfold 6] := @is_iso.inverse
abbreviation left_inverse [unfold 6] := @is_iso.left_inverse
abbreviation right_inverse [unfold 6] := @is_iso.right_inverse
postfix ⁻¹ := inverse
--a second notation for the inverse, which is not overloaded
postfix [parsing-only] `⁻¹ʰ`:std.prec.max_plus := inverse -- input using \-1h
variables {ob : Type} [C : precategory ob]
variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a}
include C
definition split_mono_of_is_iso [instance] [priority 300] [reducible]
(f : a ⟶ b) [H : is_iso f] : split_mono f :=
split_mono.mk !left_inverse
definition split_epi_of_is_iso [instance] [priority 300] [reducible]
(f : a ⟶ b) [H : is_iso f] : split_epi f :=
split_epi.mk !right_inverse
definition is_iso_id [instance] [priority 500] (a : ob) : is_iso (ID a) :=
is_iso.mk !id_id !id_id
definition is_iso_inverse [instance] [priority 200] (f : a ⟶ b) [H : is_iso f] : is_iso f⁻¹ :=
is_iso.mk !right_inverse !left_inverse
definition left_inverse_eq_right_inverse {f : a ⟶ b} {g g' : hom b a}
(Hl : g ∘ f = id) (Hr : f ∘ g' = id) : g = g' :=
by rewrite [-(id_right g), -Hr, assoc, Hl, id_left]
definition retraction_eq [H : split_mono f] (H2 : f ∘ h = id) : retraction_of f = h :=
left_inverse_eq_right_inverse !retraction_comp H2
definition section_eq [H : split_epi f] (H2 : h ∘ f = id) : section_of f = h :=
(left_inverse_eq_right_inverse H2 !comp_section)⁻¹
definition inverse_eq_right [H : is_iso f] (H2 : f ∘ h = id) : f⁻¹ = h :=
left_inverse_eq_right_inverse !left_inverse H2
definition inverse_eq_left [H : is_iso f] (H2 : h ∘ f = id) : f⁻¹ = h :=
(left_inverse_eq_right_inverse H2 !right_inverse)⁻¹
definition retraction_eq_section (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f] :
retraction_of f = section_of f :=
retraction_eq !comp_section
definition is_iso_of_split_epi_of_split_mono (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f]
: is_iso f :=
is_iso.mk ((retraction_eq_section f) ▸ (retraction_comp f)) (comp_section f)
definition inverse_unique (H H' : is_iso f) : @inverse _ _ _ _ f H = @inverse _ _ _ _ f H' :=
inverse_eq_left !left_inverse
definition inverse_involutive (f : a ⟶ b) [H : is_iso f] [H : is_iso (f⁻¹)]
: (f⁻¹)⁻¹ = f :=
inverse_eq_right !left_inverse
definition inverse_eq_inverse {f g : a ⟶ b} [H : is_iso f] [H : is_iso g] (p : f = g)
: f⁻¹ = g⁻¹ :=
by cases p;apply inverse_unique
definition retraction_id (a : ob) : retraction_of (ID a) = id :=
retraction_eq !id_id
definition section_id (a : ob) : section_of (ID a) = id :=
section_eq !id_id
definition id_inverse (a : ob) [H : is_iso (ID a)] : (ID a)⁻¹ = id :=
inverse_eq_left !id_id
definition split_mono_comp [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b)
[Hf : split_mono f] [Hg : split_mono g] : split_mono (g ∘ f) :=
split_mono.mk
(show (retraction_of f ∘ retraction_of g) ∘ g ∘ f = id,
by rewrite [-assoc, assoc _ g f, retraction_comp, id_left, retraction_comp])
definition split_epi_comp [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b)
[Hf : split_epi f] [Hg : split_epi g] : split_epi (g ∘ f) :=
split_epi.mk
(show (g ∘ f) ∘ section_of f ∘ section_of g = id,
by rewrite [-assoc, {f ∘ _}assoc, comp_section, id_left, comp_section])
definition is_iso_comp [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b)
[Hf : is_iso f] [Hg : is_iso g] : is_iso (g ∘ f) :=
!is_iso_of_split_epi_of_split_mono
definition is_hprop_is_iso [instance] (f : hom a b) : is_hprop (is_iso f) :=
begin
apply is_hprop.mk, intro H H',
cases H with g li ri, cases H' with g' li' ri',
fapply (apd0111 (@is_iso.mk ob C a b f)),
apply left_inverse_eq_right_inverse,
apply li,
apply ri',
apply is_hprop.elim,
apply is_hprop.elim,
end
end iso open iso
/- isomorphic objects -/
structure iso {ob : Type} [C : precategory ob] (a b : ob) :=
(to_hom : hom a b)
[struct : is_iso to_hom]
infix ` ≅ `:50 := iso
attribute iso.struct [instance] [priority 4000]
namespace iso
variables {ob : Type} [C : precategory ob]
variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a}
include C
attribute to_hom [coercion]
protected definition MK [constructor] (f : a ⟶ b) (g : b ⟶ a)
(H1 : g ∘ f = id) (H2 : f ∘ g = id) :=
@(mk f) (is_iso.mk H1 H2)
variable {C}
definition to_inv [unfold 5] (f : a ≅ b) : b ⟶ a := (to_hom f)⁻¹
definition to_left_inverse [unfold 5] (f : a ≅ b) : (to_hom f)⁻¹ ∘ (to_hom f) = id :=
left_inverse (to_hom f)
definition to_right_inverse [unfold 5] (f : a ≅ b) : (to_hom f) ∘ (to_hom f)⁻¹ = id :=
right_inverse (to_hom f)
variable [C]
protected definition refl [constructor] (a : ob) : a ≅ a :=
mk (ID a)
protected definition symm [constructor] ⦃a b : ob⦄ (H : a ≅ b) : b ≅ a :=
mk (to_hom H)⁻¹
protected definition trans [constructor] ⦃a b c : ob⦄ (H1 : a ≅ b) (H2 : b ≅ c) : a ≅ c :=
mk (to_hom H2 ∘ to_hom H1)
infixl ` ⬝i `:75 := iso.trans
postfix [parsing-only] `⁻¹ⁱ`:(max + 1) := iso.symm
definition iso_mk_eq {f f' : a ⟶ b} [H : is_iso f] [H' : is_iso f'] (p : f = f')
: iso.mk f = iso.mk f' :=
apd011 iso.mk p !is_hprop.elim
variable {C}
definition iso_eq {f f' : a ≅ b} (p : to_hom f = to_hom f') : f = f' :=
by (cases f; cases f'; apply (iso_mk_eq p))
variable [C]
-- The structure for isomorphism can be characterized up to equivalence by a sigma type.
protected definition sigma_char ⦃a b : ob⦄ : (Σ (f : hom a b), is_iso f) ≃ (a ≅ b) :=
begin
fapply (equiv.mk),
{intro S, apply iso.mk, apply (S.2)},
{fapply adjointify,
{intro p, cases p with f H, exact sigma.mk f H},
{intro p, cases p, apply idp},
{intro S, cases S, apply idp}},
end
-- The type of isomorphisms between two objects is a set
definition is_hset_iso [instance] : is_hset (a ≅ b) :=
begin
apply is_trunc_is_equiv_closed,
apply equiv.to_is_equiv (!iso.sigma_char),
end
definition iso_of_eq [unfold 5] (p : a = b) : a ≅ b :=
eq.rec_on p (iso.refl a)
definition hom_of_eq [reducible] [unfold 5] (p : a = b) : a ⟶ b :=
iso.to_hom (iso_of_eq p)
definition inv_of_eq [reducible] [unfold 5] (p : a = b) : b ⟶ a :=
iso.to_inv (iso_of_eq p)
definition iso_of_eq_inv (p : a = b) : iso_of_eq p⁻¹ = iso.symm (iso_of_eq p) :=
eq.rec_on p idp
definition iso_of_eq_con (p : a = b) (q : b = c)
: iso_of_eq (p ⬝ q) = iso.trans (iso_of_eq p) (iso_of_eq q) :=
eq.rec_on q (eq.rec_on p (iso_eq !id_id⁻¹))
section
open funext
variables {X : Type} {x y : X} {F G : X → ob}
definition transport_hom_of_eq (p : F = G) (f : hom (F x) (F y))
: p ▸ f = hom_of_eq (apd10 p y) ∘ f ∘ inv_of_eq (apd10 p x) :=
by induction p; exact !id_leftright⁻¹
definition transport_hom_of_eq_right (p : x = y) (f : hom c (F x))
: p ▸ f = hom_of_eq (ap F p) ∘ f :=
by induction p; exact !id_left⁻¹
definition transport_hom_of_eq_left (p : x = y) (f : hom (F x) c)
: p ▸ f = f ∘ inv_of_eq (ap F p) :=
by induction p; exact !id_right⁻¹
definition transport_hom (p : F ~ G) (f : hom (F x) (F y))
: eq_of_homotopy p ▸ f = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) :=
calc
eq_of_homotopy p ▸ f =
hom_of_eq (apd10 (eq_of_homotopy p) y) ∘ f ∘ inv_of_eq (apd10 (eq_of_homotopy p) x)
: transport_hom_of_eq
... = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) : {right_inv apd10 p}
end
structure mono [class] (f : a ⟶ b) :=
(elim : ∀c (g h : hom c a), f ∘ g = f ∘ h → g = h)
structure epi [class] (f : a ⟶ b) :=
(elim : ∀c (g h : hom b c), g ∘ f = h ∘ f → g = h)
definition mono_of_split_mono [instance] (f : a ⟶ b) [H : split_mono f] : mono f :=
mono.mk
(λ c g h H,
calc
g = id ∘ g : by rewrite id_left
... = (retraction_of f ∘ f) ∘ g : by rewrite retraction_comp
... = (retraction_of f ∘ f) ∘ h : by rewrite [-assoc, H, -assoc]
... = id ∘ h : by rewrite retraction_comp
... = h : by rewrite id_left)
definition epi_of_split_epi [instance] (f : a ⟶ b) [H : split_epi f] : epi f :=
epi.mk
(λ c g h H,
calc
g = g ∘ id : by rewrite id_right
... = g ∘ f ∘ section_of f : by rewrite -(comp_section f)
... = h ∘ f ∘ section_of f : by rewrite [assoc, H, -assoc]
... = h ∘ id : by rewrite comp_section
... = h : by rewrite id_right)
definition mono_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : mono f] [Hg : mono g]
: mono (g ∘ f) :=
mono.mk
(λ d h₁ h₂ H,
have H2 : g ∘ (f ∘ h₁) = g ∘ (f ∘ h₂),
begin
rewrite *assoc, exact H
end,
!mono.elim (!mono.elim H2))
definition epi_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : epi f] [Hg : epi g]
: epi (g ∘ f) :=
epi.mk
(λ d h₁ h₂ H,
have H2 : (h₁ ∘ g) ∘ f = (h₂ ∘ g) ∘ f,
begin
rewrite -*assoc, exact H
end,
!epi.elim (!epi.elim H2))
end iso
namespace iso
/-
rewrite lemmas for inverses, modified from
https://github.com/JasonGross/HoTT-categories/blob/master/theories/Categories/Category/Morphisms.v
-/
section
variables {ob : Type} [C : precategory ob] include C
variables {a b c d : ob} (f : b ⟶ a)
(r : c ⟶ d) (q : b ⟶ c) (p : a ⟶ b)
(g : d ⟶ c)
variable [Hq : is_iso q] include Hq
definition comp.right_inverse : q ∘ q⁻¹ = id := !right_inverse
definition comp.left_inverse : q⁻¹ ∘ q = id := !left_inverse
definition inverse_comp_cancel_left : q⁻¹ ∘ (q ∘ p) = p :=
by rewrite [assoc, left_inverse, id_left]
definition comp_inverse_cancel_left : q ∘ (q⁻¹ ∘ g) = g :=
by rewrite [assoc, right_inverse, id_left]
definition comp_inverse_cancel_right : (r ∘ q) ∘ q⁻¹ = r :=
by rewrite [-assoc, right_inverse, id_right]
definition inverse_comp_cancel_right : (f ∘ q⁻¹) ∘ q = f :=
by rewrite [-assoc, left_inverse, id_right]
definition comp_inverse [Hp : is_iso p] [Hpq : is_iso (q ∘ p)] : (q ∘ p)⁻¹ʰ = p⁻¹ʰ ∘ q⁻¹ʰ :=
inverse_eq_left
(show (p⁻¹ʰ ∘ q⁻¹ʰ) ∘ q ∘ p = id, from
by rewrite [-assoc, inverse_comp_cancel_left, left_inverse])
definition inverse_comp_inverse_left [H' : is_iso g] : (q⁻¹ ∘ g)⁻¹ = g⁻¹ ∘ q :=
inverse_involutive q ▸ comp_inverse q⁻¹ g
definition inverse_comp_inverse_right [H' : is_iso f] : (q ∘ f⁻¹)⁻¹ = f ∘ q⁻¹ :=
inverse_involutive f ▸ comp_inverse q f⁻¹
definition inverse_comp_inverse_inverse [H' : is_iso r] : (q⁻¹ ∘ r⁻¹)⁻¹ = r ∘ q :=
inverse_involutive r ▸ inverse_comp_inverse_left q r⁻¹
end
section
variables {ob : Type} {C : precategory ob} include C
variables {d c b a : ob}
{i : b ⟶ c} {f : b ⟶ a}
{r : c ⟶ d} {q : b ⟶ c} {p : a ⟶ b}
{g : d ⟶ c} {h : c ⟶ b}
{x : b ⟶ d} {z : a ⟶ c}
{y : d ⟶ b} {w : c ⟶ a}
variable [Hq : is_iso q] include Hq
definition comp_eq_of_eq_inverse_comp (H : y = q⁻¹ ∘ g) : q ∘ y = g :=
H⁻¹ ▸ comp_inverse_cancel_left q g
definition comp_eq_of_eq_comp_inverse (H : w = f ∘ q⁻¹) : w ∘ q = f :=
H⁻¹ ▸ inverse_comp_cancel_right f q
definition eq_comp_of_inverse_comp_eq (H : q⁻¹ ∘ g = y) : g = q ∘ y :=
(comp_eq_of_eq_inverse_comp H⁻¹)⁻¹
definition eq_comp_of_comp_inverse_eq (H : f ∘ q⁻¹ = w) : f = w ∘ q :=
(comp_eq_of_eq_comp_inverse H⁻¹)⁻¹
variable {Hq}
definition inverse_comp_eq_of_eq_comp (H : z = q ∘ p) : q⁻¹ ∘ z = p :=
H⁻¹ ▸ inverse_comp_cancel_left q p
definition comp_inverse_eq_of_eq_comp (H : x = r ∘ q) : x ∘ q⁻¹ = r :=
H⁻¹ ▸ comp_inverse_cancel_right r q
definition eq_inverse_comp_of_comp_eq (H : q ∘ p = z) : p = q⁻¹ ∘ z :=
(inverse_comp_eq_of_eq_comp H⁻¹)⁻¹
definition eq_comp_inverse_of_comp_eq (H : r ∘ q = x) : r = x ∘ q⁻¹ :=
(comp_inverse_eq_of_eq_comp H⁻¹)⁻¹
definition eq_inverse_of_comp_eq_id' (H : h ∘ q = id) : h = q⁻¹ := (inverse_eq_left H)⁻¹
definition eq_inverse_of_comp_eq_id (H : q ∘ h = id) : h = q⁻¹ := (inverse_eq_right H)⁻¹
definition inverse_eq_of_id_eq_comp (H : id = h ∘ q) : q⁻¹ = h :=
(eq_inverse_of_comp_eq_id' H⁻¹)⁻¹
definition inverse_eq_of_id_eq_comp' (H : id = q ∘ h) : q⁻¹ = h :=
(eq_inverse_of_comp_eq_id H⁻¹)⁻¹
variable [Hq]
definition eq_of_comp_inverse_eq_id (H : i ∘ q⁻¹ = id) : i = q :=
eq_inverse_of_comp_eq_id' H ⬝ inverse_involutive q
definition eq_of_inverse_comp_eq_id (H : q⁻¹ ∘ i = id) : i = q :=
eq_inverse_of_comp_eq_id H ⬝ inverse_involutive q
definition eq_of_id_eq_comp_inverse (H : id = i ∘ q⁻¹) : q = i := (eq_of_comp_inverse_eq_id H⁻¹)⁻¹
definition eq_of_id_eq_inverse_comp (H : id = q⁻¹ ∘ i) : q = i := (eq_of_inverse_comp_eq_id H⁻¹)⁻¹
end
end iso
|
a2d4ef359d1a1ad9b1b8d22979b2ceb4f0a118ff | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/control/basic.lean | d5ee38648ff4efa1d0a2c432c2dc6ea370200a71 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 6,673 | 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
Extends the theory on functors, applicatives and monads.
-/
import tactic.mk_simp_attribute
universes u v w
variables {α β γ : Type u}
notation a ` $< `:1 f:1 := f a
section functor
variables {f : Type u → Type v} [functor f] [is_lawful_functor f]
@[functor_norm] theorem functor.map_map (m : α → β) (g : β → γ) (x : f α) :
g <$> (m <$> x) = (g ∘ m) <$> x :=
(comp_map _ _ _).symm
@[simp] theorem id_map' (x : f α) : (λa, a) <$> x = x := id_map _
end functor
section applicative
variables {F : Type u → Type v} [applicative F]
def mzip_with
{α₁ α₂ φ : Type u}
(f : α₁ → α₂ → F φ) :
Π (ma₁ : list α₁) (ma₂: list α₂), F (list φ)
| (x :: xs) (y :: ys) := (::) <$> f x y <*> mzip_with xs ys
| _ _ := pure []
def mzip_with' (f : α → β → F γ) : list α → list β → F punit
| (x :: xs) (y :: ys) := f x y *> mzip_with' xs ys
| [] _ := pure punit.star
| _ [] := pure punit.star
variables [is_lawful_applicative F]
attribute [functor_norm] seq_assoc pure_seq_eq_map
@[simp] theorem pure_id'_seq (x : F α) : pure (λx, x) <*> x = x :=
pure_id_seq x
attribute [functor_norm] seq_assoc pure_seq_eq_map
@[functor_norm] theorem seq_map_assoc (x : F (α → β)) (f : γ → α) (y : F γ) :
(x <*> (f <$> y)) = (λ(m:α→β), m ∘ f) <$> x <*> y :=
begin
simp [(pure_seq_eq_map _ _).symm],
simp [seq_assoc, (comp_map _ _ _).symm, (∘)],
simp [pure_seq_eq_map]
end
@[functor_norm] theorem map_seq (f : β → γ) (x : F (α → β)) (y : F α) :
(f <$> (x <*> y)) = ((∘) f) <$> x <*> y :=
by simp [(pure_seq_eq_map _ _).symm]; simp [seq_assoc]
end applicative
-- TODO: setup `functor_norm` for `monad` laws
attribute [functor_norm] pure_bind bind_assoc bind_pure
section monad
variables {m : Type u → Type v} [monad m] [is_lawful_monad m]
open list
def list.mpartition {f : Type → Type} [monad f] {α : Type} (p : α → f bool) :
list α → f (list α × list α)
| [] := pure ([],[])
| (x :: xs) :=
mcond (p x) (prod.map (cons x) id <$> list.mpartition xs)
(prod.map id (cons x) <$> list.mpartition xs)
lemma map_bind (x : m α) {g : α → m β} {f : β → γ} : f <$> (x >>= g) = (x >>= λa, f <$> g a) :=
by rw [← bind_pure_comp_eq_map,bind_assoc]; simp [bind_pure_comp_eq_map]
lemma seq_bind_eq (x : m α) {g : β → m γ} {f : α → β} : (f <$> x) >>= g = (x >>= g ∘ f) :=
show bind (f <$> x) g = bind x (g ∘ f),
by rw [← bind_pure_comp_eq_map, bind_assoc]; simp [pure_bind]
@[monad_norm]
lemma seq_eq_bind_map {x : m α} {f : m (α → β)} : f <*> x = (f >>= (<$> x)) :=
(bind_map_eq_seq f x).symm
/-- This is the Kleisli composition -/
@[reducible] def fish {m} [monad m] {α β γ} (f : α → m β) (g : β → m γ) := λ x, f x >>= g
-- >=> is already defined in the core library but it is unusable
-- because of its precedence (it is defined with precedence 2) and
-- because it is defined as a lambda instead of having a named
-- function
infix ` >=> `:55 := fish
@[functor_norm]
lemma fish_pure {α β} (f : α → m β) : f >=> pure = f :=
by simp only [(>=>)] with functor_norm
@[functor_norm]
lemma fish_pipe {α β} (f : α → m β) : pure >=> f = f :=
by simp only [(>=>)] with functor_norm
@[functor_norm]
lemma fish_assoc {α β γ φ} (f : α → m β) (g : β → m γ) (h : γ → m φ) :
(f >=> g) >=> h = f >=> (g >=> h) :=
by simp only [(>=>)] with functor_norm
variables {β' γ' : Type v}
variables {m' : Type v → Type w} [monad m']
def list.mmap_accumr (f : α → β' → m' (β' × γ')) : β' → list α → m' (β' × list γ')
| a [] := pure (a,[])
| a (x :: xs) :=
do (a',ys) ← list.mmap_accumr a xs,
(a'',y) ← f x a',
pure (a'',y::ys)
def list.mmap_accuml (f : β' → α → m' (β' × γ')) : β' → list α → m' (β' × list γ')
| a [] := pure (a,[])
| a (x :: xs) :=
do (a',y) ← f a x,
(a'',ys) ← list.mmap_accuml a' xs,
pure (a'',y :: ys)
end monad
section
variables {m : Type u → Type u} [monad m] [is_lawful_monad m]
lemma mjoin_map_map {α β : Type u} (f : α → β) (a : m (m α)) :
mjoin (functor.map f <$> a) = f <$> (mjoin a) :=
by simp only [mjoin, (∘), id.def,
(bind_pure_comp_eq_map _ _).symm, bind_assoc, map_bind, pure_bind]
lemma mjoin_map_mjoin {α : Type u} (a : m (m (m α))) :
mjoin (mjoin <$> a) = mjoin (mjoin a) :=
by simp only [mjoin, (∘), id.def,
map_bind, (bind_pure_comp_eq_map _ _).symm, bind_assoc, pure_bind]
@[simp] lemma mjoin_map_pure {α : Type u} (a : m α) :
mjoin (pure <$> a) = a :=
by simp only [mjoin, (∘), id.def,
map_bind, (bind_pure_comp_eq_map _ _).symm, bind_assoc, pure_bind, bind_pure]
@[simp] lemma mjoin_pure {α : Type u} (a : m α) : mjoin (pure a) = a :=
is_lawful_monad.pure_bind a id
end
section alternative
variables {F : Type → Type v} [alternative F]
def succeeds {α} (x : F α) : F bool := (x $> tt) <|> pure ff
def mtry {α} (x : F α) : F unit := (x $> ()) <|> pure ()
@[simp] theorem guard_true {h : decidable true} :
@guard F _ true h = pure () := by simp [guard]
@[simp] theorem guard_false {h : decidable false} :
@guard F _ false h = failure := by simp [guard]
end alternative
namespace sum
variables {e : Type v}
protected def bind {α β} : e ⊕ α → (α → e ⊕ β) → e ⊕ β
| (inl x) _ := inl x
| (inr x) f := f x
instance : monad (sum.{v u} e) :=
{ pure := @sum.inr e,
bind := @sum.bind e }
instance : is_lawful_functor (sum.{v u} e) :=
by refine { .. }; intros; casesm _ ⊕ _; refl
instance : is_lawful_monad (sum.{v u} e) :=
{ bind_assoc := by { intros, casesm _ ⊕ _; refl },
pure_bind := by { intros, refl },
bind_pure_comp_eq_map := by { intros, casesm _ ⊕ _; refl },
bind_map_eq_seq := by { intros, cases f; refl } }
end sum
class is_comm_applicative (m : Type* → Type*) [applicative m] extends is_lawful_applicative m :
Prop :=
(commutative_prod : ∀{α β} (a : m α) (b : m β), prod.mk <$> a <*> b = (λb a, (a, b)) <$> b <*> a)
open functor
lemma is_comm_applicative.commutative_map
{m : Type* → Type*} [applicative m] [is_comm_applicative m]
{α β γ} (a : m α) (b : m β) {f : α → β → γ} :
f <$> a <*> b = flip f <$> b <*> a :=
calc f <$> a <*> b = (λp:α×β, f p.1 p.2) <$> (prod.mk <$> a <*> b) :
by simp [seq_map_assoc, map_seq, seq_assoc, seq_pure, map_map]
... = (λb a, f a b) <$> b <*> a :
by rw [is_comm_applicative.commutative_prod];
simp [seq_map_assoc, map_seq, seq_assoc, seq_pure, map_map]
|
db0b5b712b09a44ec7ac6c145a43431af67f89b4 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/indicator_function.lean | 8d697ad85304f0d8bdc0020122f11d30d477a9d4 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 25,431 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import algebra.support
/-!
# Indicator function
- `indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `0` otherwise.
- `mul_indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `1` otherwise.
## Implementation note
In mathematics, an indicator function or a characteristic function is a function
used to indicate membership of an element in a set `s`,
having the value `1` for all elements of `s` and the value `0` otherwise.
But since it is usually used to restrict a function to a certain set `s`,
we let the indicator function take the value `f x` for some function `f`, instead of `1`.
If the usual indicator function is needed, just set `f` to be the constant function `λx, 1`.
The indicator function is implemented non-computably, to avoid having to pass around `decidable`
arguments. This is in contrast with the design of `pi.single` or `set.piecewise`.
## Tags
indicator, characteristic
-/
open_locale big_operators
open function
variables {α β ι M N : Type*}
namespace set
section has_one
variables [has_one M] [has_one N] {s t : set α} {f g : α → M} {a : α}
/-- `indicator s f a` is `f a` if `a ∈ s`, `0` otherwise. -/
noncomputable def indicator {M} [has_zero M] (s : set α) (f : α → M) : α → M
| x := by haveI := classical.dec_pred (∈ s); exact if x ∈ s then f x else 0
/-- `mul_indicator s f a` is `f a` if `a ∈ s`, `1` otherwise. -/
@[to_additive]
noncomputable def mul_indicator (s : set α) (f : α → M) : α → M
| x := by haveI := classical.dec_pred (∈ s); exact if x ∈ s then f x else 1
@[simp, to_additive] lemma piecewise_eq_mul_indicator [decidable_pred (∈ s)] :
s.piecewise f 1 = s.mul_indicator f :=
funext $ λ x, @if_congr _ _ _ _ (id _) _ _ _ _ iff.rfl rfl rfl
@[to_additive] lemma mul_indicator_apply (s : set α) (f : α → M) (a : α) [decidable (a ∈ s)] :
mul_indicator s f a = if a ∈ s then f a else 1 := by convert rfl
@[simp, to_additive] lemma mul_indicator_of_mem (h : a ∈ s) (f : α → M) :
mul_indicator s f a = f a :=
by { letI := classical.dec (a ∈ s), exact if_pos h }
@[simp, to_additive] lemma mul_indicator_of_not_mem (h : a ∉ s) (f : α → M) :
mul_indicator s f a = 1 :=
by { letI := classical.dec (a ∈ s), exact if_neg h }
@[to_additive] lemma mul_indicator_eq_one_or_self (s : set α) (f : α → M) (a : α) :
mul_indicator s f a = 1 ∨ mul_indicator s f a = f a :=
begin
by_cases h : a ∈ s,
{ exact or.inr (mul_indicator_of_mem h f) },
{ exact or.inl (mul_indicator_of_not_mem h f) }
end
@[simp, to_additive] lemma mul_indicator_apply_eq_self :
s.mul_indicator f a = f a ↔ (a ∉ s → f a = 1) :=
by letI := classical.dec (a ∈ s); exact ite_eq_left_iff.trans (by rw [@eq_comm _ (f a)])
@[simp, to_additive] lemma mul_indicator_eq_self : s.mul_indicator f = f ↔ mul_support f ⊆ s :=
by simp only [funext_iff, subset_def, mem_mul_support, mul_indicator_apply_eq_self, not_imp_comm]
@[to_additive] lemma mul_indicator_eq_self_of_superset (h1 : s.mul_indicator f = f) (h2 : s ⊆ t) :
t.mul_indicator f = f :=
by { rw mul_indicator_eq_self at h1 ⊢, exact subset.trans h1 h2 }
@[simp, to_additive] lemma mul_indicator_apply_eq_one :
mul_indicator s f a = 1 ↔ (a ∈ s → f a = 1) :=
by letI := classical.dec (a ∈ s); exact ite_eq_right_iff
@[simp, to_additive] lemma mul_indicator_eq_one :
mul_indicator s f = (λ x, 1) ↔ disjoint (mul_support f) s :=
by simp only [funext_iff, mul_indicator_apply_eq_one, set.disjoint_left, mem_mul_support,
not_imp_not]
@[simp, to_additive] lemma mul_indicator_eq_one' :
mul_indicator s f = 1 ↔ disjoint (mul_support f) s :=
mul_indicator_eq_one
@[to_additive] lemma mul_indicator_apply_ne_one {a : α} :
s.mul_indicator f a ≠ 1 ↔ a ∈ s ∩ mul_support f :=
by simp only [ne.def, mul_indicator_apply_eq_one, not_imp, mem_inter_eq, mem_mul_support]
@[simp, to_additive] lemma mul_support_mul_indicator :
function.mul_support (s.mul_indicator f) = s ∩ function.mul_support f :=
ext $ λ x, by simp [function.mem_mul_support, mul_indicator_apply_eq_one]
/-- If a multiplicative indicator function is not equal to `1` at a point, then that point is in the
set. -/
@[to_additive "If an additive indicator function is not equal to `0` at a point, then that point is
in the set."]
lemma mem_of_mul_indicator_ne_one (h : mul_indicator s f a ≠ 1) : a ∈ s :=
not_imp_comm.1 (λ hn, mul_indicator_of_not_mem hn f) h
@[to_additive] lemma eq_on_mul_indicator : eq_on (mul_indicator s f) f s :=
λ x hx, mul_indicator_of_mem hx f
@[to_additive] lemma mul_support_mul_indicator_subset : mul_support (s.mul_indicator f) ⊆ s :=
λ x hx, hx.imp_symm (λ h, mul_indicator_of_not_mem h f)
@[simp, to_additive] lemma mul_indicator_mul_support : mul_indicator (mul_support f) f = f :=
mul_indicator_eq_self.2 subset.rfl
@[simp, to_additive] lemma mul_indicator_range_comp {ι : Sort*} (f : ι → α) (g : α → M) :
mul_indicator (range f) g ∘ f = g ∘ f :=
by letI := classical.dec_pred (∈ range f); exact piecewise_range_comp _ _ _
@[to_additive] lemma mul_indicator_congr (h : eq_on f g s) :
mul_indicator s f = mul_indicator s g :=
funext $ λx, by { simp only [mul_indicator], split_ifs, { exact h h_1 }, refl }
@[simp, to_additive] lemma mul_indicator_univ (f : α → M) : mul_indicator (univ : set α) f = f :=
mul_indicator_eq_self.2 $ subset_univ _
@[simp, to_additive] lemma mul_indicator_empty (f : α → M) : mul_indicator (∅ : set α) f = λa, 1 :=
mul_indicator_eq_one.2 $ disjoint_empty _
@[to_additive] lemma mul_indicator_empty' (f : α → M) : mul_indicator (∅ : set α) f = 1 :=
mul_indicator_empty f
variable (M)
@[simp, to_additive] lemma mul_indicator_one (s : set α) :
mul_indicator s (λx, (1:M)) = λx, (1:M) :=
mul_indicator_eq_one.2 $ by simp only [mul_support_one, empty_disjoint]
@[simp, to_additive] lemma mul_indicator_one' {s : set α} : s.mul_indicator (1 : α → M) = 1 :=
mul_indicator_one M s
variable {M}
@[to_additive] lemma mul_indicator_mul_indicator (s t : set α) (f : α → M) :
mul_indicator s (mul_indicator t f) = mul_indicator (s ∩ t) f :=
funext $ λx, by { simp only [mul_indicator], split_ifs, repeat {simp * at * {contextual := tt}} }
@[simp, to_additive] lemma mul_indicator_inter_mul_support (s : set α) (f : α → M) :
mul_indicator (s ∩ mul_support f) f = mul_indicator s f :=
by rw [← mul_indicator_mul_indicator, mul_indicator_mul_support]
@[to_additive] lemma comp_mul_indicator (h : M → β) (f : α → M) {s : set α} {x : α}
[decidable_pred (∈ s)] :
h (s.mul_indicator f x) = s.piecewise (h ∘ f) (const α (h 1)) x :=
by letI := classical.dec_pred (∈ s); convert s.apply_piecewise f (const α 1) (λ _, h)
@[to_additive] lemma mul_indicator_comp_right {s : set α} (f : β → α) {g : α → M} {x : β} :
mul_indicator (f ⁻¹' s) (g ∘ f) x = mul_indicator s g (f x) :=
by { simp only [mul_indicator], split_ifs; refl }
@[to_additive] lemma mul_indicator_image {s : set α} {f : β → M} {g : α → β} (hg : injective g)
{x : α} : mul_indicator (g '' s) f (g x) = mul_indicator s (f ∘ g) x :=
by rw [← mul_indicator_comp_right, preimage_image_eq _ hg]
@[to_additive] lemma mul_indicator_comp_of_one {g : M → N} (hg : g 1 = 1) :
mul_indicator s (g ∘ f) = g ∘ (mul_indicator s f) :=
begin
funext,
simp only [mul_indicator],
split_ifs; simp [*]
end
@[to_additive] lemma comp_mul_indicator_const (c : M) (f : M → N) (hf : f 1 = 1) :
(λ x, f (s.mul_indicator (λ x, c) x)) = s.mul_indicator (λ x, f c) :=
(mul_indicator_comp_of_one hf).symm
@[to_additive] lemma mul_indicator_preimage (s : set α) (f : α → M) (B : set M) :
(mul_indicator s f)⁻¹' B = s.ite (f ⁻¹' B) (1 ⁻¹' B) :=
by letI := classical.dec_pred (∈ s); exact piecewise_preimage s f 1 B
@[to_additive] lemma mul_indicator_preimage_of_not_mem (s : set α) (f : α → M)
{t : set M} (ht : (1:M) ∉ t) :
(mul_indicator s f)⁻¹' t = f ⁻¹' t ∩ s :=
by simp [mul_indicator_preimage, pi.one_def, set.preimage_const_of_not_mem ht]
@[to_additive] lemma mem_range_mul_indicator {r : M} {s : set α} {f : α → M} :
r ∈ range (mul_indicator s f) ↔ (r = 1 ∧ s ≠ univ) ∨ (r ∈ f '' s) :=
by simp [mul_indicator, ite_eq_iff, exists_or_distrib, eq_univ_iff_forall, and_comm, or_comm,
@eq_comm _ r 1]
@[to_additive] lemma mul_indicator_rel_mul_indicator {r : M → M → Prop} (h1 : r 1 1)
(ha : a ∈ s → r (f a) (g a)) :
r (mul_indicator s f a) (mul_indicator s g a) :=
by { simp only [mul_indicator], split_ifs with has has, exacts [ha has, h1] }
end has_one
section monoid
variables [mul_one_class M] {s t : set α} {f g : α → M} {a : α}
@[to_additive] lemma mul_indicator_union_mul_inter_apply (f : α → M) (s t : set α) (a : α) :
mul_indicator (s ∪ t) f a * mul_indicator (s ∩ t) f a =
mul_indicator s f a * mul_indicator t f a :=
by by_cases hs : a ∈ s; by_cases ht : a ∈ t; simp *
@[to_additive] lemma mul_indicator_union_mul_inter (f : α → M) (s t : set α) :
mul_indicator (s ∪ t) f * mul_indicator (s ∩ t) f = mul_indicator s f * mul_indicator t f :=
funext $ mul_indicator_union_mul_inter_apply f s t
@[to_additive] lemma mul_indicator_union_of_not_mem_inter (h : a ∉ s ∩ t) (f : α → M) :
mul_indicator (s ∪ t) f a = mul_indicator s f a * mul_indicator t f a :=
by rw [← mul_indicator_union_mul_inter_apply f s t, mul_indicator_of_not_mem h, mul_one]
@[to_additive] lemma mul_indicator_union_of_disjoint (h : disjoint s t) (f : α → M) :
mul_indicator (s ∪ t) f = λa, mul_indicator s f a * mul_indicator t f a :=
funext $ λa, mul_indicator_union_of_not_mem_inter (λ ha, h ha) _
@[to_additive] lemma mul_indicator_mul (s : set α) (f g : α → M) :
mul_indicator s (λa, f a * g a) = λa, mul_indicator s f a * mul_indicator s g a :=
by { funext, simp only [mul_indicator], split_ifs, { refl }, rw mul_one }
@[to_additive] lemma mul_indicator_mul' (s : set α) (f g : α → M) :
mul_indicator s (f * g) = mul_indicator s f * mul_indicator s g :=
mul_indicator_mul s f g
@[simp, to_additive] lemma mul_indicator_compl_mul_self_apply (s : set α) (f : α → M) (a : α) :
mul_indicator sᶜ f a * mul_indicator s f a = f a :=
classical.by_cases (λ ha : a ∈ s, by simp [ha]) (λ ha, by simp [ha])
@[simp, to_additive] lemma mul_indicator_compl_mul_self (s : set α) (f : α → M) :
mul_indicator sᶜ f * mul_indicator s f = f :=
funext $ mul_indicator_compl_mul_self_apply s f
@[simp, to_additive] lemma mul_indicator_self_mul_compl_apply (s : set α) (f : α → M) (a : α) :
mul_indicator s f a * mul_indicator sᶜ f a = f a :=
classical.by_cases (λ ha : a ∈ s, by simp [ha]) (λ ha, by simp [ha])
@[simp, to_additive] lemma mul_indicator_self_mul_compl (s : set α) (f : α → M) :
mul_indicator s f * mul_indicator sᶜ f = f :=
funext $ mul_indicator_self_mul_compl_apply s f
@[to_additive] lemma mul_indicator_mul_eq_left {f g : α → M}
(h : disjoint (mul_support f) (mul_support g)) :
(mul_support f).mul_indicator (f * g) = f :=
begin
refine (mul_indicator_congr $ λ x hx, _).trans mul_indicator_mul_support,
have : g x = 1, from nmem_mul_support.1 (disjoint_left.1 h hx),
rw [pi.mul_apply, this, mul_one]
end
@[to_additive] lemma mul_indicator_mul_eq_right {f g : α → M}
(h : disjoint (mul_support f) (mul_support g)) :
(mul_support g).mul_indicator (f * g) = g :=
begin
refine (mul_indicator_congr $ λ x hx, _).trans mul_indicator_mul_support,
have : f x = 1, from nmem_mul_support.1 (disjoint_right.1 h hx),
rw [pi.mul_apply, this, one_mul]
end
@[to_additive] lemma mul_indicator_mul_compl_eq_piecewise
[decidable_pred (∈ s)] (f g : α → M) :
s.mul_indicator f * sᶜ.mul_indicator g = s.piecewise f g :=
begin
ext x,
by_cases h : x ∈ s,
{ rw [piecewise_eq_of_mem _ _ _ h, pi.mul_apply, set.mul_indicator_of_mem h,
set.mul_indicator_of_not_mem (set.not_mem_compl_iff.2 h), mul_one] },
{ rw [piecewise_eq_of_not_mem _ _ _ h, pi.mul_apply, set.mul_indicator_of_not_mem h,
set.mul_indicator_of_mem (set.mem_compl h), one_mul] },
end
/-- `set.mul_indicator` as a `monoid_hom`. -/
@[to_additive "`set.indicator` as an `add_monoid_hom`."]
noncomputable def mul_indicator_hom {α} (M) [mul_one_class M] (s : set α) : (α → M) →* (α → M) :=
{ to_fun := mul_indicator s,
map_one' := mul_indicator_one M s,
map_mul' := mul_indicator_mul s }
end monoid
section distrib_mul_action
variables {A : Type*} [add_monoid A] [monoid M] [distrib_mul_action M A]
lemma indicator_smul_apply (s : set α) (r : α → M) (f : α → A) (x : α) :
indicator s (λ x, r x • f x) x = r x • indicator s f x :=
by { dunfold indicator, split_ifs, exacts [rfl, (smul_zero (r x)).symm] }
lemma indicator_smul (s : set α) (r : α → M) (f : α → A) :
indicator s (λ (x : α), r x • f x) = λ (x : α), r x • indicator s f x :=
funext $ indicator_smul_apply s r f
lemma indicator_const_smul_apply (s : set α) (r : M) (f : α → A) (x : α) :
indicator s (λ x, r • f x) x = r • indicator s f x :=
indicator_smul_apply s (λ x, r) f x
lemma indicator_const_smul (s : set α) (r : M) (f : α → A) :
indicator s (λ (x : α), r • f x) = λ (x : α), r • indicator s f x :=
funext $ indicator_const_smul_apply s r f
end distrib_mul_action
section group
variables {G : Type*} [group G] {s t : set α} {f g : α → G} {a : α}
@[to_additive] lemma mul_indicator_inv' (s : set α) (f : α → G) :
mul_indicator s (f⁻¹) = (mul_indicator s f)⁻¹ :=
(mul_indicator_hom G s).map_inv f
@[to_additive] lemma mul_indicator_inv (s : set α) (f : α → G) :
mul_indicator s (λa, (f a)⁻¹) = λa, (mul_indicator s f a)⁻¹ :=
mul_indicator_inv' s f
@[to_additive] lemma mul_indicator_div (s : set α) (f g : α → G) :
mul_indicator s (λ a, f a / g a) =
λ a, mul_indicator s f a / mul_indicator s g a :=
(mul_indicator_hom G s).map_div f g
@[to_additive] lemma mul_indicator_div' (s : set α) (f g : α → G) :
mul_indicator s (f / g) = mul_indicator s f / mul_indicator s g :=
mul_indicator_div s f g
@[to_additive indicator_compl'] lemma mul_indicator_compl (s : set α) (f : α → G) :
mul_indicator sᶜ f = f * (mul_indicator s f)⁻¹ :=
eq_mul_inv_of_mul_eq $ s.mul_indicator_compl_mul_self f
lemma indicator_compl {G} [add_group G] (s : set α) (f : α → G) :
indicator sᶜ f = f - indicator s f :=
by rw [sub_eq_add_neg, indicator_compl']
@[to_additive indicator_diff'] lemma mul_indicator_diff (h : s ⊆ t) (f : α → G) :
mul_indicator (t \ s) f = mul_indicator t f * (mul_indicator s f)⁻¹ :=
eq_mul_inv_of_mul_eq $ by rw [pi.mul_def, ← mul_indicator_union_of_disjoint disjoint_diff.symm f,
diff_union_self, union_eq_self_of_subset_right h]
lemma indicator_diff {G : Type*} [add_group G] {s t : set α} (h : s ⊆ t) (f : α → G) :
indicator (t \ s) f = indicator t f - indicator s f :=
by rw [indicator_diff' h, sub_eq_add_neg]
end group
section comm_monoid
variables [comm_monoid M]
/-- Consider a product of `g i (f i)` over a `finset`. Suppose `g` is a
function such as `pow`, which maps a second argument of `1` to
`1`. Then if `f` is replaced by the corresponding multiplicative indicator
function, the `finset` may be replaced by a possibly larger `finset`
without changing the value of the sum. -/
@[to_additive] lemma prod_mul_indicator_subset_of_eq_one [has_one N] (f : α → N)
(g : α → N → M) {s t : finset α} (h : s ⊆ t) (hg : ∀ a, g a 1 = 1) :
∏ i in s, g i (f i) = ∏ i in t, g i (mul_indicator ↑s f i) :=
begin
rw ← finset.prod_subset h _,
{ apply finset.prod_congr rfl,
intros i hi,
congr,
symmetry,
exact mul_indicator_of_mem hi _ },
{ refine λ i hi hn, _,
convert hg i,
exact mul_indicator_of_not_mem hn _ }
end
/-- Consider a sum of `g i (f i)` over a `finset`. Suppose `g` is a
function such as multiplication, which maps a second argument of 0 to
0. (A typical use case would be a weighted sum of `f i * h i` or `f i
• h i`, where `f` gives the weights that are multiplied by some other
function `h`.) Then if `f` is replaced by the corresponding indicator
function, the `finset` may be replaced by a possibly larger `finset`
without changing the value of the sum. -/
add_decl_doc set.sum_indicator_subset_of_eq_zero
/-- Taking the product of an indicator function over a possibly larger `finset` is the same as
taking the original function over the original `finset`. -/
@[to_additive "Summing an indicator function over a possibly larger `finset` is the same as summing
the original function over the original `finset`."]
lemma prod_mul_indicator_subset (f : α → M) {s t : finset α} (h : s ⊆ t) :
∏ i in s, f i = ∏ i in t, mul_indicator ↑s f i :=
prod_mul_indicator_subset_of_eq_one _ (λ a b, b) h (λ _, rfl)
@[to_additive] lemma _root_.finset.prod_mul_indicator_eq_prod_filter
(s : finset ι) (f : ι → α → M) (t : ι → set α) (g : ι → α) [decidable_pred (λ i, g i ∈ t i)]:
∏ i in s, mul_indicator (t i) (f i) (g i) = ∏ i in s.filter (λ i, g i ∈ t i), f i (g i) :=
begin
refine (finset.prod_filter_mul_prod_filter_not s (λ i, g i ∈ t i) _).symm.trans _,
refine eq.trans _ (mul_one _),
exact congr_arg2 (*)
(finset.prod_congr rfl $ λ x hx, mul_indicator_of_mem (finset.mem_filter.1 hx).2 _)
(finset.prod_eq_one $ λ x hx, mul_indicator_of_not_mem (finset.mem_filter.1 hx).2 _)
end
@[to_additive] lemma mul_indicator_finset_prod (I : finset ι) (s : set α) (f : ι → α → M) :
mul_indicator s (∏ i in I, f i) = ∏ i in I, mul_indicator s (f i) :=
(mul_indicator_hom M s).map_prod _ _
@[to_additive] lemma mul_indicator_finset_bUnion {ι} (I : finset ι)
(s : ι → set α) {f : α → M} : (∀ (i ∈ I) (j ∈ I), i ≠ j → disjoint (s i) (s j)) →
mul_indicator (⋃ i ∈ I, s i) f = λ a, ∏ i in I, mul_indicator (s i) f a :=
begin
classical,
refine finset.induction_on I _ _,
{ intro h, funext, simp },
assume a I haI ih hI,
funext,
rw [finset.prod_insert haI, finset.set_bUnion_insert, mul_indicator_union_of_not_mem_inter, ih _],
{ assume i hi j hj hij,
exact hI i (finset.mem_insert_of_mem hi) j (finset.mem_insert_of_mem hj) hij },
simp only [not_exists, exists_prop, mem_Union, mem_inter_eq, not_and],
assume hx a' ha',
refine disjoint_left.1 (hI a (finset.mem_insert_self _ _) a' (finset.mem_insert_of_mem ha') _) hx,
exact (ne_of_mem_of_not_mem ha' haI).symm
end
@[to_additive] lemma mul_indicator_finset_bUnion_apply {ι} (I : finset ι)
(s : ι → set α) {f : α → M} (h : ∀ (i ∈ I) (j ∈ I), i ≠ j → disjoint (s i) (s j)) (x : α) :
mul_indicator (⋃ i ∈ I, s i) f x = ∏ i in I, mul_indicator (s i) f x :=
by rw set.mul_indicator_finset_bUnion I s h
end comm_monoid
section mul_zero_class
variables [mul_zero_class M] {s t : set α} {f g : α → M} {a : α}
lemma indicator_mul (s : set α) (f g : α → M) :
indicator s (λa, f a * g a) = λa, indicator s f a * indicator s g a :=
by { funext, simp only [indicator], split_ifs, { refl }, rw mul_zero }
lemma indicator_mul_left (s : set α) (f g : α → M) :
indicator s (λa, f a * g a) a = indicator s f a * g a :=
by { simp only [indicator], split_ifs, { refl }, rw [zero_mul] }
lemma indicator_mul_right (s : set α) (f g : α → M) :
indicator s (λa, f a * g a) a = f a * indicator s g a :=
by { simp only [indicator], split_ifs, { refl }, rw [mul_zero] }
lemma inter_indicator_mul {t1 t2 : set α} (f g : α → M) (x : α) :
(t1 ∩ t2).indicator (λ x, f x * g x) x = t1.indicator f x * t2.indicator g x :=
by { rw [← set.indicator_indicator], simp [indicator] }
end mul_zero_class
section mul_zero_one_class
variables [mul_zero_one_class M]
lemma inter_indicator_one {s t : set α} :
(s ∩ t).indicator (1 : _ → M) = s.indicator 1 * t.indicator 1 :=
funext (λ _, by simpa only [← inter_indicator_mul, pi.mul_apply, pi.one_apply, one_mul])
lemma indicator_prod_one {s : set α} {t : set β} {x : α} {y : β} :
(s ×ˢ t : set _).indicator (1 : _ → M) (x, y) = s.indicator 1 x * t.indicator 1 y :=
begin
letI := classical.dec_pred (∈ s),
letI := classical.dec_pred (∈ t),
simp [indicator_apply, ← ite_and],
end
variables (M) [nontrivial M]
lemma indicator_eq_zero_iff_not_mem {U : set α} {x : α} :
indicator U 1 x = (0 : M) ↔ x ∉ U :=
by { classical, simp [indicator_apply, imp_false] }
lemma indicator_eq_one_iff_mem {U : set α} {x : α} :
indicator U 1 x = (1 : M) ↔ x ∈ U :=
by { classical, simp [indicator_apply, imp_false] }
lemma indicator_one_inj {U V : set α} (h : indicator U (1 : α → M) = indicator V 1) : U = V :=
by { ext, simp_rw [← indicator_eq_one_iff_mem M, h] }
end mul_zero_one_class
section order
variables [has_one M] {s t : set α} {f g : α → M} {a : α} {y : M}
section
variables [has_le M]
@[to_additive] lemma mul_indicator_apply_le' (hfg : a ∈ s → f a ≤ y) (hg : a ∉ s → 1 ≤ y) :
mul_indicator s f a ≤ y :=
begin
by_cases ha : a ∈ s,
{ simpa [ha] using hfg ha },
{ simpa [ha] using hg ha },
end
@[to_additive] lemma mul_indicator_le' (hfg : ∀ a ∈ s, f a ≤ g a) (hg : ∀ a ∉ s, 1 ≤ g a) :
mul_indicator s f ≤ g :=
λ a, mul_indicator_apply_le' (hfg _) (hg _)
@[to_additive] lemma le_mul_indicator_apply {y} (hfg : a ∈ s → y ≤ g a) (hf : a ∉ s → y ≤ 1) :
y ≤ mul_indicator s g a :=
@mul_indicator_apply_le' α Mᵒᵈ ‹_› _ _ _ _ _ hfg hf
@[to_additive] lemma le_mul_indicator (hfg : ∀ a ∈ s, f a ≤ g a) (hf : ∀ a ∉ s, f a ≤ 1) :
f ≤ mul_indicator s g :=
λ a, le_mul_indicator_apply (hfg _) (hf _)
end
variables [preorder M]
@[to_additive indicator_apply_nonneg]
lemma one_le_mul_indicator_apply (h : a ∈ s → 1 ≤ f a) : 1 ≤ mul_indicator s f a :=
le_mul_indicator_apply h (λ _, le_rfl)
@[to_additive indicator_nonneg]
lemma one_le_mul_indicator (h : ∀ a ∈ s, 1 ≤ f a) (a : α) : 1 ≤ mul_indicator s f a :=
one_le_mul_indicator_apply (h a)
@[to_additive] lemma mul_indicator_apply_le_one (h : a ∈ s → f a ≤ 1) : mul_indicator s f a ≤ 1 :=
mul_indicator_apply_le' h (λ _, le_rfl)
@[to_additive] lemma mul_indicator_le_one (h : ∀ a ∈ s, f a ≤ 1) (a : α) :
mul_indicator s f a ≤ 1 :=
mul_indicator_apply_le_one (h a)
@[to_additive] lemma mul_indicator_le_mul_indicator (h : f a ≤ g a) :
mul_indicator s f a ≤ mul_indicator s g a :=
mul_indicator_rel_mul_indicator le_rfl (λ _, h)
attribute [mono] mul_indicator_le_mul_indicator indicator_le_indicator
@[to_additive] lemma mul_indicator_le_mul_indicator_of_subset (h : s ⊆ t) (hf : ∀ a, 1 ≤ f a)
(a : α) :
mul_indicator s f a ≤ mul_indicator t f a :=
mul_indicator_apply_le' (λ ha, le_mul_indicator_apply (λ _, le_rfl) (λ hat, (hat $ h ha).elim))
(λ ha, one_le_mul_indicator_apply (λ _, hf _))
@[to_additive] lemma mul_indicator_le_self' (hf : ∀ x ∉ s, 1 ≤ f x) : mul_indicator s f ≤ f :=
mul_indicator_le' (λ _ _, le_rfl) hf
@[to_additive] lemma mul_indicator_Union_apply {ι M} [complete_lattice M] [has_one M]
(h1 : (⊥:M) = 1) (s : ι → set α) (f : α → M) (x : α) :
mul_indicator (⋃ i, s i) f x = ⨆ i, mul_indicator (s i) f x :=
begin
by_cases hx : x ∈ ⋃ i, s i,
{ rw [mul_indicator_of_mem hx],
rw [mem_Union] at hx,
refine le_antisymm _ (supr_le $ λ i, mul_indicator_le_self' (λ x hx, h1 ▸ bot_le) x),
rcases hx with ⟨i, hi⟩,
exact le_supr_of_le i (ge_of_eq $ mul_indicator_of_mem hi _) },
{ rw [mul_indicator_of_not_mem hx],
simp only [mem_Union, not_exists] at hx,
simp [hx, ← h1] }
end
end order
section canonically_ordered_monoid
variables [canonically_ordered_monoid M]
@[to_additive] lemma mul_indicator_le_self (s : set α) (f : α → M) :
mul_indicator s f ≤ f :=
mul_indicator_le_self' $ λ _ _, one_le _
@[to_additive] lemma mul_indicator_apply_le {a : α} {s : set α} {f g : α → M}
(hfg : a ∈ s → f a ≤ g a) :
mul_indicator s f a ≤ g a :=
mul_indicator_apply_le' hfg $ λ _, one_le _
@[to_additive] lemma mul_indicator_le {s : set α} {f g : α → M} (hfg : ∀ a ∈ s, f a ≤ g a) :
mul_indicator s f ≤ g :=
mul_indicator_le' hfg $ λ _ _, one_le _
end canonically_ordered_monoid
lemma indicator_le_indicator_nonneg {β} [linear_order β] [has_zero β] (s : set α) (f : α → β) :
s.indicator f ≤ {x | 0 ≤ f x}.indicator f :=
begin
intro x,
classical,
simp_rw indicator_apply,
split_ifs,
{ exact le_rfl, },
{ exact (not_le.mp h_1).le, },
{ exact h_1, },
{ exact le_rfl, },
end
lemma indicator_nonpos_le_indicator {β} [linear_order β] [has_zero β] (s : set α) (f : α → β) :
{x | f x ≤ 0}.indicator f ≤ s.indicator f :=
@indicator_le_indicator_nonneg α βᵒᵈ _ _ s f
end set
@[to_additive] lemma monoid_hom.map_mul_indicator
{M N : Type*} [mul_one_class M] [mul_one_class N] (f : M →* N)
(s : set α) (g : α → M) (x : α) :
f (s.mul_indicator g x) = s.mul_indicator (f ∘ g) x :=
congr_fun (set.mul_indicator_comp_of_one f.map_one).symm x
|
71473e158d3ad4d4868af31f01d3897487be74db | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/category_theory/simple.lean | 54bda903b35a3c5c1cc1ff1f818a5c04a9e48a8f | [
"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 | 4,263 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel, Scott Morrison
-/
import category_theory.limits.shapes.zero
import category_theory.limits.shapes.kernels
import category_theory.abelian.basic
/-!
# Simple objects
We define simple objects in any category with zero morphisms.
A simple object is an object `Y` such that any monomorphism `f : X ⟶ Y`
is either an isomorphism or zero (but not both).
This is formalized as a `Prop` valued typeclass `simple X`.
If a morphism `f` out of a simple object is nonzero and has a kernel, then that kernel is zero.
(We state this as `kernel.ι f = 0`, but should add `kernel f ≅ 0`.)
When the category is abelian, being simple is the same as being cosimple (although we do not
state a separate typeclass for this).
As a consequence, any nonzero epimorphism out of a simple object is an isomorphism,
and any nonzero morphism into a simple object has trivial cokernel.
-/
noncomputable theory
open category_theory.limits
namespace category_theory
universes v u
variables {C : Type u} [category.{v} C]
section
variables [has_zero_morphisms C]
/-- An object is simple if monomorphisms into it are (exclusively) either isomorphisms or zero. -/
class simple (X : C) : Prop :=
(mono_is_iso_iff_nonzero : ∀ {Y : C} (f : Y ⟶ X) [mono f], is_iso f ↔ (f ≠ 0))
/-- A nonzero monomorphism to a simple object is an isomorphism. -/
lemma is_iso_of_mono_of_nonzero {X Y : C} [simple Y] {f : X ⟶ Y} [mono f] (w : f ≠ 0) :
is_iso f :=
(simple.mono_is_iso_iff_nonzero f).mpr w
lemma kernel_zero_of_nonzero_from_simple
{X Y : C} [simple X] {f : X ⟶ Y} [has_kernel f] (w : f ≠ 0) :
kernel.ι f = 0 :=
begin
classical,
by_contra,
haveI := is_iso_of_mono_of_nonzero h,
exact w (eq_zero_of_epi_kernel f),
end
lemma mono_to_simple_zero_of_not_iso
{X Y : C} [simple Y] {f : X ⟶ Y} [mono f] (w : is_iso f → false) : f = 0 :=
begin
classical,
by_contra,
exact w (is_iso_of_mono_of_nonzero h)
end
lemma id_nonzero (X : C) [simple.{v} X] : 𝟙 X ≠ 0 :=
(simple.mono_is_iso_iff_nonzero (𝟙 X)).mp (by apply_instance)
instance (X : C) [simple.{v} X] : nontrivial (End X) :=
nontrivial_of_ne 1 0 (id_nonzero X)
section
variable [has_zero_object C]
open_locale zero_object
/-- We don't want the definition of 'simple' to include the zero object, so we check that here. -/
lemma zero_not_simple [simple (0 : C)] : false :=
(simple.mono_is_iso_iff_nonzero (0 : (0 : C) ⟶ (0 : C))).mp ⟨⟨0, by tidy⟩⟩ rfl
end
end
-- We next make the dual arguments, but for this we must be in an abelian category.
section abelian
variables [abelian C]
/-- In an abelian category, an object satisfying the dual of the definition of a simple object is
simple. -/
lemma simple_of_cosimple (X : C) (h : ∀ {Z : C} (f : X ⟶ Z) [epi f], is_iso f ↔ (f ≠ 0)) :
simple X :=
⟨λ Y f I,
begin
classical,
fsplit,
{ introsI,
have hx := cokernel.π_of_epi f,
by_contra,
substI h,
exact (h _).mp (cokernel.π_of_zero _ _) hx },
{ intro hf,
suffices : epi f,
{ resetI, apply abelian.is_iso_of_mono_of_epi },
apply preadditive.epi_of_cokernel_zero,
by_contra h',
exact cokernel_not_iso_of_nonzero hf ((h _).mpr h') }
end⟩
/-- A nonzero epimorphism from a simple object is an isomorphism. -/
lemma is_iso_of_epi_of_nonzero {X Y : C} [simple X] {f : X ⟶ Y} [epi f] (w : f ≠ 0) :
is_iso f :=
begin
-- `f ≠ 0` means that `kernel.ι f` is not an iso, and hence zero, and hence `f` is a mono.
haveI : mono f :=
preadditive.mono_of_kernel_zero (mono_to_simple_zero_of_not_iso (kernel_not_iso_of_nonzero w)),
exact abelian.is_iso_of_mono_of_epi f,
end
lemma cokernel_zero_of_nonzero_to_simple
{X Y : C} [simple Y] {f : X ⟶ Y} [has_cokernel f] (w : f ≠ 0) :
cokernel.π f = 0 :=
begin
classical,
by_contradiction h,
haveI := is_iso_of_epi_of_nonzero h,
exact w (eq_zero_of_mono_cokernel f),
end
lemma epi_from_simple_zero_of_not_iso
{X Y : C} [simple X] {f : X ⟶ Y} [epi f] (w : is_iso f → false) : f = 0 :=
begin
classical,
by_contra,
exact w (is_iso_of_epi_of_nonzero h),
end
end abelian
end category_theory
|
4c14d097aa3325f4dcb42a34d306071bff2d8195 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/category_theory/groupoid.lean | 4f694eb0680c79840cb52807007e4ec88a8f8377 | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 1,034 | lean | /-
Copyright (c) 2018 Reid Barton All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton
-/
import category_theory.category
import category_theory.isomorphism
namespace category_theory
universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation
class groupoid (obj : Type u) extends category.{v} obj : Type (max u v) :=
(inv : Π {X Y : obj}, (X ⟶ Y) → (Y ⟶ X))
(inv_comp' : ∀ {X Y : obj} (f : X ⟶ Y), comp (inv f) f = id Y . obviously)
(comp_inv' : ∀ {X Y : obj} (f : X ⟶ Y), comp f (inv f) = id X . obviously)
restate_axiom groupoid.inv_comp'
restate_axiom groupoid.comp_inv'
attribute [simp] groupoid.inv_comp groupoid.comp_inv
abbreviation large_groupoid (C : Type (u+1)) : Type (u+1) := groupoid.{u+1} C
abbreviation small_groupoid (C : Type u) : Type (u+1) := groupoid.{u+1} C
instance of_groupoid {C : Type u} [groupoid.{v} C] {X Y : C} (f : X ⟶ Y) : is_iso f :=
{ inv := groupoid.inv f }
end category_theory
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.