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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
54d612139aabe5aeb8f55a64bfcd44430e76e7f9 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/measure_theory/measure_space.lean | eb136a42f720fef80fa932654bfe29b6dcb9e0d7 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 73,787 | 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 measure_theory.outer_measure
import order.filter.countable_Inter
/-!
# Measure spaces
Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the
extended nonnegative reals that satisfies the following conditions:
1. `μ ∅ = 0`;
2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint
sets is equal to the measure of the individual sets.
Every measure can be canonically extended to an outer measure, so that it assigns values to
all subsets, not just the measurable subsets. On the other hand, a measure that is countably
additive on measurable sets can be restricted to measurable sets to obtain a measure.
In this file a measure is defined to be an outer measure that is countably additive on
measurable sets, with the additional assumption that the outer measure is the canonical
extension of the restricted measure.
Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ennreal`.
We introduce the following typeclasses for measures:
* `probability_measure μ`: `μ univ = 1`;
* `finite_measure μ`: `μ univ < ⊤`;
* `locally_finite_measure μ` : `∀ x, ∃ s ∈ 𝓝 x, μ s < ⊤`;
* `has_no_atoms μ` : `∀ x, μ {x} = 0`; possibly should be redefined as
`∀ s, 0 < μ s → ∃ t ⊆ s, 0 < μ t ∧ μ t < μ s`.
Given a measure, the null sets are the sets where `μ s = 0`, where `μ` denotes the corresponding
outer measure (so `s` might not be measurable). We can then define the completion of `μ` as the
measure on the least `σ`-algebra that also contains all null sets, by defining the measure to be `0`
on the null sets.
## Main statements
* `completion` is the completion of a measure to all null measurable sets.
* `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure.
## Implementation notes
Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`.
This conveniently allows us to apply the measure to sets without proving that they are measurable.
We get countable subadditivity for all sets, but only countable additivity for measurable sets.
You often don't want to define a measure via its constructor.
Two ways that are sometimes more convenient:
* `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets
and proving the properties (1) and (2) mentioned above.
* `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that
all measurable sets in the measurable space are Carathéodory measurable.
To prove that two measures are equal, there are multiple options:
* `ext`: two measures are equal if they are equal on all measurable sets.
* `ext_of_generate_from_of_Union`: two measures are equal if they are equal on a π-system generating
the measurable sets, if the π-system contains a spanning increasing sequence of sets where the
measures take finite value (in particular the measures are σ-finite). This is a special case of the
more general `ext_of_generate_from_of_cover`
* `ext_of_generate_finite`: two finite measures are equal if they are equal on a π-system
generating the measurable sets. This is a special case of `ext_of_generate_from_of_Union` using
`C ∪ {univ}`, but is easier to work with.
A `measure_space` is a class that is a measurable space with a canonical measure.
The measure is denoted `volume`.
## References
* <https://en.wikipedia.org/wiki/Measure_(mathematics)>
* <https://en.wikipedia.org/wiki/Complete_measure>
* <https://en.wikipedia.org/wiki/Almost_everywhere>
## Tags
measure, almost everywhere, measure space, completion, null set, null measurable set
-/
noncomputable theory
open classical set filter function
open_locale classical topological_space big_operators filter
universes u v w x
namespace measure_theory
/-- A measure is defined to be an outer measure that is countably additive on
measurable sets, with the additional assumption that the outer measure is the canonical
extension of the restricted measure. -/
structure measure (α : Type*) [measurable_space α] extends outer_measure α :=
(m_Union ⦃f : ℕ → set α⦄ :
(∀i, is_measurable (f i)) → pairwise (disjoint on f) →
measure_of (⋃i, f i) = (∑'i, measure_of (f i)))
(trimmed : to_outer_measure.trim = to_outer_measure)
/-- Measure projections for a measure space.
For measurable sets this returns the measure assigned by the `measure_of` field in `measure`.
But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and
subadditivity for all sets.
-/
instance measure.has_coe_to_fun {α} [measurable_space α] : has_coe_to_fun (measure α) :=
⟨λ _, set α → ennreal, λ m, m.to_outer_measure⟩
namespace measure
/-! ### General facts about measures -/
/-- Obtain a measure by giving a countably additive function that sends `∅` to `0`. -/
def of_measurable {α} [measurable_space α]
(m : Π (s : set α), is_measurable s → ennreal)
(m0 : m ∅ is_measurable.empty = 0)
(mU : ∀ {{f : ℕ → set α}} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑'i, m (f i) (h i))) :
measure α :=
{ m_Union := λ f hf hd,
show induced_outer_measure m _ m0 (Union f) =
∑' i, induced_outer_measure m _ m0 (f i), begin
rw [induced_outer_measure_eq m0 mU, mU hf hd],
congr, funext n, rw induced_outer_measure_eq m0 mU
end,
trimmed :=
show (induced_outer_measure m _ m0).trim = induced_outer_measure m _ m0, begin
unfold outer_measure.trim,
congr, funext s hs,
exact induced_outer_measure_eq m0 mU hs
end,
..induced_outer_measure m _ m0 }
lemma of_measurable_apply {α} [measurable_space α]
{m : Π (s : set α), is_measurable s → ennreal}
{m0 : m ∅ is_measurable.empty = 0}
{mU : ∀ {{f : ℕ → set α}} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑'i, m (f i) (h i))}
(s : set α) (hs : is_measurable s) :
of_measurable m m0 mU s = m s hs :=
induced_outer_measure_eq m0 mU hs
lemma to_outer_measure_injective {α} [measurable_space α] :
injective (to_outer_measure : measure α → outer_measure α) :=
λ ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h, by { congr, exact h }
@[ext] lemma ext {α} [measurable_space α] {μ₁ μ₂ : measure α}
(h : ∀s, is_measurable s → μ₁ s = μ₂ s) :
μ₁ = μ₂ :=
to_outer_measure_injective $ by rw [← trimmed, outer_measure.trim_congr h, trimmed]
lemma ext_iff {α} [measurable_space α] {μ₁ μ₂ : measure α} :
μ₁ = μ₂ ↔ ∀s, is_measurable s → μ₁ s = μ₂ s :=
⟨by { rintro rfl s hs, refl }, measure.ext⟩
end measure
section
variables {α : Type*} {β : Type*} {ι : Type*} [measurable_space α] {μ μ₁ μ₂ : measure α}
{s s₁ s₂ : set α}
@[simp] lemma coe_to_outer_measure : ⇑μ.to_outer_measure = μ := rfl
lemma to_outer_measure_apply (s) : μ.to_outer_measure s = μ s := rfl
lemma measure_eq_trim (s) : μ s = μ.to_outer_measure.trim s :=
by rw μ.trimmed; refl
lemma measure_eq_infi (s) : μ s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), μ t :=
by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl
lemma measure_eq_induced_outer_measure :
μ s = induced_outer_measure (λ s _, μ s) is_measurable.empty μ.empty s :=
measure_eq_trim _
lemma to_outer_measure_eq_induced_outer_measure :
μ.to_outer_measure = induced_outer_measure (λ s _, μ s) is_measurable.empty μ.empty :=
μ.trimmed.symm
lemma measure_eq_extend (hs : is_measurable s) :
μ s = extend (λ t (ht : is_measurable t), μ t) s :=
by { rw [measure_eq_induced_outer_measure, induced_outer_measure_eq_extend _ _ hs], exact μ.m_Union }
@[simp] lemma measure_empty : μ ∅ = 0 := μ.empty
lemma nonempty_of_measure_ne_zero (h : μ s ≠ 0) : s.nonempty :=
ne_empty_iff_nonempty.1 $ λ h', h $ h'.symm ▸ measure_empty
lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h
lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 :=
le_zero_iff_eq.1 $ h₂ ▸ measure_mono h
lemma measure_mono_top (h : s₁ ⊆ s₂) (h₁ : μ s₁ = ⊤) : μ s₂ = ⊤ :=
top_unique $ h₁ ▸ measure_mono h
lemma exists_is_measurable_superset_of_measure_eq_zero {s : set α} (h : μ s = 0) :
∃t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 :=
outer_measure.exists_is_measurable_superset_of_trim_eq_zero (by rw [← measure_eq_trim, h])
lemma exists_is_measurable_superset_iff_measure_eq_zero {s : set α} :
(∃ t, s ⊆ t ∧ is_measurable t ∧ μ t = 0) ↔ μ s = 0 :=
⟨λ ⟨t, hst, _, ht⟩, measure_mono_null hst ht, exists_is_measurable_superset_of_measure_eq_zero⟩
theorem measure_Union_le {β} [encodable β] (s : β → set α) : μ (⋃i, s i) ≤ (∑'i, μ (s i)) :=
μ.to_outer_measure.Union _
lemma measure_bUnion_le {s : set β} (hs : countable s) (f : β → set α) :
μ (⋃b∈s, f b) ≤ ∑'p:s, μ (f p) :=
begin
haveI := hs.to_encodable,
rw [bUnion_eq_Union],
apply measure_Union_le
end
lemma measure_bUnion_finset_le (s : finset β) (f : β → set α) :
μ (⋃b∈s, f b) ≤ ∑ p in s, μ (f p) :=
begin
rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype],
exact measure_bUnion_le s.countable_to_set f
end
lemma measure_Union_null {β} [encodable β] {s : β → set α} :
(∀ i, μ (s i) = 0) → μ (⋃i, s i) = 0 :=
μ.to_outer_measure.Union_null
theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ :=
μ.to_outer_measure.union _ _
lemma measure_union_null {s₁ s₂ : set α} : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 :=
μ.to_outer_measure.union_null
lemma measure_Union {β} [encodable β] {f : β → set α}
(hn : pairwise (disjoint on f)) (h : ∀i, is_measurable (f i)) :
μ (⋃i, f i) = (∑'i, μ (f i)) :=
begin
rw [measure_eq_extend (is_measurable.Union h),
extend_Union is_measurable.empty _ is_measurable.Union _ hn h],
{ simp [measure_eq_extend, h] },
{ exact μ.empty },
{ exact μ.m_Union }
end
lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
μ (s₁ ∪ s₂) = μ s₁ + μ s₂ :=
begin
rw [union_eq_Union, measure_Union, tsum_fintype, fintype.sum_bool, cond, cond],
exacts [pairwise_disjoint_on_bool.2 hd, λ b, bool.cases_on b h₂ h₁]
end
lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s)
(hd : pairwise_on s (disjoint on f)) (h : ∀b∈s, is_measurable (f b)) :
μ (⋃b∈s, f b) = ∑'p:s, μ (f p) :=
begin
haveI := hs.to_encodable,
rw [← measure_Union, bUnion_eq_Union],
{ rintro ⟨i, hi⟩ ⟨j, hj⟩ ij x ⟨h₁, h₂⟩,
exact hd i hi j hj (mt subtype.ext_val ij:_) ⟨h₁, h₂⟩ },
{ simpa }
end
lemma measure_sUnion {S : set (set α)} (hs : countable S)
(hd : pairwise_on S disjoint) (h : ∀s∈S, is_measurable s) :
μ (⋃₀ S) = ∑' s:S, μ s :=
by rw [sUnion_eq_bUnion, measure_bUnion hs hd h]
lemma measure_bUnion_finset {s : finset ι} {f : ι → set α} (hd : pairwise_on ↑s (disjoint on f))
(hm : ∀b∈s, is_measurable (f b)) :
μ (⋃b∈s, f b) = ∑ p in s, μ (f p) :=
begin
rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype],
exact measure_bUnion s.countable_to_set hd hm
end
/-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
lemma tsum_measure_preimage_singleton {s : set β} (hs : countable s) {f : α → β}
(hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) :
(∑' b : s, μ (f ⁻¹' {↑b})) = μ (f ⁻¹' s) :=
by rw [← set.bUnion_preimage_singleton, measure_bUnion hs (pairwise_on_disjoint_fiber _ _) hf]
/-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
lemma sum_measure_preimage_singleton (s : finset β) {f : α → β}
(hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) :
∑ b in s, μ (f ⁻¹' {b}) = μ (f ⁻¹' ↑s) :=
by simp only [← measure_bUnion_finset (pairwise_on_disjoint_fiber _ _) hf,
finset.bUnion_preimage_singleton]
lemma measure_diff {s₁ s₂ : set α} (h : s₂ ⊆ s₁) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂)
(h_fin : μ s₂ < ⊤) :
μ (s₁ \ s₂) = μ s₁ - μ s₂ :=
begin
refine (ennreal.add_sub_self' h_fin).symm.trans _,
rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h]
end
lemma measure_compl {μ : measure α} {s : set α} (h₁ : is_measurable s) (h_fin : μ s < ⊤) :
μ (sᶜ) = μ univ - μ s :=
by { rw compl_eq_univ_diff, exact measure_diff (subset_univ s) is_measurable.univ h₁ h_fin }
lemma sum_measure_le_measure_univ {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i))
(H : pairwise_on ↑s (disjoint on t)) :
∑ i in s, μ (t i) ≤ μ (univ : set α) :=
by { rw ← measure_bUnion_finset H h, exact measure_mono (subset_univ _) }
lemma tsum_measure_le_measure_univ {s : ι → set α} (hs : ∀ i, is_measurable (s i))
(H : pairwise (disjoint on s)) :
(∑' i, μ (s i)) ≤ μ (univ : set α) :=
begin
rw [ennreal.tsum_eq_supr_sum],
exact supr_le (λ s, sum_measure_le_measure_univ (λ i hi, hs i) (λ i hi j hj hij, H i j hij))
end
/-- Pigeonhole principle for measure spaces: if `∑' i, μ (s i) > μ univ`, then
one of the intersections `s i ∩ s j` is not empty. -/
lemma exists_nonempty_inter_of_measure_univ_lt_tsum_measure (μ : measure α) {s : ι → set α}
(hs : ∀ i, is_measurable (s i)) (H : μ (univ : set α) < ∑' i, μ (s i)) :
∃ i j (h : i ≠ j), (s i ∩ s j).nonempty :=
begin
contrapose! H,
apply tsum_measure_le_measure_univ hs,
exact λ i j hij x hx, H i j hij ⟨x, hx⟩
end
/-- Pigeonhole principle for measure spaces: if `s` is a `finset` and
`∑ i in s, μ (t i) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/
lemma exists_nonempty_inter_of_measure_univ_lt_sum_measure (μ : measure α) {s : finset ι}
{t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i)) (H : μ (univ : set α) < ∑ i in s, μ (t i)) :
∃ (i ∈ s) (j ∈ s) (h : i ≠ j), (t i ∩ t j).nonempty :=
begin
contrapose! H,
apply sum_measure_le_measure_univ h,
exact λ i hi j hj hij x hx, H i hi j hj hij ⟨x, hx⟩
end
/-- Continuity from below: the measure of the union of a directed sequence of measurable sets
is the supremum of the measures. -/
lemma measure_Union_eq_supr [encodable ι] {s : ι → set α} (h : ∀ i, is_measurable (s i))
(hd : directed (⊆) s) : μ (⋃ i, s i) = ⨆ i, μ (s i) :=
begin
by_cases hι : nonempty ι, swap,
{ simp only [supr_of_empty hι, Union], exact measure_empty },
resetI,
refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _),
have : ∀ n, is_measurable (disjointed (λ n, ⋃ b ∈ encodable.decode2 ι n, s b) n) :=
is_measurable.disjointed (is_measurable.bUnion_decode2 h),
rw [← encodable.Union_decode2, ← Union_disjointed, measure_Union disjoint_disjointed this,
ennreal.tsum_eq_supr_nat],
simp only [← measure_bUnion_finset (disjoint_disjointed.pairwise_on _) (λ n _, this n)],
refine supr_le (λ n, _),
refine le_trans (_ : _ ≤ μ (⋃ (k ∈ finset.range n) (i ∈ encodable.decode2 ι k), s i)) _,
exact measure_mono (bUnion_subset_bUnion_right (λ k hk, disjointed_subset)),
simp only [← finset.bUnion_option_to_finset, ← finset.bUnion_bind],
generalize : (finset.range n).bind (λ k, (encodable.decode2 ι k).to_finset) = t,
rcases hd.finset_le t with ⟨i, hi⟩,
exact le_supr_of_le i (measure_mono $ bUnion_subset hi)
end
lemma measure_bUnion_eq_supr {s : ι → set α} {t : set ι} (ht : countable t)
(h : ∀ i ∈ t, is_measurable (s i)) (hd : directed_on ((⊆) on s) t) :
μ (⋃ i ∈ t, s i) = ⨆ i ∈ t, μ (s i) :=
begin
haveI := ht.to_encodable,
rw [bUnion_eq_Union, measure_Union_eq_supr (set_coe.forall'.1 h) hd.directed_coe,
supr_subtype'],
refl
end
/-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable
sets is the infimum of the measures. -/
lemma measure_Inter_eq_infi [encodable ι] {s : ι → set α}
(h : ∀i, is_measurable (s i)) (hd : directed (⊇) s)
(hfin : ∃i, μ (s i) < ⊤) :
μ (⋂i, s i) = (⨅i, μ (s i)) :=
begin
rcases hfin with ⟨k, hk⟩,
rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k), ennreal.sub_infi,
← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)),
← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h)
(lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk),
diff_Inter, measure_Union_eq_supr],
{ congr' 1,
refine le_antisymm (supr_le_supr2 $ λ i, _) (supr_le_supr $ λ i, _),
{ rcases hd i k with ⟨j, hji, hjk⟩,
use j,
rw [← measure_diff hjk (h _) (h _) ((measure_mono hjk).trans_lt hk)],
exact measure_mono (diff_subset_diff_right hji) },
{ rw [ennreal.sub_le_iff_le_add, ← measure_union disjoint_diff.symm ((h k).diff (h i)) (h i),
set.union_comm],
exact measure_mono (diff_subset_iff.1 $ subset.refl _) } },
{ exact λ i, (h k).diff (h i) },
{ exact hd.mono_comp _ (λ _ _, diff_subset_diff_right) }
end
lemma measure_eq_inter_diff {s t : set α} (hs : is_measurable s) (ht : is_measurable t) :
μ s = μ (s ∩ t) + μ (s \ t) :=
have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs ,
by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t]
lemma measure_union_add_inter {s t : set α} (hs : is_measurable s) (ht : is_measurable t) :
μ (s ∪ t) + μ (s ∩ t) = μ s + μ t :=
by { rw [measure_eq_inter_diff (hs.union ht) ht, set.union_inter_cancel_right,
union_diff_right, measure_eq_inter_diff hs ht], ac_refl }
/-- Continuity from below: the measure of the union of an increasing sequence of measurable sets
is the limit of the measures. -/
lemma tendsto_measure_Union {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : monotone s) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋃n, s n))) :=
begin
rw measure_Union_eq_supr hs (directed_of_sup hm),
exact tendsto_at_top_supr_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm hnm)
end
/-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable
sets is the limit of the measures. -/
lemma tendsto_measure_Inter {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : ∀ ⦃n m⦄, n ≤ m → s m ⊆ s n) (hf : ∃i, μ (s i) < ⊤) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋂n, s n))) :=
begin
rw measure_Inter_eq_infi hs (directed_of_sup hm) hf,
exact tendsto_at_top_infi_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm hnm),
end
/-- One direction of the Borel-Cantelli lemma: if (sᵢ) is a sequence of measurable sets such that
∑ μ sᵢ exists, then the limit superior of the sᵢ is a null set. -/
lemma measure_limsup_eq_zero {s : ℕ → set α} (hs : ∀ i, is_measurable (s i))
(hs' : (∑' i, μ (s i)) ≠ ⊤) : μ (limsup at_top s) = 0 :=
begin
rw limsup_eq_infi_supr_of_nat',
-- We will show that both `μ (⨅ n, ⨆ i, s (i + n))` and `0` are the limit of `μ (⊔ i, s (i + n))`
-- as `n` tends to infinity. For the former, we use continuity from above.
refine tendsto_nhds_unique
(tendsto_measure_Inter (λ i, is_measurable.Union (λ b, hs (b + i))) _
⟨0, lt_of_le_of_lt (measure_Union_le s) (ennreal.lt_top_iff_ne_top.2 hs')⟩) _,
{ intros n m hnm x,
simp only [set.mem_Union],
exact λ ⟨i, hi⟩, ⟨i + (m - n), by simpa only [add_assoc, nat.sub_add_cancel hnm] using hi⟩ },
{ -- For the latter, notice that, `μ (⨆ i, s (i + n)) ≤ ∑' s (i + n)`. Since the right hand side
-- converges to `0` by hypothesis, so does the former and the proof is complete.
exact (tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds
(ennreal.tendsto_sum_nat_add (μ ∘ s) hs')
(eventually_of_forall (by simp only [forall_const, zero_le]))
(eventually_of_forall (λ i, measure_Union_le _))) }
end
end
/-- Obtain a measure by giving an outer measure where all sets in the σ-algebra are
Carathéodory measurable. -/
def outer_measure.to_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
measure α :=
measure.of_measurable (λ s _, m s) m.empty
(λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd)
lemma le_to_outer_measure_caratheodory {α} [ms : measurable_space α]
(μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory :=
begin
assume s hs,
rw to_outer_measure_eq_induced_outer_measure,
refine outer_measure.of_function_caratheodory (λ t, le_infi $ λ ht, _),
rw [← measure_eq_extend (ht.inter hs),
← measure_eq_extend (ht.diff hs),
← measure_union _ (ht.inter hs) (ht.diff hs),
inter_union_diff],
exact le_refl _,
exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁
end
@[simp] lemma to_measure_to_outer_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
(m.to_measure h).to_outer_measure = m.trim := rfl
@[simp] lemma to_measure_apply {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory)
{s : set α} (hs : is_measurable s) :
m.to_measure h s = m s := m.trim_eq hs
lemma le_to_measure_apply {α} (m : outer_measure α) [ms : measurable_space α]
(h : ms ≤ m.caratheodory) (s : set α) :
m s ≤ m.to_measure h s :=
m.le_trim s
@[simp] lemma to_outer_measure_to_measure {α : Type*} [ms : measurable_space α] {μ : measure α} :
μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ :=
measure.ext $ λ s, μ.to_outer_measure.trim_eq
namespace measure
variables {α : Type*} {β : Type*} {γ : Type*}
[measurable_space α] [measurable_space β] [measurable_space γ]
/-! ### The `ennreal`-module of measures -/
instance : has_zero (measure α) :=
⟨{ to_outer_measure := 0,
m_Union := λ f hf hd, tsum_zero.symm,
trimmed := outer_measure.trim_zero }⟩
@[simp] theorem zero_to_outer_measure : (0 : measure α).to_outer_measure = 0 := rfl
@[simp, norm_cast] theorem coe_zero : ⇑(0 : measure α) = 0 := rfl
lemma eq_zero_of_not_nonempty (h : ¬nonempty α) (μ : measure α) : μ = 0 :=
ext $ λ s hs, by simp only [eq_empty_of_not_nonempty h s, measure_empty]
instance : inhabited (measure α) := ⟨0⟩
instance : has_add (measure α) :=
⟨λμ₁ μ₂, {
to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure,
m_Union := λs hs hd,
show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑' i, μ₁ (s i) + μ₂ (s i),
by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs],
trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩
@[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) :
(μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl
@[simp, norm_cast] theorem coe_add (μ₁ μ₂ : measure α) : ⇑(μ₁ + μ₂) = μ₁ + μ₂ := rfl
theorem add_apply (μ₁ μ₂ : measure α) (s) : (μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl
instance add_comm_monoid : add_comm_monoid (measure α) :=
to_outer_measure_injective.add_comm_monoid to_outer_measure zero_to_outer_measure
add_to_outer_measure
instance : has_scalar ennreal (measure α) :=
⟨λ c μ,
{ to_outer_measure := c • μ.to_outer_measure,
m_Union := λ s hs hd, by simp [measure_Union, *, ennreal.tsum_mul_left],
trimmed := by rw [outer_measure.trim_smul, μ.trimmed] }⟩
@[simp] theorem smul_to_outer_measure (c : ennreal) (μ : measure α) :
(c • μ).to_outer_measure = c • μ.to_outer_measure :=
rfl
@[simp, norm_cast] theorem coe_smul (c : ennreal) (μ : measure α) :
⇑(c • μ) = c • μ :=
rfl
theorem smul_apply (c : ennreal) (μ : measure α) (s : set α) :
(c • μ) s = c * μ s :=
rfl
instance : semimodule ennreal (measure α) :=
injective.semimodule ennreal ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩
to_outer_measure_injective smul_to_outer_measure
/-! ### The complete lattice of measures -/
instance : partial_order (measure α) :=
{ le := λm₁ m₂, ∀ s, is_measurable s → m₁ s ≤ m₂ s,
le_refl := assume m s hs, le_refl _,
le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs),
le_antisymm := assume m₁ m₂ h₁ h₂, ext $
assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) }
theorem le_iff {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, is_measurable s → μ₁ s ≤ μ₂ s := iff.rfl
theorem to_outer_measure_le {μ₁ μ₂ : measure α} :
μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ :=
by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl
theorem le_iff' {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s :=
to_outer_measure_le.symm
theorem lt_iff {μ ν : measure α} : μ < ν ↔ μ ≤ ν ∧ ∃ s, is_measurable s ∧ μ s < ν s :=
lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff, not_forall, not_le, exists_prop]
theorem lt_iff' {μ ν : measure α} : μ < ν ↔ μ ≤ ν ∧ ∃ s, μ s < ν s :=
lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff', not_forall, not_le]
section
variables {m : set (measure α)} {μ : measure α}
lemma Inf_caratheodory (s : set α) (hs : is_measurable s) :
(Inf (measure.to_outer_measure '' m)).caratheodory.is_measurable' s :=
begin
rw [outer_measure.Inf_eq_of_function_Inf_gen],
refine outer_measure.of_function_caratheodory (assume t, _),
cases t.eq_empty_or_nonempty with ht ht, by simp [ht],
simp only [outer_measure.Inf_gen_nonempty1 _ _ ht, le_infi_iff, ball_image_iff,
coe_to_outer_measure, measure_eq_infi t],
assume μ hμ u htu hu,
have hm : ∀{s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t,
{ assume s t hst,
rw [outer_measure.Inf_gen_nonempty2 _ _ (mem_image_of_mem _ hμ)],
refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _),
rw [to_outer_measure_apply],
refine measure_mono hst },
rw [measure_eq_inter_diff hu hs],
refine add_le_add (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu)
end
instance : has_Inf (measure α) :=
⟨λm, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩
lemma Inf_apply {m : set (measure α)} {s : set α} (hs : is_measurable s) :
Inf m s = Inf (to_outer_measure '' m) s :=
to_measure_apply _ _ hs
private lemma Inf_le (h : μ ∈ m) : Inf m ≤ μ :=
have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h),
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
private lemma le_Inf (h : ∀μ' ∈ m, μ ≤ μ') : μ ≤ Inf m :=
have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) :=
le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ,
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
instance : complete_lattice (measure α) :=
{ bot := 0,
bot_le := assume a s hs, by exact bot_le,
/- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now
top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top),
le_top := assume a s hs,
by cases s.eq_empty_or_nonempty with h h;
simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply],
-/
.. complete_lattice_of_Inf (measure α) (λ ms, ⟨λ _, Inf_le, λ _, le_Inf⟩) }
@[simp] lemma measure_univ_eq_zero {μ : measure α} : μ univ = 0 ↔ μ = 0 :=
⟨λ h, bot_unique $ λ s hs, trans_rel_left (≤) (measure_mono (subset_univ s)) h, λ h, h.symm ▸ rfl⟩
-- TODO: add typeclasses for `∀ c, monotone ((*) c)` and `∀ c, monotone ((+) c)`
protected lemma add_le_add_left {μ₁ μ₂ : measure α} (ν : measure α) (hμ : μ₁ ≤ μ₂) :
ν + μ₁ ≤ ν + μ₂ :=
λ s hs, add_le_add_left (hμ s hs) _
protected lemma add_le_add_right {μ₁ μ₂ : measure α} (hμ : μ₁ ≤ μ₂) (ν : measure α) :
μ₁ + ν ≤ μ₂ + ν :=
λ s hs, add_le_add_right (hμ s hs) _
protected lemma add_le_add {μ₁ μ₂ : measure α} (hμ : μ₁ ≤ μ₂) {ν₁ ν₂ : measure α} (hν : ν₁ ≤ ν₂) :
μ₁ + ν₁ ≤ μ₂ + ν₂ :=
λ s hs, add_le_add (hμ s hs) (hν s hs)
protected lemma zero_le (μ : measure α) : 0 ≤ μ := bot_le
protected lemma le_add_left {ν ν' : measure α} (h : μ ≤ ν) : μ ≤ ν' + ν :=
λ s hs, le_add_left (h s hs)
protected lemma le_add_right {ν ν' : measure α} (h : μ ≤ ν) : μ ≤ ν + ν' :=
λ s hs, le_add_right (h s hs)
end
/-! ### Pushforward and pullback -/
/-- Lift a linear map between `outer_measure` spaces such that for each measure `μ` every measurable
set is caratheodory-measurable w.r.t. `f μ` to a linear map between `measure` spaces. -/
def lift_linear (f : outer_measure α →ₗ[ennreal] outer_measure β)
(hf : ∀ μ : measure α, ‹_› ≤ (f μ.to_outer_measure).caratheodory) :
measure α →ₗ[ennreal] measure β :=
{ to_fun := λ μ, (f μ.to_outer_measure).to_measure (hf μ),
map_add' := λ μ₁ μ₂, ext $ λ s hs, by simp [hs],
map_smul' := λ c μ, ext $ λ s hs, by simp [hs] }
@[simp] lemma lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf)
{μ : measure α} {s : set β} (hs : is_measurable s) :
lift_linear f hf μ s = f μ.to_outer_measure s :=
to_measure_apply _ _ hs
lemma le_lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf)
{μ : measure α} (s : set β) :
f μ.to_outer_measure s ≤ lift_linear f hf μ s :=
le_to_measure_apply _ _ s
/-- The pushforward of a measure. It is defined to be `0` if `f` is not a measurable function. -/
def map (f : α → β) : measure α →ₗ[ennreal] measure β :=
if hf : measurable f then
lift_linear (outer_measure.map f) $ λ μ s hs t,
le_to_outer_measure_caratheodory μ _ (hf hs) (f ⁻¹' t)
else 0
variables {μ ν : measure α}
@[simp] theorem map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) :
map f μ s = μ (f ⁻¹' s) :=
by simp [map, dif_pos hf, hs]
@[simp] lemma map_id : map id μ = μ :=
ext $ λ s, map_apply measurable_id
lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) :
map g (map f μ) = map (g ∘ f) μ :=
ext $ λ s hs,
by simp [hf, hg, hs, hg hs, hg.comp hf, ← preimage_comp]
/-- Pullback of a `measure`. If `f` sends each `measurable` set to a `measurable` set, then for each
measurable set `s` we have `comap f μ s = μ (f '' s)`. -/
def comap (f : α → β) : measure β →ₗ[ennreal] measure α :=
if hf : injective f ∧ ∀ s, is_measurable s → is_measurable (f '' s) then
lift_linear (outer_measure.comap f) $ λ μ s hs t,
begin
simp only [coe_to_outer_measure, outer_measure.comap_apply, ← image_inter hf.1, image_diff hf.1],
apply le_to_outer_measure_caratheodory,
exact hf.2 s hs
end
else 0
lemma comap_apply (f : α → β) (hfi : injective f)
(hf : ∀ s, is_measurable s → is_measurable (f '' s)) (μ : measure β)
{s : set α} (hs : is_measurable s) :
comap f μ s = μ (f '' s) :=
begin
rw [comap, dif_pos, lift_linear_apply _ hs, outer_measure.comap_apply, coe_to_outer_measure],
exact ⟨hfi, hf⟩
end
/-! ### Restricting a measure -/
/-- Restrict a measure `μ` to a set `s` as an `ennreal`-linear map. -/
def restrictₗ (s : set α) : measure α →ₗ[ennreal] measure α :=
lift_linear (outer_measure.restrict s) $ λ μ s' hs' t,
begin
suffices : μ (s ∩ t) = μ (s ∩ t ∩ s') + μ (s ∩ t \ s'),
{ simpa [← set.inter_assoc, set.inter_comm _ s, ← inter_diff_assoc] },
exact le_to_outer_measure_caratheodory _ _ hs' _,
end
/-- Restrict a measure `μ` to a set `s`. -/
def restrict (μ : measure α) (s : set α) : measure α := restrictₗ s μ
@[simp] lemma restrictₗ_apply (s : set α) (μ : measure α) :
restrictₗ s μ = μ.restrict s :=
rfl
@[simp] lemma restrict_apply {s t : set α} (ht : is_measurable t) :
μ.restrict s t = μ (t ∩ s) :=
by simp [← restrictₗ_apply, restrictₗ, ht]
lemma restrict_apply_univ (s : set α) : μ.restrict s univ = μ s :=
by rw [restrict_apply is_measurable.univ, set.univ_inter]
lemma le_restrict_apply (s t : set α) :
μ (t ∩ s) ≤ μ.restrict s t :=
by { rw [restrict, restrictₗ], convert le_lift_linear_apply _ t, simp }
@[simp] lemma restrict_add (μ ν : measure α) (s : set α) :
(μ + ν).restrict s = μ.restrict s + ν.restrict s :=
(restrictₗ s).map_add μ ν
@[simp] lemma restrict_zero (s : set α) : (0 : measure α).restrict s = 0 :=
(restrictₗ s).map_zero
@[simp] lemma restrict_smul (c : ennreal) (μ : measure α) (s : set α) :
(c • μ).restrict s = c • μ.restrict s :=
(restrictₗ s).map_smul c μ
@[simp] lemma restrict_restrict {s t : set α} (hs : is_measurable s) :
(μ.restrict t).restrict s = μ.restrict (s ∩ t) :=
ext $ λ u hu, by simp [*, set.inter_assoc]
lemma restrict_apply_eq_zero {s t : set α} (ht : is_measurable t) :
μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 :=
by rw [restrict_apply ht]
lemma restrict_apply_eq_zero' {s t : set α} (hs : is_measurable s) :
μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 :=
begin
refine ⟨λ h, le_zero_iff_eq.1 (h ▸ le_restrict_apply _ _), λ h, _⟩,
rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t', htt', ht', ht'0⟩,
apply measure_mono_null ((inter_subset _ _ _).1 htt'),
rw [restrict_apply (hs.compl.union ht'), union_inter_distrib_right, compl_inter_self,
set.empty_union],
exact measure_mono_null (inter_subset_left _ _) ht'0
end
@[simp] lemma restrict_eq_zero {s} : μ.restrict s = 0 ↔ μ s = 0 :=
by rw [← measure_univ_eq_zero, restrict_apply_univ]
@[simp] lemma restrict_empty : μ.restrict ∅ = 0 := ext $ λ s hs, by simp [hs]
@[simp] lemma restrict_univ : μ.restrict univ = μ := ext $ λ s hs, by simp [hs]
lemma restrict_union_apply {s s' t : set α} (h : disjoint (t ∩ s) (t ∩ s')) (hs : is_measurable s)
(hs' : is_measurable s') (ht : is_measurable t) :
μ.restrict (s ∪ s') t = μ.restrict s t + μ.restrict s' t :=
begin
simp only [restrict_apply, ht, set.inter_union_distrib_left],
exact measure_union h (ht.inter hs) (ht.inter hs'),
end
lemma restrict_union {s t : set α} (h : disjoint s t) (hs : is_measurable s)
(ht : is_measurable t) :
μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t :=
ext $ λ t' ht', restrict_union_apply (h.mono inf_le_right inf_le_right) hs ht ht'
lemma restrict_union_add_inter {s t : set α} (hs : is_measurable s) (ht : is_measurable t) :
μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t :=
begin
ext1 u hu,
simp only [add_apply, restrict_apply hu, inter_union_distrib_left],
convert measure_union_add_inter (hu.inter hs) (hu.inter ht) using 3,
rw [set.inter_left_comm (u ∩ s), set.inter_assoc, ← set.inter_assoc u u, set.inter_self]
end
@[simp] lemma restrict_add_restrict_compl {s : set α} (hs : is_measurable s) :
μ.restrict s + μ.restrict sᶜ = μ :=
by rw [← restrict_union (disjoint_compl_right _) hs hs.compl, union_compl_self, restrict_univ]
@[simp] lemma restrict_compl_add_restrict {s : set α} (hs : is_measurable s) :
μ.restrict sᶜ + μ.restrict s = μ :=
by rw [add_comm, restrict_add_restrict_compl hs]
lemma restrict_union_le (s s' : set α) : μ.restrict (s ∪ s') ≤ μ.restrict s + μ.restrict s' :=
begin
intros t ht,
suffices : μ (t ∩ s ∪ t ∩ s') ≤ μ (t ∩ s) + μ (t ∩ s'),
by simpa [ht, inter_union_distrib_left],
apply measure_union_le
end
lemma restrict_Union_apply {ι} [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ i, is_measurable (s i)) {t : set α} (ht : is_measurable t) :
μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t :=
begin
simp only [restrict_apply, ht, inter_Union],
exact measure_Union (λ i j hij, (hd i j hij).mono inf_le_right inf_le_right)
(λ i, ht.inter (hm i))
end
lemma restrict_Union_apply_eq_supr {ι} [encodable ι] {s : ι → set α}
(hm : ∀ i, is_measurable (s i)) (hd : directed (⊆) s) {t : set α} (ht : is_measurable t) :
μ.restrict (⋃ i, s i) t = ⨆ i, μ.restrict (s i) t :=
begin
simp only [restrict_apply ht, inter_Union],
rw [measure_Union_eq_supr],
exacts [λ i, ht.inter (hm i), hd.mono_comp _ (λ s₁ s₂, inter_subset_inter_right _)]
end
lemma restrict_map {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) :
(map f μ).restrict s = map f (μ.restrict $ f ⁻¹' s) :=
ext $ λ t ht, by simp [*, hf ht]
lemma map_comap_subtype_coe {s : set α} (hs : is_measurable s) :
(map (coe : s → α)).comp (comap coe) = restrictₗ s :=
linear_map.ext $ λ μ, ext $ λ t ht,
by rw [restrictₗ_apply, restrict_apply ht, linear_map.comp_apply,
map_apply measurable_subtype_coe ht,
comap_apply (coe : s → α) subtype.val_injective (λ _, hs.subtype_image) _
(measurable_subtype_coe ht), subtype.image_preimage_coe]
/-- Restriction of a measure to a subset is monotone both in set and in measure. -/
@[mono] lemma restrict_mono ⦃s s' : set α⦄ (hs : s ⊆ s') ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) :
μ.restrict s ≤ ν.restrict s' :=
assume t ht,
calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht
... ≤ μ (t ∩ s') : measure_mono $ inter_subset_inter_right _ hs
... ≤ ν (t ∩ s') : le_iff'.1 hμν (t ∩ s')
... = ν.restrict s' t : (restrict_apply ht).symm
lemma restrict_le_self {s} : μ.restrict s ≤ μ :=
assume t ht,
calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht
... ≤ μ t : measure_mono $ inter_subset_left t s
lemma restrict_congr_meas {s} (hs : is_measurable s) :
μ.restrict s = ν.restrict s ↔ ∀ t ⊆ s, is_measurable t → μ t = ν t :=
⟨λ H t hts ht,
by rw [← inter_eq_self_of_subset_left hts, ← restrict_apply ht, H, restrict_apply ht],
λ H, ext $ λ t ht,
by rw [restrict_apply ht, restrict_apply ht, H _ (inter_subset_right _ _) (ht.inter hs)]⟩
lemma restrict_congr_mono {s t} (hs : s ⊆ t) (hm : is_measurable s)
(h : μ.restrict t = ν.restrict t) :
μ.restrict s = ν.restrict s :=
by rw [← inter_eq_self_of_subset_left hs, ← restrict_restrict hm, h, restrict_restrict hm]
/-- If two measures agree on all measurable subsets of `s` and `t`, then they agree on all
measurable subsets of `s ∪ t`. -/
lemma restrict_union_congr {s t : set α} (hsm : is_measurable s) (htm : is_measurable t) :
μ.restrict (s ∪ t) = ν.restrict (s ∪ t) ↔
μ.restrict s = ν.restrict s ∧ μ.restrict t = ν.restrict t :=
begin
refine ⟨λ h, ⟨restrict_congr_mono (subset_union_left _ _) hsm h,
restrict_congr_mono (subset_union_right _ _) htm h⟩, _⟩,
simp only [restrict_congr_meas, hsm, htm, hsm.union htm],
rintros ⟨hs, ht⟩ u hu hum,
rw [measure_eq_inter_diff hum hsm, measure_eq_inter_diff hum hsm,
hs _ (inter_subset_right _ _) (hum.inter hsm),
ht _ (diff_subset_iff.2 hu) (hum.diff hsm)]
end
variables {ι : Type*}
lemma restrict_finset_bUnion_congr {s : finset ι} {t : ι → set α}
(htm : ∀ i ∈ s, is_measurable (t i)) :
μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔
∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) :=
begin
induction s using finset.induction_on with i s hi hs, { simp },
simp only [finset.mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at htm ⊢,
simp only [finset.bUnion_insert, ← hs htm.2],
exact restrict_union_congr htm.1 (is_measurable.bUnion s.countable_to_set htm.2)
end
lemma restrict_Union_congr [encodable ι] {s : ι → set α} (hm : ∀ i, is_measurable (s i)) :
μ.restrict (⋃ i, s i) = ν.restrict (⋃ i, s i) ↔
∀ i, μ.restrict (s i) = ν.restrict (s i) :=
begin
refine ⟨λ h i, restrict_congr_mono (subset_Union _ _) (hm i) h, λ h, _⟩,
ext1 t ht,
have M : ∀ t : finset ι, is_measurable (⋃ i ∈ t, s i) :=
λ t, is_measurable.bUnion t.countable_to_set (λ i _, hm i),
have D : directed (⊆) (λ t : finset ι, ⋃ i ∈ t, s i) :=
directed_of_sup (λ t₁ t₂ ht, bUnion_subset_bUnion_left ht),
rw [Union_eq_Union_finset],
simp only [restrict_Union_apply_eq_supr M D ht,
(restrict_finset_bUnion_congr (λ i hi, hm i)).2 (λ i hi, h i)],
end
lemma restrict_bUnion_congr {s : set ι} {t : ι → set α} (hc : countable s)
(htm : ∀ i ∈ s, is_measurable (t i)) :
μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔
∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) :=
begin
simp only [bUnion_eq_Union, set_coe.forall'] at htm ⊢,
haveI := hc.to_encodable,
exact restrict_Union_congr htm
end
lemma restrict_sUnion_congr {S : set (set α)} (hc : countable S) (hm : ∀ s ∈ S, is_measurable s) :
μ.restrict (⋃₀ S) = ν.restrict (⋃₀ S) ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s :=
by rw [sUnion_eq_bUnion, restrict_bUnion_congr hc hm]
/-! ### Extensionality results -/
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `Union`). -/
lemma ext_iff_of_Union_eq_univ [encodable ι] {s : ι → set α}
(hm : ∀ i, is_measurable (s i)) (hs : (⋃ i, s i) = univ) :
μ = ν ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) :=
by rw [← restrict_Union_congr hm, hs, restrict_univ, restrict_univ]
alias ext_iff_of_Union_eq_univ ↔ _ measure_theory.measure.ext_of_Union_eq_univ
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `bUnion`). -/
lemma ext_iff_of_bUnion_eq_univ {S : set ι} {s : ι → set α} (hc : countable S)
(hm : ∀ i ∈ S, is_measurable (s i)) (hs : (⋃ i ∈ S, s i) = univ) :
μ = ν ↔ ∀ i ∈ S, μ.restrict (s i) = ν.restrict (s i) :=
by rw [← restrict_bUnion_congr hc hm, hs, restrict_univ, restrict_univ]
alias ext_iff_of_bUnion_eq_univ ↔ _ measure_theory.measure.ext_of_bUnion_eq_univ
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `sUnion`). -/
lemma ext_iff_of_sUnion_eq_univ {S : set (set α)} (hc : countable S)
(hm : ∀ s ∈ S, is_measurable s) (hs : (⋃₀ S) = univ) :
μ = ν ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s :=
ext_iff_of_bUnion_eq_univ hc hm $ by rwa ← sUnion_eq_bUnion
alias ext_iff_of_sUnion_eq_univ ↔ _ measure_theory.measure.ext_of_sUnion_eq_univ
open measurable_space
lemma ext_of_generate_from_of_cover {S T : set (set α)}
(h_gen : ‹_› = generate_from S) (hc : countable T)
(h_inter : is_pi_system S)
(hm : ∀ t ∈ T, is_measurable t) (hU : ⋃₀ T = univ) (htop : ∀ t ∈ T, μ t < ⊤)
(ST_eq : ∀ (t ∈ T) (s ∈ S), μ (s ∩ t) = ν (s ∩ t)) (T_eq : ∀ t ∈ T, μ t = ν t) :
μ = ν :=
begin
refine ext_of_sUnion_eq_univ hc hm hU (λ t ht, _),
ext1 u hu,
simp only [restrict_apply hu],
refine induction_on_inter h_gen h_inter _ (ST_eq t ht) _ _ hu,
{ simp only [set.empty_inter, measure_empty] },
{ intros v hv hvt,
have := T_eq t ht,
rw [set.inter_comm] at hvt ⊢,
rwa [measure_eq_inter_diff (hm _ ht) hv, measure_eq_inter_diff (hm _ ht) hv, ← hvt,
ennreal.add_right_inj] at this,
exact (measure_mono $ set.inter_subset_left _ _).trans_lt (htop t ht) },
{ intros f hfd hfm h_eq,
have : pairwise (disjoint on λ n, f n ∩ t) :=
λ m n hmn, (hfd m n hmn).mono (inter_subset_left _ _) (inter_subset_left _ _),
simp only [Union_inter, measure_Union this (λ n, is_measurable.inter (hfm n) (hm t ht)), h_eq] }
end
/-- Two measures are equal if they are equal on the π-system generating the σ-algebra,
and they are both finite on a increasing spanning sequence of sets in the π-system.
This lemma is formulated using `sUnion`. -/
lemma ext_of_generate_from_of_cover_subset {S T : set (set α)}
(h_gen : ‹_› = generate_from S)
(h_inter : is_pi_system S)
(h_sub : T ⊆ S) (hc : countable T) (hU : ⋃₀ T = univ) (htop : ∀ s ∈ T, μ s < ⊤)
(h_eq : ∀ s ∈ S, μ s = ν s) :
μ = ν :=
begin
refine ext_of_generate_from_of_cover h_gen hc h_inter _ hU htop _ (λ t ht, h_eq t (h_sub ht)),
{ intros t ht, rw [h_gen], exact generate_measurable.basic _ (h_sub ht) },
{ intros t ht s hs, cases (s ∩ t).eq_empty_or_nonempty with H H,
{ simp only [H, measure_empty] },
{ exact h_eq _ (h_inter _ _ hs (h_sub ht) H) } }
end
/-- Two measures are equal if they are equal on the π-system generating the σ-algebra,
and they are both finite on a increasing spanning sequence of sets in the π-system.
This lemma is formulated using `Union`. -/
lemma ext_of_generate_from_of_Union (C : set (set α)) (B : ℕ → set α)
(hA : ‹_› = generate_from C) (hC : is_pi_system C) (h1B : (⋃ i, B i) = univ)
(h2B : ∀ i, B i ∈ C) (hμB : ∀ i, μ (B i) < ⊤) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν :=
begin
refine measure.ext_of_generate_from_of_cover_subset hA hC _ (countable_range B) h1B _ h_eq,
{ rintro _ ⟨i, rfl⟩, apply h2B },
{ rintro _ ⟨i, rfl⟩, apply hμB }
end
/-- The dirac measure. -/
def dirac (a : α) : measure α :=
(outer_measure.dirac a).to_measure (by simp)
lemma dirac_apply' (a : α) {s : set α} (hs : is_measurable s) :
dirac a s = ⨆ h : a ∈ s, 1 :=
to_measure_apply _ _ hs
@[simp] lemma dirac_apply (a : α) {s : set α} (hs : is_measurable s) :
dirac a s = s.indicator 1 a :=
(dirac_apply' a hs).trans $ by { by_cases h : a ∈ s; simp [h] }
lemma dirac_apply_of_mem {a : α} {s : set α} (h : a ∈ s) :
dirac a s = 1 :=
begin
rw [measure_eq_infi, infi_subtype', infi_subtype'],
convert infi_const,
{ ext1 ⟨⟨t, hst⟩, ht⟩,
dsimp only [subtype.coe_mk] at *,
simp only [dirac_apply _ ht, indicator_of_mem (hst h), pi.one_apply] },
{ exact ⟨⟨⟨set.univ, subset_univ _⟩, is_measurable.univ⟩⟩ }
end
/-- Sum of an indexed family of measures. -/
def sum {ι : Type*} (f : ι → measure α) : measure α :=
(outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $
le_trans
(by exact le_infi (λ i, le_to_outer_measure_caratheodory _))
(outer_measure.le_sum_caratheodory _)
@[simp] lemma sum_apply {ι : Type*} (f : ι → measure α) {s : set α} (hs : is_measurable s) :
sum f s = ∑' i, f i s :=
to_measure_apply _ _ hs
lemma le_sum {ι : Type*} (μ : ι → measure α) (i : ι) : μ i ≤ sum μ :=
λ s hs, by simp only [sum_apply μ hs, ennreal.le_tsum i]
lemma restrict_Union {ι} [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ i, is_measurable (s i)) :
μ.restrict (⋃ i, s i) = sum (λ i, μ.restrict (s i)) :=
ext $ λ t ht, by simp only [sum_apply _ ht, restrict_Union_apply hd hm ht]
lemma restrict_Union_le {ι} [encodable ι] {s : ι → set α} :
μ.restrict (⋃ i, s i) ≤ sum (λ i, μ.restrict (s i)) :=
begin
intros t ht,
suffices : μ (⋃ i, t ∩ s i) ≤ ∑' i, μ (t ∩ s i), by simpa [ht, inter_Union],
apply measure_Union_le
end
@[simp] lemma sum_bool (f : bool → measure α) : sum f = f tt + f ff :=
ext $ λ s hs, by simp [hs, tsum_fintype]
@[simp] lemma restrict_sum {ι : Type*} (μ : ι → measure α) {s : set α} (hs : is_measurable s) :
(sum μ).restrict s = sum (λ i, (μ i).restrict s) :=
ext $ λ t ht, by simp only [sum_apply, restrict_apply, ht, ht.inter hs]
/-- Counting measure on any measurable space. -/
def count : measure α := sum dirac
lemma count_apply {s : set α} (hs : is_measurable s) :
count s = ∑' i : s, 1 :=
by simp only [count, sum_apply, hs, dirac_apply, ← tsum_subtype s 1, pi.one_apply]
@[simp] lemma count_apply_finset [measurable_singleton_class α] (s : finset α) :
count (↑s : set α) = s.card :=
calc count (↑s : set α) = ∑' i : (↑s : set α), (1 : α → ennreal) i : count_apply s.is_measurable
... = ∑ i in s, 1 : s.tsum_subtype 1
... = s.card : by simp
lemma count_apply_finite [measurable_singleton_class α] (s : set α) (hs : finite s) :
count s = hs.to_finset.card :=
by rw [← count_apply_finset, finite.coe_to_finset]
/-- `count` measure evaluates to infinity at infinite sets. -/
lemma count_apply_infinite [measurable_singleton_class α] {s : set α} (hs : s.infinite) :
count s = ⊤ :=
begin
by_contra H,
rcases ennreal.exists_nat_gt H with ⟨n, hn⟩,
rcases hs.exists_subset_card_eq n with ⟨t, ht, rfl⟩,
have := lt_of_le_of_lt (measure_mono ht) hn,
simpa [lt_irrefl] using this
end
@[simp] lemma count_apply_eq_top [measurable_singleton_class α] {s : set α} :
count s = ⊤ ↔ s.infinite :=
begin
by_cases hs : s.finite,
{ simp [set.infinite, hs, count_apply_finite] },
{ change s.infinite at hs,
simp [hs, count_apply_infinite] }
end
@[simp] lemma count_apply_lt_top [measurable_singleton_class α] {s : set α} :
count s < ⊤ ↔ s.finite :=
calc count s < ⊤ ↔ count s ≠ ⊤ : lt_top_iff_ne_top
... ↔ ¬s.infinite : not_congr count_apply_eq_top
... ↔ s.finite : not_not
open measurable_space
/-! ### The almost everywhere filter -/
/-- The “almost everywhere” filter of co-null sets. -/
def ae (μ : measure α) : filter α :=
{ sets := {s | μ sᶜ = 0},
univ_sets := by simp,
inter_sets := λ s t hs ht, by simp only [compl_inter, mem_set_of_eq];
exact measure_union_null hs ht,
sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs }
/-- The filter of sets `s` such that `sᶜ` has finite measure. -/
def cofinite (μ : measure α) : filter α :=
{ sets := {s | μ sᶜ < ⊤},
univ_sets := by simp,
inter_sets := λ s t hs ht, by { simp only [compl_inter, mem_set_of_eq],
calc μ (sᶜ ∪ tᶜ) ≤ μ sᶜ + μ tᶜ : measure_union_le _ _
... < ⊤ : ennreal.add_lt_top.2 ⟨hs, ht⟩ },
sets_of_superset := λ s t hs hst, lt_of_le_of_lt (measure_mono $ compl_subset_compl.2 hst) hs }
lemma mem_cofinite {s : set α} : s ∈ μ.cofinite ↔ μ sᶜ < ⊤ := iff.rfl
lemma compl_mem_cofinite {s : set α} : sᶜ ∈ μ.cofinite ↔ μ s < ⊤ :=
by rw [mem_cofinite, compl_compl]
lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in μ.cofinite, p x) ↔ μ {x | ¬p x} < ⊤ := iff.rfl
end measure
variables {α : Type*} {β : Type*} [measurable_space α] {μ : measure α}
notation `∀ᵐ` binders ` ∂` μ `, ` r:(scoped P, filter.eventually P (measure.ae μ)) := r
notation f ` =ᵐ[`:50 μ:50 `] `:0 g:50 := f =ᶠ[measure.ae μ] g
notation f ` ≤ᵐ[`:50 μ:50 `] `:0 g:50 := f ≤ᶠ[measure.ae μ] g
lemma mem_ae_iff {s : set α} : s ∈ μ.ae ↔ μ sᶜ = 0 := iff.rfl
lemma ae_iff {p : α → Prop} : (∀ᵐ a ∂ μ, p a) ↔ μ { a | ¬ p a } = 0 := iff.rfl
lemma compl_mem_ae_iff {s : set α} : sᶜ ∈ μ.ae ↔ μ s = 0 := by simp only [mem_ae_iff, compl_compl]
lemma measure_zero_iff_ae_nmem {s : set α} : μ s = 0 ↔ ∀ᵐ a ∂ μ, a ∉ s :=
compl_mem_ae_iff.symm
@[simp] lemma ae_eq_bot : μ.ae = ⊥ ↔ μ = 0 :=
by rw [← empty_in_sets_eq_bot, mem_ae_iff, compl_empty, measure.measure_univ_eq_zero]
lemma ae_of_all {p : α → Prop} (μ : measure α) : (∀a, p a) → ∀ᵐ a ∂ μ, p a :=
eventually_of_forall
@[mono] lemma ae_mono {μ ν : measure α} (h : μ ≤ ν) : μ.ae ≤ ν.ae :=
λ s hs, bot_unique $ trans_rel_left (≤) (measure.le_iff'.1 h _) hs
instance : countable_Inter_filter μ.ae :=
⟨begin
intros S hSc hS,
simp only [mem_ae_iff, compl_sInter, sUnion_image, bUnion_eq_Union] at hS ⊢,
haveI := hSc.to_encodable,
exact measure_Union_null (subtype.forall.2 hS)
end⟩
instance ae_is_measurably_generated : is_measurably_generated μ.ae :=
⟨λ s hs, let ⟨t, hst, htm, htμ⟩ := exists_is_measurable_superset_of_measure_eq_zero hs in
⟨tᶜ, compl_mem_ae_iff.2 htμ, htm.compl, compl_subset_comm.1 hst⟩⟩
lemma ae_all_iff {ι : Type*} [encodable ι] {p : α → ι → Prop} :
(∀ᵐ a ∂ μ, ∀i, p a i) ↔ (∀i, ∀ᵐ a ∂ μ, p a i) :=
eventually_countable_forall
lemma ae_ball_iff {ι} {S : set ι} (hS : countable S) {p : Π (x : α) (i ∈ S), Prop} :
(∀ᵐ x ∂ μ, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᵐ x ∂ μ, p x i ‹_› :=
eventually_countable_ball hS
lemma ae_eq_refl (f : α → β) : f =ᵐ[μ] f := eventually_eq.refl _ _
lemma ae_eq_symm {f g : α → β} (h : f =ᵐ[μ] g) : g =ᵐ[μ] f :=
h.symm
lemma ae_eq_trans {f g h: α → β} (h₁ : f =ᵐ[μ] g) (h₂ : g =ᵐ[μ] h) :
f =ᵐ[μ] h :=
h₁.trans h₂
lemma ae_eq_empty {s : set α} : s =ᵐ[μ] (∅ : set α) ↔ μ s = 0 :=
eventually_eq_empty.trans $ by simp [ae_iff]
lemma ae_le_set {s t : set α} : s ≤ᵐ[μ] t ↔ μ (s \ t) = 0 :=
calc s ≤ᵐ[μ] t ↔ ∀ᵐ x ∂μ, x ∈ s → x ∈ t : iff.rfl
... ↔ μ (s \ t) = 0 : by simp [ae_iff]; refl
lemma union_ae_eq_right {s t : set α} :
(s ∪ t : set α) =ᵐ[μ] t ↔ μ (s \ t) = 0 :=
by simp [eventually_le_antisymm_iff, ae_le_set, union_diff_right,
diff_eq_empty.2 (set.subset_union_right _ _)]
lemma diff_ae_eq_self {s t : set α} :
(s \ t : set α) =ᵐ[μ] s ↔ μ (s ∩ t) = 0 :=
by simp [eventually_le_antisymm_iff, ae_le_set, diff_diff_right,
diff_diff, diff_eq_empty.2 (set.subset_union_right _ _)]
lemma mem_ae_map_iff [measurable_space β] {f : α → β} (hf : measurable f)
{s : set β} (hs : is_measurable s) :
s ∈ (measure.map f μ).ae ↔ (f ⁻¹' s) ∈ μ.ae :=
by simp only [mem_ae_iff, measure.map_apply hf hs.compl, preimage_compl]
lemma ae_map_iff [measurable_space β] {f : α → β} (hf : measurable f)
{p : β → Prop} (hp : is_measurable {x | p x}) :
(∀ᵐ y ∂ (measure.map f μ), p y) ↔ ∀ᵐ x ∂ μ, p (f x) :=
mem_ae_map_iff hf hp
lemma ae_restrict_iff {s : set α} {p : α → Prop} (hp : is_measurable {x | p x}) :
(∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x :=
begin
simp only [ae_iff, ← compl_set_of, measure.restrict_apply hp.compl],
congr' with x, simp [and_comm]
end
lemma ae_smul_measure {p : α → Prop} (h : ∀ᵐ x ∂μ, p x) (c : ennreal) : ∀ᵐ x ∂(c • μ), p x :=
ae_iff.2 $ by rw [measure.smul_apply, ae_iff.1 h, mul_zero]
lemma ae_add_measure_iff {p : α → Prop} {ν} : (∀ᵐ x ∂μ + ν, p x) ↔ (∀ᵐ x ∂μ, p x) ∧ ∀ᵐ x ∂ν, p x :=
add_eq_zero_iff
@[simp] lemma ae_restrict_eq {s : set α} (hs : is_measurable s):
(μ.restrict s).ae = μ.ae ⊓ 𝓟 s :=
begin
ext t,
simp only [mem_inf_principal, mem_ae_iff, measure.restrict_apply_eq_zero' hs, compl_set_of,
not_imp, and_comm (_ ∈ s)],
refl
end
@[simp] lemma ae_restrict_eq_bot {s} : (μ.restrict s).ae = ⊥ ↔ μ s = 0 :=
ae_eq_bot.trans measure.restrict_eq_zero
@[simp] lemma ae_restrict_ne_bot {s} : (μ.restrict s).ae.ne_bot ↔ 0 < μ s :=
(not_congr ae_restrict_eq_bot).trans zero_lt_iff_ne_zero.symm
/-- A version of the Borel-Cantelli lemma: if sᵢ is a sequence of measurable sets such that
∑ μ sᵢ exists, then for almost all x, x does not belong to almost all sᵢ. -/
lemma ae_eventually_not_mem {s : ℕ → set α} (hs : ∀ i, is_measurable (s i))
(hs' : (∑' i, μ (s i)) ≠ ⊤) : ∀ᵐ x ∂ μ, ∀ᶠ n in at_top, x ∉ s n :=
begin
refine measure_mono_null _ (measure_limsup_eq_zero hs hs'),
rw ←set.le_eq_subset,
refine le_Inf (λ t ht x hx, _),
simp only [le_eq_subset, not_exists, eventually_map, exists_prop, ge_iff_le, mem_set_of_eq,
eventually_at_top, mem_compl_eq, not_forall, not_not_mem] at hx ht,
rcases ht with ⟨i, hi⟩,
rcases hx i with ⟨j, ⟨hj, hj'⟩⟩,
exact hi j hj hj'
end
lemma mem_dirac_ae_iff {a : α} {s : set α} (hs : is_measurable s) :
s ∈ (measure.dirac a).ae ↔ a ∈ s :=
by by_cases a ∈ s; simp [mem_ae_iff, measure.dirac_apply, hs.compl, indicator_apply, *]
lemma eventually_dirac {a : α} {p : α → Prop} (hp : is_measurable {x | p x}) :
(∀ᵐ x ∂(measure.dirac a), p x) ↔ p a :=
mem_dirac_ae_iff hp
lemma eventually_eq_dirac [measurable_space β] [measurable_singleton_class β] {a : α} {f : α → β}
(hf : measurable f) :
f =ᵐ[measure.dirac a] const α (f a) :=
(eventually_dirac $ show is_measurable (f ⁻¹' {f a}), from hf $ is_measurable_singleton _).2 rfl
lemma dirac_ae_eq [measurable_singleton_class α] (a : α) : (measure.dirac a).ae = pure a :=
begin
ext s,
simp only [mem_ae_iff, mem_pure_sets],
by_cases ha : a ∈ s,
{ simp only [ha, iff_true],
rw [← set.singleton_subset_iff, ← compl_subset_compl] at ha,
refine measure_mono_null ha _,
simp [measure.dirac_apply a (is_measurable_singleton a).compl] },
{ simp only [ha, iff_false, measure.dirac_apply_of_mem (mem_compl ha)],
exact one_ne_zero }
end
lemma eventually_eq_dirac' [measurable_singleton_class α] {a : α} (f : α → β) :
f =ᵐ[measure.dirac a] const α (f a) :=
by { rw [dirac_ae_eq], show f a = f a, refl }
lemma measure_diff_of_ae_le {s t : set α} (H : s ≤ᵐ[μ] t) :
μ (s \ t) = 0 :=
flip measure_mono_null H $ λ x hx H, hx.2 (H hx.1)
/-- If `s ⊆ t` modulo a set of measure `0`, then `μ s ≤ μ t`. -/
lemma measure_mono_ae {s t : set α} (H : s ≤ᵐ[μ] t) :
μ s ≤ μ t :=
calc μ s ≤ μ (s ∪ t) : measure_mono $ subset_union_left s t
... = μ (t ∪ s \ t) : by rw [union_diff_self, set.union_comm]
... ≤ μ t + μ (s \ t) : measure_union_le _ _
... = μ t : by rw [measure_diff_of_ae_le H, add_zero]
alias measure_mono_ae ← filter.eventually_le.measure_le
/-- If two sets are equal modulo a set of measure zero, then `μ s = μ t`. -/
lemma measure_congr {s t : set α} (H : s =ᵐ[μ] t) : μ s = μ t :=
le_antisymm H.le.measure_le H.symm.le.measure_le
lemma restrict_mono_ae {s t : set α} (h : s ≤ᵐ[μ] t) : μ.restrict s ≤ μ.restrict t :=
begin
intros u hu,
simp only [measure.restrict_apply hu],
exact measure_mono_ae (h.mono $ λ x hx, and.imp id hx)
end
lemma restrict_congr_set {s t : set α} (H : s =ᵐ[μ] t) : μ.restrict s = μ.restrict t :=
le_antisymm (restrict_mono_ae H.le) (restrict_mono_ae H.symm.le)
/-- A measure `μ` is called a probability measure if `μ univ = 1`. -/
class probability_measure (μ : measure α) : Prop := (measure_univ : μ univ = 1)
/-- A measure `μ` is called finite if `μ univ < ⊤`. -/
class finite_measure (μ : measure α) : Prop := (measure_univ_lt_top : μ univ < ⊤)
/-- Measure `μ` *has no atoms* if the measure of each singleton is zero.
NB: Wikipedia assumes that for any measurable set `s` with positive `μ`-measure,
there exists a measurable `t ⊆ s` such that `0 < μ t < μ s`. While this implies `μ {x} = 0`,
the converse is not true. -/
class has_no_atoms (μ : measure α) : Prop :=
(measure_singleton : ∀ x, μ {x} = 0)
export probability_measure (measure_univ) has_no_atoms (measure_singleton)
attribute [simp] measure_singleton
lemma measure_lt_top (μ : measure α) [finite_measure μ] (s : set α) : μ s < ⊤ :=
(measure_mono (subset_univ s)).trans_lt finite_measure.measure_univ_lt_top
lemma measure_ne_top (μ : measure α) [finite_measure μ] (s : set α) : μ s ≠ ⊤ :=
ne_of_lt (measure_lt_top μ s)
@[priority 100]
instance probability_measure.to_finite_measure (μ : measure α) [probability_measure μ] :
finite_measure μ :=
⟨by simp only [measure_univ, ennreal.one_lt_top]⟩
section no_atoms
variables [has_no_atoms μ]
lemma measure_countable {s : set α} (h : countable s) : μ s = 0 :=
begin
rw [← bUnion_of_singleton s, ← le_zero_iff_eq],
refine le_trans (measure_bUnion_le h _) _,
simp
end
lemma measure_finite {s : set α} (h : s.finite) : μ s = 0 :=
measure_countable h.countable
lemma measure_finset (s : finset α) : μ ↑s = 0 :=
measure_finite s.finite_to_set
lemma insert_ae_eq_self (a : α) (s : set α) :
(insert a s : set α) =ᵐ[μ] s :=
union_ae_eq_right.2 $ measure_mono_null (diff_subset _ _) (measure_singleton _)
variables [partial_order α] {a b : α}
lemma Iio_ae_eq_Iic : Iio a =ᵐ[μ] Iic a :=
by simp only [← Iic_diff_right, diff_ae_eq_self,
measure_mono_null (set.inter_subset_right _ _) (measure_singleton a)]
lemma Ioi_ae_eq_Ici : Ioi a =ᵐ[μ] Ici a :=
@Iio_ae_eq_Iic (order_dual α) ‹_› ‹_› _ _ _
lemma Ioo_ae_eq_Ioc : Ioo a b =ᵐ[μ] Ioc a b :=
(ae_eq_refl _).inter Iio_ae_eq_Iic
lemma Ioc_ae_eq_Icc : Ioc a b =ᵐ[μ] Icc a b :=
Ioi_ae_eq_Ici.inter (ae_eq_refl _)
lemma Ioo_ae_eq_Ico : Ioo a b =ᵐ[μ] Ico a b :=
Ioi_ae_eq_Ici.inter (ae_eq_refl _)
lemma Ioo_ae_eq_Icc : Ioo a b =ᵐ[μ] Icc a b :=
Ioi_ae_eq_Ici.inter Iio_ae_eq_Iic
lemma Ico_ae_eq_Icc : Ico a b =ᵐ[μ] Icc a b :=
(ae_eq_refl _).inter Iio_ae_eq_Iic
lemma Ico_ae_eq_Ioc : Ico a b =ᵐ[μ] Ioc a b :=
Ioo_ae_eq_Ico.symm.trans Ioo_ae_eq_Ioc
end no_atoms
/-- A measure is called finite at filter `f` if it is finite at some set `s ∈ f`.
Equivalently, it is eventually finite at `s` in `f.lift' powerset`. -/
def measure.finite_at_filter (μ : measure α) (f : filter α) : Prop := ∃ s ∈ f, μ s < ⊤
lemma finite_at_filter_of_finite (μ : measure α) [finite_measure μ] (f : filter α) :
μ.finite_at_filter f :=
⟨univ, univ_mem_sets, measure_lt_top μ univ⟩
lemma measure.finite_at_bot (μ : measure α) : μ.finite_at_filter ⊥ :=
⟨∅, mem_bot_sets, by simp only [measure_empty, with_top.zero_lt_top]⟩
instance restrict.finite_measure (μ : measure α) {s : set α} [hs : fact (μ s < ⊤)] :
finite_measure (μ.restrict s) :=
⟨by simp [hs.elim]⟩
/-- A measure is called locally finite if it is finite in some neighborhood of each point. -/
class locally_finite_measure [topological_space α] (μ : measure α) : Prop :=
(finite_at_nhds : ∀ x, μ.finite_at_filter (𝓝 x))
@[priority 100]
instance finite_measure.to_locally_finite_measure [topological_space α] (μ : measure α)
[finite_measure μ] :
locally_finite_measure μ :=
⟨λ x, finite_at_filter_of_finite _ _⟩
lemma measure.finite_at_nhds [topological_space α] (μ : measure α)
[locally_finite_measure μ] (x : α) :
μ.finite_at_filter (𝓝 x) :=
locally_finite_measure.finite_at_nhds x
open measurable_space
/-- Two finite measures are equal if they are equal on the π-system generating the σ-algebra
(and `univ`). -/
lemma ext_of_generate_finite (C : set (set α)) (hA : _inst_1 = generate_from C)
(hC : is_pi_system C) {μ ν : measure α}
[finite_measure μ] [finite_measure ν] (hμν : ∀ s ∈ C, μ s = ν s) (h_univ : μ univ = ν univ) :
μ = ν :=
begin
ext1 s hs,
refine induction_on_inter hA hC (by simp) hμν _ _ hs,
{ rintros t h1t h2t, change is_measurable t at h1t, simp [measure_compl, measure_lt_top, *] },
{ rintros f h1f h2f h3f, simp [measure_Union, is_measurable.Union, *] }
end
namespace measure
namespace finite_at_filter
variables {ν : measure α} {f g : filter α}
lemma filter_mono (h : f ≤ g) : μ.finite_at_filter g → μ.finite_at_filter f :=
λ ⟨s, hs, hμ⟩, ⟨s, h hs, hμ⟩
lemma inf_of_left (h : μ.finite_at_filter f) : μ.finite_at_filter (f ⊓ g) :=
h.filter_mono inf_le_left
lemma inf_of_right (h : μ.finite_at_filter g) : μ.finite_at_filter (f ⊓ g) :=
h.filter_mono inf_le_right
@[simp] lemma inf_ae_iff : μ.finite_at_filter (f ⊓ μ.ae) ↔ μ.finite_at_filter f :=
begin
refine ⟨_, λ h, h.filter_mono inf_le_left⟩,
rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hμ⟩,
suffices : μ t ≤ μ s, from ⟨t, ht, this.trans_lt hμ⟩,
exact measure_mono_ae (mem_sets_of_superset hu (λ x hu ht, hs ⟨ht, hu⟩))
end
alias inf_ae_iff ↔ measure_theory.measure.finite_at_filter.of_inf_ae _
lemma filter_mono_ae (h : f ⊓ μ.ae ≤ g) (hg : μ.finite_at_filter g) : μ.finite_at_filter f :=
inf_ae_iff.1 (hg.filter_mono h)
protected lemma measure_mono (h : μ ≤ ν) : ν.finite_at_filter f → μ.finite_at_filter f :=
λ ⟨s, hs, hν⟩, ⟨s, hs, (measure.le_iff'.1 h s).trans_lt hν⟩
@[mono] protected lemma mono (hf : f ≤ g) (hμ : μ ≤ ν) :
ν.finite_at_filter g → μ.finite_at_filter f :=
λ h, (h.filter_mono hf).measure_mono hμ
protected lemma eventually (h : μ.finite_at_filter f) : ∀ᶠ s in f.lift' powerset, μ s < ⊤ :=
(eventually_lift'_powerset' $ λ s t hst ht, (measure_mono hst).trans_lt ht).2 h
lemma filter_sup : μ.finite_at_filter f → μ.finite_at_filter g → μ.finite_at_filter (f ⊔ g) :=
λ ⟨s, hsf, hsμ⟩ ⟨t, htg, htμ⟩,
⟨s ∪ t, union_mem_sup hsf htg, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hsμ, htμ⟩)⟩
end finite_at_filter
lemma finite_at_nhds_within [topological_space α] (μ : measure α) [locally_finite_measure μ]
(x : α) (s : set α) :
μ.finite_at_filter (𝓝[s] x) :=
(finite_at_nhds μ x).inf_of_left
@[simp] lemma finite_at_principal {s : set α} : μ.finite_at_filter (𝓟 s) ↔ μ s < ⊤ :=
⟨λ ⟨t, ht, hμ⟩, (measure_mono ht).trans_lt hμ, λ h, ⟨s, mem_principal_self s, h⟩⟩
end measure
end measure_theory
section is_complete
open measure_theory measure_theory.measure
/-- 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] def measure_theory.measure.is_complete {α} {_:measurable_space α} (μ : measure α) : Prop :=
∀ s, μ s = 0 → is_measurable s
variables {α : Type*} [measurable_space α] (μ : measure α)
/-- A set is null measurable if it is the union of a null set and a measurable set. -/
def is_null_measurable (s : set α) : Prop :=
∃ t z, s = t ∪ z ∧ is_measurable t ∧ μ z = 0
theorem is_null_measurable_iff {μ : measure α} {s : set α} :
is_null_measurable μ s ↔
∃ t, t ⊆ s ∧ is_measurable t ∧ μ (s \ t) = 0 :=
begin
split,
{ rintro ⟨t, z, rfl, ht, hz⟩,
refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩,
simp [union_diff_left, diff_subset] },
{ rintro ⟨t, st, ht, hz⟩,
exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ }
end
theorem is_null_measurable_measure_eq {μ : measure α} {s t : set α}
(st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t :=
begin
refine le_antisymm _ (measure_mono st),
have := measure_union_le t (s \ t),
rw [union_diff_cancel st, hz] at this, simpa
end
theorem is_measurable.is_null_measurable
{s : set α} (hs : is_measurable s) : is_null_measurable μ s :=
⟨s, ∅, by simp, hs, μ.empty⟩
theorem is_null_measurable_of_complete [c : μ.is_complete]
{s : set α} : is_null_measurable μ s ↔ is_measurable s :=
⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact
is_measurable.union ht (c _ hz),
λ h, h.is_null_measurable _⟩
variables {μ}
theorem is_null_measurable.union_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s ∪ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, le_zero_iff_eq.1
(le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩
end
theorem null_is_null_measurable {z : set α}
(hz : μ z = 0) : is_null_measurable μ z :=
by simpa using (is_measurable.empty.is_null_measurable _).union_null hz
theorem is_null_measurable.Union_nat {s : ℕ → set α}
(hs : ∀ i, is_null_measurable μ (s i)) :
is_null_measurable μ (Union s) :=
begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht,
rcases ht with ⟨st, ht, hz⟩,
refine is_null_measurable_iff.2
⟨Union t, Union_subset_Union st, is_measurable.Union ht,
measure_mono_null _ (measure_Union_null hz)⟩,
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff)
end
theorem is_measurable.diff_null {s z : set α}
(hs : is_measurable s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rw measure_eq_infi at hz,
choose f hf using show ∀ q : {q:ℚ//q>0}, ∃ t:set α,
z ⊆ t ∧ is_measurable t ∧ μ t < (nnreal.of_real q.1 : ennreal),
{ rintro ⟨ε, ε0⟩,
have : 0 < (nnreal.of_real ε : ennreal), { simpa using ε0 },
rw ← hz at this, simpa [infi_lt_iff] },
refine is_null_measurable_iff.2 ⟨s \ Inter f,
diff_subset_diff_right (subset_Inter (λ i, (hf i).1)),
hs.diff (is_measurable.Inter (λ i, (hf i).2.1)),
measure_mono_null _ (le_zero_iff_eq.1 $ le_of_not_lt $ λ h, _)⟩,
{ exact Inter f },
{ rw [diff_subset_iff, diff_union_self],
exact subset.trans (diff_subset _ _) (subset_union_left _ _) },
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩,
simp at ε0,
apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h),
exact measure_mono (Inter_subset _ _)
end
theorem is_null_measurable.diff_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
rw [set.union_diff_distrib],
exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz')
end
theorem is_null_measurable.compl {s : set α}
(hs : is_null_measurable μ s) :
is_null_measurable μ sᶜ :=
begin
rcases hs with ⟨t, z, rfl, ht, hz⟩,
rw compl_union,
exact ht.compl.diff_null hz
end
/-- The measurable space of all null measurable sets. -/
def null_measurable {α : Type u} [measurable_space α]
(μ : measure α) : measurable_space α :=
{ is_measurable' := is_null_measurable μ,
is_measurable_empty := is_measurable.empty.is_null_measurable _,
is_measurable_compl := λ s hs, hs.compl,
is_measurable_Union := λ f, is_null_measurable.Union_nat }
/-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/
def completion {α : Type u} [measurable_space α] (μ : measure α) :
@measure_theory.measure α (null_measurable μ) :=
{ to_outer_measure := μ.to_outer_measure,
m_Union := λ s hs hd, show μ (Union s) = ∑' i, μ (s i), begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩,
rw is_null_measurable_measure_eq (Union_subset_Union st),
{ rw measure_Union _ ht,
{ congr, funext i,
exact (is_null_measurable_measure_eq (st i) (hz i)).symm },
{ rintro i j ij x ⟨h₁, h₂⟩,
exact hd i j ij ⟨st i h₁, st j h₂⟩ } },
{ refine measure_mono_null _ (measure_Union_null hz),
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff) }
end,
trimmed := begin
letI := null_measurable μ,
refine le_antisymm (λ s, _) (outer_measure.le_trim _),
rw outer_measure.trim_eq_infi,
dsimp,
clear _inst,
resetI,
rw measure_eq_infi s,
exact infi_le_infi (λ t, infi_le_infi $ λ st,
infi_le_infi2 $ λ ht, ⟨ht.is_null_measurable _, le_refl _⟩)
end }
instance completion.is_complete {α : Type u} [measurable_space α] (μ : measure α) :
(completion μ).is_complete :=
λ z hz, null_is_null_measurable hz
end is_complete
namespace measure_theory
/-- A measure space is a measurable space equipped with a
measure, referred to as `volume`. -/
class measure_space (α : Type*) extends measurable_space α :=
(volume : measure α)
export measure_space (volume)
/-- `volume` is the canonical measure on `α`. -/
add_decl_doc volume
section measure_space
variables {α : Type*} {ι : Type*} [measure_space α] {s₁ s₂ : set α}
notation `∀ᵐ` binders `, ` r:(scoped P, filter.eventually P (measure.ae volume)) := r
/-- The tactic `exact volume`, to be used in optional (`auto_param`) arguments. -/
meta def volume_tac : tactic unit := `[exact measure_theory.measure_space.volume]
end measure_space
end measure_theory
open measure_theory
namespace is_compact
variables {α : Type*} [topological_space α] [measurable_space α] {μ : measure α} {s : set α}
lemma finite_measure_of_nhds_within (hs : is_compact s) :
(∀ a ∈ s, μ.finite_at_filter (𝓝[s] a)) → μ s < ⊤ :=
by simpa only [← measure.compl_mem_cofinite, measure.finite_at_filter]
using hs.compl_mem_sets_of_nhds_within
lemma finite_measure [locally_finite_measure μ] (hs : is_compact s) : μ s < ⊤ :=
hs.finite_measure_of_nhds_within $ λ a ha, μ.finite_at_nhds_within _ _
lemma measure_zero_of_nhds_within (hs : is_compact s) :
(∀ a ∈ s, ∃ t ∈ 𝓝[s] a, μ t = 0) → μ s = 0 :=
by simpa only [← compl_mem_ae_iff] using hs.compl_mem_sets_of_nhds_within
end is_compact
lemma metric.bounded.finite_measure {α : Type*} [metric_space α] [proper_space α]
[measurable_space α] {μ : measure α} [locally_finite_measure μ] {s : set α}
(hs : metric.bounded s) :
μ s < ⊤ :=
(measure_mono subset_closure).trans_lt (metric.compact_iff_closed_bounded.2
⟨is_closed_closure, metric.bounded_closure_of_bounded hs⟩).finite_measure
|
5b3faa04107f2a4ef105ff92c0c52e0fcbcf99ce | 4727251e0cd73359b15b664c3170e5d754078599 | /archive/imo/imo1960_q1.lean | 7caef8294f29bb83363e6154566cdd5697586377 | [
"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 | 3,334 | lean | /-
Copyright (c) 2020 Kevin Lacker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Lacker
-/
import data.nat.digits
/-!
# IMO 1960 Q1
Determine all three-digit numbers $N$ having the property that $N$ is divisible by 11, and
$\dfrac{N}{11}$ is equal to the sum of the squares of the digits of $N$.
Since Lean doesn't have a way to directly express problem statements of the form
"Determine all X satisfying Y", we express two predicates where proving that one implies the
other is equivalent to solving the problem. A human solver also has to discover the
second predicate.
The strategy here is roughly brute force, checking the possible multiples of 11.
-/
open nat
def sum_of_squares (L : list ℕ) : ℕ := (L.map (λ x, x * x)).sum
def problem_predicate (n : ℕ) : Prop :=
(nat.digits 10 n).length = 3 ∧ 11 ∣ n ∧ n / 11 = sum_of_squares (nat.digits 10 n)
def solution_predicate (n : ℕ) : Prop := n = 550 ∨ n = 803
/-
Proving that three digit numbers are the ones in [100, 1000).
-/
lemma not_zero {n : ℕ} (h1 : problem_predicate n) : n ≠ 0 :=
have h2 : nat.digits 10 n ≠ list.nil, from list.ne_nil_of_length_eq_succ h1.left,
digits_ne_nil_iff_ne_zero.mp h2
lemma ge_100 {n : ℕ} (h1 : problem_predicate n) : 100 ≤ n :=
have h2 : 10^3 ≤ 10 * n, begin
rw ← h1.left,
refine nat.base_pow_length_digits_le 10 n _ (not_zero h1),
simp,
end,
by linarith
lemma lt_1000 {n : ℕ} (h1 : problem_predicate n) : n < 1000 :=
have h2 : n < 10^3, begin
rw ← h1.left,
refine nat.lt_base_pow_length_digits _,
simp,
end,
by linarith
/-
We do an exhaustive search to show that all results are covered by `solution_predicate`.
-/
def search_up_to (c n : ℕ) : Prop :=
n = c * 11 ∧ ∀ m : ℕ, m < n → problem_predicate m → solution_predicate m
lemma search_up_to_start : search_up_to 9 99 := ⟨rfl, λ n h p, by linarith [ge_100 p]⟩
lemma search_up_to_step {c n} (H : search_up_to c n)
{c' n'} (ec : c + 1 = c') (en : n + 11 = n')
{l} (el : nat.digits 10 n = l)
(H' : c = sum_of_squares l → c = 50 ∨ c = 73) :
search_up_to c' n' :=
begin
subst ec, subst en, subst el,
obtain ⟨rfl, H⟩ := H,
refine ⟨by ring, λ m l p, _⟩,
obtain ⟨h₁, ⟨m, rfl⟩, h₂⟩ := id p,
by_cases h : 11 * m < c * 11, { exact H _ h p },
obtain rfl : m = c := by linarith,
rw [nat.mul_div_cancel_left _ (by norm_num : 11 > 0), mul_comm] at h₂,
refine (H' h₂).imp _ _; {rintro rfl, norm_num}
end
lemma search_up_to_end {c} (H : search_up_to c 1001)
{n : ℕ} (ppn : problem_predicate n) : solution_predicate n :=
H.2 _ (by linarith [lt_1000 ppn]) ppn
lemma right_direction {n : ℕ} : problem_predicate n → solution_predicate n :=
begin
have := search_up_to_start,
iterate 82
{ replace := search_up_to_step this (by norm_num1; refl) (by norm_num1; refl)
(by norm_num1; refl) dec_trivial },
exact search_up_to_end this
end
/-
Now we just need to prove the equivalence, for the precise problem statement.
-/
lemma left_direction (n : ℕ) (spn : solution_predicate n) : problem_predicate n :=
by rcases spn with (rfl | rfl); norm_num [problem_predicate, sum_of_squares]
theorem imo1960_q1 (n : ℕ) : problem_predicate n ↔ solution_predicate n :=
⟨right_direction, left_direction n⟩
|
e77914b46d23884f3b6f880c137b6c1ff5439dfb | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /03_Propositions_and_Proofs.org.1.lean | 6a2f52bdfb8ca14a3080d43a95278ee6eed21924 | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 372 | lean | /- page 32 -/
import standard
namespace hide
-- BEGIN
constant and : Prop → Prop → Prop
constant or : Prop → Prop → Prop
constant not : Prop → Prop
constant implies : Prop → Prop → Prop
variables p q r : Prop
check and p q -- Prop
check or (and p q) r -- Prop
check implies (and p q) (and q p) -- Prop
-- END
end hide
|
665187c39720c0bba1d2b9e884f16d89de05066e | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/order/succ_pred/basic.lean | 1c47559b70feece7ac1dea7b63ee5ee74a284ada | [
"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 | 30,132 | 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.bounded_order
import order.complete_lattice
import order.cover
import order.iterate
import tactic.monotonicity
/-!
# Successor and predecessor
This file defines successor and predecessor orders. `succ a`, the successor of an element `a : α` is
the least element greater than `a`. `pred a` is the greatest element less than `a`. Typical examples
include `ℕ`, `ℤ`, `ℕ+`, `fin n`, but also `enat`, the lexicographic order of a successor/predecessor
order...
## Typeclasses
* `succ_order`: Order equipped with a sensible successor function.
* `pred_order`: Order equipped with a sensible predecessor function.
* `is_succ_archimedean`: `succ_order` where `succ` iterated to an element gives all the greater
ones.
* `is_pred_archimedean`: `pred_order` where `pred` iterated to an element gives all the greater
ones.
## Implementation notes
Maximal elements don't have a sensible successor. Thus the naïve typeclass
```lean
class naive_succ_order (α : Type*) [preorder α] :=
(succ : α → α)
(succ_le_iff : ∀ {a b}, succ a ≤ b ↔ a < b)
(lt_succ_iff : ∀ {a b}, a < succ b ↔ a ≤ b)
```
can't apply to an `order_top` because plugging in `a = b = ⊤` into either of `succ_le_iff` and
`lt_succ_iff` yields `⊤ < ⊤` (or more generally `m < m` for a maximal element `m`).
The solution taken here is to remove the implications `≤ → <` and instead require that `a < succ a`
for all non maximal elements (enforced by the combination of `le_succ` and the contrapositive of
`maximal_of_succ_le`).
The stricter condition of every element having a sensible successor can be obtained through the
combination of `succ_order α` and `no_max_order α`.
## TODO
Is `galois_connection pred succ` always true? If not, we should introduce
```lean
class succ_pred_order (α : Type*) [preorder α] extends succ_order α, pred_order α :=
(pred_succ_gc : galois_connection (pred : α → α) succ)
```
`covers` should help here.
-/
open function
/-! ### Successor order -/
variables {α : Type*}
/-- Order equipped with a sensible successor function. -/
@[ext] class succ_order (α : Type*) [preorder α] :=
(succ : α → α)
(le_succ : ∀ a, a ≤ succ a)
(maximal_of_succ_le : ∀ ⦃a⦄, succ a ≤ a → ∀ ⦃b⦄, ¬a < b)
(succ_le_of_lt : ∀ {a b}, a < b → succ a ≤ b)
(le_of_lt_succ : ∀ {a b}, a < succ b → a ≤ b)
namespace succ_order
section preorder
variables [preorder α]
/-- A constructor for `succ_order α` usable when `α` has no maximal element. -/
def of_succ_le_iff_of_le_lt_succ (succ : α → α)
(hsucc_le_iff : ∀ {a b}, succ a ≤ b ↔ a < b)
(hle_of_lt_succ : ∀ {a b}, a < succ b → a ≤ b) :
succ_order α :=
{ succ := succ,
le_succ := λ a, (hsucc_le_iff.1 le_rfl).le,
maximal_of_succ_le := λ a ha, (lt_irrefl a (hsucc_le_iff.1 ha)).elim,
succ_le_of_lt := λ a b, hsucc_le_iff.2,
le_of_lt_succ := λ a b, hle_of_lt_succ }
variables [succ_order α]
@[simp, mono] lemma succ_le_succ {a b : α} (h : a ≤ b) : succ a ≤ succ b :=
begin
by_cases ha : ∀ ⦃c⦄, ¬a < c,
{ have hba : succ b ≤ a,
{ by_contra H,
exact ha ((h.trans (le_succ b)).lt_of_not_le H) },
by_contra H,
exact ha ((h.trans (le_succ b)).trans_lt ((hba.trans (le_succ a)).lt_of_not_le H)) },
{ push_neg at ha,
obtain ⟨c, hc⟩ := ha,
exact succ_le_of_lt ((h.trans (le_succ b)).lt_of_not_le $ λ hba,
maximal_of_succ_le (hba.trans h) (((le_succ b).trans hba).trans_lt hc)) }
end
lemma succ_mono : monotone (succ : α → α) := λ a b, succ_le_succ
lemma lt_succ_of_not_maximal {a b : α} (h : a < b) : a < succ a :=
(le_succ a).lt_of_not_le (λ ha, maximal_of_succ_le ha h)
alias lt_succ_of_not_maximal ← has_lt.lt.lt_succ
protected lemma _root_.has_lt.lt.covers_succ {a b : α} (h : a < b) : a ⋖ succ a :=
⟨h.lt_succ, λ c hc, (succ_le_of_lt hc).not_lt⟩
@[simp] lemma covers_succ_of_nonempty_Ioi {a : α} (h : (set.Ioi a).nonempty) : a ⋖ succ a :=
has_lt.lt.covers_succ h.some_mem
section no_max_order
variables [no_max_order α] {a b : α}
lemma lt_succ (a : α) : a < succ a :=
(le_succ a).lt_of_not_le $ λ h, not_exists.2 (maximal_of_succ_le h) (exists_gt a)
lemma lt_succ_iff : a < succ b ↔ a ≤ b :=
⟨le_of_lt_succ, λ h, h.trans_lt $ lt_succ b⟩
lemma succ_le_iff : succ a ≤ b ↔ a < b :=
⟨(lt_succ a).trans_le, succ_le_of_lt⟩
@[simp] lemma succ_le_succ_iff : succ a ≤ succ b ↔ a ≤ b :=
⟨λ h, le_of_lt_succ $ (lt_succ a).trans_le h, λ h, succ_le_of_lt $ h.trans_lt $ lt_succ b⟩
alias succ_le_succ_iff ↔ le_of_succ_le_succ _
lemma succ_lt_succ_iff : succ a < succ b ↔ a < b :=
by simp_rw [lt_iff_le_not_le, succ_le_succ_iff]
alias succ_lt_succ_iff ↔ lt_of_succ_lt_succ succ_lt_succ
lemma succ_strict_mono : strict_mono (succ : α → α) := λ a b, succ_lt_succ
lemma covers_succ (a : α) : a ⋖ succ a := ⟨lt_succ a, λ c hc, (succ_le_of_lt hc).not_lt⟩
end no_max_order
end preorder
section partial_order
variables [partial_order α]
/-- There is at most one way to define the successors in a `partial_order`. -/
instance : subsingleton (succ_order α) :=
begin
refine subsingleton.intro (λ h₀ h₁, _),
ext a,
by_cases ha : @succ _ _ h₀ a ≤ a,
{ refine (ha.trans (@le_succ _ _ h₁ a)).antisymm _,
by_contra H,
exact @maximal_of_succ_le _ _ h₀ _ ha _
((@le_succ _ _ h₁ a).lt_of_not_le $ λ h, H $ h.trans $ @le_succ _ _ h₀ a) },
{ exact (@succ_le_of_lt _ _ h₀ _ _ $ (@le_succ _ _ h₁ a).lt_of_not_le $ λ h,
@maximal_of_succ_le _ _ h₁ _ h _ $ (@le_succ _ _ h₀ a).lt_of_not_le ha).antisymm
(@succ_le_of_lt _ _ h₁ _ _ $ (@le_succ _ _ h₀ a).lt_of_not_le ha) }
end
variables [succ_order α]
lemma le_le_succ_iff {a b : α} : a ≤ b ∧ b ≤ succ a ↔ b = a ∨ b = succ a :=
begin
split,
{ rintro h,
rw or_iff_not_imp_left,
exact λ hba : b ≠ a, h.2.antisymm (succ_le_of_lt $ h.1.lt_of_ne $ hba.symm) },
rintro (rfl | rfl),
{ exact ⟨le_rfl, le_succ b⟩ },
{ exact ⟨le_succ a, le_rfl⟩ }
end
lemma _root_.covers.succ_eq {a b : α} (h : a ⋖ b) : succ a = b :=
(succ_le_of_lt h.lt).eq_of_not_lt $ λ h', h.2 (lt_succ_of_not_maximal h.lt) h'
section no_max_order
variables [no_max_order α] {a b : α}
lemma succ_injective : injective (succ : α → α) :=
begin
rintro a b,
simp_rw [eq_iff_le_not_lt, succ_le_succ_iff, succ_lt_succ_iff],
exact id,
end
lemma succ_eq_succ_iff : succ a = succ b ↔ a = b :=
succ_injective.eq_iff
lemma succ_ne_succ_iff : succ a ≠ succ b ↔ a ≠ b :=
succ_injective.ne_iff
alias succ_ne_succ_iff ↔ ne_of_succ_ne_succ succ_ne_succ
lemma lt_succ_iff_lt_or_eq : a < succ b ↔ (a < b ∨ a = b) :=
lt_succ_iff.trans le_iff_lt_or_eq
lemma le_succ_iff_lt_or_eq : a ≤ succ b ↔ (a ≤ b ∨ a = succ b) :=
by rw [←lt_succ_iff, ←lt_succ_iff, lt_succ_iff_lt_or_eq]
lemma _root_.covers_iff_succ_eq : a ⋖ b ↔ succ a = b :=
⟨covers.succ_eq, by { rintro rfl, exact covers_succ _ }⟩
end no_max_order
end partial_order
section order_top
variables [partial_order α] [order_top α] [succ_order α]
@[simp] lemma succ_top : succ (⊤ : α) = ⊤ :=
le_top.antisymm (le_succ _)
@[simp] lemma succ_le_iff_eq_top {a : α} : succ a ≤ a ↔ a = ⊤ :=
⟨λ h, eq_top_of_maximal (maximal_of_succ_le h), λ h, by rw [h, succ_top]⟩
@[simp] lemma lt_succ_iff_ne_top {a : α} : a < succ a ↔ a ≠ ⊤ :=
begin
simp only [lt_iff_le_not_le, true_and, le_succ a],
exact not_iff_not.2 succ_le_iff_eq_top,
end
end order_top
section order_bot
variables [partial_order α] [order_bot α] [succ_order α] [nontrivial α]
lemma bot_lt_succ (a : α) : ⊥ < succ a :=
begin
obtain ⟨b, hb⟩ := exists_ne (⊥ : α),
refine bot_lt_iff_ne_bot.2 (λ h, _),
have := eq_bot_iff.2 ((le_succ a).trans h.le),
rw this at h,
exact maximal_of_succ_le h.le (bot_lt_iff_ne_bot.2 hb),
end
lemma succ_ne_bot (a : α) : succ a ≠ ⊥ :=
(bot_lt_succ a).ne'
end order_bot
section linear_order
variables [linear_order α]
/-- A constructor for `succ_order α` usable when `α` is a linear order with no maximal element. -/
def of_succ_le_iff (succ : α → α) (hsucc_le_iff : ∀ {a b}, succ a ≤ b ↔ a < b) :
succ_order α :=
{ succ := succ,
le_succ := λ a, (hsucc_le_iff.1 le_rfl).le,
maximal_of_succ_le := λ a ha, (lt_irrefl a (hsucc_le_iff.1 ha)).elim,
succ_le_of_lt := λ a b, hsucc_le_iff.2,
le_of_lt_succ := λ a b h, le_of_not_lt ((not_congr hsucc_le_iff).1 h.not_le) }
end linear_order
section complete_lattice
variables [complete_lattice α] [succ_order α]
lemma succ_eq_infi (a : α) : succ a = ⨅ (b : α) (h : a < b), b :=
begin
refine le_antisymm (le_infi (λ b, le_infi succ_le_of_lt)) _,
obtain rfl | ha := eq_or_ne a ⊤,
{ rw succ_top,
exact le_top },
exact binfi_le _ (lt_succ_iff_ne_top.2 ha),
end
end complete_lattice
end succ_order
/-! ### Predecessor order -/
/-- Order equipped with a sensible predecessor function. -/
@[ext] class pred_order (α : Type*) [preorder α] :=
(pred : α → α)
(pred_le : ∀ a, pred a ≤ a)
(minimal_of_le_pred : ∀ ⦃a⦄, a ≤ pred a → ∀ ⦃b⦄, ¬b < a)
(le_pred_of_lt : ∀ {a b}, a < b → a ≤ pred b)
(le_of_pred_lt : ∀ {a b}, pred a < b → a ≤ b)
namespace pred_order
section preorder
variables [preorder α]
/-- A constructor for `pred_order α` usable when `α` has no minimal element. -/
def of_le_pred_iff_of_pred_le_pred (pred : α → α)
(hle_pred_iff : ∀ {a b}, a ≤ pred b ↔ a < b)
(hle_of_pred_lt : ∀ {a b}, pred a < b → a ≤ b) :
pred_order α :=
{ pred := pred,
pred_le := λ a, (hle_pred_iff.1 le_rfl).le,
minimal_of_le_pred := λ a ha, (lt_irrefl a (hle_pred_iff.1 ha)).elim,
le_pred_of_lt := λ a b, hle_pred_iff.2,
le_of_pred_lt := λ a b, hle_of_pred_lt }
variables [pred_order α]
@[simp, mono] lemma pred_le_pred {a b : α} (h : a ≤ b) : pred a ≤ pred b :=
begin
by_cases hb : ∀ ⦃c⦄, ¬c < b,
{ have hba : b ≤ pred a,
{ by_contra H,
exact hb (((pred_le a).trans h).lt_of_not_le H) },
by_contra H,
exact hb ((((pred_le b).trans hba).lt_of_not_le H).trans_le ((pred_le a).trans h)) },
{ push_neg at hb,
obtain ⟨c, hc⟩ := hb,
exact le_pred_of_lt (((pred_le a).trans h).lt_of_not_le $ λ hba,
minimal_of_le_pred (h.trans hba) $ hc.trans_le $ hba.trans $ pred_le a) }
end
lemma pred_mono : monotone (pred : α → α) := λ a b, pred_le_pred
lemma pred_lt_of_not_minimal {a b : α} (h : b < a) : pred a < a :=
(pred_le a).lt_of_not_le (λ ha, minimal_of_le_pred ha h)
alias pred_lt_of_not_minimal ← has_lt.lt.pred_lt
protected lemma _root_.has_lt.lt.pred_covers {a b : α} (h : b < a) : pred a ⋖ a :=
⟨h.pred_lt, λ c hc, (le_of_pred_lt hc).not_lt⟩
@[simp] lemma pred_covers_of_nonempty_Iio {a : α} (h : (set.Iio a).nonempty) : pred a ⋖ a :=
has_lt.lt.pred_covers h.some_mem
section no_min_order
variables [no_min_order α] {a b : α}
lemma pred_lt (a : α) : pred a < a :=
(pred_le a).lt_of_not_le $ λ h, not_exists.2 (minimal_of_le_pred h) (exists_lt a)
lemma pred_lt_iff : pred a < b ↔ a ≤ b :=
⟨le_of_pred_lt, (pred_lt a).trans_le⟩
lemma le_pred_iff : a ≤ pred b ↔ a < b :=
⟨λ h, h.trans_lt (pred_lt b), le_pred_of_lt⟩
@[simp] lemma pred_le_pred_iff : pred a ≤ pred b ↔ a ≤ b :=
⟨λ h, le_of_pred_lt $ h.trans_lt (pred_lt b), λ h, le_pred_of_lt $ (pred_lt a).trans_le h⟩
alias pred_le_pred_iff ↔ le_of_pred_le_pred _
@[simp] lemma pred_lt_pred_iff : pred a < pred b ↔ a < b :=
by simp_rw [lt_iff_le_not_le, pred_le_pred_iff]
alias pred_lt_pred_iff ↔ lt_of_pred_lt_pred pred_lt_pred
lemma pred_strict_mono : strict_mono (pred : α → α) := λ a b, pred_lt_pred
lemma pred_covers (a : α) : pred a ⋖ a := ⟨pred_lt a, λ c hc, (le_of_pred_lt hc).not_lt⟩
end no_min_order
end preorder
section partial_order
variables [partial_order α]
/-- There is at most one way to define the predecessors in a `partial_order`. -/
instance : subsingleton (pred_order α) :=
begin
refine subsingleton.intro (λ h₀ h₁, _),
ext a,
by_cases ha : a ≤ @pred _ _ h₀ a,
{ refine le_antisymm _ ((@pred_le _ _ h₁ a).trans ha),
by_contra H,
exact @minimal_of_le_pred _ _ h₀ _ ha _
((@pred_le _ _ h₁ a).lt_of_not_le $ λ h, H $ (@pred_le _ _ h₀ a).trans h) },
{ exact (@le_pred_of_lt _ _ h₁ _ _ $ (@pred_le _ _ h₀ a).lt_of_not_le ha).antisymm
(@le_pred_of_lt _ _ h₀ _ _ $ (@pred_le _ _ h₁ a).lt_of_not_le $ λ h,
@minimal_of_le_pred _ _ h₁ _ h _ $ (@pred_le _ _ h₀ a).lt_of_not_le ha) }
end
variables [pred_order α]
lemma pred_le_le_iff {a b : α} : pred a ≤ b ∧ b ≤ a ↔ b = a ∨ b = pred a :=
begin
split,
{ rintro h,
rw or_iff_not_imp_left,
exact λ hba, (le_pred_of_lt $ h.2.lt_of_ne hba).antisymm h.1 },
rintro (rfl | rfl),
{ exact ⟨pred_le b, le_rfl⟩ },
{ exact ⟨le_rfl, pred_le a⟩ }
end
lemma _root_.covers.pred_eq {a b : α} (h : a ⋖ b) : pred b = a :=
(le_pred_of_lt h.lt).eq_of_not_gt $ λ h', h.2 h' $ pred_lt_of_not_minimal h.lt
section no_min_order
variables [no_min_order α] {a b : α}
lemma pred_injective : injective (pred : α → α) :=
begin
rintro a b,
simp_rw [eq_iff_le_not_lt, pred_le_pred_iff, pred_lt_pred_iff],
exact id,
end
lemma pred_eq_pred_iff : pred a = pred b ↔ a = b :=
pred_injective.eq_iff
lemma pred_ne_pred_iff : pred a ≠ pred b ↔ a ≠ b :=
pred_injective.ne_iff
lemma pred_lt_iff_lt_or_eq : pred a < b ↔ (a < b ∨ a = b) :=
pred_lt_iff.trans le_iff_lt_or_eq
lemma le_pred_iff_lt_or_eq : pred a ≤ b ↔ (a ≤ b ∨ pred a = b) :=
by rw [←pred_lt_iff, ←pred_lt_iff, pred_lt_iff_lt_or_eq]
lemma _root_.covers_iff_pred_eq : a ⋖ b ↔ pred b = a :=
⟨covers.pred_eq, by { rintro rfl, exact pred_covers _ }⟩
end no_min_order
end partial_order
section order_bot
variables [partial_order α] [order_bot α] [pred_order α]
@[simp] lemma pred_bot : pred (⊥ : α) = ⊥ :=
(pred_le _).antisymm bot_le
@[simp] lemma le_pred_iff_eq_bot {a : α} : a ≤ pred a ↔ a = ⊥ :=
⟨λ h, eq_bot_of_minimal (minimal_of_le_pred h), λ h, by rw [h, pred_bot]⟩
@[simp] lemma pred_lt_iff_ne_bot {a : α} : pred a < a ↔ a ≠ ⊥ :=
begin
simp only [lt_iff_le_not_le, true_and, pred_le a],
exact not_iff_not.2 le_pred_iff_eq_bot,
end
end order_bot
section order_top
variables [partial_order α] [order_top α] [pred_order α]
lemma pred_lt_top [nontrivial α] (a : α) : pred a < ⊤ :=
begin
obtain ⟨b, hb⟩ := exists_ne (⊤ : α),
refine lt_top_iff_ne_top.2 (λ h, _),
have := eq_top_iff.2 (h.ge.trans (pred_le a)),
rw this at h,
exact minimal_of_le_pred h.ge (lt_top_iff_ne_top.2 hb),
end
lemma pred_ne_top [nontrivial α] (a : α) : pred a ≠ ⊤ :=
(pred_lt_top a).ne
end order_top
section linear_order
variables [linear_order α] {a b : α}
/-- A constructor for `pred_order α` usable when `α` is a linear order with no maximal element. -/
def of_le_pred_iff (pred : α → α) (hle_pred_iff : ∀ {a b}, a ≤ pred b ↔ a < b) :
pred_order α :=
{ pred := pred,
pred_le := λ a, (hle_pred_iff.1 le_rfl).le,
minimal_of_le_pred := λ a ha, (lt_irrefl a (hle_pred_iff.1 ha)).elim,
le_pred_of_lt := λ a b, hle_pred_iff.2,
le_of_pred_lt := λ a b h, le_of_not_lt ((not_congr hle_pred_iff).1 h.not_le) }
end linear_order
section complete_lattice
variables [complete_lattice α] [pred_order α]
lemma pred_eq_supr (a : α) : pred a = ⨆ (b : α) (h : b < a), b :=
begin
refine le_antisymm _ (supr_le (λ b, supr_le le_pred_of_lt)),
obtain rfl | ha := eq_or_ne a ⊥,
{ rw pred_bot,
exact bot_le },
exact @le_bsupr _ _ _ (λ b, b < a) (λ a _, a) (pred a) (pred_lt_iff_ne_bot.2 ha),
end
end complete_lattice
end pred_order
open succ_order pred_order
/-! ### Successor-predecessor orders -/
section succ_pred_order
variables [partial_order α] [succ_order α] [pred_order α] {a b : α}
protected lemma _root_.has_lt.lt.succ_pred (h : b < a) : succ (pred a) = a := h.pred_covers.succ_eq
protected lemma _root_.has_lt.lt.pred_succ (h : a < b) : pred (succ a) = a := h.covers_succ.pred_eq
@[simp] lemma succ_pred_of_nonempty_Iio {a : α} (h : (set.Iio a).nonempty) : succ (pred a) = a :=
has_lt.lt.succ_pred h.some_mem
@[simp] lemma pred_succ_of_nonempty_Ioi {a : α} (h : (set.Ioi a).nonempty) : pred (succ a) = a :=
has_lt.lt.pred_succ h.some_mem
@[simp] lemma succ_pred [no_min_order α] (a : α) : succ (pred a) = a := (pred_covers _).succ_eq
@[simp] lemma pred_succ [no_max_order α] (a : α) : pred (succ a) = a := (covers_succ _).pred_eq
end succ_pred_order
/-! ### Dual order -/
section order_dual
variables [preorder α]
instance [pred_order α] : succ_order (order_dual α) :=
{ succ := (pred : α → α),
le_succ := pred_le,
maximal_of_succ_le := minimal_of_le_pred,
succ_le_of_lt := λ a b h, le_pred_of_lt h,
le_of_lt_succ := λ a b, le_of_pred_lt }
instance [succ_order α] : pred_order (order_dual α) :=
{ pred := (succ : α → α),
pred_le := le_succ,
minimal_of_le_pred := maximal_of_succ_le,
le_pred_of_lt := λ a b h, succ_le_of_lt h,
le_of_pred_lt := λ a b, le_of_lt_succ }
end order_dual
/-! ### `with_bot`, `with_top`
Adding a greatest/least element to a `succ_order` or to a `pred_order`.
As far as successors and predecessors are concerned, there are four ways to add a bottom or top
element to an order:
* Adding a `⊤` to an `order_top`: Preserves `succ` and `pred`.
* Adding a `⊤` to a `no_max_order`: Preserves `succ`. Never preserves `pred`.
* Adding a `⊥` to an `order_bot`: Preserves `succ` and `pred`.
* Adding a `⊥` to a `no_min_order`: Preserves `pred`. Never preserves `succ`.
where "preserves `(succ/pred)`" means
`(succ/pred)_order α → (succ/pred)_order ((with_top/with_bot) α)`.
-/
section with_top
open with_top
/-! #### Adding a `⊤` to an `order_top` -/
instance [decidable_eq α] [partial_order α] [order_top α] [succ_order α] :
succ_order (with_top α) :=
{ succ := λ a, match a with
| ⊤ := ⊤
| (some a) := ite (a = ⊤) ⊤ (some (succ a))
end,
le_succ := λ a, begin
cases a,
{ exact le_top },
change ((≤) : with_top α → with_top α → Prop) _ (ite _ _ _),
split_ifs,
{ exact le_top },
{ exact some_le_some.2 (le_succ a) }
end,
maximal_of_succ_le := λ a ha b h, begin
cases a,
{ exact not_top_lt h },
change ((≤) : with_top α → with_top α → Prop) (ite _ _ _) _ at ha,
split_ifs at ha with ha',
{ exact not_top_lt (ha.trans_lt h) },
{ rw [some_le_some, succ_le_iff_eq_top] at ha,
exact ha' ha }
end,
succ_le_of_lt := λ a b h, begin
cases b,
{ exact le_top },
cases a,
{ exact (not_top_lt h).elim },
rw some_lt_some at h,
change ((≤) : with_top α → with_top α → Prop) (ite _ _ _) _,
split_ifs with ha,
{ rw ha at h,
exact (not_top_lt h).elim },
{ exact some_le_some.2 (succ_le_of_lt h) }
end,
le_of_lt_succ := λ a b h, begin
cases a,
{ exact (not_top_lt h).elim },
cases b,
{ exact le_top },
change ((<) : with_top α → with_top α → Prop) _ (ite _ _ _) at h,
rw some_le_some,
split_ifs at h with hb,
{ rw hb,
exact le_top },
{ exact le_of_lt_succ (some_lt_some.1 h) }
end }
instance [partial_order α] [order_top α] [pred_order α] : pred_order (with_top α) :=
{ pred := λ a, match a with
| ⊤ := some ⊤
| (some a) := some (pred a)
end,
pred_le := λ a, match a with
| ⊤ := le_top
| (some a) := some_le_some.2 (pred_le a)
end,
minimal_of_le_pred := λ a ha b h, begin
cases a,
{ exact (coe_lt_top (⊤ : α)).not_le ha },
cases b,
{ exact h.not_le le_top },
{ exact minimal_of_le_pred (some_le_some.1 ha) (some_lt_some.1 h) }
end,
le_pred_of_lt := λ a b h, begin
cases a,
{ exact ((le_top).not_lt h).elim },
cases b,
{ exact some_le_some.2 le_top },
exact some_le_some.2 (le_pred_of_lt $ some_lt_some.1 h),
end,
le_of_pred_lt := λ a b h, begin
cases b,
{ exact le_top },
cases a,
{ exact (not_top_lt $ some_lt_some.1 h).elim },
{ exact some_le_some.2 (le_of_pred_lt $ some_lt_some.1 h) }
end }
/-! #### Adding a `⊤` to a `no_max_order` -/
instance with_top.succ_order_of_no_max_order [partial_order α] [no_max_order α] [succ_order α] :
succ_order (with_top α) :=
{ succ := λ a, match a with
| ⊤ := ⊤
| (some a) := some (succ a)
end,
le_succ := λ a, begin
cases a,
{ exact le_top },
{ exact some_le_some.2 (le_succ a) }
end,
maximal_of_succ_le := λ a ha b h, begin
cases a,
{ exact not_top_lt h },
{ exact not_exists.2 (maximal_of_succ_le (some_le_some.1 ha)) (exists_gt a) }
end,
succ_le_of_lt := λ a b h, begin
cases a,
{ exact (not_top_lt h).elim },
cases b,
{ exact le_top} ,
{ exact some_le_some.2 (succ_le_of_lt $ some_lt_some.1 h) }
end,
le_of_lt_succ := λ a b h, begin
cases a,
{ exact (not_top_lt h).elim },
cases b,
{ exact le_top },
{ exact some_le_some.2 (le_of_lt_succ $ some_lt_some.1 h) }
end }
instance [partial_order α] [no_max_order α] [hα : nonempty α] :
is_empty (pred_order (with_top α)) :=
⟨begin
introI,
set b := pred (⊤ : with_top α) with h,
cases pred (⊤ : with_top α) with a ha; change b with pred ⊤ at h,
{ exact hα.elim (λ a, minimal_of_le_pred h.ge (coe_lt_top a)) },
{ obtain ⟨c, hc⟩ := exists_gt a,
rw [←some_lt_some, ←h] at hc,
exact (le_of_pred_lt hc).not_lt (some_lt_none _) }
end⟩
end with_top
section with_bot
open with_bot
/-! #### Adding a `⊥` to a `bot_order` -/
instance [preorder α] [order_bot α] [succ_order α] : succ_order (with_bot α) :=
{ succ := λ a, match a with
| ⊥ := some ⊥
| (some a) := some (succ a)
end,
le_succ := λ a, match a with
| ⊥ := bot_le
| (some a) := some_le_some.2 (le_succ a)
end,
maximal_of_succ_le := λ a ha b h, begin
cases a,
{ exact (none_lt_some (⊥ : α)).not_le ha },
cases b,
{ exact not_lt_bot h },
{ exact maximal_of_succ_le (some_le_some.1 ha) (some_lt_some.1 h) }
end,
succ_le_of_lt := λ a b h, begin
cases b,
{ exact (not_lt_bot h).elim },
cases a,
{ exact some_le_some.2 bot_le },
{ exact some_le_some.2 (succ_le_of_lt $ some_lt_some.1 h) }
end,
le_of_lt_succ := λ a b h, begin
cases a,
{ exact bot_le },
cases b,
{ exact (not_lt_bot $ some_lt_some.1 h).elim },
{ exact some_le_some.2 (le_of_lt_succ $ some_lt_some.1 h) }
end }
instance [decidable_eq α] [partial_order α] [order_bot α] [pred_order α] :
pred_order (with_bot α) :=
{ pred := λ a, match a with
| ⊥ := ⊥
| (some a) := ite (a = ⊥) ⊥ (some (pred a))
end,
pred_le := λ a, begin
cases a,
{ exact bot_le },
change (ite _ _ _ : with_bot α) ≤ some a,
split_ifs,
{ exact bot_le },
{ exact some_le_some.2 (pred_le a) }
end,
minimal_of_le_pred := λ a ha b h, begin
cases a,
{ exact not_lt_bot h },
change ((≤) : with_bot α → with_bot α → Prop) _ (ite _ _ _) at ha,
split_ifs at ha with ha',
{ exact not_lt_bot (h.trans_le ha) },
{ rw [some_le_some, le_pred_iff_eq_bot] at ha,
exact ha' ha }
end,
le_pred_of_lt := λ a b h, begin
cases a,
{ exact bot_le },
cases b,
{ exact (not_lt_bot h).elim },
rw some_lt_some at h,
change ((≤) : with_bot α → with_bot α → Prop) _ (ite _ _ _),
split_ifs with hb,
{ rw hb at h,
exact (not_lt_bot h).elim },
{ exact some_le_some.2 (le_pred_of_lt h) }
end,
le_of_pred_lt := λ a b h, begin
cases b,
{ exact (not_lt_bot h).elim },
cases a,
{ exact bot_le },
change ((<) : with_bot α → with_bot α → Prop) (ite _ _ _) _ at h,
rw some_le_some,
split_ifs at h with ha,
{ rw ha,
exact bot_le },
{ exact le_of_pred_lt (some_lt_some.1 h) }
end }
/-! #### Adding a `⊥` to a `no_min_order` -/
instance [partial_order α] [no_min_order α] [hα : nonempty α] :
is_empty (succ_order (with_bot α)) :=
⟨begin
introI,
set b : with_bot α := succ ⊥ with h,
cases succ (⊥ : with_bot α) with a ha; change b with succ ⊥ at h,
{ exact hα.elim (λ a, maximal_of_succ_le h.le (bot_lt_coe a)) },
{ obtain ⟨c, hc⟩ := exists_lt a,
rw [←some_lt_some, ←h] at hc,
exact (le_of_lt_succ hc).not_lt (none_lt_some _) }
end⟩
instance with_bot.pred_order_of_no_min_order [partial_order α] [no_min_order α] [pred_order α] :
pred_order (with_bot α) :=
{ pred := λ a, match a with
| ⊥ := ⊥
| (some a) := some (pred a)
end,
pred_le := λ a, begin
cases a,
{ exact bot_le },
{ exact some_le_some.2 (pred_le a) }
end,
minimal_of_le_pred := λ a ha b h, begin
cases a,
{ exact not_lt_bot h },
{ exact not_exists.2 (minimal_of_le_pred (some_le_some.1 ha)) (exists_lt a) }
end,
le_pred_of_lt := λ a b h, begin
cases b,
{ exact (not_lt_bot h).elim },
cases a,
{ exact bot_le },
{ exact some_le_some.2 (le_pred_of_lt $ some_lt_some.1 h) }
end,
le_of_pred_lt := λ a b h, begin
cases b,
{ exact (not_lt_bot h).elim },
cases a,
{ exact bot_le },
{ exact some_le_some.2 (le_of_pred_lt $ some_lt_some.1 h) }
end }
end with_bot
/-! ### Archimedeanness -/
/-- A `succ_order` is succ-archimedean if one can go from any two comparable elements by iterating
`succ` -/
class is_succ_archimedean (α : Type*) [preorder α] [succ_order α] : Prop :=
(exists_succ_iterate_of_le {a b : α} (h : a ≤ b) : ∃ n, succ^[n] a = b)
/-- A `pred_order` is pred-archimedean if one can go from any two comparable elements by iterating
`pred` -/
class is_pred_archimedean (α : Type*) [preorder α] [pred_order α] : Prop :=
(exists_pred_iterate_of_le {a b : α} (h : a ≤ b) : ∃ n, pred^[n] b = a)
export is_succ_archimedean (exists_succ_iterate_of_le)
export is_pred_archimedean (exists_pred_iterate_of_le)
section preorder
variables [preorder α]
section succ_order
variables [succ_order α] [is_succ_archimedean α] {a b : α}
instance : is_pred_archimedean (order_dual α) :=
{ exists_pred_iterate_of_le := λ a b h, by convert @exists_succ_iterate_of_le α _ _ _ _ _ h }
lemma has_le.le.exists_succ_iterate (h : a ≤ b) : ∃ n, succ^[n] a = b :=
exists_succ_iterate_of_le h
lemma exists_succ_iterate_iff_le : (∃ n, succ^[n] a = b) ↔ a ≤ b :=
begin
refine ⟨_, exists_succ_iterate_of_le⟩,
rintro ⟨n, rfl⟩,
exact id_le_iterate_of_id_le le_succ n a,
end
/-- Induction principle on a type with a `succ_order` for all elements above a given element `m`. -/
@[elab_as_eliminator] lemma succ.rec {P : α → Prop} {m : α}
(h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (succ n)) ⦃n : α⦄ (hmn : m ≤ n) : P n :=
begin
obtain ⟨n, rfl⟩ := hmn.exists_succ_iterate, clear hmn,
induction n with n ih,
{ exact h0 },
{ rw [function.iterate_succ_apply'], exact h1 _ (id_le_iterate_of_id_le le_succ n m) ih }
end
lemma succ.rec_iff {p : α → Prop} (hsucc : ∀ a, p a ↔ p (succ a)) {a b : α} (h : a ≤ b) :
p a ↔ p b :=
begin
obtain ⟨n, rfl⟩ := h.exists_succ_iterate,
exact iterate.rec (λ b, p a ↔ p b) (λ c hc, hc.trans (hsucc _)) iff.rfl n,
end
end succ_order
section pred_order
variables [pred_order α] [is_pred_archimedean α] {a b : α}
instance : is_succ_archimedean (order_dual α) :=
{ exists_succ_iterate_of_le := λ a b h, by convert @exists_pred_iterate_of_le α _ _ _ _ _ h }
lemma has_le.le.exists_pred_iterate (h : a ≤ b) : ∃ n, pred^[n] b = a :=
exists_pred_iterate_of_le h
lemma exists_pred_iterate_iff_le : (∃ n, pred^[n] b = a) ↔ a ≤ b :=
@exists_succ_iterate_iff_le (order_dual α) _ _ _ _ _
/-- Induction principle on a type with a `pred_order` for all elements below a given element `m`. -/
@[elab_as_eliminator] lemma pred.rec {P : α → Prop} {m : α}
(h0 : P m) (h1 : ∀ n, n ≤ m → P n → P (pred n)) ⦃n : α⦄ (hmn : n ≤ m) : P n :=
@succ.rec (order_dual α) _ _ _ _ _ h0 h1 _ hmn
lemma pred.rec_iff {p : α → Prop} (hsucc : ∀ a, p a ↔ p (pred a)) {a b : α} (h : a ≤ b) :
p a ↔ p b :=
(@succ.rec_iff (order_dual α) _ _ _ _ hsucc _ _ h).symm
end pred_order
end preorder
section linear_order
variables [linear_order α]
section succ_order
variables [succ_order α] [is_succ_archimedean α] {a b : α}
lemma exists_succ_iterate_or : (∃ n, succ^[n] a = b) ∨ ∃ n, succ^[n] b = a :=
(le_total a b).imp exists_succ_iterate_of_le exists_succ_iterate_of_le
lemma succ.rec_linear {p : α → Prop} (hsucc : ∀ a, p a ↔ p (succ a)) (a b : α) : p a ↔ p b :=
(le_total a b).elim (succ.rec_iff hsucc) (λ h, (succ.rec_iff hsucc h).symm)
end succ_order
section pred_order
variables [pred_order α] [is_pred_archimedean α] {a b : α}
lemma exists_pred_iterate_or : (∃ n, pred^[n] b = a) ∨ ∃ n, pred^[n] a = b :=
(le_total a b).imp exists_pred_iterate_of_le exists_pred_iterate_of_le
lemma pred.rec_linear {p : α → Prop} (hsucc : ∀ a, p a ↔ p (pred a)) (a b : α) : p a ↔ p b :=
(le_total a b).elim (pred.rec_iff hsucc) (λ h, (pred.rec_iff hsucc h).symm)
end pred_order
end linear_order
section order_bot
variables [preorder α] [order_bot α] [succ_order α] [is_succ_archimedean α]
lemma succ.rec_bot (p : α → Prop) (hbot : p ⊥) (hsucc : ∀ a, p a → p (succ a)) (a : α) : p a :=
succ.rec hbot (λ x _ h, hsucc x h) (bot_le : ⊥ ≤ a)
end order_bot
section order_top
variables [preorder α] [order_top α] [pred_order α] [is_pred_archimedean α]
lemma pred.rec_top (p : α → Prop) (htop : p ⊤) (hpred : ∀ a, p a → p (pred a)) (a : α) : p a :=
pred.rec htop (λ x _ h, hpred x h) (le_top : a ≤ ⊤)
end order_top
|
6dfc78e16b4ec525ec14e47ac5c6e0c29b1268b5 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /library/logic/if.lean | 2944aed52a439a0bda6701d4576a2e3d39b52b7e | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,684 | lean | ----------------------------------------------------------------------------------------------------
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Author: Leonardo de Moura
----------------------------------------------------------------------------------------------------
import logic.decidable tools.tactic
open decidable tactic eq.ops
definition ite (c : Prop) [H : decidable c] {A : Type} (t e : A) : A :=
decidable.rec_on H (λ Hc, t) (λ Hnc, e)
notation `if` c `then` t:45 `else` e:45 := ite c t e
definition if_pos {c : Prop} [H : decidable c] (Hc : c) {A : Type} {t e : A} : (if c then t else e) = t :=
decidable.rec
(λ Hc : c, eq.refl (@ite c (inl Hc) A t e))
(λ Hnc : ¬c, absurd Hc Hnc)
H
definition if_neg {c : Prop} [H : decidable c] (Hnc : ¬c) {A : Type} {t e : A} : (if c then t else e) = e :=
decidable.rec
(λ Hc : c, absurd Hc Hnc)
(λ Hnc : ¬c, eq.refl (@ite c (inr Hnc) A t e))
H
definition if_t_t (c : Prop) [H : decidable c] {A : Type} (t : A) : (if c then t else t) = t :=
decidable.rec
(λ Hc : c, eq.refl (@ite c (inl Hc) A t t))
(λ Hnc : ¬c, eq.refl (@ite c (inr Hnc) A t t))
H
definition if_true {A : Type} (t e : A) : (if true then t else e) = t :=
if_pos trivial
definition if_false {A : Type} (t e : A) : (if false then t else e) = e :=
if_neg not_false_trivial
theorem if_cond_congr {c₁ c₂ : Prop} [H₁ : decidable c₁] [H₂ : decidable c₂] (Heq : c₁ ↔ c₂) {A : Type} (t e : A)
: (if c₁ then t else e) = (if c₂ then t else e) :=
decidable.rec_on H₁
(λ Hc₁ : c₁, decidable.rec_on H₂
(λ Hc₂ : c₂, if_pos Hc₁ ⬝ (if_pos Hc₂)⁻¹)
(λ Hnc₂ : ¬c₂, absurd (iff.elim_left Heq Hc₁) Hnc₂))
(λ Hnc₁ : ¬c₁, decidable.rec_on H₂
(λ Hc₂ : c₂, absurd (iff.elim_right Heq Hc₂) Hnc₁)
(λ Hnc₂ : ¬c₂, if_neg Hnc₁ ⬝ (if_neg Hnc₂)⁻¹))
theorem if_congr_aux {c₁ c₂ : Prop} [H₁ : decidable c₁] [H₂ : decidable c₂] {A : Type} {t₁ t₂ e₁ e₂ : A}
(Hc : c₁ ↔ c₂) (Ht : t₁ = t₂) (He : e₁ = e₂) :
(if c₁ then t₁ else e₁) = (if c₂ then t₂ else e₂) :=
Ht ▸ He ▸ (if_cond_congr Hc t₁ e₁)
theorem if_congr {c₁ c₂ : Prop} [H₁ : decidable c₁] {A : Type} {t₁ t₂ e₁ e₂ : A} (Hc : c₁ ↔ c₂) (Ht : t₁ = t₂) (He : e₁ = e₂) :
(if c₁ then t₁ else e₁) = (@ite c₂ (decidable_iff_equiv H₁ Hc) A t₂ e₂) :=
have H2 [visible] : decidable c₂, from (decidable_iff_equiv H₁ Hc),
if_congr_aux Hc Ht He
-- We use "dependent" if-then-else to be able to communicate the if-then-else condition
-- to the branches
definition dite (c : Prop) [H : decidable c] {A : Type} (t : c → A) (e : ¬ c → A) : A :=
decidable.rec_on H (λ Hc, t Hc) (λ Hnc, e Hnc)
notation `dif` c `then` t:45 `else` e:45 := dite c t e
definition dif_pos {c : Prop} [H : decidable c] (Hc : c) {A : Type} {t : c → A} {e : ¬ c → A} : (dif c then t else e) = t Hc :=
decidable.rec
(λ Hc : c, eq.refl (@dite c (inl Hc) A t e))
(λ Hnc : ¬c, absurd Hc Hnc)
H
definition dif_neg {c : Prop} [H : decidable c] (Hnc : ¬c) {A : Type} {t : c → A} {e : ¬ c → A} : (dif c then t else e) = e Hnc :=
decidable.rec
(λ Hc : c, absurd Hc Hnc)
(λ Hnc : ¬c, eq.refl (@dite c (inr Hnc) A t e))
H
-- Remark: dite and ite are "definitionally equal" when we ignore the proofs.
theorem dite_ite_eq (c : Prop) [H : decidable c] {A : Type} (t : A) (e : A) : dite c (λh, t) (λh, e) = ite c t e :=
rfl
|
71a55237995bd2cd383f74203e0cf308a5fb301f | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/algebra/basic.lean | 3c63db1cd280eec2d598e61107ef649f767b8d6f | [
"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 | 55,899 | 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 algebra.module.basic
import linear_algebra.basic
import tactic.abel
import data.equiv.ring_aut
/-!
# Algebras over commutative semirings
In this file we define associative unital `algebra`s over commutative (semi)rings, algebra
homomorphisms `alg_hom`, and algebra equivalences `alg_equiv`.
`subalgebra`s are defined in `algebra.algebra.subalgebra`.
For the category of `R`-algebras, denoted `Algebra R`, see the file
`algebra/category/Algebra/basic.lean`.
See the implementation notes for remarks about non-associative and non-unital algebras.
## Main definitions:
* `algebra R A`: the algebra typeclass.
* `alg_hom R A B`: the type of `R`-algebra morphisms from `A` to `B`.
* `alg_equiv R A B`: the type of `R`-algebra isomorphisms between `A` to `B`.
* `algebra_map R A : R →+* A`: the canonical map from `R` to `A`, as a `ring_hom`. This is the
preferred spelling of this map.
* `algebra.linear_map R A : R →ₗ[R] A`: the canonical map from `R` to `A`, as a `linear_map`.
* `algebra.of_id R A : R →ₐ[R] A`: the canonical map from `R` to `A`, as n `alg_hom`.
* Instances of `algebra` in this file:
* `algebra.id`
* `pi.algebra`
* `prod.algebra`
* `algebra_nat`
* `algebra_int`
* `algebra_rat`
* `mul_opposite.algebra`
* `module.End.algebra`
## Notations
* `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`.
* `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`.
## Implementation notes
Given a commutative (semi)ring `R`, there are two ways to define an `R`-algebra structure on a
(possibly noncommutative) (semi)ring `A`:
* By endowing `A` with a morphism of rings `R →+* A` denoted `algebra_map R A` which lands in the
center of `A`.
* By requiring `A` be an `R`-module such that the action associates and commutes with multiplication
as `r • (a₁ * a₂) = (r • a₁) * a₂ = a₁ * (r • a₂)`.
We define `algebra R A` in a way that subsumes both definitions, by extending `has_scalar R A` and
requiring that this scalar action `r • x` must agree with left multiplication by the image of the
structure morphism `algebra_map R A r * x`.
As a result, there are two ways to talk about an `R`-algebra `A` when `A` is a semiring:
1. ```lean
variables [comm_semiring R] [semiring A]
variables [algebra R A]
```
2. ```lean
variables [comm_semiring R] [semiring A]
variables [module R A] [smul_comm_class R A A] [is_scalar_tower R A A]
```
The first approach implies the second via typeclass search; so any lemma stated with the second set
of arguments will automatically apply to the first set. Typeclass search does not know that the
second approach implies the first, but this can be shown with:
```lean
example {R A : Type*} [comm_semiring R] [semiring A]
[module R A] [smul_comm_class R A A] [is_scalar_tower R A A] : algebra R A :=
algebra.of_module smul_mul_assoc mul_smul_comm
```
The advantage of the first approach is that `algebra_map R A` is available, and `alg_hom R A B` and
`subalgebra R A` can be used. For concrete `R` and `A`, `algebra_map R A` is often definitionally
convenient.
The advantage of the second approach is that `comm_semiring R`, `semiring A`, and `module R A` can
all be relaxed independently; for instance, this allows us to:
* Replace `semiring A` with `non_unital_non_assoc_semiring A` in order to describe non-unital and/or
non-associative algebras.
* Replace `comm_semiring R` and `module R A` with `comm_group R'` and `distrib_mul_action R' A`,
which when `R' = Rˣ` lets us talk about the "algebra-like" action of `Rˣ` on an
`R`-algebra `A`.
While `alg_hom R A B` cannot be used in the second approach, `non_unital_alg_hom R A B` still can.
You should always use the first approach when working with associative unital algebras, and mimic
the second approach only when you need to weaken a condition on either `R` or `A`.
-/
universes u v w u₁ v₁
open_locale big_operators
section prio
-- We set this priority to 0 later in this file
set_option extends_priority 200 /- control priority of
`instance [algebra R A] : has_scalar R A` -/
/--
An associative unital `R`-algebra is a semiring `A` equipped with a map into its center `R → A`.
See the implementation notes in this file for discussion of the details of this definition.
-/
@[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,
to_ring_hom := 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 _
lemma ring_hom.algebra_map_to_algebra {R S} [comm_semiring R] [comm_semiring S]
(i : R →+* S) :
@algebra_map R S _ _ i.to_algebra = i :=
rfl
namespace algebra
variables {R : Type u} {S : Type v} {A : Type w} {B : Type*}
/-- Let `R` be a commutative semiring, let `A` be a semiring with a `module 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`.
See note [reducible non-instances]. -/
@[reducible]
def of_module' [comm_semiring R] [semiring A] [module 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 `module 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`.
See note [reducible non-instances]. -/
@[reducible]
def of_module [comm_semiring R] [semiring A] [module 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_module' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one])
section semiring
variables [comm_semiring R] [comm_semiring S]
variables [semiring A] [algebra R A] [semiring B] [algebra R B]
/-- We keep this lemma private because it picks up the `algebra.to_has_scalar` instance
which we set to priority 0 shortly. See `smul_def` below for the public version. -/
private 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 [←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_module : module R A :=
{ one_smul := by simp [smul_def''],
mul_smul := by simp [smul_def'', mul_assoc],
smul_add := by simp [smul_def'', mul_add],
smul_zero := by simp [smul_def''],
add_smul := by simp [smul_def'', add_mul],
zero_smul := by simp [smul_def''] }
-- From now on, we don't want to use the following instance anymore.
-- Unfortunately, leaving it in place causes deterministic timeouts later in mathlib.
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
lemma algebra_map_eq_smul_one' : ⇑(algebra_map R A) = λ r, r • (1 : A) :=
funext algebra_map_eq_smul_one
/-- `mul_comm` for `algebra`s when one element is from the base ring. -/
theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r :=
algebra.commutes' r x
/-- `mul_left_comm` for `algebra`s when one element is from the base ring. -/
theorem left_comm (x : A) (r : R) (y : A) :
x * (algebra_map R A r * y) = algebra_map R A r * (x * y) :=
by rw [← mul_assoc, ← commutes, mul_assoc]
/-- `mul_right_comm` for `algebra`s when one element is from the base ring. -/
theorem right_comm (x : A) (r : R) (y : A) :
(x * algebra_map R A r) * y = (x * y) * algebra_map R A r :=
by rw [mul_assoc, commutes, ←mul_assoc]
instance _root_.is_scalar_tower.right : is_scalar_tower R A A :=
⟨λ x y z, by rw [smul_eq_mul, smul_eq_mul, smul_def, smul_def, mul_assoc]⟩
/-- This is just a special case of the global `mul_smul_comm` lemma that requires less typeclass
search (and was here first). -/
@[simp] protected lemma mul_smul_comm (s : R) (x y : A) :
x * (s • y) = s • (x * y) :=
-- TODO: set up `is_scalar_tower.smul_comm_class` earlier so that we can actually prove this using
-- `mul_smul_comm s x y`.
by rw [smul_def, smul_def, left_comm]
/-- This is just a special case of the global `smul_mul_assoc` lemma that requires less typeclass
search (and was here first). -/
@[simp] protected lemma smul_mul_assoc (r : R) (x y : A) :
(r • x) * y = r • (x * y) :=
smul_mul_assoc r x y
section
variables {r : R} {a : A}
@[simp] lemma bit0_smul_one : bit0 r • (1 : A) = bit0 (r • (1 : A)) :=
by simp [bit0, add_smul]
lemma bit0_smul_one' : bit0 r • (1 : A) = r • 2 :=
by simp [bit0, add_smul, smul_add]
@[simp] lemma bit0_smul_bit0 : bit0 r • bit0 a = r • (bit0 (bit0 a)) :=
by simp [bit0, add_smul, smul_add]
@[simp] lemma bit0_smul_bit1 : bit0 r • bit1 a = r • (bit0 (bit1 a)) :=
by simp [bit0, add_smul, smul_add]
@[simp] lemma bit1_smul_one : bit1 r • (1 : A) = bit1 (r • (1 : A)) :=
by simp [bit1, add_smul]
lemma bit1_smul_one' : bit1 r • (1 : A) = r • 2 + 1 :=
by simp [bit1, bit0, add_smul, smul_add]
@[simp] lemma bit1_smul_bit0 : bit1 r • bit0 a = r • (bit0 (bit0 a)) + bit0 a :=
by simp [bit1, add_smul, smul_add]
@[simp] lemma bit1_smul_bit1 : bit1 r • bit1 a = r • (bit0 (bit1 a)) + bit1 a :=
by { simp only [bit0, bit1, add_smul, smul_add, one_smul], abel }
end
variables (R A)
/--
The canonical ring homomorphism `algebra_map R A : R →* A` for any `R`-algebra `A`,
packaged as an `R`-linear map.
-/
protected def linear_map : R →ₗ[R] A :=
{ map_smul' := λ x y, by simp [algebra.smul_def],
..algebra_map R A }
@[simp]
lemma linear_map_apply (r : R) : algebra.linear_map R A r = algebra_map R A r := rfl
lemma coe_linear_map : ⇑(algebra.linear_map R A) = algebra_map R A := rfl
instance id : algebra R R := (ring_hom.id R).to_algebra
variables {R A}
namespace id
@[simp] lemma map_eq_id : algebra_map R R = ring_hom.id _ := rfl
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
section prod
variables (R A B)
instance _root_.prod.algebra : algebra R (A × B) :=
{ commutes' := by { rintro r ⟨a, b⟩, dsimp, rw [commutes r a, commutes r b] },
smul_def' := by { rintro r ⟨a, b⟩, dsimp, rw [smul_def r a, smul_def r b] },
.. prod.module,
.. ring_hom.prod (algebra_map R A) (algebra_map R B) }
variables {R A B}
@[simp] lemma algebra_map_prod_apply (r : R) :
algebra_map R (A × B) r = (algebra_map R A r, algebra_map R B r) := rfl
end prod
/-- Algebra over a subsemiring. This builds upon `subsemiring.module`. -/
instance of_subsemiring (S : subsemiring R) : algebra S A :=
{ smul := (•),
commutes' := λ r x, algebra.commutes r x,
smul_def' := λ r x, algebra.smul_def r x,
.. (algebra_map R A).comp S.subtype }
/-- Algebra over a subring. This builds upon `subring.module`. -/
instance of_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A]
(S : subring R) : algebra S A :=
{ smul := (•),
.. algebra.of_subsemiring S.to_subsemiring,
.. (algebra_map R A).comp S.subtype }
lemma algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) :
(algebra_map S R : S →+* R) = subring.subtype S := rfl
lemma coe_algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) :
(algebra_map S R : S → R) = subtype.val := rfl
lemma algebra_map_of_subring_apply {R : Type*} [comm_ring R] (S : subring R) (x : S) :
algebra_map S R x = x := rfl
/-- Explicit characterization of the submonoid map in the case of an algebra.
`S` is made explicit to help with type inference -/
def algebra_map_submonoid (S : Type*) [semiring S] [algebra R S]
(M : submonoid R) : (submonoid S) :=
submonoid.map (algebra_map R S : R →* S) M
lemma mem_algebra_map_submonoid_of_mem [algebra R S] {M : submonoid R} (x : M) :
(algebra_map R S x) ∈ algebra_map_submonoid S M :=
set.mem_image_of_mem (algebra_map R S) x.2
end semiring
section ring
variables [comm_ring R]
variables (R)
/-- A `semiring` that is an `algebra` over a commutative ring carries a natural `ring` structure.
See note [reducible non-instances]. -/
@[reducible]
def semiring_to_ring [semiring A] [algebra R A] : ring A :=
{ ..module.add_comm_monoid_to_add_comm_group R,
..(infer_instance : semiring A) }
variables {R}
lemma mul_sub_algebra_map_commutes [ring A] [algebra R A] (x : A) (r : R) :
x * (x - algebra_map R A r) = (x - algebra_map R A r) * x :=
by rw [mul_sub, ←commutes, sub_mul]
lemma mul_sub_algebra_map_pow_commutes [ring A] [algebra R A] (x : A) (r : R) (n : ℕ) :
x * (x - algebra_map R A r) ^ n = (x - algebra_map R A r) ^ n * x :=
begin
induction n with n ih,
{ simp },
{ rw [pow_succ, ←mul_assoc, mul_sub_algebra_map_commutes,
mul_assoc, ih, ←mul_assoc], }
end
end ring
end algebra
namespace no_zero_smul_divisors
variables {R A : Type*}
open algebra
section ring
variables [comm_ring R]
/-- If `algebra_map R A` is injective and `A` has no zero divisors,
`R`-multiples in `A` are zero only if one of the factors is zero.
Cannot be an instance because there is no `injective (algebra_map R A)` typeclass.
-/
lemma of_algebra_map_injective
[semiring A] [algebra R A] [no_zero_divisors A]
(h : function.injective (algebra_map R A)) : no_zero_smul_divisors R A :=
⟨λ c x hcx, (mul_eq_zero.mp ((smul_def c x).symm.trans hcx)).imp_left
((algebra_map R A).injective_iff.mp h _)⟩
variables (R A)
lemma algebra_map_injective [ring A] [nontrivial A]
[algebra R A] [no_zero_smul_divisors R A] :
function.injective (algebra_map R A) :=
suffices function.injective (λ (c : R), c • (1 : A)),
by { convert this, ext, rw [algebra.smul_def, mul_one] },
smul_left_injective R one_ne_zero
variables {R A}
lemma iff_algebra_map_injective [ring A] [is_domain A] [algebra R A] :
no_zero_smul_divisors R A ↔ function.injective (algebra_map R A) :=
⟨@@no_zero_smul_divisors.algebra_map_injective R A _ _ _ _,
no_zero_smul_divisors.of_algebra_map_injective⟩
end ring
section field
variables [field R] [semiring A] [algebra R A]
@[priority 100] -- see note [lower instance priority]
instance algebra.no_zero_smul_divisors [nontrivial A] [no_zero_divisors A] :
no_zero_smul_divisors R A :=
no_zero_smul_divisors.of_algebra_map_injective (algebra_map R A).injective
end field
end no_zero_smul_divisors
namespace mul_opposite
variables {R A : Type*} [comm_semiring R] [semiring A] [algebra R A]
instance : algebra R Aᵐᵒᵖ :=
{ to_ring_hom := (algebra_map R A).to_opposite $ λ x y, algebra.commutes _ _,
smul_def' := λ c x, unop_injective $
by { dsimp, simp only [op_mul, algebra.smul_def, algebra.commutes, op_unop] },
commutes' := λ r, mul_opposite.rec $ λ x, by dsimp; simp only [← op_mul, algebra.commutes],
.. mul_opposite.has_scalar A R }
@[simp] lemma algebra_map_apply (c : R) : algebra_map R Aᵐᵒᵖ c = op (algebra_map R A c) := rfl
end mul_opposite
namespace module
variables (R : Type u) (M : Type v) [comm_semiring R] [add_comm_monoid M] [module R M]
instance : algebra R (module.End R M) :=
algebra.of_module smul_mul_assoc (λ r f g, (smul_comm r f g).symm)
lemma algebra_map_End_eq_smul_id (a : R) :
(algebra_map R (End R M)) a = a • linear_map.id := rfl
@[simp] lemma algebra_map_End_apply (a : R) (m : M) :
(algebra_map R (End R M)) a m = a • m := rfl
@[simp] lemma ker_algebra_map_End (K : Type u) (V : Type v)
[field K] [add_comm_group V] [module K V] (a : K) (ha : a ≠ 0) :
((algebra_map K (End K V)) a).ker = ⊥ :=
linear_map.ker_smul _ _ ha
end module
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) (λ _, A → B) := ⟨alg_hom.to_fun⟩
initialize_simps_projections alg_hom (to_fun → apply)
@[simp] lemma to_fun_eq_coe (f : A →ₐ[R] B) : f.to_fun = f := rfl
instance : ring_hom_class (A →ₐ[R] B) A B :=
{ coe := to_fun,
coe_injective' := λ f g h, by { cases f, cases g, congr' },
map_add := map_add',
map_zero := map_zero',
map_mul := map_mul',
map_one := map_one' }
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
-- make the coercion the simp-normal form
@[simp] lemma to_ring_hom_eq_coe (f : A →ₐ[R] B) : f.to_ring_hom = f := rfl
@[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl
@[simp, norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl
@[simp, norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl
variables (φ : A →ₐ[R] B)
theorem coe_fn_injective : @function.injective (A →ₐ[R] B) (A → B) coe_fn := fun_like.coe_injective
theorem coe_fn_inj {φ₁ φ₂ : A →ₐ[R] B} : (φ₁ : A → B) = φ₂ ↔ φ₁ = φ₂ := fun_like.coe_fn_eq
theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) :=
λ φ₁ φ₂ H, coe_fn_injective $ 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
protected lemma congr_fun {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁ = φ₂) (x : A) : φ₁ x = φ₂ x :=
fun_like.congr_fun H x
protected lemma congr_arg (φ : A →ₐ[R] B) {x y : A} (h : x = y) : φ x = φ y :=
fun_like.congr_arg φ h
@[ext]
theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := fun_like.ext _ _ H
theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x := fun_like.ext_iff
@[simp] theorem mk_coe {f : A →ₐ[R] B} (h₁ h₂ h₃ h₄ h₅) :
(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := ext $ λ _, rfl
@[simp]
theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r
theorem comp_algebra_map : (φ : A →+* B).comp (algebra_map R A) = algebra_map R B :=
ring_hom.ext $ φ.commutes
lemma map_add (r s : A) : φ (r + s) = φ r + φ s := map_add _ _ _
lemma map_zero : φ 0 = 0 := map_zero _
lemma map_mul (x y) : φ (x * y) = φ x * φ y := map_mul _ _ _
lemma map_one : φ 1 = 1 := map_one _
lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n :=
map_pow _ _ _
@[simp] lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x :=
by simp only [algebra.smul_def, map_mul, commutes]
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
lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) :
φ (f.sum g) = f.sum (λ i a, φ (g i a)) :=
φ.map_sum _ _
lemma map_bit0 (x) : φ (bit0 x) = bit0 (φ x) := map_bit0 _ _
lemma map_bit1 (x) : φ (bit1 x) = bit1 (φ x) := map_bit1 _ _
/-- If a `ring_hom` is `R`-linear, then it is an `alg_hom`. -/
def mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : A →ₐ[R] B :=
{ to_fun := f,
commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, h, f.map_one],
.. f }
@[simp] lemma coe_mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : ⇑(mk' f h) = f := rfl
section
variables (R A)
/-- Identity map as an `alg_hom`. -/
protected def id : A →ₐ[R] A :=
{ commutes' := λ _, rfl,
..ring_hom.id A }
@[simp] lemma coe_id : ⇑(alg_hom.id R A) = id := rfl
@[simp] lemma id_to_ring_hom : (alg_hom.id R A : A →+* A) = ring_hom.id _ := rfl
end
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 coe_comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : ⇑(φ₁.comp φ₂) = φ₁ ∘ φ₂ := rfl
lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl
lemma comp_to_ring_hom (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) :
⇑(φ₁.comp φ₂ : A →+* C) = (φ₁ : B →+* C).comp ↑φ₂ := 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 →ₗ[R] 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_injective : function.injective (to_linear_map : _ → (A →ₗ[R] B)) :=
λ φ₁ φ₂ h, ext $ linear_map.congr_fun 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
@[simp] lemma to_linear_map_id : to_linear_map (alg_hom.id R A) = linear_map.id :=
linear_map.ext $ λ _, rfl
/-- Promote a `linear_map` to an `alg_hom` by supplying proofs about the behavior on `1` and `*`. -/
@[simps]
def of_linear_map (f : A →ₗ[R] B) (map_one : f 1 = 1) (map_mul : ∀ x y, f (x * y) = f x * f y) :
A →ₐ[R] B :=
{ to_fun := f,
map_one' := map_one,
map_mul' := map_mul,
commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, f.map_smul, map_one],
.. f.to_add_monoid_hom }
@[simp] lemma of_linear_map_to_linear_map (map_one) (map_mul) :
of_linear_map φ.to_linear_map map_one map_mul = φ :=
by { ext, refl }
@[simp] lemma to_linear_map_of_linear_map (f : A →ₗ[R] B) (map_one) (map_mul) :
to_linear_map (of_linear_map f map_one map_mul) = f :=
by { ext, refl }
@[simp] lemma of_linear_map_id (map_one) (map_mul) :
of_linear_map linear_map.id map_one map_mul = alg_hom.id R A :=
ext $ λ _, rfl
lemma map_list_prod (s : list A) :
φ s.prod = (s.map φ).prod :=
φ.to_ring_hom.map_list_prod s
section prod
/-- First projection as `alg_hom`. -/
def fst : A × B →ₐ[R] A :=
{ commutes' := λ r, rfl, .. ring_hom.fst A B}
/-- Second projection as `alg_hom`. -/
def snd : A × B →ₐ[R] B :=
{ commutes' := λ r, rfl, .. ring_hom.snd A B}
end prod
lemma algebra_map_eq_apply (f : A →ₐ[R] B) {y : R} {x : A} (h : algebra_map R A y = x) :
algebra_map R B y = f x :=
h ▸ (f.commutes _).symm
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [comm_semiring B]
variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B)
lemma map_multiset_prod (s : multiset A) :
φ s.prod = (s.map φ).prod :=
φ.to_ring_hom.map_multiset_prod s
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
lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) :
φ (f.prod g) = f.prod (λ i a, φ (g i a)) :=
φ.map_prod _ _
end comm_semiring
section ring
variables [comm_semiring R] [ring A] [ring B]
variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B)
lemma map_neg (x) : φ (-x) = -φ x := map_neg _ _
lemma map_sub (x y) : φ (x - y) = φ x - φ y := map_sub _ _ _
@[simp] lemma map_int_cast (n : ℤ) : φ n = n :=
φ.to_ring_hom.map_int_cast n
end ring
section division_ring
variables [comm_ring R] [division_ring A] [division_ring B]
variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B)
@[simp] lemma map_inv (x) : φ (x⁻¹) = (φ x)⁻¹ :=
φ.to_ring_hom.map_inv x
@[simp] lemma map_div (x y) : φ (x / y) = φ x / φ y :=
φ.to_ring_hom.map_div x y
end division_ring
theorem injective_iff {R A B : Type*} [comm_semiring R] [ring A] [semiring B]
[algebra R A] [algebra R B] (f : A →ₐ[R] B) :
function.injective f ↔ (∀ x, f x = 0 → x = 0) :=
ring_hom.injective_iff (f : A →+* B)
end alg_hom
@[simp] lemma rat.smul_one_eq_coe {A : Type*} [division_ring A] [algebra ℚ A] (m : ℚ) :
m • (1 : A) = ↑m :=
by rw [algebra.smul_def, mul_one, ring_hom.eq_rat_cast]
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₁}
section semiring
variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃]
variables [algebra R A₁] [algebra R A₂] [algebra R A₃]
variables (e : A₁ ≃ₐ[R] A₂)
instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) (λ _, A₁ → 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
protected lemma congr_arg {f : A₁ ≃ₐ[R] A₂} : Π {x x' : A₁}, x = x' → f x = f x'
| _ _ rfl := rfl
protected lemma congr_fun {f g : A₁ ≃ₐ[R] A₂} (h : f = g) (x : A₁) : f x = g x := h ▸ rfl
lemma ext_iff {f g : A₁ ≃ₐ[R] A₂} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, ext⟩
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 coe_mk {to_fun inv_fun left_inv right_inv map_mul map_add commutes} :
⇑(⟨to_fun, inv_fun, left_inv, right_inv, map_mul, map_add, commutes⟩ : A₁ ≃ₐ[R] A₂) = to_fun :=
rfl
@[simp] theorem mk_coe (e : A₁ ≃ₐ[R] A₂) (e' h₁ h₂ h₃ h₄ h₅) :
(⟨e, e', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂) = e := ext $ λ _, rfl
@[simp] lemma to_fun_eq_coe (e : A₁ ≃ₐ[R] A₂) : e.to_fun = e := rfl
@[simp] lemma to_ring_equiv_eq_coe : e.to_ring_equiv = e := rfl
@[simp, norm_cast] lemma coe_ring_equiv : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl
lemma coe_ring_equiv' : (e.to_ring_equiv : A₁ → A₂) = e := rfl
lemma coe_ring_equiv_injective : function.injective (coe : (A₁ ≃ₐ[R] A₂) → (A₁ ≃+* A₂)) :=
λ e₁ e₂ h, ext $ ring_equiv.congr_fun h
@[simp] lemma map_add : ∀ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add
@[simp] lemma map_zero : e 0 = 0 := e.to_add_equiv.map_zero
@[simp] lemma map_mul : ∀ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul
@[simp] lemma map_one : e 1 = 1 := e.to_mul_equiv.map_one
@[simp] lemma commutes : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r :=
e.commutes'
@[simp] lemma map_smul (r : R) (x : A₁) : e (r • x) = r • e x :=
by simp only [algebra.smul_def, map_mul, commutes]
lemma map_sum {ι : 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
lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A₁) :
e (f.sum g) = f.sum (λ i b, e (g i b)) :=
e.map_sum _ _
/-- Interpret an algebra equivalence as an algebra homomorphism.
This definition is included for symmetry with the other `to_*_hom` projections.
The `simp` normal form is to use the coercion of the `has_coe_to_alg_hom` instance. -/
def to_alg_hom : A₁ →ₐ[R] A₂ :=
{ map_one' := e.map_one, map_zero' := e.map_zero, ..e }
instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) :=
⟨to_alg_hom⟩
@[simp] lemma to_alg_hom_eq_coe : e.to_alg_hom = e := rfl
@[simp, norm_cast] lemma coe_alg_hom : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e :=
rfl
lemma coe_alg_hom_injective : function.injective (coe : (A₁ ≃ₐ[R] A₂) → (A₁ →ₐ[R] A₂)) :=
λ e₁ e₂ h, ext $ alg_hom.congr_fun h
/-- The two paths coercion can take to a `ring_hom` are equivalent -/
lemma coe_ring_hom_commutes : ((e : A₁ →ₐ[R] A₂) : A₁ →+* A₂) = ((e : A₁ ≃+* A₂) : A₁ →+* A₂) :=
rfl
@[simp] lemma map_pow : ∀ (x : A₁) (n : ℕ), e (x ^ n) = (e x) ^ n := e.to_alg_hom.map_pow
lemma injective : function.injective e := e.to_equiv.injective
lemma surjective : function.surjective e := e.to_equiv.surjective
lemma bijective : function.bijective e := e.to_equiv.bijective
/-- Algebra equivalences are reflexive. -/
@[refl] def refl : A₁ ≃ₐ[R] A₁ := {commutes' := λ r, rfl, ..(1 : A₁ ≃+* A₁)}
instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨refl⟩
@[simp] lemma refl_to_alg_hom : ↑(refl : A₁ ≃ₐ[R] A₁) = alg_hom.id R A₁ := rfl
@[simp] lemma coe_refl : ⇑(refl : A₁ ≃ₐ[R] A₁) = id := 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, }
/-- See Note [custom simps projection] -/
def simps.symm_apply (e : A₁ ≃ₐ[R] A₂) : A₂ → A₁ := e.symm
initialize_simps_projections alg_equiv (to_fun → apply, inv_fun → symm_apply)
@[simp] lemma inv_fun_eq_symm {e : A₁ ≃ₐ[R] A₂} : e.inv_fun = e.symm := rfl
@[simp] lemma symm_symm (e : A₁ ≃ₐ[R] A₂) : e.symm.symm = e :=
by { ext, refl, }
lemma symm_bijective : function.bijective (symm : (A₁ ≃ₐ[R] A₂) → (A₂ ≃ₐ[R] A₁)) :=
equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩
@[simp] lemma mk_coe' (e : A₁ ≃ₐ[R] A₂) (f h₁ h₂ h₃ h₄ h₅) :
(⟨f, e, h₁, h₂, h₃, h₄, h₅⟩ : A₂ ≃ₐ[R] A₁) = e.symm :=
symm_bijective.injective $ ext $ λ x, rfl
@[simp] theorem symm_mk (f f') (h₁ h₂ h₃ h₄ h₅) :
(⟨f, f', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂).symm =
{ to_fun := f', inv_fun := f,
..(⟨f, f', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂).symm } := rfl
/-- 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 symm_trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₃) :
(e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := rfl
@[simp] lemma coe_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) :
⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl
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 }
theorem left_inverse_symm (e : A₁ ≃ₐ[R] A₂) : function.left_inverse e.symm e := e.left_inv
theorem right_inverse_symm (e : A₁ ≃ₐ[R] A₂) : function.right_inverse e.symm e := e.right_inv
/-- If `A₁` is equivalent to `A₁'` and `A₂` is equivalent to `A₂'`, then the type of maps
`A₁ →ₐ[R] A₂` is equivalent to the type of maps `A₁' →ₐ[R] A₂'`. -/
def arrow_congr {A₁' A₂' : Type*} [semiring A₁'] [semiring A₂'] [algebra R A₁'] [algebra R A₂']
(e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') : (A₁ →ₐ[R] A₂) ≃ (A₁' →ₐ[R] A₂') :=
{ to_fun := λ f, (e₂.to_alg_hom.comp f).comp e₁.symm.to_alg_hom,
inv_fun := λ f, (e₂.symm.to_alg_hom.comp f).comp e₁.to_alg_hom,
left_inv := λ f, by { simp only [alg_hom.comp_assoc, to_alg_hom_eq_coe, symm_comp],
simp only [←alg_hom.comp_assoc, symm_comp, alg_hom.id_comp, alg_hom.comp_id] },
right_inv := λ f, by { simp only [alg_hom.comp_assoc, to_alg_hom_eq_coe, comp_symm],
simp only [←alg_hom.comp_assoc, comp_symm, alg_hom.id_comp, alg_hom.comp_id] } }
lemma arrow_congr_comp {A₁' A₂' A₃' : Type*} [semiring A₁'] [semiring A₂'] [semiring A₃']
[algebra R A₁'] [algebra R A₂'] [algebra R A₃'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂')
(e₃ : A₃ ≃ₐ[R] A₃') (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₃) :
arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) :=
by { ext, simp only [arrow_congr, equiv.coe_fn_mk, alg_hom.comp_apply],
congr, exact (e₂.symm_apply_apply _).symm }
@[simp] lemma arrow_congr_refl :
arrow_congr alg_equiv.refl alg_equiv.refl = equiv.refl (A₁ →ₐ[R] A₂) :=
by { ext, refl }
@[simp] lemma arrow_congr_trans {A₁' A₂' A₃' : Type*} [semiring A₁'] [semiring A₂'] [semiring A₃']
[algebra R A₁'] [algebra R A₂'] [algebra R A₃'] (e₁ : A₁ ≃ₐ[R] A₂) (e₁' : A₁' ≃ₐ[R] A₂')
(e₂ : A₂ ≃ₐ[R] A₃) (e₂' : A₂' ≃ₐ[R] A₃') :
arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') :=
by { ext, refl }
@[simp] lemma arrow_congr_symm {A₁' A₂' : Type*} [semiring A₁'] [semiring A₂']
[algebra R A₁'] [algebra R A₂'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') :
(arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm :=
by { ext, refl }
/-- 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₂ :=
{ to_fun := f,
inv_fun := g,
left_inv := alg_hom.ext_iff.1 h₂,
right_inv := alg_hom.ext_iff.1 h₁,
..f }
lemma coe_alg_hom_of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) :
↑(of_alg_hom f g h₁ h₂) = f := alg_hom.ext $ λ _, rfl
@[simp]
lemma of_alg_hom_coe_alg_hom (f : A₁ ≃ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) :
of_alg_hom ↑f g h₁ h₂ = f := ext $ λ _, rfl
lemma of_alg_hom_symm (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) :
(of_alg_hom f g h₁ h₂).symm = of_alg_hom g f h₂ h₁ := rfl
/-- Promotes a bijective algebra homomorphism to an algebra equivalence. -/
noncomputable def of_bijective (f : A₁ →ₐ[R] A₂) (hf : function.bijective f) : A₁ ≃ₐ[R] A₂ :=
{ .. ring_equiv.of_bijective (f : A₁ →+* A₂) hf, .. f }
@[simp] lemma coe_of_bijective {f : A₁ →ₐ[R] A₂} {hf : function.bijective f} :
(alg_equiv.of_bijective f hf : A₁ → A₂) = f := rfl
lemma of_bijective_apply {f : A₁ →ₐ[R] A₂} {hf : function.bijective f} (a : A₁) :
(alg_equiv.of_bijective f hf) a = f a := rfl
/-- Forgetting the multiplicative structures, an equivalence of algebras is a linear equivalence. -/
@[simps apply] def to_linear_equiv (e : A₁ ≃ₐ[R] A₂) : A₁ ≃ₗ[R] A₂ :=
{ to_fun := e,
map_smul' := e.map_smul,
inv_fun := e.symm,
.. e }
@[simp] lemma to_linear_equiv_refl :
(alg_equiv.refl : A₁ ≃ₐ[R] A₁).to_linear_equiv = linear_equiv.refl R A₁ := rfl
@[simp] lemma to_linear_equiv_symm (e : A₁ ≃ₐ[R] A₂) :
e.to_linear_equiv.symm = e.symm.to_linear_equiv := rfl
@[simp] lemma to_linear_equiv_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) :
(e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := rfl
theorem to_linear_equiv_injective : function.injective (to_linear_equiv : _ → (A₁ ≃ₗ[R] A₂)) :=
λ e₁ e₂ h, ext $ linear_equiv.congr_fun h
/-- Interpret an algebra equivalence as a linear map. -/
def to_linear_map : A₁ →ₗ[R] A₂ :=
e.to_alg_hom.to_linear_map
@[simp] lemma to_alg_hom_to_linear_map :
(e : A₁ →ₐ[R] A₂).to_linear_map = e.to_linear_map := rfl
@[simp] lemma to_linear_equiv_to_linear_map :
e.to_linear_equiv.to_linear_map = e.to_linear_map := rfl
@[simp] lemma to_linear_map_apply (x : A₁) : e.to_linear_map x = e x := rfl
theorem to_linear_map_injective : function.injective (to_linear_map : _ → (A₁ →ₗ[R] A₂)) :=
λ e₁ e₂ h, ext $ linear_map.congr_fun h
@[simp] lemma trans_to_linear_map (f : A₁ ≃ₐ[R] A₂) (g : A₂ ≃ₐ[R] A₃) :
(f.trans g).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl
section of_linear_equiv
variables (l : A₁ ≃ₗ[R] A₂)
(map_mul : ∀ x y : A₁, l (x * y) = l x * l y)
(commutes : ∀ r : R, l (algebra_map R A₁ r) = algebra_map R A₂ r)
/--
Upgrade a linear equivalence to an algebra equivalence,
given that it distributes over multiplication and action of scalars.
-/
@[simps apply]
def of_linear_equiv : A₁ ≃ₐ[R] A₂ :=
{ to_fun := l,
inv_fun := l.symm,
map_mul' := map_mul,
commutes' := commutes,
..l }
@[simp]
lemma of_linear_equiv_symm :
(of_linear_equiv l map_mul commutes).symm = of_linear_equiv l.symm
((of_linear_equiv l map_mul commutes).symm.map_mul)
((of_linear_equiv l map_mul commutes).symm.commutes) :=
rfl
@[simp] lemma of_linear_equiv_to_linear_equiv (map_mul) (commutes) :
of_linear_equiv e.to_linear_equiv map_mul commutes = e :=
by { ext, refl }
@[simp] lemma to_linear_equiv_of_linear_equiv :
to_linear_equiv (of_linear_equiv l map_mul commutes) = l :=
by { ext, refl }
end of_linear_equiv
@[simps mul one {attrs := []}] instance aut : group (A₁ ≃ₐ[R] A₁) :=
{ mul := λ ϕ ψ, ψ.trans ϕ,
mul_assoc := λ ϕ ψ χ, rfl,
one := refl,
one_mul := λ ϕ, ext $ λ x, rfl,
mul_one := λ ϕ, ext $ λ x, rfl,
inv := symm,
mul_left_inv := λ ϕ, ext $ symm_apply_apply ϕ }
@[simp] lemma one_apply (x : A₁) : (1 : A₁ ≃ₐ[R] A₁) x = x := rfl
@[simp] lemma mul_apply (e₁ e₂ : A₁ ≃ₐ[R] A₁) (x : A₁) : (e₁ * e₂) x = e₁ (e₂ x) := rfl
/-- An algebra isomorphism induces a group isomorphism between automorphism groups -/
@[simps apply]
def aut_congr (ϕ : A₁ ≃ₐ[R] A₂) : (A₁ ≃ₐ[R] A₁) ≃* (A₂ ≃ₐ[R] A₂) :=
{ to_fun := λ ψ, ϕ.symm.trans (ψ.trans ϕ),
inv_fun := λ ψ, ϕ.trans (ψ.trans ϕ.symm),
left_inv := λ ψ, by { ext, simp_rw [trans_apply, symm_apply_apply] },
right_inv := λ ψ, by { ext, simp_rw [trans_apply, apply_symm_apply] },
map_mul' := λ ψ χ, by { ext, simp only [mul_apply, trans_apply, symm_apply_apply] } }
@[simp] lemma aut_congr_refl : aut_congr (alg_equiv.refl) = mul_equiv.refl (A₁ ≃ₐ[R] A₁) :=
by { ext, refl }
@[simp] lemma aut_congr_symm (ϕ : A₁ ≃ₐ[R] A₂) : (aut_congr ϕ).symm = aut_congr ϕ.symm := rfl
@[simp] lemma aut_congr_trans (ϕ : A₁ ≃ₐ[R] A₂) (ψ : A₂ ≃ₐ[R] A₃) :
(aut_congr ϕ).trans (aut_congr ψ) = aut_congr (ϕ.trans ψ) := rfl
/-- The tautological action by `A₁ ≃ₐ[R] A₁` on `A₁`.
This generalizes `function.End.apply_mul_action`. -/
instance apply_mul_semiring_action : mul_semiring_action (A₁ ≃ₐ[R] A₁) A₁ :=
{ smul := ($),
smul_zero := alg_equiv.map_zero,
smul_add := alg_equiv.map_add,
smul_one := alg_equiv.map_one,
smul_mul := alg_equiv.map_mul,
one_smul := λ _, rfl,
mul_smul := λ _ _ _, rfl }
@[simp] protected lemma smul_def (f : A₁ ≃ₐ[R] A₁) (a : A₁) : f • a = f a := rfl
instance apply_has_faithful_scalar : has_faithful_scalar (A₁ ≃ₐ[R] A₁) A₁ :=
⟨λ _ _, alg_equiv.ext⟩
instance apply_smul_comm_class : smul_comm_class R (A₁ ≃ₐ[R] A₁) A₁ :=
{ smul_comm := λ r e a, (e.map_smul r a).symm }
instance apply_smul_comm_class' : smul_comm_class (A₁ ≃ₐ[R] A₁) R A₁ :=
{ smul_comm := λ e r a, (e.map_smul r a) }
@[simp] lemma algebra_map_eq_apply (e : A₁ ≃ₐ[R] A₂) {y : R} {x : A₁} :
(algebra_map R A₂ y = e x) ↔ (algebra_map R A₁ y = x) :=
⟨λ h, by simpa using e.symm.to_alg_hom.algebra_map_eq_apply h,
λ h, e.to_alg_hom.algebra_map_eq_apply h⟩
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A₁] [comm_semiring A₂]
variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂)
lemma map_prod {ι : Type*} (f : ι → A₁) (s : finset ι) :
e (∏ x in s, f x) = ∏ x in s, e (f x) :=
e.to_alg_hom.map_prod f s
lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A₁) :
e (f.prod g) = f.prod (λ i a, e (g i a)) :=
e.to_alg_hom.map_finsupp_prod f g
end comm_semiring
section ring
variables [comm_ring R] [ring A₁] [ring A₂]
variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂)
@[simp] lemma map_neg (x) : e (-x) = -e x :=
e.to_alg_hom.map_neg x
@[simp] lemma map_sub (x y) : e (x - y) = e x - e y :=
e.to_alg_hom.map_sub x y
end ring
section division_ring
variables [comm_ring R] [division_ring A₁] [division_ring A₂]
variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂)
@[simp] lemma map_inv (x) : e (x⁻¹) = (e x)⁻¹ :=
e.to_alg_hom.map_inv x
@[simp] lemma map_div (x y) : e (x / y) = e x / e y :=
e.to_alg_hom.map_div x y
end division_ring
end alg_equiv
namespace mul_semiring_action
variables {M G : Type*} (R A : Type*) [comm_semiring R] [semiring A] [algebra R A]
section
variables [monoid M] [mul_semiring_action M A] [smul_comm_class M R A]
/-- Each element of the monoid defines a algebra homomorphism.
This is a stronger version of `mul_semiring_action.to_ring_hom` and
`distrib_mul_action.to_linear_map`. -/
@[simps]
def to_alg_hom (m : M) : A →ₐ[R] A :=
alg_hom.mk' (mul_semiring_action.to_ring_hom _ _ m) (smul_comm _)
theorem to_alg_hom_injective [has_faithful_scalar M A] :
function.injective (mul_semiring_action.to_alg_hom R A : M → A →ₐ[R] A) :=
λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_hom.ext_iff.1 h r
end
section
variables [group G] [mul_semiring_action G A] [smul_comm_class G R A]
/-- Each element of the group defines a algebra equivalence.
This is a stronger version of `mul_semiring_action.to_ring_equiv` and
`distrib_mul_action.to_linear_equiv`. -/
@[simps]
def to_alg_equiv (g : G) : A ≃ₐ[R] A :=
{ .. mul_semiring_action.to_ring_equiv _ _ g,
.. mul_semiring_action.to_alg_hom R A g }
theorem to_alg_equiv_injective [has_faithful_scalar G A] :
function.injective (mul_semiring_action.to_alg_equiv R A : G → A ≃ₐ[R] A) :=
λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_equiv.ext_iff.1 h r
end
end mul_semiring_action
section nat
variables {R : Type*} [semiring R]
-- Lower the priority so that `algebra.id` is picked most of the time when working with
-- `ℕ`-algebras. This is only an issue since `algebra.id` and `algebra_nat` are not yet defeq.
-- TODO: fix this by adding an `of_nat` field to semirings.
/-- Semiring ⥤ ℕ-Alg -/
@[priority 99] instance algebra_nat : algebra ℕ R :=
{ commutes' := nat.cast_commute,
smul_def' := λ _ _, nsmul_eq_mul _ _,
to_ring_hom := nat.cast_ring_hom R }
instance nat_algebra_subsingleton : subsingleton (algebra ℕ R) :=
⟨λ P Q, by { ext, simp, }⟩
end nat
namespace ring_hom
variables {R S : Type*}
/-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/
def to_nat_alg_hom [semiring R] [semiring S] (f : R →+* S) :
R →ₐ[ℕ] S :=
{ to_fun := f, commutes' := λ n, by simp, .. f }
/-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/
def to_int_alg_hom [ring R] [ring S] [algebra ℤ R] [algebra ℤ S] (f : R →+* S) :
R →ₐ[ℤ] S :=
{ commutes' := λ n, by simp, .. f }
@[simp] lemma map_rat_algebra_map [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S)
(r : ℚ) :
f (algebra_map ℚ R r) = algebra_map ℚ S r :=
ring_hom.ext_iff.1 (subsingleton.elim (f.comp (algebra_map ℚ R)) (algebra_map ℚ S)) r
/-- Reinterpret a `ring_hom` as a `ℚ`-algebra homomorphism. -/
def to_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) :
R →ₐ[ℚ] S :=
{ commutes' := f.map_rat_algebra_map, .. f }
end ring_hom
section rat
instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α :=
(rat.cast_hom α).to_algebra' $ λ r x, r.cast_commute x
@[simp] theorem algebra_map_rat_rat : algebra_map ℚ ℚ = ring_hom.id ℚ :=
subsingleton.elim _ _
-- TODO[gh-6025]: make this an instance once safe to do so
lemma algebra_rat_subsingleton {α} [semiring α] :
subsingleton (algebra ℚ α) :=
⟨λ x y, algebra.algebra_ext x y $ ring_hom.congr_fun $ subsingleton.elim _ _⟩
end rat
namespace algebra
open module
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
section int
variables (R : Type*) [ring R]
-- Lower the priority so that `algebra.id` is picked most of the time when working with
-- `ℤ`-algebras. This is only an issue since `algebra.id ℤ` and `algebra_int ℤ` are not yet defeq.
-- TODO: fix this by adding an `of_int` field to rings.
/-- Ring ⥤ ℤ-Alg -/
@[priority 99] instance algebra_int : algebra ℤ R :=
{ commutes' := int.cast_commute,
smul_def' := λ _ _, zsmul_eq_mul _ _,
to_ring_hom := int.cast_ring_hom R }
/-- A special case of `ring_hom.eq_int_cast'` that happens to be true definitionally -/
@[simp] lemma algebra_map_int_eq : algebra_map ℤ R = int.cast_ring_hom R := rfl
variables {R}
instance int_algebra_subsingleton : subsingleton (algebra ℤ R) :=
⟨λ P Q, by { ext, simp, }⟩
end int
/-!
The R-algebra structure on `Π i : I, A i` when each `A i` is an R-algebra.
We couldn't set this up back in `algebra.pi_instances` because this file imports it.
-/
namespace pi
variable {I : Type u} -- The indexing type
variable {R : Type*} -- The scalar type
variable {f : I → Type v} -- The family of types already equipped with instances
variables (x y : Π i, f i) (i : I)
variables (I f)
instance algebra {r : comm_semiring R}
[s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] :
algebra R (Π i : I, f i) :=
{ commutes' := λ a f, begin ext, simp [algebra.commutes], end,
smul_def' := λ a f, begin ext, simp [algebra.smul_def], end,
..(pi.ring_hom (λ i, algebra_map R (f i)) : R →+* Π i : I, f i) }
@[simp] lemma algebra_map_apply {r : comm_semiring R}
[s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] (a : R) (i : I) :
algebra_map R (Π i, f i) a i = algebra_map R (f i) a := rfl
-- One could also build a `Π i, R i`-algebra structure on `Π i, A i`,
-- when each `A i` is an `R i`-algebra, although I'm not sure that it's useful.
variables {I} (R) (f)
/-- `function.eval` as an `alg_hom`. The name matches `pi.eval_ring_hom`, `pi.eval_monoid_hom`,
etc. -/
@[simps]
def eval_alg_hom {r : comm_semiring R} [Π i, semiring (f i)] [Π i, algebra R (f i)] (i : I) :
(Π i, f i) →ₐ[R] f i :=
{ to_fun := λ f, f i, commutes' := λ r, rfl, .. pi.eval_ring_hom f i}
variables (A B : Type*) [comm_semiring R] [semiring B] [algebra R B]
/-- `function.const` as an `alg_hom`. The name matches `pi.const_ring_hom`, `pi.const_monoid_hom`,
etc. -/
@[simps]
def const_alg_hom : B →ₐ[R] (A → B) :=
{ to_fun := function.const _,
commutes' := λ r, rfl,
.. pi.const_ring_hom A B}
/-- When `R` is commutative and permits an `algebra_map`, `pi.const_ring_hom` is equal to that
map. -/
@[simp] lemma const_ring_hom_eq_algebra_map : const_ring_hom A R = algebra_map R (A → R) :=
rfl
@[simp] lemma const_alg_hom_eq_algebra_of_id : const_alg_hom R A R = algebra.of_id R (A → R) :=
rfl
end pi
section is_scalar_tower
variables {R : Type*} [comm_semiring R]
variables (A : Type*) [semiring A] [algebra R A]
variables {M : Type*} [add_comm_monoid M] [module A M] [module R M] [is_scalar_tower R A M]
variables {N : Type*} [add_comm_monoid N] [module A N] [module R N] [is_scalar_tower R A N]
lemma algebra_compatible_smul (r : R) (m : M) : r • m = ((algebra_map R A) r) • m :=
by rw [←(one_smul A m), ←smul_assoc, algebra.smul_def, mul_one, one_smul]
@[simp] lemma algebra_map_smul (r : R) (m : M) : ((algebra_map R A) r) • m = r • m :=
(algebra_compatible_smul A r m).symm
variable {A}
@[priority 100] -- see Note [lower instance priority]
instance is_scalar_tower.to_smul_comm_class : smul_comm_class R A M :=
⟨λ r a m, by rw [algebra_compatible_smul A r (a • m), smul_smul, algebra.commutes, mul_smul,
←algebra_compatible_smul]⟩
@[priority 100] -- see Note [lower instance priority]
instance is_scalar_tower.to_smul_comm_class' : smul_comm_class A R M :=
smul_comm_class.symm _ _ _
lemma smul_algebra_smul_comm (r : R) (a : A) (m : M) : a • r • m = r • a • m :=
smul_comm _ _ _
namespace linear_map
instance coe_is_scalar_tower : has_coe (M →ₗ[A] N) (M →ₗ[R] N) :=
⟨restrict_scalars R⟩
variables (R) {A M N}
@[simp, norm_cast squash] lemma coe_restrict_scalars_eq_coe (f : M →ₗ[A] N) :
(f.restrict_scalars R : M → N) = f := rfl
@[simp, norm_cast squash] lemma coe_coe_is_scalar_tower (f : M →ₗ[A] N) :
((f : M →ₗ[R] N) : M → N) = f := rfl
/-- `A`-linearly coerce a `R`-linear map from `M` to `A` to a function, given an algebra `A` over
a commutative semiring `R` and `M` a module over `R`. -/
def lto_fun (R : Type u) (M : Type v) (A : Type w)
[comm_semiring R] [add_comm_monoid M] [module R M] [comm_ring A] [algebra R A] :
(M →ₗ[R] A) →ₗ[A] (M → A) :=
{ to_fun := linear_map.to_fun,
map_add' := λ f g, rfl,
map_smul' := λ c f, rfl }
end linear_map
end is_scalar_tower
/-! TODO: The following lemmas no longer involve `algebra` at all, and could be moved closer
to `algebra/module/submodule.lean`. Currently this is tricky because `ker`, `range`, `⊤`, and `⊥`
are all defined in `linear_algebra/basic.lean`. -/
section module
open module
variables (R S M N : Type*) [semiring R] [semiring S] [has_scalar R S]
variables [add_comm_monoid M] [module R M] [module S M] [is_scalar_tower R S M]
variables [add_comm_monoid N] [module R N] [module S N] [is_scalar_tower R S N]
variables {S M N}
@[simp]
lemma linear_map.ker_restrict_scalars (f : M →ₗ[S] N) :
(f.restrict_scalars R).ker = f.ker.restrict_scalars R :=
rfl
end module
namespace submodule
variables (R A M : Type*)
variables [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M]
variables [module R M] [module A M] [is_scalar_tower R A M]
/-- If `A` is an `R`-algebra such that the induced morhpsim `R →+* A` is surjective, then the
`R`-module generated by a set `X` equals the `A`-module generated by `X`. -/
lemma span_eq_restrict_scalars (X : set M) (hsur : function.surjective (algebra_map R A)) :
span R X = restrict_scalars R (span A X) :=
begin
apply (span_le_restrict_scalars R A X).antisymm (λ m hm, _),
refine span_induction hm subset_span (zero_mem _) (λ _ _, add_mem _) (λ a m hm, _),
obtain ⟨r, rfl⟩ := hsur a,
simpa [algebra_map_smul] using smul_mem _ r hm
end
end submodule
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w} {I : Type*}
variables [comm_semiring R] [semiring A] [semiring B]
variables [algebra R A] [algebra R B]
/-- `R`-algebra homomorphism between the function spaces `I → A` and `I → B`, induced by an
`R`-algebra homomorphism `f` between `A` and `B`. -/
@[simps] protected def comp_left (f : A →ₐ[R] B) (I : Type*) : (I → A) →ₐ[R] (I → B) :=
{ to_fun := λ h, f ∘ h,
commutes' := λ c, by { ext, exact f.commutes' c },
.. f.to_ring_hom.comp_left I }
end alg_hom
example {R A} [comm_semiring R] [semiring A]
[module R A] [smul_comm_class R A A] [is_scalar_tower R A A] : algebra R A :=
algebra.of_module smul_mul_assoc mul_smul_comm
|
055d894d188ff6da63f7f468f0002c11f1fb9eb2 | 367134ba5a65885e863bdc4507601606690974c1 | /src/category_theory/limits/shapes/normal_mono.lean | fe619eecf8a5c4cf3c812d3346ee0d0812057a32 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 7,290 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta
-/
import category_theory.limits.shapes.regular_mono
import category_theory.limits.shapes.kernels
/-!
# Definitions and basic properties of normal monomorphisms and epimorphisms.
A normal monomorphism is a morphism that is the kernel of some other morphism.
We give the construction `normal_mono → regular_mono` (`category_theory.normal_mono.regular_mono`)
as well as the dual construction for normal epimorphisms. We show equivalences reflect normal
monomorphisms (`category_theory.equivalence_reflects_normal_mono`), and that the pullback of a
normal monomorphism is normal (`category_theory.normal_of_is_pullback_snd_of_normal`).
-/
noncomputable theory
namespace category_theory
open category_theory.limits
universes v₁ u₁ u₂
variables {C : Type u₁} [category.{v₁} C]
variables {X Y : C}
section
variables [has_zero_morphisms C]
/-- A normal monomorphism is a morphism which is the kernel of some morphism. -/
class normal_mono (f : X ⟶ Y) :=
(Z : C)
(g : Y ⟶ Z)
(w : f ≫ g = 0)
(is_limit : is_limit (kernel_fork.of_ι f w))
section
local attribute [instance] fully_faithful_reflects_limits
local attribute [instance] equivalence.ess_surj_of_equivalence
/-- If `F` is an equivalence and `F.map f` is a normal mono, then `f` is a normal mono. -/
def equivalence_reflects_normal_mono {D : Type u₂} [category.{v₁} D] [has_zero_morphisms D]
(F : C ⥤ D) [is_equivalence F] {X Y : C} {f : X ⟶ Y} (hf : normal_mono (F.map f)) :
normal_mono f :=
{ Z := F.obj_preimage hf.Z,
g := full.preimage (hf.g ≫ (F.obj_obj_preimage_iso hf.Z).inv),
w := faithful.map_injective F $ by simp [reassoc_of hf.w],
is_limit := reflects_limit.reflects $
is_limit.of_cone_equiv (cones.postcompose_equivalence (comp_nat_iso F)) $
is_limit.of_iso_limit
(by exact is_limit.of_iso_limit
(is_kernel.of_comp_iso _ _ (F.obj_obj_preimage_iso hf.Z) (by simp) hf.is_limit)
(of_ι_congr (category.comp_id _).symm)) (iso_of_ι _).symm }
end
/-- Every normal monomorphism is a regular monomorphism. -/
@[priority 100]
instance normal_mono.regular_mono (f : X ⟶ Y) [I : normal_mono f] : regular_mono f :=
{ left := I.g,
right := 0,
w := (by simpa using I.w),
..I }
/-- If `f` is a normal mono, then any map `k : W ⟶ Y` such that `k ≫ normal_mono.g = 0` induces
a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/
def normal_mono.lift' {W : C} (f : X ⟶ Y) [normal_mono f] (k : W ⟶ Y) (h : k ≫ normal_mono.g = 0) :
{l : W ⟶ X // l ≫ f = k} :=
kernel_fork.is_limit.lift' normal_mono.is_limit _ h
/--
The second leg of a pullback cone is a normal monomorphism if the right component is too.
See also `pullback.snd_of_mono` for the basic monomorphism version, and
`normal_of_is_pullback_fst_of_normal` for the flipped version.
-/
def normal_of_is_pullback_snd_of_normal
{P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S}
[hn : normal_mono h] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk _ _ comm)) :
normal_mono g :=
{ Z := hn.Z,
g := k ≫ hn.g,
w := by rw [← reassoc_of comm, hn.w, has_zero_morphisms.comp_zero],
is_limit :=
begin
letI gr := regular_of_is_pullback_snd_of_regular comm t,
have q := (has_zero_morphisms.comp_zero k hn.Z).symm,
convert gr.is_limit,
dunfold kernel_fork.of_ι fork.of_ι,
congr, exact q, exact q, exact q, apply proof_irrel_heq,
end }
/--
The first leg of a pullback cone is a normal monomorphism if the left component is too.
See also `pullback.fst_of_mono` for the basic monomorphism version, and
`normal_of_is_pullback_snd_of_normal` for the flipped version.
-/
def normal_of_is_pullback_fst_of_normal
{P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S}
[hn : normal_mono k] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk _ _ comm)) :
normal_mono f :=
normal_of_is_pullback_snd_of_normal comm.symm (pullback_cone.flip_is_limit t)
end
section
variables [has_zero_morphisms C]
/-- A normal epimorphism is a morphism which is the cokernel of some morphism. -/
class normal_epi (f : X ⟶ Y) :=
(W : C)
(g : W ⟶ X)
(w : g ≫ f = 0)
(is_colimit : is_colimit (cokernel_cofork.of_π f w))
section
local attribute [instance] fully_faithful_reflects_colimits
local attribute [instance] equivalence.ess_surj_of_equivalence
/-- If `F` is an equivalence and `F.map f` is a normal epi, then `f` is a normal epi. -/
def equivalence_reflects_normal_epi {D : Type u₂} [category.{v₁} D] [has_zero_morphisms D]
(F : C ⥤ D) [is_equivalence F] {X Y : C} {f : X ⟶ Y} (hf : normal_epi (F.map f)) :
normal_epi f :=
{ W := F.obj_preimage hf.W,
g := full.preimage ((F.obj_obj_preimage_iso hf.W).hom ≫ hf.g),
w := faithful.map_injective F $ by simp [hf.w],
is_colimit := reflects_colimit.reflects $
is_colimit.of_cocone_equiv (cocones.precompose_equivalence (comp_nat_iso F).symm) $
is_colimit.of_iso_colimit
(by exact is_colimit.of_iso_colimit
(is_cokernel.of_iso_comp _ _ (F.obj_obj_preimage_iso hf.W).symm (by simp) hf.is_colimit)
(of_π_congr (category.id_comp _).symm))
(iso_of_π _).symm }
end
/-- Every normal epimorphism is a regular epimorphism. -/
@[priority 100]
instance normal_epi.regular_epi (f : X ⟶ Y) [I : normal_epi f] : regular_epi f :=
{ left := I.g,
right := 0,
w := (by simpa using I.w),
..I }
/-- If `f` is a normal epi, then every morphism `k : X ⟶ W` satisfying `normal_epi.g ≫ k = 0`
induces `l : Y ⟶ W` such that `f ≫ l = k`. -/
def normal_epi.desc' {W : C} (f : X ⟶ Y) [normal_epi f] (k : X ⟶ W) (h : normal_epi.g ≫ k = 0) :
{l : Y ⟶ W // f ≫ l = k} :=
cokernel_cofork.is_colimit.desc' (normal_epi.is_colimit) _ h
/--
The second leg of a pushout cocone is a normal epimorphism if the right component is too.
See also `pushout.snd_of_epi` for the basic epimorphism version, and
`normal_of_is_pushout_fst_of_normal` for the flipped version.
-/
def normal_of_is_pushout_snd_of_normal {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S}
[gn : normal_epi g] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :
normal_epi h :=
{ W := gn.W,
g := gn.g ≫ f,
w := by rw [category.assoc, comm, reassoc_of gn.w, zero_comp],
is_colimit :=
begin
letI hn := regular_of_is_pushout_snd_of_regular comm t,
have q := (@zero_comp _ _ _ gn.W _ _ f).symm,
convert hn.is_colimit,
dunfold cokernel_cofork.of_π cofork.of_π,
congr, exact q, exact q, exact q, apply proof_irrel_heq,
end }
/--
The first leg of a pushout cocone is a normal epimorphism if the left component is too.
See also `pushout.fst_of_epi` for the basic epimorphism version, and
`normal_of_is_pushout_snd_of_normal` for the flipped version.
-/
def normal_of_is_pushout_fst_of_normal {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S}
[hn : normal_epi f] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :
normal_epi k :=
normal_of_is_pushout_snd_of_normal comm.symm (pushout_cocone.flip_is_colimit t)
end
end category_theory
|
08af6dc45a1847b56c39e2ea887239c76bbc7d4a | 4727251e0cd73359b15b664c3170e5d754078599 | /src/set_theory/cardinal/ordinal.lean | 01e94fa0c6b252d4d51c98826d8d2b37df14db15 | [
"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 | 42,104 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Floris van Doorn
-/
import order.bounded
import set_theory.ordinal.principal
import tactic.linarith
/-!
# Cardinals and ordinals
Relationships between cardinals and ordinals, properties of cardinals that are proved
using ordinals.
## Main definitions
* The function `cardinal.aleph'` gives the cardinals listed by their ordinal
index, and is the inverse of `cardinal.aleph_idx`.
`aleph' n = n`, `aleph' ω = cardinal.omega = ℵ₀`, `aleph' (ω + 1) = ℵ₁`, etc.
It is an order isomorphism between ordinals and cardinals.
* The function `cardinal.aleph` gives the infinite cardinals listed by their
ordinal index. `aleph 0 = cardinal.omega = ℵ₀`, `aleph 1 = ℵ₁` is the first
uncountable cardinal, and so on.
## Main Statements
* `cardinal.mul_eq_max` and `cardinal.add_eq_max` state that the product (resp. sum) of two infinite
cardinals is just their maximum. Several variations around this fact are also given.
* `cardinal.mk_list_eq_mk` : when `α` is infinite, `α` and `list α` have the same cardinality.
* simp lemmas for inequalities between `bit0 a` and `bit1 b` are registered, making `simp`
able to prove inequalities about numeral cardinals.
## Tags
cardinal arithmetic (for infinite cardinals)
-/
noncomputable theory
open function cardinal set equiv
open_locale classical cardinal
universes u v w
namespace cardinal
section using_ordinals
open ordinal
theorem ord_is_limit {c} (co : ω ≤ c) : (ord c).is_limit :=
begin
refine ⟨λ h, omega_ne_zero _, λ a, lt_imp_lt_of_le_imp_le _⟩,
{ rw [← ordinal.le_zero, ord_le] at h,
simpa only [card_zero, nonpos_iff_eq_zero] using le_trans co h },
{ intro h, rw [ord_le] at h ⊢,
rwa [← @add_one_of_omega_le (card a), ← card_succ],
rw [← ord_le, ← le_succ_of_is_limit, ord_le],
{ exact le_trans co h },
{ rw ord_omega, exact omega_is_limit } }
end
/-- The `aleph'` index function, which gives the ordinal index of a cardinal.
(The `aleph'` part is because unlike `aleph` this counts also the
finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`,
`aleph_idx ℵ₁ = ω + 1` and so on.)
In this definition, we register additionally that this function is an initial segment,
i.e., it is order preserving and its range is an initial segment of the ordinals.
For the basic function version, see `aleph_idx`.
For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/
def aleph_idx.initial_seg : @initial_seg cardinal ordinal (<) (<) :=
@rel_embedding.collapse cardinal ordinal (<) (<) _ cardinal.ord.order_embedding.lt_embedding
/-- The `aleph'` index function, which gives the ordinal index of a cardinal.
(The `aleph'` part is because unlike `aleph` this counts also the
finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`,
`aleph_idx ℵ₁ = ω + 1` and so on.)
For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/
def aleph_idx : cardinal → ordinal := aleph_idx.initial_seg
@[simp] theorem aleph_idx.initial_seg_coe :
(aleph_idx.initial_seg : cardinal → ordinal) = aleph_idx := rfl
@[simp] theorem aleph_idx_lt {a b} : aleph_idx a < aleph_idx b ↔ a < b :=
aleph_idx.initial_seg.to_rel_embedding.map_rel_iff
@[simp] theorem aleph_idx_le {a b} : aleph_idx a ≤ aleph_idx b ↔ a ≤ b :=
by rw [← not_lt, ← not_lt, aleph_idx_lt]
theorem aleph_idx.init {a b} : b < aleph_idx a → ∃ c, aleph_idx c = b :=
aleph_idx.initial_seg.init _ _
/-- The `aleph'` index function, which gives the ordinal index of a cardinal.
(The `aleph'` part is because unlike `aleph` this counts also the
finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`,
`aleph_idx ℵ₁ = ω + 1` and so on.)
In this version, we register additionally that this function is an order isomorphism
between cardinals and ordinals.
For the basic function version, see `aleph_idx`. -/
def aleph_idx.rel_iso : @rel_iso cardinal.{u} ordinal.{u} (<) (<) :=
@rel_iso.of_surjective cardinal.{u} ordinal.{u} (<) (<) aleph_idx.initial_seg.{u} $
(initial_seg.eq_or_principal aleph_idx.initial_seg.{u}).resolve_right $
λ ⟨o, e⟩, begin
have : ∀ c, aleph_idx c < o := λ c, (e _).2 ⟨_, rfl⟩,
refine ordinal.induction_on o _ this, introsI α r _ h,
let s := sup.{u u} (λ a:α, inv_fun aleph_idx (ordinal.typein r a)),
apply not_le_of_gt (lt_succ_self s),
have I : injective aleph_idx := aleph_idx.initial_seg.to_embedding.injective,
simpa only [typein_enum, left_inverse_inv_fun I (succ s)] using
le_sup.{u u} (λ a, inv_fun aleph_idx (ordinal.typein r a))
(ordinal.enum r _ (h (succ s))),
end
@[simp] theorem aleph_idx.rel_iso_coe :
(aleph_idx.rel_iso : cardinal → ordinal) = aleph_idx := rfl
@[simp] theorem type_cardinal : @ordinal.type cardinal (<) _ = ordinal.univ.{u (u+1)} :=
by rw ordinal.univ_id; exact quotient.sound ⟨aleph_idx.rel_iso⟩
@[simp] theorem mk_cardinal : #cardinal = univ.{u (u+1)} :=
by simpa only [card_type, card_univ] using congr_arg card type_cardinal
/-- The `aleph'` function gives the cardinals listed by their ordinal
index, and is the inverse of `aleph_idx`.
`aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc.
In this version, we register additionally that this function is an order isomorphism
between ordinals and cardinals.
For the basic function version, see `aleph'`. -/
def aleph'.rel_iso := cardinal.aleph_idx.rel_iso.symm
/-- The `aleph'` function gives the cardinals listed by their ordinal
index, and is the inverse of `aleph_idx`.
`aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. -/
def aleph' : ordinal → cardinal := aleph'.rel_iso
@[simp] theorem aleph'.rel_iso_coe :
(aleph'.rel_iso : ordinal → cardinal) = aleph' := rfl
@[simp] theorem aleph'_lt {o₁ o₂ : ordinal.{u}} : aleph' o₁ < aleph' o₂ ↔ o₁ < o₂ :=
aleph'.rel_iso.map_rel_iff
@[simp] theorem aleph'_le {o₁ o₂ : ordinal.{u}} : aleph' o₁ ≤ aleph' o₂ ↔ o₁ ≤ o₂ :=
le_iff_le_iff_lt_iff_lt.2 aleph'_lt
@[simp] theorem aleph'_aleph_idx (c : cardinal.{u}) : aleph' c.aleph_idx = c :=
cardinal.aleph_idx.rel_iso.to_equiv.symm_apply_apply c
@[simp] theorem aleph_idx_aleph' (o : ordinal.{u}) : (aleph' o).aleph_idx = o :=
cardinal.aleph_idx.rel_iso.to_equiv.apply_symm_apply o
@[simp] theorem aleph'_zero : aleph' 0 = 0 :=
by rw [← nonpos_iff_eq_zero, ← aleph'_aleph_idx 0, aleph'_le];
apply ordinal.zero_le
@[simp] theorem aleph'_succ {o : ordinal.{u}} : aleph' o.succ = (aleph' o).succ :=
le_antisymm
(cardinal.aleph_idx_le.1 $
by rw [aleph_idx_aleph', ordinal.succ_le, ← aleph'_lt, aleph'_aleph_idx];
apply cardinal.lt_succ_self)
(cardinal.succ_le.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _)
@[simp] theorem aleph'_nat : ∀ n : ℕ, aleph' n = n
| 0 := aleph'_zero
| (n+1) := show aleph' (ordinal.succ n) = n.succ,
by rw [aleph'_succ, aleph'_nat, nat_succ]
theorem aleph'_le_of_limit {o : ordinal.{u}} (l : o.is_limit) {c} :
aleph' o ≤ c ↔ ∀ o' < o, aleph' o' ≤ c :=
⟨λ h o' h', le_trans (aleph'_le.2 $ le_of_lt h') h,
λ h, begin
rw [← aleph'_aleph_idx c, aleph'_le, ordinal.limit_le l],
intros x h',
rw [← aleph'_le, aleph'_aleph_idx],
exact h _ h'
end⟩
@[simp] theorem aleph'_omega : aleph' ordinal.omega = ω :=
eq_of_forall_ge_iff $ λ c, begin
simp only [aleph'_le_of_limit omega_is_limit, ordinal.lt_omega, exists_imp_distrib, omega_le],
exact forall_swap.trans (forall_congr $ λ n, by simp only [forall_eq, aleph'_nat]),
end
/-- `aleph'` and `aleph_idx` form an equivalence between `ordinal` and `cardinal` -/
@[simp] def aleph'_equiv : ordinal ≃ cardinal :=
⟨aleph', aleph_idx, aleph_idx_aleph', aleph'_aleph_idx⟩
/-- The `aleph` function gives the infinite cardinals listed by their
ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first
uncountable cardinal, and so on. -/
def aleph (o : ordinal) : cardinal := aleph' (ordinal.omega + o)
@[simp] theorem aleph_lt {o₁ o₂ : ordinal.{u}} : aleph o₁ < aleph o₂ ↔ o₁ < o₂ :=
aleph'_lt.trans (add_lt_add_iff_left _)
@[simp] theorem aleph_le {o₁ o₂ : ordinal.{u}} : aleph o₁ ≤ aleph o₂ ↔ o₁ ≤ o₂ :=
le_iff_le_iff_lt_iff_lt.2 aleph_lt
@[simp] theorem max_aleph_eq (o₁ o₂ : ordinal) : max (aleph o₁) (aleph o₂) = aleph (max o₁ o₂) :=
begin
cases le_total (aleph o₁) (aleph o₂) with h h,
{ rw [max_eq_right h, max_eq_right (aleph_le.1 h)] },
{ rw [max_eq_left h, max_eq_left (aleph_le.1 h)] }
end
@[simp] theorem aleph_succ {o : ordinal.{u}} : aleph o.succ = (aleph o).succ :=
by rw [aleph, ordinal.add_succ, aleph'_succ]; refl
@[simp] theorem aleph_zero : aleph 0 = ω :=
by simp only [aleph, add_zero, aleph'_omega]
theorem omega_le_aleph' {o : ordinal} : ω ≤ aleph' o ↔ ordinal.omega ≤ o :=
by rw [← aleph'_omega, aleph'_le]
theorem omega_le_aleph (o : ordinal) : ω ≤ aleph o :=
by rw [aleph, omega_le_aleph']; apply ordinal.le_add_right
theorem aleph'_pos {o : ordinal} (ho : 0 < o) : 0 < aleph' o :=
by rwa [←aleph'_zero, aleph'_lt]
theorem aleph_pos (o : ordinal) : 0 < aleph o :=
omega_pos.trans_le (omega_le_aleph o)
instance (o : ordinal) : nonempty (aleph o).ord.out.α :=
begin
rw [out_nonempty_iff_ne_zero, ←ord_zero],
exact λ h, (ord_injective h).not_gt (aleph_pos o)
end
theorem ord_aleph_is_limit (o : ordinal) : is_limit (aleph o).ord :=
ord_is_limit $ omega_le_aleph _
instance (o : ordinal) : no_max_order (aleph o).ord.out.α :=
ordinal.out_no_max_of_succ_lt (ord_aleph_is_limit o).2
theorem exists_aleph {c : cardinal} : ω ≤ c ↔ ∃ o, c = aleph o :=
⟨λ h, ⟨aleph_idx c - ordinal.omega,
by rw [aleph, ordinal.add_sub_cancel_of_le, aleph'_aleph_idx];
rwa [← omega_le_aleph', aleph'_aleph_idx]⟩,
λ ⟨o, e⟩, e.symm ▸ omega_le_aleph _⟩
theorem aleph'_is_normal : is_normal (ord ∘ aleph') :=
⟨λ o, ord_lt_ord.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _,
λ o l a, by simp only [ord_le, aleph'_le_of_limit l]⟩
theorem aleph_is_normal : is_normal (ord ∘ aleph) :=
aleph'_is_normal.trans $ add_is_normal ordinal.omega
theorem succ_omega : succ ω = aleph 1 :=
by rw [← aleph_zero, ← aleph_succ, ordinal.succ_zero]
lemma omega_lt_aleph_one : ω < aleph 1 :=
by { rw ← succ_omega, exact lt_succ_self _ }
lemma countable_iff_lt_aleph_one {α : Type*} (s : set α) : countable s ↔ #s < aleph 1 :=
by rw [← succ_omega, lt_succ, mk_set_le_omega]
/-- Ordinals that are cardinals are unbounded. -/
theorem ord_card_unbounded : unbounded (<) {b : ordinal | b.card.ord = b} :=
unbounded_lt_iff.2 $ λ a, ⟨_, ⟨(by { dsimp, rw card_ord }), (lt_ord_succ_card a).le⟩⟩
theorem eq_aleph'_of_eq_card_ord {o : ordinal} (ho : o.card.ord = o) : ∃ a, (aleph' a).ord = o :=
⟨cardinal.aleph_idx.rel_iso o.card, by simpa using ho⟩
/-- `ord ∘ aleph'` enumerates the ordinals that are cardinals. -/
theorem ord_aleph'_eq_enum_card : ord ∘ aleph' = enum_ord {b : ordinal | b.card.ord = b} :=
begin
rw [←eq_enum_ord _ ord_card_unbounded, range_eq_iff],
exact ⟨aleph'_is_normal.strict_mono, ⟨(λ a, (by { dsimp, rw card_ord })),
λ b hb, eq_aleph'_of_eq_card_ord hb⟩⟩
end
/-- Infinite ordinals that are cardinals are unbounded. -/
theorem ord_card_unbounded' : unbounded (<) {b : ordinal | b.card.ord = b ∧ ordinal.omega ≤ b} :=
(unbounded_lt_inter_le ordinal.omega).2 ord_card_unbounded
theorem eq_aleph_of_eq_card_ord {o : ordinal} (ho : o.card.ord = o) (ho' : ordinal.omega ≤ o) :
∃ a, (aleph a).ord = o :=
begin
cases eq_aleph'_of_eq_card_ord ho with a ha,
use a - ordinal.omega,
unfold aleph,
rwa ordinal.add_sub_cancel_of_le,
rwa [←omega_le_aleph', ←ord_le_ord, ha, ord_omega]
end
/-- `ord ∘ aleph` enumerates the infinite ordinals that are cardinals. -/
theorem ord_aleph_eq_enum_card :
ord ∘ aleph = enum_ord {b : ordinal | b.card.ord = b ∧ ordinal.omega ≤ b} :=
begin
rw ←eq_enum_ord _ ord_card_unbounded',
use aleph_is_normal.strict_mono,
rw range_eq_iff,
refine ⟨(λ a, ⟨_, _⟩), λ b hb, eq_aleph_of_eq_card_ord hb.1 hb.2⟩,
{ rw card_ord },
{ rw [←ord_omega, ord_le_ord],
exact omega_le_aleph _ }
end
/-! ### Properties of `mul` -/
/-- If `α` is an infinite type, then `α × α` and `α` have the same cardinality. -/
theorem mul_eq_self {c : cardinal} (h : ω ≤ c) : c * c = c :=
begin
refine le_antisymm _
(by simpa only [mul_one] using
mul_le_mul_left' (one_lt_omega.le.trans h) c),
-- the only nontrivial part is `c * c ≤ c`. We prove it inductively.
refine acc.rec_on (cardinal.wf.apply c) (λ c _,
quotient.induction_on c $ λ α IH ol, _) h,
-- consider the minimal well-order `r` on `α` (a type with cardinality `c`).
rcases ord_eq α with ⟨r, wo, e⟩, resetI,
letI := linear_order_of_STO' r,
haveI : is_well_order α (<) := wo,
-- Define an order `s` on `α × α` by writing `(a, b) < (c, d)` if `max a b < max c d`, or
-- the max are equal and `a < c`, or the max are equal and `a = c` and `b < d`.
let g : α × α → α := λ p, max p.1 p.2,
let f : α × α ↪ ordinal × (α × α) :=
⟨λ p:α×α, (typein (<) (g p), p), λ p q, congr_arg prod.snd⟩,
let s := f ⁻¹'o (prod.lex (<) (prod.lex (<) (<))),
-- this is a well order on `α × α`.
haveI : is_well_order _ s := (rel_embedding.preimage _ _).is_well_order,
/- it suffices to show that this well order is smaller than `r`
if it were larger, then `r` would be a strict prefix of `s`. It would be contained in
`β × β` for some `β` of cardinality `< c`. By the inductive assumption, this set has the
same cardinality as `β` (or it is finite if `β` is finite), so it is `< c`, which is a
contradiction. -/
suffices : type s ≤ type r, {exact card_le_card this},
refine le_of_forall_lt (λ o h, _),
rcases typein_surj s h with ⟨p, rfl⟩,
rw [← e, lt_ord],
refine lt_of_le_of_lt (_ : _ ≤ card (typein (<) (g p)).succ * card (typein (<) (g p)).succ) _,
{ have : {q | s q p} ⊆ insert (g p) {x | x < g p} ×ˢ insert (g p) {x | x < g p},
{ intros q h,
simp only [s, embedding.coe_fn_mk, order.preimage, typein_lt_typein, prod.lex_def, typein_inj]
at h,
exact max_le_iff.1 (le_iff_lt_or_eq.2 $ h.imp_right and.left) },
suffices H : (insert (g p) {x | r x (g p)} : set α) ≃ ({x | r x (g p)} ⊕ punit),
{ exact ⟨(set.embedding_of_subset _ _ this).trans
((equiv.set.prod _ _).trans (H.prod_congr H)).to_embedding⟩ },
refine (equiv.set.insert _).trans
((equiv.refl _).sum_congr punit_equiv_punit),
apply @irrefl _ r },
cases lt_or_le (card (typein (<) (g p)).succ) ω with qo qo,
{ exact lt_of_lt_of_le (mul_lt_omega qo qo) ol },
{ suffices, {exact lt_of_le_of_lt (IH _ this qo) this},
rw ← lt_ord, apply (ord_is_limit ol).2,
rw [mk_def, e], apply typein_lt_type }
end
end using_ordinals
/-- If `α` and `β` are infinite types, then the cardinality of `α × β` is the maximum
of the cardinalities of `α` and `β`. -/
theorem mul_eq_max {a b : cardinal} (ha : ω ≤ a) (hb : ω ≤ b) : a * b = max a b :=
le_antisymm
(mul_eq_self (le_trans ha (le_max_left a b)) ▸
mul_le_mul' (le_max_left _ _) (le_max_right _ _)) $
max_le
(by simpa only [mul_one] using
mul_le_mul_left' (one_lt_omega.le.trans hb) a)
(by simpa only [one_mul] using
mul_le_mul_right' (one_lt_omega.le.trans ha) b)
@[simp] theorem mul_mk_eq_max {α β : Type*} [infinite α] [infinite β] : #α * #β = max (#α) (#β) :=
mul_eq_max (omega_le_mk α) (omega_le_mk β)
@[simp] theorem aleph_mul_aleph (o₁ o₂ : ordinal) : aleph o₁ * aleph o₂ = aleph (max o₁ o₂) :=
by rw [cardinal.mul_eq_max (omega_le_aleph o₁) (omega_le_aleph o₂), max_aleph_eq]
@[simp] theorem omega_mul_eq {a : cardinal} (ha : ω ≤ a) : ω * a = a :=
(mul_eq_max le_rfl ha).trans (max_eq_right ha)
@[simp] theorem mul_omega_eq {a : cardinal} (ha : ω ≤ a) : a * ω = a :=
(mul_eq_max ha le_rfl).trans (max_eq_left ha)
@[simp] theorem omega_mul_mk_eq {α : Type*} [infinite α] : ω * #α = #α :=
omega_mul_eq (omega_le_mk α)
@[simp] theorem mk_mul_omega_eq {α : Type*} [infinite α] : #α * ω = #α :=
mul_omega_eq (omega_le_mk α)
@[simp] theorem omega_mul_aleph (o : ordinal) : ω * aleph o = aleph o :=
omega_mul_eq (omega_le_aleph o)
@[simp] theorem aleph_mul_omega (o : ordinal) : aleph o * ω = aleph o :=
mul_omega_eq (omega_le_aleph o)
theorem mul_lt_of_lt {a b c : cardinal} (hc : ω ≤ c)
(h1 : a < c) (h2 : b < c) : a * b < c :=
lt_of_le_of_lt (mul_le_mul' (le_max_left a b) (le_max_right a b)) $
(lt_or_le (max a b) ω).elim
(λ h, lt_of_lt_of_le (mul_lt_omega h h) hc)
(λ h, by rw mul_eq_self h; exact max_lt h1 h2)
lemma mul_le_max_of_omega_le_left {a b : cardinal} (h : ω ≤ a) : a * b ≤ max a b :=
begin
convert mul_le_mul' (le_max_left a b) (le_max_right a b),
rw [mul_eq_self],
refine le_trans h (le_max_left a b)
end
lemma mul_eq_max_of_omega_le_left {a b : cardinal} (h : ω ≤ a) (h' : b ≠ 0) : a * b = max a b :=
begin
cases le_or_lt ω b with hb hb, { exact mul_eq_max h hb },
refine (mul_le_max_of_omega_le_left h).antisymm _,
have : b ≤ a, from hb.le.trans h,
rw [max_eq_left this],
convert mul_le_mul_left' (one_le_iff_ne_zero.mpr h') _, rw [mul_one],
end
lemma mul_eq_max' {a b : cardinal} (h : ω ≤ a * b) : a * b = max a b :=
begin
rcases omega_le_mul_iff.mp h with ⟨ha, hb, h⟩,
wlog h : ω ≤ a := h using [a b],
exact mul_eq_max_of_omega_le_left h hb
end
theorem mul_le_max (a b : cardinal) : a * b ≤ max (max a b) ω :=
begin
by_cases ha0 : a = 0,
{ simp [ha0] },
by_cases hb0 : b = 0,
{ simp [hb0] },
by_cases ha : ω ≤ a,
{ rw [mul_eq_max_of_omega_le_left ha hb0],
exact le_max_left _ _ },
{ by_cases hb : ω ≤ b,
{ rw [mul_comm, mul_eq_max_of_omega_le_left hb ha0, max_comm],
exact le_max_left _ _ },
{ exact le_max_of_le_right (le_of_lt (mul_lt_omega (lt_of_not_ge ha) (lt_of_not_ge hb))) } }
end
lemma mul_eq_left {a b : cardinal} (ha : ω ≤ a) (hb : b ≤ a) (hb' : b ≠ 0) : a * b = a :=
by { rw [mul_eq_max_of_omega_le_left ha hb', max_eq_left hb] }
lemma mul_eq_right {a b : cardinal} (hb : ω ≤ b) (ha : a ≤ b) (ha' : a ≠ 0) : a * b = b :=
by { rw [mul_comm, mul_eq_left hb ha ha'] }
lemma le_mul_left {a b : cardinal} (h : b ≠ 0) : a ≤ b * a :=
by { convert mul_le_mul_right' (one_le_iff_ne_zero.mpr h) _,
rw [one_mul] }
lemma le_mul_right {a b : cardinal} (h : b ≠ 0) : a ≤ a * b :=
by { rw [mul_comm], exact le_mul_left h }
lemma mul_eq_left_iff {a b : cardinal} : a * b = a ↔ ((max ω b ≤ a ∧ b ≠ 0) ∨ b = 1 ∨ a = 0) :=
begin
rw [max_le_iff], split,
{ intro h,
cases (le_or_lt ω a) with ha ha,
{ have : a ≠ 0, { rintro rfl, exact not_lt_of_le ha omega_pos },
left, use ha,
{ rw [← not_lt], intro hb, apply ne_of_gt _ h, refine lt_of_lt_of_le hb (le_mul_left this) },
{ rintro rfl, apply this, rw [_root_.mul_zero] at h, subst h }},
right, by_cases h2a : a = 0, { right, exact h2a },
have hb : b ≠ 0, { rintro rfl, apply h2a, rw [mul_zero] at h, subst h },
left, rw [← h, mul_lt_omega_iff, lt_omega, lt_omega] at ha,
rcases ha with rfl|rfl|⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, contradiction, contradiction,
rw [← ne] at h2a, rw [← one_le_iff_ne_zero] at h2a hb, norm_cast at h2a hb h ⊢,
apply le_antisymm _ hb, rw [← not_lt], intro h2b,
apply ne_of_gt _ h, conv_lhs { rw [← mul_one n] },
rwa [mul_lt_mul_left], apply nat.lt_of_succ_le h2a },
{ rintro (⟨⟨ha, hab⟩, hb⟩|rfl|rfl),
{ rw [mul_eq_max_of_omega_le_left ha hb, max_eq_left hab] },
all_goals {simp}}
end
/-! ### Properties of `add` -/
/-- If `α` is an infinite type, then `α ⊕ α` and `α` have the same cardinality. -/
theorem add_eq_self {c : cardinal} (h : ω ≤ c) : c + c = c :=
le_antisymm
(by simpa only [nat.cast_bit0, nat.cast_one, mul_eq_self h, two_mul] using
mul_le_mul_right' ((nat_lt_omega 2).le.trans h) c)
(self_le_add_left c c)
/-- If `α` is an infinite type, then the cardinality of `α ⊕ β` is the maximum
of the cardinalities of `α` and `β`. -/
theorem add_eq_max {a b : cardinal} (ha : ω ≤ a) : a + b = max a b :=
le_antisymm
(add_eq_self (le_trans ha (le_max_left a b)) ▸
add_le_add (le_max_left _ _) (le_max_right _ _)) $
max_le (self_le_add_right _ _) (self_le_add_left _ _)
theorem add_eq_max' {a b : cardinal} (ha : ω ≤ b) : a + b = max a b :=
by rw [add_comm, max_comm, add_eq_max ha]
@[simp] theorem add_mk_eq_max {α β : Type*} [infinite α] : #α + #β = max (#α) (#β) :=
add_eq_max (omega_le_mk α)
@[simp] theorem add_mk_eq_max' {α β : Type*} [infinite β] : #α + #β = max (#α) (#β) :=
add_eq_max' (omega_le_mk β)
theorem add_le_max (a b : cardinal) : a + b ≤ max (max a b) ω :=
begin
by_cases ha : ω ≤ a,
{ rw [add_eq_max ha],
exact le_max_left _ _ },
{ by_cases hb : ω ≤ b,
{ rw [add_comm, add_eq_max hb, max_comm],
exact le_max_left _ _ },
{ exact le_max_of_le_right (le_of_lt (add_lt_omega (lt_of_not_ge ha) (lt_of_not_ge hb))) } }
end
theorem add_le_of_le {a b c : cardinal} (hc : ω ≤ c)
(h1 : a ≤ c) (h2 : b ≤ c) : a + b ≤ c :=
(add_le_add h1 h2).trans $ le_of_eq $ add_eq_self hc
theorem add_lt_of_lt {a b c : cardinal} (hc : ω ≤ c)
(h1 : a < c) (h2 : b < c) : a + b < c :=
lt_of_le_of_lt (add_le_add (le_max_left a b) (le_max_right a b)) $
(lt_or_le (max a b) ω).elim
(λ h, lt_of_lt_of_le (add_lt_omega h h) hc)
(λ h, by rw add_eq_self h; exact max_lt h1 h2)
lemma eq_of_add_eq_of_omega_le {a b c : cardinal} (h : a + b = c) (ha : a < c) (hc : ω ≤ c) :
b = c :=
begin
apply le_antisymm,
{ rw [← h], apply self_le_add_left },
rw[← not_lt], intro hb,
have : a + b < c := add_lt_of_lt hc ha hb,
simpa [h, lt_irrefl] using this
end
lemma add_eq_left {a b : cardinal} (ha : ω ≤ a) (hb : b ≤ a) : a + b = a :=
by { rw [add_eq_max ha, max_eq_left hb] }
lemma add_eq_right {a b : cardinal} (hb : ω ≤ b) (ha : a ≤ b) : a + b = b :=
by { rw [add_comm, add_eq_left hb ha] }
lemma add_eq_left_iff {a b : cardinal} : a + b = a ↔ (max ω b ≤ a ∨ b = 0) :=
begin
rw [max_le_iff], split,
{ intro h, cases (le_or_lt ω a) with ha ha,
{ left, use ha, rw [← not_lt], intro hb, apply ne_of_gt _ h,
exact lt_of_lt_of_le hb (self_le_add_left b a) },
right, rw [← h, add_lt_omega_iff, lt_omega, lt_omega] at ha,
rcases ha with ⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, norm_cast at h ⊢,
rw [← add_right_inj, h, add_zero] },
{ rintro (⟨h1, h2⟩|h3), rw [add_eq_max h1, max_eq_left h2], rw [h3, add_zero] }
end
lemma add_eq_right_iff {a b : cardinal} : a + b = b ↔ (max ω a ≤ b ∨ a = 0) :=
by { rw [add_comm, add_eq_left_iff] }
lemma add_one_eq {a : cardinal} (ha : ω ≤ a) : a + 1 = a :=
have 1 ≤ a, from le_trans (le_of_lt one_lt_omega) ha,
add_eq_left ha this
@[simp] lemma mk_add_one_eq {α : Type*} [infinite α] : #α + 1 = #α :=
add_one_eq (omega_le_mk α)
protected lemma eq_of_add_eq_add_left {a b c : cardinal} (h : a + b = a + c) (ha : a < ω) :
b = c :=
begin
cases le_or_lt ω b with hb hb,
{ have : a < b := lt_of_lt_of_le ha hb,
rw [add_eq_right hb (le_of_lt this), eq_comm] at h,
rw [eq_of_add_eq_of_omega_le h this hb] },
{ have hc : c < ω,
{ rw [← not_le], intro hc,
apply lt_irrefl ω, apply lt_of_le_of_lt (le_trans hc (self_le_add_left _ a)),
rw [← h], apply add_lt_omega ha hb },
rw [lt_omega] at *,
rcases ha with ⟨n, rfl⟩, rcases hb with ⟨m, rfl⟩, rcases hc with ⟨k, rfl⟩,
norm_cast at h ⊢, apply add_left_cancel h }
end
protected lemma eq_of_add_eq_add_right {a b c : cardinal} (h : a + b = c + b) (hb : b < ω) :
a = c :=
by { rw [add_comm a b, add_comm c b] at h, exact cardinal.eq_of_add_eq_add_left h hb }
@[simp] theorem aleph_add_aleph (o₁ o₂ : ordinal) : aleph o₁ + aleph o₂ = aleph (max o₁ o₂) :=
by rw [cardinal.add_eq_max (omega_le_aleph o₁), max_aleph_eq]
theorem principal_add_ord {c : cardinal} (hc : ω ≤ c) : ordinal.principal (+) c.ord :=
λ a b ha hb, by { rw [lt_ord, ordinal.card_add] at *, exact add_lt_of_lt hc ha hb }
theorem principal_add_aleph (o : ordinal) : ordinal.principal (+) (aleph o).ord :=
principal_add_ord $ omega_le_aleph o
/-! ### Properties about power -/
theorem pow_le {κ μ : cardinal.{u}} (H1 : ω ≤ κ) (H2 : μ < ω) : κ ^ μ ≤ κ :=
let ⟨n, H3⟩ := lt_omega.1 H2 in
H3.symm ▸ (quotient.induction_on κ (λ α H1, nat.rec_on n
(le_of_lt $ lt_of_lt_of_le (by rw [nat.cast_zero, power_zero];
from one_lt_omega) H1)
(λ n ih, trans_rel_left _
(by { rw [nat.cast_succ, power_add, power_one];
exact mul_le_mul_right' ih _ })
(mul_eq_self H1))) H1)
theorem pow_eq {κ μ : cardinal.{u}} (H1 : ω ≤ κ) (H2 : 1 ≤ μ) (H3 : μ < ω) : κ ^ μ = κ :=
(pow_le H1 H3).antisymm $ self_le_power κ H2
lemma power_self_eq {c : cardinal} (h : ω ≤ c) : c ^ c = 2 ^ c :=
begin
apply le_antisymm,
{ apply le_trans (power_le_power_right $ le_of_lt $ cantor c), rw [← power_mul, mul_eq_self h] },
{ convert power_le_power_right (le_trans (le_of_lt $ nat_lt_omega 2) h), apply nat.cast_two.symm }
end
lemma prod_eq_two_power {ι : Type u} [infinite ι] {c : ι → cardinal.{v}} (h₁ : ∀ i, 2 ≤ c i)
(h₂ : ∀ i, lift.{u} (c i) ≤ lift.{v} (#ι)) :
prod c = 2 ^ lift.{v} (#ι) :=
begin
rw [← lift_id' (prod c), lift_prod, ← lift_two_power],
apply le_antisymm,
{ refine (prod_le_prod _ _ h₂).trans_eq _,
rw [prod_const, lift_lift, ← lift_power, power_self_eq (omega_le_mk ι), lift_umax.{u v}] },
{ rw [← prod_const', lift_prod],
refine prod_le_prod _ _ (λ i, _),
rw [lift_two, ← lift_two.{u v}, lift_le],
exact h₁ i }
end
lemma power_eq_two_power {c₁ c₂ : cardinal} (h₁ : ω ≤ c₁) (h₂ : 2 ≤ c₂) (h₂' : c₂ ≤ c₁) :
c₂ ^ c₁ = 2 ^ c₁ :=
le_antisymm (power_self_eq h₁ ▸ power_le_power_right h₂') (power_le_power_right h₂)
lemma nat_power_eq {c : cardinal.{u}} (h : ω ≤ c) {n : ℕ} (hn : 2 ≤ n) :
(n : cardinal.{u}) ^ c = 2 ^ c :=
power_eq_two_power h (by assumption_mod_cast) ((nat_lt_omega n).le.trans h)
lemma power_nat_le {c : cardinal.{u}} {n : ℕ} (h : ω ≤ c) : c ^ n ≤ c :=
pow_le h (nat_lt_omega n)
lemma power_nat_eq {c : cardinal.{u}} {n : ℕ} (h1 : ω ≤ c) (h2 : 1 ≤ n) : c ^ n = c :=
pow_eq h1 (by exact_mod_cast h2) (nat_lt_omega n)
lemma power_nat_le_max {c : cardinal.{u}} {n : ℕ} : c ^ (n : cardinal.{u}) ≤ max c ω :=
begin
by_cases hc : ω ≤ c,
{ exact le_max_of_le_left (power_nat_le hc) },
{ exact le_max_of_le_right (le_of_lt (power_lt_omega (lt_of_not_ge hc) (nat_lt_omega _))) }
end
@[simp] lemma powerlt_omega {c : cardinal} (h : ω ≤ c) : c ^< ω = c :=
begin
apply le_antisymm,
{ rw [powerlt_le], intro c', rw [lt_omega], rintro ⟨n, rfl⟩, apply power_nat_le h },
convert le_powerlt one_lt_omega, rw [power_one]
end
lemma powerlt_omega_le (c : cardinal) : c ^< ω ≤ max c ω :=
begin
cases le_or_lt ω c,
{ rw [powerlt_omega h], apply le_max_left },
rw [powerlt_le], intros c' hc',
refine le_trans (le_of_lt $ power_lt_omega h hc') (le_max_right _ _)
end
/-! ### Computing cardinality of various types -/
theorem mk_list_eq_mk (α : Type u) [infinite α] : #(list α) = #α :=
have H1 : ω ≤ #α := omega_le_mk α,
eq.symm $ le_antisymm ⟨⟨λ x, [x], λ x y H, (list.cons.inj H).1⟩⟩ $
calc #(list α)
= sum (λ n : ℕ, #α ^ (n : cardinal.{u})) : mk_list_eq_sum_pow α
... ≤ sum (λ n : ℕ, #α) : sum_le_sum _ _ $ λ n, pow_le H1 $ nat_lt_omega n
... = #α : by simp [H1]
theorem mk_list_eq_omega (α : Type u) [encodable α] [nonempty α] : #(list α) = ω :=
mk_le_omega.antisymm (omega_le_mk _)
theorem mk_list_eq_max_mk_omega (α : Type u) [nonempty α] : #(list α) = max (#α) ω :=
begin
casesI fintype_or_infinite α,
{ haveI : encodable α := fintype.to_encodable α,
rw [mk_list_eq_omega, eq_comm, max_eq_right],
exact mk_le_omega },
{ rw [mk_list_eq_mk, eq_comm, max_eq_left],
exact omega_le_mk α }
end
theorem mk_list_le_max (α : Type u) : #(list α) ≤ max ω (#α) :=
begin
casesI fintype_or_infinite α,
{ haveI := fintype.to_encodable α,
exact mk_le_omega.trans (le_max_left _ _) },
{ rw mk_list_eq_mk,
apply le_max_right }
end
theorem mk_finset_eq_mk (α : Type u) [infinite α] : #(finset α) = #α :=
eq.symm $ le_antisymm (mk_le_of_injective (λ x y, finset.singleton_inj.1)) $
calc #(finset α) ≤ #(list α) : mk_le_of_surjective list.to_finset_surjective
... = #α : mk_list_eq_mk α
lemma mk_bounded_set_le_of_infinite (α : Type u) [infinite α] (c : cardinal) :
#{t : set α // mk t ≤ c} ≤ #α ^ c :=
begin
refine le_trans _ (by rw [←add_one_eq (omega_le_mk α)]),
induction c using cardinal.induction_on with β,
fapply mk_le_of_surjective,
{ intro f, use sum.inl ⁻¹' range f,
refine le_trans (mk_preimage_of_injective _ _ (λ x y, sum.inl.inj)) _,
apply mk_range_le },
rintro ⟨s, ⟨g⟩⟩,
use λ y, if h : ∃(x : s), g x = y then sum.inl (classical.some h).val else sum.inr ⟨⟩,
apply subtype.eq, ext,
split,
{ rintro ⟨y, h⟩, dsimp only at h, by_cases h' : ∃ (z : s), g z = y,
{ rw [dif_pos h'] at h, cases sum.inl.inj h, exact (classical.some h').2 },
{ rw [dif_neg h'] at h, cases h }},
{ intro h, have : ∃(z : s), g z = g ⟨x, h⟩, exact ⟨⟨x, h⟩, rfl⟩,
use g ⟨x, h⟩, dsimp only, rw [dif_pos this], congr',
suffices : classical.some this = ⟨x, h⟩, exact congr_arg subtype.val this,
apply g.2, exact classical.some_spec this }
end
lemma mk_bounded_set_le (α : Type u) (c : cardinal) :
#{t : set α // #t ≤ c} ≤ max (#α) ω ^ c :=
begin
transitivity #{t : set (ulift.{u} ℕ ⊕ α) // #t ≤ c},
{ refine ⟨embedding.subtype_map _ _⟩, apply embedding.image,
use sum.inr, apply sum.inr.inj, intros s hs, exact le_trans mk_image_le hs },
refine le_trans
(mk_bounded_set_le_of_infinite (ulift.{u} ℕ ⊕ α) c) _,
rw [max_comm, ←add_eq_max]; refl
end
lemma mk_bounded_subset_le {α : Type u} (s : set α) (c : cardinal.{u}) :
#{t : set α // t ⊆ s ∧ #t ≤ c} ≤ max (#s) ω ^ c :=
begin
refine le_trans _ (mk_bounded_set_le s c),
refine ⟨embedding.cod_restrict _ _ _⟩,
use λ t, coe ⁻¹' t.1,
{ rintros ⟨t, ht1, ht2⟩ ⟨t', h1t', h2t'⟩ h, apply subtype.eq, dsimp only at h ⊢,
refine (preimage_eq_preimage' _ _).1 h; rw [subtype.range_coe]; assumption },
rintro ⟨t, h1t, h2t⟩, exact le_trans (mk_preimage_of_injective _ _ subtype.val_injective) h2t
end
/-! ### Properties of `compl` -/
lemma mk_compl_of_infinite {α : Type*} [infinite α] (s : set α) (h2 : #s < #α) :
#(sᶜ : set α) = #α :=
by { refine eq_of_add_eq_of_omega_le _ h2 (omega_le_mk α), exact mk_sum_compl s }
lemma mk_compl_finset_of_infinite {α : Type*} [infinite α] (s : finset α) :
#((↑s)ᶜ : set α) = #α :=
by { apply mk_compl_of_infinite, exact (finset_card_lt_omega s).trans_le (omega_le_mk α) }
lemma mk_compl_eq_mk_compl_infinite {α : Type*} [infinite α] {s t : set α} (hs : #s < #α)
(ht : #t < #α) : #(sᶜ : set α) = #(tᶜ : set α) :=
by { rw [mk_compl_of_infinite s hs, mk_compl_of_infinite t ht] }
lemma mk_compl_eq_mk_compl_finite_lift {α : Type u} {β : Type v} [fintype α]
{s : set α} {t : set β} (h1 : lift.{(max v w)} (#α) = lift.{(max u w)} (#β))
(h2 : lift.{(max v w)} (#s) = lift.{(max u w)} (#t)) :
lift.{(max v w)} (#(sᶜ : set α)) = lift.{(max u w)} (#(tᶜ : set β)) :=
begin
rcases lift_mk_eq.1 h1 with ⟨e⟩, letI : fintype β := fintype.of_equiv α e,
replace h1 : fintype.card α = fintype.card β := (fintype.of_equiv_card _).symm,
classical,
lift s to finset α using finite.of_fintype s,
lift t to finset β using finite.of_fintype t,
simp only [finset.coe_sort_coe, mk_finset, lift_nat_cast, nat.cast_inj] at h2,
simp only [← finset.coe_compl, finset.coe_sort_coe, mk_finset, finset.card_compl,
lift_nat_cast, nat.cast_inj, h1, h2]
end
lemma mk_compl_eq_mk_compl_finite {α β : Type u} [fintype α] {s : set α} {t : set β}
(h1 : #α = #β) (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set β) :=
by { rw ← lift_inj, apply mk_compl_eq_mk_compl_finite_lift; rwa [lift_inj] }
lemma mk_compl_eq_mk_compl_finite_same {α : Type*} [fintype α] {s t : set α}
(h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set α) :=
mk_compl_eq_mk_compl_finite rfl h
/-! ### Extending an injection to an equiv -/
theorem extend_function {α β : Type*} {s : set α} (f : s ↪ β)
(h : nonempty ((sᶜ : set α) ≃ ((range f)ᶜ : set β))) :
∃ (g : α ≃ β), ∀ x : s, g x = f x :=
begin
intros, have := h, cases this with g,
let h : α ≃ β := (set.sum_compl (s : set α)).symm.trans
((sum_congr (equiv.of_injective f f.2) g).trans
(set.sum_compl (range f))),
refine ⟨h, _⟩, rintro ⟨x, hx⟩, simp [set.sum_compl_symm_apply_of_mem, hx]
end
theorem extend_function_finite {α β : Type*} [fintype α] {s : set α} (f : s ↪ β)
(h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x :=
begin
apply extend_function f,
cases id h with g,
rw [← lift_mk_eq] at h,
rw [←lift_mk_eq, mk_compl_eq_mk_compl_finite_lift h],
rw [mk_range_eq_lift], exact f.2
end
theorem extend_function_of_lt {α β : Type*} {s : set α} (f : s ↪ β) (hs : #s < #α)
(h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x :=
begin
casesI fintype_or_infinite α,
{ exact extend_function_finite f h },
{ apply extend_function f, cases id h with g, haveI := infinite.of_injective _ g.injective,
rw [← lift_mk_eq'] at h ⊢,
rwa [mk_compl_of_infinite s hs, mk_compl_of_infinite],
rwa [← lift_lt, mk_range_eq_of_injective f.injective, ← h, lift_lt] },
end
section bit
/-!
This section proves inequalities for `bit0` and `bit1`, enabling `simp` to solve inequalities
for numeral cardinals. The complexity of the resulting algorithm is not good, as in some cases
`simp` reduces an inequality to a disjunction of two situations, depending on whether a cardinal
is finite or infinite. Since the evaluation of the branches is not lazy, this is bad. It is good
enough for practical situations, though.
For specific numbers, these inequalities could also be deduced from the corresponding
inequalities of natural numbers using `norm_cast`:
```
example : (37 : cardinal) < 42 :=
by { norm_cast, norm_num }
```
-/
lemma bit0_ne_zero (a : cardinal) : ¬bit0 a = 0 ↔ ¬a = 0 :=
by simp [bit0]
@[simp] lemma bit1_ne_zero (a : cardinal) : ¬bit1 a = 0 :=
by simp [bit1]
@[simp] lemma zero_lt_bit0 (a : cardinal) : 0 < bit0 a ↔ 0 < a :=
by { rw ←not_iff_not, simp [bit0], }
@[simp] lemma zero_lt_bit1 (a : cardinal) : 0 < bit1 a :=
lt_of_lt_of_le zero_lt_one (self_le_add_left _ _)
@[simp] lemma one_le_bit0 (a : cardinal) : 1 ≤ bit0 a ↔ 0 < a :=
⟨λ h, (zero_lt_bit0 a).mp (lt_of_lt_of_le zero_lt_one h),
λ h, le_trans (one_le_iff_pos.mpr h) (self_le_add_left a a)⟩
@[simp] lemma one_le_bit1 (a : cardinal) : 1 ≤ bit1 a :=
self_le_add_left _ _
theorem bit0_eq_self {c : cardinal} (h : ω ≤ c) : bit0 c = c :=
add_eq_self h
@[simp] theorem bit0_lt_omega {c : cardinal} : bit0 c < ω ↔ c < ω :=
by simp [bit0, add_lt_omega_iff]
@[simp] theorem omega_le_bit0 {c : cardinal} : ω ≤ bit0 c ↔ ω ≤ c :=
by { rw ← not_iff_not, simp }
@[simp] theorem bit1_eq_self_iff {c : cardinal} : bit1 c = c ↔ ω ≤ c :=
begin
by_cases h : ω ≤ c,
{ simp only [bit1, bit0_eq_self h, h, eq_self_iff_true, add_one_of_omega_le] },
{ refine iff_of_false (ne_of_gt _) h,
rcases lt_omega.1 (not_le.1 h) with ⟨n, rfl⟩,
norm_cast,
dsimp [bit1, bit0],
linarith }
end
@[simp] theorem bit1_lt_omega {c : cardinal} : bit1 c < ω ↔ c < ω :=
by simp [bit1, bit0, add_lt_omega_iff, one_lt_omega]
@[simp] theorem omega_le_bit1 {c : cardinal} : ω ≤ bit1 c ↔ ω ≤ c :=
by { rw ← not_iff_not, simp }
@[simp] lemma bit0_le_bit0 {a b : cardinal} : bit0 a ≤ bit0 b ↔ a ≤ b :=
begin
cases le_or_lt ω a with ha ha; cases le_or_lt ω b with hb hb,
{ rw [bit0_eq_self ha, bit0_eq_self hb] },
{ rw bit0_eq_self ha,
refine iff_of_false (λ h, _) (not_le_of_lt (hb.trans_le ha)),
have A : bit0 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) },
{ rw [bit0_eq_self hb],
exact iff_of_true ((bit0_lt_omega.2 ha).le.trans hb) (ha.le.trans hb) },
{ rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
exact bit0_le_bit0 }
end
@[simp] lemma bit0_le_bit1 {a b : cardinal} : bit0 a ≤ bit1 b ↔ a ≤ b :=
begin
cases le_or_lt ω a with ha ha; cases le_or_lt ω b with hb hb,
{ rw [bit0_eq_self ha, bit1_eq_self_iff.2 hb], },
{ rw bit0_eq_self ha,
refine iff_of_false (λ h, _) (not_le_of_lt (hb.trans_le ha)),
have A : bit1 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) },
{ rw [bit1_eq_self_iff.2 hb],
exact iff_of_true ((bit0_lt_omega.2 ha).le.trans hb) (ha.le.trans hb) },
{ rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
exact nat.bit0_le_bit1_iff }
end
@[simp] lemma bit1_le_bit1 {a b : cardinal} : bit1 a ≤ bit1 b ↔ a ≤ b :=
begin
split,
{ assume h,
apply bit0_le_bit1.1 (le_trans (self_le_add_right (bit0 a) 1) h) },
{ assume h,
calc a + a + 1 ≤ a + b + 1 : add_le_add_right (add_le_add_left h a) 1
... ≤ b + b + 1 : add_le_add_right (add_le_add_right h b) 1 }
end
@[simp] lemma bit1_le_bit0 {a b : cardinal} : bit1 a ≤ bit0 b ↔ (a < b ∨ (a ≤ b ∧ ω ≤ a)) :=
begin
cases le_or_lt ω a with ha ha; cases le_or_lt ω b with hb hb,
{ simp only [bit1_eq_self_iff.mpr ha, bit0_eq_self hb, ha, and_true],
refine ⟨λ h, or.inr h, λ h, _⟩,
cases h,
{ exact le_of_lt h },
{ exact h } },
{ rw bit1_eq_self_iff.2 ha,
refine iff_of_false (λ h, _) (λ h, _),
{ have A : bit0 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) },
{ exact not_le_of_lt (hb.trans_le ha) (h.elim le_of_lt and.left) } },
{ rw [bit0_eq_self hb],
exact iff_of_true ((bit1_lt_omega.2 ha).le.trans hb) (or.inl $ ha.trans_le hb) },
{ rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
simp [not_le.mpr ha], }
end
@[simp] lemma bit0_lt_bit0 {a b : cardinal} : bit0 a < bit0 b ↔ a < b :=
begin
cases le_or_lt ω a with ha ha; cases le_or_lt ω b with hb hb,
{ rw [bit0_eq_self ha, bit0_eq_self hb] },
{ rw bit0_eq_self ha,
refine iff_of_false (λ h, _) (not_lt_of_le (hb.le.trans ha)),
have A : bit0 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) },
{ rw [bit0_eq_self hb],
exact iff_of_true ((bit0_lt_omega.2 ha).trans_le hb) (ha.trans_le hb) },
{ rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
exact bit0_lt_bit0 }
end
@[simp] lemma bit1_lt_bit0 {a b : cardinal} : bit1 a < bit0 b ↔ a < b :=
begin
cases le_or_lt ω a with ha ha; cases le_or_lt ω b with hb hb,
{ rw [bit1_eq_self_iff.2 ha, bit0_eq_self hb], },
{ rw bit1_eq_self_iff.2 ha,
refine iff_of_false (λ h, _) (not_lt_of_le (hb.le.trans ha)),
have A : bit0 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) },
{ rw [bit0_eq_self hb],
exact iff_of_true ((bit1_lt_omega.2 ha).trans_le hb) (ha.trans_le hb) },
{ rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
exact nat.bit1_lt_bit0_iff }
end
@[simp] lemma bit1_lt_bit1 {a b : cardinal} : bit1 a < bit1 b ↔ a < b :=
begin
cases le_or_lt ω a with ha ha; cases le_or_lt ω b with hb hb,
{ rw [bit1_eq_self_iff.2 ha, bit1_eq_self_iff.2 hb], },
{ rw bit1_eq_self_iff.2 ha,
refine iff_of_false (λ h, _) (not_lt_of_le (hb.le.trans ha)),
have A : bit1 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) },
{ rw [bit1_eq_self_iff.2 hb],
exact iff_of_true ((bit1_lt_omega.2 ha).trans_le hb) (ha.trans_le hb) },
{ rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
exact bit1_lt_bit1 }
end
@[simp] lemma bit0_lt_bit1 {a b : cardinal} : bit0 a < bit1 b ↔ (a < b ∨ (a ≤ b ∧ a < ω)) :=
begin
cases le_or_lt ω a with ha ha; cases le_or_lt ω b with hb hb,
{ simp [bit0_eq_self ha, bit1_eq_self_iff.2 hb, not_lt.mpr ha] },
{ rw bit0_eq_self ha,
refine iff_of_false (λ h, _) (λ h, _),
{ have A : bit1 b < ω, by simpa using hb,
exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) },
{ exact not_le_of_lt (hb.trans_le ha) (h.elim le_of_lt and.left) } },
{ rw [bit1_eq_self_iff.2 hb],
exact iff_of_true ((bit0_lt_omega.2 ha).trans_le hb) (or.inl $ ha.trans_le hb) },
{ rcases lt_omega.1 ha with ⟨m, rfl⟩,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
norm_cast,
simp only [ha, and_true, nat.bit0_lt_bit1_iff, or_iff_right_of_imp le_of_lt] }
end
lemma one_lt_two : (1 : cardinal) < 2 :=
-- This strategy works generally to prove inequalities between numerals in `cardinality`.
by { norm_cast, norm_num }
@[simp] lemma one_lt_bit0 {a : cardinal} : 1 < bit0 a ↔ 0 < a :=
by simp [← bit1_zero]
@[simp] lemma one_lt_bit1 (a : cardinal) : 1 < bit1 a ↔ 0 < a :=
by simp [← bit1_zero]
@[simp] lemma one_le_one : (1 : cardinal) ≤ 1 :=
le_rfl
end bit
end cardinal
|
3a329c180bafbc2f79232bd7714a9ea42736efad | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/group_theory/congruence.lean | 436675123c05fb0003d6ae21870275215687e287 | [
"Apache-2.0"
] | permissive | eric-wieser/mathlib | 42842584f584359bbe1fc8b88b3ff937c8acd72d | d0df6b81cd0920ad569158c06a3fd5abb9e63301 | refs/heads/master | 1,669,546,404,255 | 1,595,254,668,000 | 1,595,254,668,000 | 281,173,504 | 0 | 0 | Apache-2.0 | 1,595,263,582,000 | 1,595,263,581,000 | null | UTF-8 | Lean | false | false | 42,785 | lean | /-
Copyright (c) 2019 Amelia Livingston. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Amelia Livingston
-/
import data.setoid.basic
import algebra.pi_instances
/-!
# Congruence relations
This file defines congruence relations: equivalence relations that preserve a binary operation,
which in this case is multiplication or addition. The principal definition is a `structure`
extending a `setoid` (an equivalence relation), and the inductive definition of the smallest
congruence relation containing a binary relation is also given (see `con_gen`).
The file also proves basic properties of the quotient of a type by a congruence relation, and the
complete lattice of congruence relations on a type. We then establish an order-preserving bijection
between the set of congruence relations containing a congruence relation `c` and the set of
congruence relations on the quotient by `c`.
The second half of the file concerns congruence relations on monoids, in which case the
quotient by the congruence relation is also a monoid. There are results about the universal
property of quotients of monoids, and the isomorphism theorems for monoids.
## Implementation notes
The inductive definition of a congruence relation could be a nested inductive type, defined using
the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work.
A nested inductive definition could conceivably shorten proofs, because they would allow invocation
of the corresponding lemmas about `eqv_gen`.
The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]`
respectively as these tags do not work on a structure coerced to a binary relation.
There is a coercion from elements of a type to the element's equivalence class under a
congruence relation.
A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which
membership is an equivalence relation, but whilst this fact is established in the file, it is not
used, since this perspective adds more layers of definitional unfolding.
## Tags
congruence, congruence relation, quotient, quotient by congruence relation, monoid,
quotient monoid, isomorphism theorems
-/
variables (M : Type*) {N : Type*} {P : Type*}
set_option old_structure_cmd true
open function setoid
/-- A congruence relation on a type with an addition is an equivalence relation which
preserves addition. -/
structure add_con [has_add M] extends setoid M :=
(add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z))
/-- A congruence relation on a type with a multiplication is an equivalence relation which
preserves multiplication. -/
@[to_additive add_con] structure con [has_mul M] extends setoid M :=
(mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z))
variables {M}
/-- The inductively defined smallest additive congruence relation containing a given binary
relation. -/
inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop
| of : Π x y, r x y → add_con_gen.rel x y
| refl : Π x, add_con_gen.rel x x
| symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x
| trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z
| add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z)
/-- The inductively defined smallest multiplicative congruence relation containing a given binary
relation. -/
@[to_additive add_con_gen.rel]
inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop
| of : Π x y, r x y → con_gen.rel x y
| refl : Π x, con_gen.rel x x
| symm : Π x y, con_gen.rel x y → con_gen.rel y x
| trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z
| mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z)
/-- The inductively defined smallest multiplicative congruence relation containing a given binary
relation. -/
@[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing
a given binary relation."]
def con_gen [has_mul M] (r : M → M → Prop) : con M :=
⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩
namespace con
section
variables [has_mul M] [has_mul N] [has_mul P] (c : con M)
@[to_additive]
instance : inhabited (con M) :=
⟨con_gen empty_relation⟩
/-- A coercion from a congruence relation to its underlying binary relation. -/
@[to_additive "A coercion from an additive congruence relation to its underlying binary relation."]
instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩
@[simp, to_additive] lemma rel_eq_coe (c : con M) : c.r = c := rfl
/-- Congruence relations are reflexive. -/
@[to_additive "Additive congruence relations are reflexive."]
protected lemma refl (x) : c x x := c.2.1 x
/-- Congruence relations are symmetric. -/
@[to_additive "Additive congruence relations are symmetric."]
protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h
/-- Congruence relations are transitive. -/
@[to_additive "Additive congruence relations are transitive."]
protected lemma trans : ∀ {x y z}, c x y → c y z → c x z :=
λ _ _ _ h, c.2.2.2 h
/-- Multiplicative congruence relations preserve multiplication. -/
@[to_additive "Additive congruence relations preserve addition."]
protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) :=
λ _ _ _ _ h1 h2, c.3 h1 h2
/-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M`
`x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/
@[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation
`c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."]
instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩
variables {c}
/-- The map sending a congruence relation to its underlying binary relation is injective. -/
@[to_additive "The map sending an additive congruence relation to its underlying binary relation
is injective."]
lemma ext' {c d : con M} (H : c.r = d.r) : c = d :=
by cases c; cases d; simpa using H
/-- Extensionality rule for congruence relations. -/
@[ext, to_additive "Extensionality rule for additive congruence relations."]
lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d :=
ext' $ by ext; apply H
attribute [ext] add_con.ext
/-- The map sending a congruence relation to its underlying equivalence relation is injective. -/
@[to_additive "The map sending an additive congruence relation to its underlying equivalence
relation is injective."]
lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d :=
ext $ ext_iff.1 H
/-- Iff version of extensionality rule for congruence relations. -/
@[to_additive "Iff version of extensionality rule for additive congruence relations."]
lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d :=
⟨ext, λ h _ _, h ▸ iff.rfl⟩
/-- Two congruence relations are equal iff their underlying binary relations are equal. -/
@[to_additive "Two additive congruence relations are equal iff their underlying binary relations
are equal."]
lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d :=
⟨ext', λ h, h ▸ rfl⟩
/-- The kernel of a multiplication-preserving function as a congruence relation. -/
@[to_additive "The kernel of an addition-preserving function as an additive congruence relation."]
def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M :=
{ r := λ x y, f x = f y,
iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩,
mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] }
/-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and
`d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁`
by `c` and `x₂` is related to `y₂` by `d`. -/
@[to_additive prod "Given types with additions `M, N`, the product of two congruence relations
`c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁`
is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."]
protected def prod (c : con M) (d : con N) : con (M × N) :=
{ mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid }
/-- The product of an indexed collection of congruence relations. -/
@[to_additive "The product of an indexed collection of additive congruence relations."]
def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)]
(C : Π i, con (f i)) : con (Π i, f i) :=
{ mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid }
variables (c)
@[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl
-- Quotients
/-- Defining the quotient by a congruence relation of a type with a multiplication. -/
@[to_additive "Defining the quotient by an additive congruence relation of a type with
an addition."]
protected def quotient := quotient $ c.to_setoid
/-- Coercion from a type with a multiplication to its quotient by a congruence relation.
See Note [use has_coe_t]. -/
@[to_additive "Coercion from a type with an addition to its quotient by an additive congruence
relation", priority 0]
instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩
/-- The quotient of a type with decidable equality by a congruence relation also has
decidable equality. -/
@[to_additive "The quotient of a type with decidable equality by an additive congruence relation
also has decidable equality."]
instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient :=
@quotient.decidable_eq M c.to_setoid d
/-- The function on the quotient by a congruence relation `c` induced by a function that is
constant on `c`'s equivalence classes. -/
@[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c`
induced by a function that is constant on `c`'s equivalence classes."]
protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β)
(h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h
/-- The binary function on the quotient by a congruence relation `c` induced by a binary function
that is constant on `c`'s equivalence classes. -/
@[elab_as_eliminator, to_additive "The binary function on the quotient by a congruence relation `c`
induced by a binary function that is constant on `c`'s equivalence classes."]
protected def lift_on₂ {β} {c : con M} (q r : c.quotient) (f : M → M → β)
(h : ∀ a₁ a₂ b₁ b₂, c a₁ b₁ → c a₂ b₂ → f a₁ a₂ = f b₁ b₂) : β := quotient.lift_on₂' q r f h
variables {c}
/-- The inductive principle used to prove propositions about the elements of a quotient by a
congruence relation. -/
@[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about
the elements of a quotient by an additive congruence relation."]
protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q :=
quotient.induction_on' q H
/-- A version of `con.induction_on` for predicates which take two arguments. -/
@[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take
two arguments."]
protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop}
(p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q :=
quotient.induction_on₂' p q H
variables (c)
/-- Two elements are related by a congruence relation `c` iff they are represented by the same
element of the quotient by `c`. -/
@[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they
are represented by the same element of the quotient by `c`."]
protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b :=
quotient.eq'
/-- The multiplication induced on the quotient by a congruence relation on a type with a
multiplication. -/
@[to_additive "The addition induced on the quotient by an additive congruence relation on a type
with an addition."]
instance has_mul : has_mul c.quotient :=
⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient))
$ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩
/-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/
@[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation
`c` equals `c`."]
lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c :=
ext $ λ x y, quotient.eq'
variables {c}
/-- The coercion to the quotient of a congruence relation commutes with multiplication (by
definition). -/
@[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with
addition (by definition)."]
lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl
/-- Definition of the function on the quotient by a congruence relation `c` induced by a function
that is constant on `c`'s equivalence classes. -/
@[simp, to_additive "Definition of the function on the quotient by an additive congruence
relation `c` induced by a function that is constant on `c`'s equivalence classes."]
protected lemma lift_on_beta {β} (c : con M) (f : M → β)
(h : ∀ a b, c a b → f a = f b) (x : M) :
con.lift_on (x : c.quotient) f h = f x := rfl
/-- Makes an isomorphism of quotients by two congruence relations, given that the relations are
equal. -/
@[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations,
given that the relations are equal."]
protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient :=
{ map_mul' := λ x y, by rcases x; rcases y; refl,
..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h }
-- The complete lattice of congruence relations on a type
/-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`,
`x` is related to `y` by `d` if `x` is related to `y` by `c`. -/
@[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff
`∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."]
instance : has_le (con M) := ⟨λ c d, ∀ ⦃x y⦄, c x y → d x y⟩
/-- Definition of `≤` for congruence relations. -/
@[to_additive "Definition of `≤` for additive congruence relations."]
theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl
/-- The infimum of a set of congruence relations on a given type with a multiplication. -/
@[to_additive "The infimum of a set of additive congruence relations on a given type with
an addition."]
instance : has_Inf (con M) :=
⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y,
⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc,
λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩,
λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩
/-- The infimum of a set of congruence relations is the same as the infimum of the set's image
under the map to the underlying equivalence relation. -/
@[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of
the set's image under the map to the underlying equivalence relation."]
lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) :=
setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS,
λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩
/-- The infimum of a set of congruence relations is the same as the infimum of the set's image
under the map to the underlying binary relation. -/
@[to_additive "The infimum of a set of additive congruence relations is the same as the infimum
of the set's image under the map to the underlying binary relation."]
lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) :=
by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl }
@[to_additive]
instance : partial_order (con M) :=
{ le := (≤),
lt := λ c d, c ≤ d ∧ ¬d ≤ c,
le_refl := λ c _ _, id,
le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h,
lt_iff_le_not_le := λ _ _, iff.rfl,
le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ }
/-- The complete lattice of congruence relations on a given type with a multiplication. -/
@[to_additive "The complete lattice of additive congruence relations on a given type with
an addition."]
instance : complete_lattice (con M) :=
{ inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2,
λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩,
inf_le_left := λ _ _ _ _ h, h.1,
inf_le_right := λ _ _ _ _ h, h.2,
le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩,
top := { mul' := by tauto, ..setoid.complete_lattice.top},
le_top := λ _ _ _ h, trivial,
bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot},
bot_le := λ c x y h, h ▸ c.refl x,
.. complete_lattice_of_Inf (con M) $ assume s,
⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ }
/-- The infimum of two congruence relations equals the infimum of the underlying binary
operations. -/
@[to_additive "The infimum of two additive congruence relations equals the infimum of the
underlying binary operations."]
lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl
/-- Definition of the infimum of two congruence relations. -/
@[to_additive "Definition of the infimum of two additive congruence relations."]
theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl
/-- The inductively defined smallest congruence relation containing a binary relation `r` equals
the infimum of the set of congruence relations containing `r`. -/
@[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation
containing a binary relation `r` equals the infimum of the set of additive congruence relations
containing `r`."]
theorem con_gen_eq (r : M → M → Prop) :
con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} :=
le_antisymm
(λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _)
(λ _ _ _ _ _, con.trans _)
$ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc)
(Inf_le (λ _ _, con_gen.rel.of _ _))
/-- The smallest congruence relation containing a binary relation `r` is contained in any
congruence relation containing `r`. -/
@[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary
relation `r` is contained in any additive congruence relation containing `r`."]
theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) :
con_gen r ≤ c :=
by rw con_gen_eq; exact Inf_le h
/-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation
containing `s` contains the smallest congruence relation containing `r`. -/
@[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the
smallest additive congruence relation containing `s` contains the smallest additive congruence
relation containing `r`."]
theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) :
con_gen r ≤ con_gen s :=
con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr
/-- Congruence relations equal the smallest congruence relation in which they are contained. -/
@[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest
additive congruence relation in which they are contained."]
lemma con_gen_of_con (c : con M) : con_gen c = c :=
le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of
/-- The map sending a binary relation to the smallest congruence relation in which it is
contained is idempotent. -/
@[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive
congruence relation in which it is contained is idempotent."]
lemma con_gen_idem (r : M → M → Prop) :
con_gen (con_gen r) = con_gen r :=
con_gen_of_con _
/-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing
the binary relation '`x` is related to `y` by `c` or `d`'. -/
@[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the
smallest additive congruence relation containing the binary relation '`x` is related to `y`
by `c` or `d`'."]
lemma sup_eq_con_gen (c d : con M) :
c ⊔ d = con_gen (λ x y, c x y ∨ d x y) :=
begin
rw con_gen_eq,
apply congr_arg Inf,
simp only [le_def, or_imp_distrib, ← forall_and_distrib]
end
/-- The supremum of two congruence relations equals the smallest congruence relation containing
the supremum of the underlying binary operations. -/
@[to_additive "The supremum of two additive congruence relations equals the smallest additive
congruence relation containing the supremum of the underlying binary operations."]
lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) :=
by rw sup_eq_con_gen; refl
/-- The supremum of a set of congruence relations `S` equals the smallest congruence relation
containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by
`c`'. -/
@[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations `S` equals
the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S`
such that `x` is related to `y` by `c`'."]
lemma Sup_eq_con_gen (S : set (con M)) :
Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) :=
begin
rw con_gen_eq,
apply congr_arg Inf,
ext,
exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2,
λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩,
end
/-- The supremum of a set of congruence relations is the same as the smallest congruence relation
containing the supremum of the set's image under the map to the underlying binary relation. -/
@[to_additive "The supremum of a set of additive congruence relations is the same as the smallest
additive congruence relation containing the supremum of the set's image under the map to the
underlying binary relation."]
lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) :=
begin
rw [Sup_eq_con_gen, Sup_image],
congr,
ext x y,
simp only [Sup_image, supr_apply, supr_Prop_eq, exists_prop, rel_eq_coe]
end
variables (M)
/-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into
binary relations on `M`. -/
@[to_additive "There is a Galois insertion of additive congruence relations on a type with
an addition `M` into binary relations on `M`."]
protected def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r :=
{ choice := λ r h, con_gen r,
gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩,
le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x,
choice_eq := λ _ _, rfl }
variables {M} (c)
/-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s
image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)`
by a congruence relation `c`.' -/
@[to_additive "Given a function `f`, the smallest additive congruence relation containing the
binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the
elements of `f⁻¹(y)` by an additive congruence relation `c`.'"]
def map_gen (f : M → N) : con N :=
con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b
/-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a
congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the
elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/
@[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in
an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined
by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"]
def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c)
(hf : surjective f) : con N :=
{ mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩,
⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩,
..c.to_setoid.map_of_surjective f h hf }
/-- A specialization of 'the smallest congruence relation containing a congruence relation `c`
equals `c`'. -/
@[to_additive "A specialization of 'the smallest additive congruence relation containing
an additive congruence relation `c` equals `c`'."]
lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y)
(h : mul_ker f H ≤ c) (hf : surjective f) :
c.map_gen f = c.map_of_surjective f H h hf :=
by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl
/-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a
multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain
defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/
@[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`,
an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain
defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "]
def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M :=
{ mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2,
..c.to_setoid.comap f }
section
open quotient
/-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving
bijection between the set of congruence relations containing `c` and the congruence relations
on the quotient of `M` by `c`. -/
@[to_additive "Given an additive congruence relation `c` on a type `M` with an addition,
the order-preserving bijection between the set of additive congruence relations containing `c` and
the additive congruence relations on the quotient of `M` by `c`."]
def correspondence : ((≤) : {d // c ≤ d} → {d // c ≤ d} → Prop) ≃o
((≤) : con c.quotient → con c.quotient → Prop) :=
{ to_fun := λ d, d.1.map_of_surjective coe _
(by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid,
inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h,
show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩,
left_inv := λ d, subtype.ext_iff_val.2 $ ext $ λ _ _,
⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in
d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy,
λ h, ⟨_, _, rfl, rfl, h⟩⟩,
right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤
comap (coe : M → c.quotient) (λ x y, rfl) d :=
λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in
ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H,
con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩,
ord' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩,
λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in
t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy⟩ }
end
end
-- Monoids
variables {M} [monoid M] [monoid N] [monoid P] (c : con M)
/-- The quotient of a monoid by a congruence relation is a monoid. -/
@[to_additive add_monoid "The quotient of an `add_monoid` by an additive congruence relation is
an `add_monoid`."]
instance monoid : monoid c.quotient :=
{ one := ((1 : M) : c.quotient),
mul := (*),
mul_assoc := λ x y z, quotient.induction_on₃' x y z
$ λ _ _ _, congr_arg coe $ mul_assoc _ _ _,
mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _,
one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ }
/-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/
@[to_additive add_comm_monoid "The quotient of an `add_comm_monoid` by an additive congruence
relation is an `add_comm_monoid`."]
instance comm_monoid {α : Type*} [comm_monoid α] (c : con α) :
comm_monoid c.quotient :=
{ mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm],
..c.monoid}
variables {c}
/-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the
monoid's 1. -/
@[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation
is the equivalence class of the `add_monoid`'s 0."]
lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl
variables (M c)
/-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/
@[to_additive add_submonoid "The `add_submonoid` of `M × M` defined by an additive congruence
relation on an `add_monoid` `M`."]
protected def submonoid : submonoid (M × M) :=
{ carrier := { x | c x.1 x.2 },
one_mem' := c.iseqv.1 1,
mul_mem' := λ _ _, c.mul }
variables {M c}
/-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership
is an equivalence relation. -/
@[to_additive of_add_submonoid "The additive congruence relation on an `add_monoid` `M` from
an `add_submonoid` of `M × M` for which membership is an equivalence relation."]
def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M :=
{ r := λ x y, (x, y) ∈ N,
iseqv := H,
mul' := λ _ _ _ _, N.mul_mem }
/-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose
elements are `(x, y)` such that `x` is related to `y` by `c`. -/
@[to_additive to_add_submonoid "Coercion from a congruence relation `c` on an `add_monoid` `M`
to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x`
is related to `y` by `c`."]
instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩
@[to_additive] lemma mem_coe {c : con M} {x y} :
(x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl
@[to_additive to_add_submonoid_inj]
theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d :=
ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H
@[to_additive]
lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d :=
⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩
/-- The kernel of a monoid homomorphism as a congruence relation. -/
@[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."]
def ker (f : M →* P) : con M := mul_ker f f.3
/-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/
@[to_additive "The definition of the additive congruence relation defined by an `add_monoid`
homomorphism's kernel."]
lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl
/-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/
@[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation
(namely 0)."]
instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩
variables (c)
/-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/
@[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive
congruence relation."]
def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩
variables (x y : M)
/-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence
relation `c` equals `c`. -/
@[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by
an additive congruence relation `c` equals `c`."]
lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq
variables {c}
/-- The natural homomorphism from a monoid to its quotient by a congruence relation is
surjective. -/
@[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence
relation is surjective."]
lemma mk'_surjective : surjective c.mk' :=
λ x, by rcases x; exact ⟨x, rfl⟩
@[simp, to_additive] lemma comp_mk'_apply (g : c.quotient →* P) {x} :
g.comp c.mk' x = g x := rfl
/-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are
those in the preimage of `f(x)` under `f`. -/
@[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of
an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "]
lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} :=
set.ext $ λ x,
⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm,
λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩
/-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence
relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with
`f`. -/
@[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation
`c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s
quotient homomorphism composed with `f`."]
lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) :=
ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl
variables (c) (f : M →* P)
/-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a
homomorphism constant on `c`'s equivalence classes. -/
@[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence
relation `c` induced by a homomorphism constant on `c`'s equivalence classes."]
def lift (H : c ≤ ker f) : c.quotient →* P :=
{ to_fun := λ x, con.lift_on x f $ λ _ _ h, H h,
map_one' := by rw ←f.map_one; refl,
map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl }
variables {c f}
/-- The diagram describing the universal property for quotients of monoids commutes. -/
@[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s
commutes."]
lemma lift_mk' (H : c ≤ ker f) (x) :
c.lift f H (c.mk' x) = f x := rfl
/-- The diagram describing the universal property for quotients of monoids commutes. -/
@[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s
commutes."]
lemma lift_coe (H : c ≤ ker f) (x : M) :
c.lift f H x = f x := rfl
/-- The diagram describing the universal property for quotients of monoids commutes. -/
@[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s
commutes."]
theorem lift_comp_mk' (H : c ≤ ker f) :
(c.lift f H).comp c.mk' = f := by ext; refl
/-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the
homomorphism on the quotient induced by `f` composed with the natural map from the monoid to
the quotient. -/
@[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive
congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the
natural map from the `add_monoid` to the quotient."]
lemma lift_apply_mk' (f : c.quotient →* P) :
c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f :=
by ext; rcases x; refl
/-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they
are equal on elements that are coercions from the monoid. -/
@[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation
are equal if they are equal on elements that are coercions from the `add_monoid`."]
lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g :=
begin
rw [←lift_apply_mk' f, ←lift_apply_mk' g],
congr' 1,
exact monoid_hom.ext_iff.2 h,
end
/-- The uniqueness part of the universal property for quotients of monoids. -/
@[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."]
theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P)
(Hg : g.comp c.mk' = f) : g = c.lift f H :=
lift_funext g (c.lift f H) $ λ x, by rw [lift_coe H, ←comp_mk'_apply, Hg]
/-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s
equivalence classes, `f` has the same image as the homomorphism that `f` induces on the
quotient. -/
@[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f`
constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces
on the quotient."]
theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange :=
submonoid.ext $ λ x,
⟨λ ⟨y, hy⟩, by revert hy; rcases y; exact
λ hy, ⟨y, hy.1, by rw [hy.2.symm, ←lift_coe H]; refl⟩,
λ ⟨y, hy⟩, ⟨↑y, hy.1, by rw ←hy.2; refl⟩⟩
/-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes
induce a surjective homomorphism on `c`'s quotient. -/
@[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence
relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."]
lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) :
surjective (c.lift f h) :=
λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩
variables (c f)
/-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence
relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/
@[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f`
is the unique additive congruence relation on `M` whose induced map from the quotient of `M`
to `P` is injective."]
lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) :
ker f = c :=
to_setoid_inj $ ker_eq_lift_of_injective f H h
variables {c}
/-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/
@[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel
of an `add_monoid` homomorphism."]
def ker_lift : (ker f).quotient →* P :=
(ker f).lift f $ λ _ _, id
variables {f}
/-- The diagram described by the universal property for quotients of monoids, when the congruence
relation is the kernel of the homomorphism, commutes. -/
@[simp, to_additive "The diagram described by the universal property for quotients
of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism,
commutes."]
lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl
/-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has
the same image as `f`. -/
@[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism
on the quotient by `f`'s kernel has the same image as `f`."]
lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange :=
lift_range $ λ _ _, id
/-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/
@[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient
by `f`'s kernel."]
lemma ker_lift_injective (f : M →* P) : injective (ker_lift f) :=
λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2
/-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient
map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/
@[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d`
contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient
by `d`."]
def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient :=
c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from
(mk'_ker d).symm ▸ h hc
/-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of
the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient
map. -/
@[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d`
contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d`
induced by `d`'s quotient map."]
lemma map_apply {c d : con M} (h : c ≤ d) (x) :
c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl
variables (c)
/-- The first isomorphism theorem for monoids. -/
@[to_additive "The first isomorphism theorem for `add_monoid`s."]
noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange :=
{ map_mul' := monoid_hom.map_mul _,
..equiv.of_bijective
((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _
$ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).mrange_restrict) $
(equiv.bijective _).comp
⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections,
λ ⟨w, z, hzm, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ }
/-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. -/
@[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective
homomorphism."]
noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) :
(ker f).quotient ≃* P :=
{ map_mul' := monoid_hom.map_mul _,
..equiv.of_bijective (ker_lift f)
⟨ker_lift_injective f, lift_surjective_of_surjective (le_refl _) hf⟩ }
/-- The second isomorphism theorem for monoids. -/
@[to_additive "The second isomorphism theorem for `add_monoid`s."]
noncomputable def comap_quotient_equiv (f : N →* M) :
(comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange :=
(con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f
/-- The third isomorphism theorem for monoids. -/
@[to_additive "The third isomorphism theorem for `add_monoid`s."]
def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) :
(ker (c.map d h)).quotient ≃* d.quotient :=
{ map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b,
show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl,
..quotient_quotient_equiv_quotient c.to_setoid d.to_setoid h }
end con
|
39f9024e28328692c8eaeaceadabd920dd7d8cff | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/ring_theory/localization/integral.lean | f6bdd17f8d5b0bdbc0e34885180e5444aa349e45 | [
"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 | 19,461 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen
-/
import data.polynomial.lifts
import group_theory.monoid_localization
import ring_theory.algebraic
import ring_theory.ideal.local_ring
import ring_theory.integral_closure
import ring_theory.localization.fraction_ring
import ring_theory.localization.integer
import ring_theory.non_zero_divisors
import tactic.ring_exp
/-!
# Integral and algebraic elements of a fraction field
## Implementation notes
See `src/ring_theory/localization/basic.lean` for a design overview.
## Tags
localization, ring localization, commutative ring localization, characteristic predicate,
commutative ring, field of fractions
-/
variables {R : Type*} [comm_ring R] (M : submonoid R) {S : Type*} [comm_ring S]
variables [algebra R S] {P : Type*} [comm_ring P]
open_locale big_operators polynomial
namespace is_localization
section integer_normalization
open polynomial
variables (M) {S} [is_localization M S]
open_locale classical
/-- `coeff_integer_normalization p` gives the coefficients of the polynomial
`integer_normalization p` -/
noncomputable def coeff_integer_normalization (p : S[X]) (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 : S[X]) (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 : S[X]) (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 : S[X]) :
R[X] :=
∑ i in p.support, monomial i (coeff_integer_normalization M p i)
@[simp]
lemma integer_normalization_coeff (p : S[X]) (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 : S[X]) :
∃ (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 : S[X]) :
∃ (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 : S[X])
{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 : S[X]) {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
end is_localization
namespace is_fraction_ring
open is_localization
variables {A K C : Type*} [comm_ring A] [is_domain A] [field K] [algebra A K] [is_fraction_ring A K]
variables [comm_ring C]
lemma integer_normalization_eq_zero_iff {p : K[X]} :
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
variables (A K C)
/-- An element of a ring is algebraic over the ring `A` iff it is algebraic
over the field of fractions of `A`.
-/
lemma is_algebraic_iff [algebra A C] [algebra K C] [is_scalar_tower A K C] {x : C} :
is_algebraic A x ↔ is_algebraic K x :=
begin
split; rintros ⟨p, hp, px⟩,
{ 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 },
{ exact (polynomial.aeval_map_algebra_map K _ _).trans px, } },
{ exact ⟨integer_normalization _ p,
mt integer_normalization_eq_zero_iff.mp hp,
integer_normalization_aeval_eq_zero _ p px⟩ },
end
variables {A K C}
/-- A ring is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`.
-/
lemma comap_is_algebraic_iff [algebra A C] [algebra K C] [is_scalar_tower A K C] :
algebra.is_algebraic A C ↔ algebra.is_algebraic K C :=
⟨λ h x, (is_algebraic_iff A K C).mp (h x), λ h x, (is_algebraic_iff A K C).mpr (h x)⟩
end is_fraction_ring
open is_localization
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ₘ]
variables {S M}
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 : R[X]) (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 : R[X])
(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,
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 : _ ≤ submonoid.comap (f : R →* S) _) : localization M →+* _).is_integral :=
@is_integral_localization R _ M S _ f.to_algebra _ _ _ _ _ _ _ _ hf
variable (M)
lemma is_localization.scale_roots_common_denom_mem_lifts (p : Rₘ[X])
(hp : p.leading_coeff ∈ (algebra_map R Rₘ).range) :
p.scale_roots (algebra_map R Rₘ $ is_localization.common_denom M p.support p.coeff) ∈
polynomial.lifts (algebra_map R Rₘ) :=
begin
rw polynomial.lifts_iff_coeff_lifts,
intro n,
rw [polynomial.coeff_scale_roots],
by_cases h₁ : n ∈ p.support,
by_cases h₂ : n = p.nat_degree,
{ rwa [h₂, polynomial.coeff_nat_degree, tsub_self, pow_zero, _root_.mul_one] },
{ have : n + 1 ≤ p.nat_degree := lt_of_le_of_ne (polynomial.le_nat_degree_of_mem_supp _ h₁) h₂,
rw [← tsub_add_cancel_of_le (le_tsub_of_add_le_left this), pow_add, pow_one, mul_comm,
_root_.mul_assoc, ← map_pow],
change _ ∈ (algebra_map R Rₘ).range,
apply mul_mem,
{ exact ring_hom.mem_range_self _ _ },
{ rw ← algebra.smul_def,
exact ⟨_, is_localization.map_integer_multiple M p.support p.coeff ⟨n, h₁⟩⟩ } },
{ rw polynomial.not_mem_support_iff at h₁,
rw [h₁, zero_mul],
exact zero_mem (algebra_map R Rₘ).range }
end
lemma is_integral.exists_multiple_integral_of_is_localization
[algebra Rₘ S] [is_scalar_tower R Rₘ S] (x : S) (hx : is_integral Rₘ x) :
∃ m : M, is_integral R (m • x) :=
begin
cases subsingleton_or_nontrivial Rₘ with _ nontriv; resetI,
{ haveI := (algebra_map Rₘ S).codomain_trivial,
exact ⟨1, polynomial.X, polynomial.monic_X, subsingleton.elim _ _⟩ },
obtain ⟨p, hp₁, hp₂⟩ := hx,
obtain ⟨p', hp'₁, -, hp'₂⟩ := lifts_and_nat_degree_eq_and_monic
(is_localization.scale_roots_common_denom_mem_lifts M p _) _,
{ refine ⟨is_localization.common_denom M p.support p.coeff, p', hp'₂, _⟩,
rw [is_scalar_tower.algebra_map_eq R Rₘ S, ← polynomial.eval₂_map, hp'₁,
submonoid.smul_def, algebra.smul_def, is_scalar_tower.algebra_map_apply R Rₘ S],
exact polynomial.scale_roots_eval₂_eq_zero _ hp₂ },
{ rw hp₁.leading_coeff, exact one_mem _ },
{ rwa polynomial.monic_scale_roots_iff },
end
end is_integral
variables {A K : Type*} [comm_ring A] [is_domain A]
namespace is_integral_closure
variables (A) {L : Type*} [field K] [field L] [algebra A K] [algebra A L] [is_fraction_ring A K]
variables (C : Type*) [comm_ring C] [is_domain C] [algebra C L] [is_integral_closure C A L]
variables [algebra A C] [is_scalar_tower A C L]
open algebra
/-- If the field `L` is an algebraic extension of the integral domain `A`,
the integral closure `C` of `A` in `L` has fraction field `L`. -/
lemma is_fraction_ring_of_algebraic (alg : is_algebraic A L)
(inj : ∀ x, algebra_map A L x = 0 → x = 0) :
is_fraction_ring C L :=
{ map_units := λ ⟨y, hy⟩,
is_unit.mk0 _ (show algebra_map C L y ≠ 0, from λ h, mem_non_zero_divisors_iff_ne_zero.mp hy
((injective_iff_map_eq_zero (algebra_map C L)).mp (algebra_map_injective C A L) _ h)),
surj := λ z, let ⟨x, y, hy, hxy⟩ := exists_integral_multiple (alg z) inj in
⟨⟨mk' C (x : L) x.2, algebra_map _ _ y,
mem_non_zero_divisors_iff_ne_zero.mpr (λ h, hy (inj _
(by rw [is_scalar_tower.algebra_map_apply A C L, h, ring_hom.map_zero])))⟩,
by rw [set_like.coe_mk, algebra_map_mk', ← is_scalar_tower.algebra_map_apply A C L, hxy]⟩,
eq_iff_exists := λ x y, ⟨λ h, ⟨1, by simpa using algebra_map_injective C A L 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 `C` of `A` in `L` has fraction field `L`. -/
lemma is_fraction_ring_of_finite_extension [algebra K L] [is_scalar_tower A K L]
[finite_dimensional K L] : is_fraction_ring C L :=
is_fraction_ring_of_algebraic A C
(is_fraction_ring.comap_is_algebraic_iff.mpr (is_algebraic_of_finite K L))
(λ x hx, is_fraction_ring.to_map_eq_zero_iff.mp ((map_eq_zero $ algebra_map K L).mp $
(is_scalar_tower.algebra_map_apply _ _ _ _).symm.trans hx))
end is_integral_closure
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 :=
is_integral_closure.is_fraction_ring_of_algebraic A (integral_closure A L) alg inj
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_integral_closure.is_fraction_ring_of_finite_extension A K L (integral_closure A L)
end integral_closure
namespace is_fraction_ring
variables (R S K)
/-- `S` is algebraic over `R` iff a fraction ring of `S` is algebraic over `R` -/
lemma is_algebraic_iff' [field K] [is_domain R] [is_domain S] [algebra R K] [algebra S K]
[no_zero_smul_divisors R K] [is_fraction_ring S K] [is_scalar_tower R S K] :
algebra.is_algebraic R S ↔ algebra.is_algebraic R K :=
begin
simp only [algebra.is_algebraic],
split,
{ intros h x,
rw [is_fraction_ring.is_algebraic_iff R (fraction_ring R) K, is_algebraic_iff_is_integral],
obtain ⟨(a : S), b, ha, rfl⟩ := @div_surjective S _ _ _ _ _ _ x,
obtain ⟨f, hf₁, hf₂⟩ := h b,
rw [div_eq_mul_inv],
refine is_integral_mul _ _,
{ rw [← is_algebraic_iff_is_integral],
refine _root_.is_algebraic_of_larger_base_of_injective
(no_zero_smul_divisors.algebra_map_injective R (fraction_ring R)) _,
exact is_algebraic_algebra_map_of_is_algebraic (h a) },
{ rw [← is_algebraic_iff_is_integral],
use (f.map (algebra_map R (fraction_ring R))).reverse,
split,
{ rwa [ne.def, polynomial.reverse_eq_zero, ← polynomial.degree_eq_bot,
polynomial.degree_map_eq_of_injective
(no_zero_smul_divisors.algebra_map_injective R (fraction_ring R)),
polynomial.degree_eq_bot]},
{ haveI : invertible (algebra_map S K b),
from is_unit.invertible (is_unit_of_mem_non_zero_divisors
(mem_non_zero_divisors_iff_ne_zero.2
(λ h, non_zero_divisors.ne_zero ha
((injective_iff_map_eq_zero (algebra_map S K)).1
(no_zero_smul_divisors.algebra_map_injective _ _) b h)))),
rw [polynomial.aeval_def, ← inv_of_eq_inv, polynomial.eval₂_reverse_eq_zero_iff,
polynomial.eval₂_map, ← is_scalar_tower.algebra_map_eq, ← polynomial.aeval_def,
polynomial.aeval_algebra_map_apply, hf₂, ring_hom.map_zero] } } },
{ intros h x,
obtain ⟨f, hf₁, hf₂⟩ := h (algebra_map S K x),
use [f, hf₁],
rw [polynomial.aeval_algebra_map_apply] at hf₂,
exact (injective_iff_map_eq_zero (algebra_map S K)).1
(no_zero_smul_divisors.algebra_map_injective _ _) _ hf₂ }
end
open_locale non_zero_divisors
variables (R) {S K}
/-- If the `S`-multiples of `a` are contained in some `R`-span, then `Frac(S)`-multiples of `a`
are contained in the equivalent `Frac(R)`-span. -/
lemma ideal_span_singleton_map_subset {L : Type*}
[is_domain R] [is_domain S] [field K] [field L]
[algebra R K] [algebra R L] [algebra S L] [is_integral_closure S R L]
[is_fraction_ring S L] [algebra K L] [is_scalar_tower R S L] [is_scalar_tower R K L]
{a : S} {b : set S} (alg : algebra.is_algebraic R L) (inj : function.injective (algebra_map R L))
(h : (ideal.span ({a} : set S) : set S) ⊆ submodule.span R b) :
(ideal.span ({algebra_map S L a} : set L) : set L) ⊆ submodule.span K (algebra_map S L '' b) :=
begin
intros x hx,
obtain ⟨x', rfl⟩ := ideal.mem_span_singleton.mp hx,
obtain ⟨y', z', rfl⟩ := is_localization.mk'_surjective (S⁰) x',
obtain ⟨y, z, hz0, yz_eq⟩ := is_integral_closure.exists_smul_eq_mul alg inj y'
(non_zero_divisors.coe_ne_zero z'),
have injRS : function.injective (algebra_map R S),
{ refine function.injective.of_comp
(show function.injective (algebra_map S L ∘ algebra_map R S), from _),
rwa [← ring_hom.coe_comp, ← is_scalar_tower.algebra_map_eq] },
have hz0' : algebra_map R S z ∈ S⁰ := map_mem_non_zero_divisors (algebra_map R S) injRS
(mem_non_zero_divisors_of_ne_zero hz0),
have mk_yz_eq : is_localization.mk' L y' z' = is_localization.mk' L y ⟨_, hz0'⟩,
{ rw [algebra.smul_def, mul_comm _ y, mul_comm _ y', ← set_like.coe_mk (algebra_map R S z) hz0']
at yz_eq,
exact is_localization.mk'_eq_of_eq yz_eq.symm },
suffices hy : algebra_map S L (a * y) ∈ submodule.span K (⇑(algebra_map S L) '' b),
{ rw [mk_yz_eq, is_fraction_ring.mk'_eq_div, set_like.coe_mk,
← is_scalar_tower.algebra_map_apply, is_scalar_tower.algebra_map_apply R K L,
div_eq_mul_inv, ← mul_assoc, mul_comm, ← map_inv₀, ← algebra.smul_def,
← _root_.map_mul],
exact (submodule.span K _).smul_mem _ hy },
refine submodule.span_subset_span R K _ _,
rw submodule.span_algebra_map_image_of_tower,
exact submodule.mem_map_of_mem (h (ideal.mem_span_singleton.mpr ⟨y, rfl⟩))
end
end is_fraction_ring
|
2c673a92a05602e4e2a607ee5505602024e7337f | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/group_theory/perm/cycles.lean | 252a2db0e73a05210a18e8689714b86d012d5c5a | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 30,571 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.nat.parity
import data.equiv.fintype
import group_theory.perm.sign
/-!
# Cyclic permutations
## Main definitions
In the following, `f : equiv.perm β`.
* `equiv.perm.is_cycle`: `f.is_cycle` when two nonfixed points of `β`
are related by repeated application of `f`.
* `equiv.perm.same_cycle`: `f.same_cycle x y` when `x` and `y` are in the same cycle of `f`.
The following two definitions require that `β` is a `fintype`:
* `equiv.perm.cycle_of`: `f.cycle_of x` is the cycle of `f` that `x` belongs to.
* `equiv.perm.cycle_factors`: `f.cycle_factors` is a list of disjoint cyclic permutations that
multiply to `f`.
## Main results
* This file contains several closure results:
- `closure_is_cycle` : The symmetric group is generated by cycles
- `closure_cycle_adjacent_swap` : The symmetric group is generated by
a cycle and an adjacent transposition
- `closure_cycle_coprime_swap` : The symmetric group is generated by
a cycle and a coprime transposition
- `closure_prime_cycle_swap` : The symmetric group is generated by
a prime cycle and a transposition
-/
namespace equiv.perm
open equiv function finset
variables {α : Type*} {β : Type*} [decidable_eq α]
section sign_cycle
/-!
### `is_cycle`
-/
variables [fintype α]
/-- A permutation is a cycle when any two nonfixed points of the permutation are related by repeated
application of the permutation. -/
def is_cycle (f : perm β) : Prop := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y
lemma is_cycle.ne_one {f : perm β} (h : is_cycle f) : f ≠ 1 :=
λ hf, by simpa [hf, is_cycle] using h
lemma is_cycle.two_le_card_support {f : perm α} (h : is_cycle f) :
2 ≤ f.support.card :=
two_le_card_support_of_ne_one h.ne_one
lemma is_cycle_swap {α : Type*} [decidable_eq α] {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) :=
⟨y, by rwa swap_apply_right,
λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a),
if hya : y = a then ⟨0, hya⟩
else ⟨1, by { rw [gpow_one, swap_apply_def], split_ifs at *; cc }⟩⟩
lemma is_swap.is_cycle {α : Type*} [decidable_eq α] {f : perm α} (hf : is_swap f) : is_cycle f :=
begin
obtain ⟨x, y, hxy, rfl⟩ := hf,
exact is_cycle_swap hxy,
end
lemma is_cycle.inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) :=
let ⟨x, hx⟩ := hf in
⟨x, by { simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *, cc },
λ y hy, let ⟨i, hi⟩ := hx.2 y (by { simp only [inv_eq_iff_eq, *, forall_prop_of_true,
ne.def] at *, cc }) in
⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩
lemma is_cycle.is_cycle_conj {f g : perm β} (hf : is_cycle f) : is_cycle (g * f * g⁻¹) :=
begin
obtain ⟨a, ha1, ha2⟩ := hf,
refine ⟨g a, by simp [ha1], λ b hb, _⟩,
obtain ⟨i, hi⟩ := ha2 (g⁻¹ b) _,
{ refine ⟨i, _⟩,
rw conj_gpow,
simp [hi] },
{ contrapose! hb,
rw [perm.mul_apply, perm.mul_apply, hb, apply_inv_self] }
end
lemma is_cycle.exists_gpow_eq {f : perm β} (hf : is_cycle f) {x y : β}
(hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y :=
let ⟨g, hg⟩ := hf in
let ⟨a, ha⟩ := hg.2 x hx in
let ⟨b, hb⟩ := hg.2 y hy in
⟨b - a, by rw [← ha, ← mul_apply, ← gpow_add, sub_add_cancel, hb]⟩
lemma is_cycle.exists_pow_eq [fintype β] {f : perm β} (hf : is_cycle f) {x y : β}
(hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℕ, (f ^ i) x = y :=
let ⟨n, hn⟩ := hf.exists_gpow_eq hx hy in
by classical; exact ⟨(n % order_of f).to_nat, by {
have := n.mod_nonneg (int.coe_nat_ne_zero.mpr (ne_of_gt (order_of_pos f))),
rwa [← gpow_coe_nat, int.to_nat_of_nonneg this, ← gpow_eq_mod_order_of] }⟩
/-- The subgroup generated by a cycle is in bijection with its support -/
noncomputable def is_cycle.gpowers_equiv_support {σ : perm α} (hσ : is_cycle σ) :
(↑(subgroup.gpowers σ) : set (perm α)) ≃ (↑(σ.support) : set α) :=
equiv.of_bijective (λ τ, ⟨τ (classical.some hσ),
begin
obtain ⟨τ, n, rfl⟩ := τ,
rw [finset.mem_coe, coe_fn_coe_base, subtype.coe_mk, gpow_apply_mem_support, mem_support],
exact (classical.some_spec hσ).1,
end⟩)
begin
split,
{ rintros ⟨a, m, rfl⟩ ⟨b, n, rfl⟩ h,
ext y,
by_cases hy : σ y = y,
{ simp_rw [subtype.coe_mk, gpow_apply_eq_self_of_apply_eq_self hy] },
{ obtain ⟨i, rfl⟩ := (classical.some_spec hσ).2 y hy,
rw [subtype.coe_mk, subtype.coe_mk, gpow_apply_comm σ m i, gpow_apply_comm σ n i],
exact congr_arg _ (subtype.ext_iff.mp h) } }, by
{ rintros ⟨y, hy⟩,
rw [finset.mem_coe, mem_support] at hy,
obtain ⟨n, rfl⟩ := (classical.some_spec hσ).2 y hy,
exact ⟨⟨σ ^ n, n, rfl⟩, rfl⟩ },
end
@[simp] lemma is_cycle.gpowers_equiv_support_apply {σ : perm α} (hσ : is_cycle σ) {n : ℕ} :
hσ.gpowers_equiv_support ⟨σ ^ n, n, rfl⟩ = ⟨(σ ^ n) (classical.some hσ),
pow_apply_mem_support.2 (mem_support.2 (classical.some_spec hσ).1)⟩ :=
rfl
@[simp] lemma is_cycle.gpowers_equiv_support_symm_apply {σ : perm α} (hσ : is_cycle σ) (n : ℕ) :
hσ.gpowers_equiv_support.symm ⟨(σ ^ n) (classical.some hσ),
pow_apply_mem_support.2 (mem_support.2 (classical.some_spec hσ).1)⟩ =
⟨σ ^ n, n, rfl⟩ :=
(equiv.symm_apply_eq _).2 hσ.gpowers_equiv_support_apply
lemma order_of_is_cycle {σ : perm α} (hσ : is_cycle σ) : order_of σ = σ.support.card :=
begin
rw [order_eq_card_gpowers, ←fintype.card_coe],
convert fintype.card_congr (is_cycle.gpowers_equiv_support hσ),
end
lemma is_cycle_swap_mul_aux₁ {α : Type*} [decidable_eq α] : ∀ (n : ℕ) {b x : α} {f : perm α}
(hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b),
∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b
| 0 := λ b x f hb h, ⟨0, h⟩
| (n+1 : ℕ) := λ b x f hb h,
if hfbx : f x = b then ⟨0, hfbx⟩
else
have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb,
have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b,
by { rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx),
ne.def, ← f.injective.eq_iff, apply_inv_self],
exact this.1 },
let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb'
(f.injective $ by { rw [apply_inv_self], rwa [pow_succ, mul_apply] at h }) in
⟨i + 1, by rw [add_comm, gpow_add, mul_apply, hi, gpow_one, mul_apply, apply_inv_self,
swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩
lemma is_cycle_swap_mul_aux₂ {α : Type*} [decidable_eq α] :
∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b),
∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b
| (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n
| -[1+ n] := λ b x f hb h,
if hfbx : f⁻¹ x = b then
⟨-1, by rwa [gpow_neg, gpow_one, mul_inv_rev, mul_apply, swap_inv, swap_apply_right]⟩
else if hfbx' : f x = b then ⟨0, hfbx'⟩
else
have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb,
have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b,
by { rw [mul_apply, swap_apply_def],
split_ifs;
simp only [inv_eq_iff_eq, perm.mul_apply, gpow_neg_succ_of_nat, ne.def,
perm.apply_inv_self] at *;
cc },
let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb
(show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by
rw [← gpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, gpow_neg_succ_of_nat,
← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, gpow_coe_nat,
← pow_succ', ← pow_succ]) in
have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left],
⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, gpow_add, gpow_one, gpow_neg,
← inv_gpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x,
gpow_add, gpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self,
swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩
lemma is_cycle.eq_swap_of_apply_apply_eq_self {α : Type*} [decidable_eq α]
{f : perm α} (hf : is_cycle f) {x : α}
(hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) :=
equiv.ext $ λ y,
let ⟨z, hz⟩ := hf in
let ⟨i, hi⟩ := hz.2 x hfx in
if hyx : y = x then by simp [hyx]
else if hfyx : y = f x then by simp [hfyx, hffx]
else begin
rw [swap_apply_of_ne_of_ne hyx hfyx],
refine by_contradiction (λ hy, _),
cases hz.2 y hy with j hj,
rw [← sub_add_cancel j i, gpow_add, mul_apply, hi] at hj,
cases gpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji,
{ rw [← hj, hji] at hyx, cc },
{ rw [← hj, hji] at hfyx, cc }
end
lemma is_cycle.swap_mul {α : Type*} [decidable_eq α] {f : perm α} (hf : is_cycle f) {x : α}
(hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) :=
⟨f x, by { simp only [swap_apply_def, mul_apply],
split_ifs; simp [f.injective.eq_iff] at *; cc },
λ y hy,
let ⟨i, hi⟩ := hf.exists_gpow_eq hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in
have hi : (f ^ (i - 1)) (f x) = y, from
calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [gpow_one, mul_apply]
... = y : by rwa [← gpow_add, sub_add_cancel],
is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩
lemma is_cycle.sign : ∀ {f : perm α} (hf : is_cycle f),
sign f = -(-1) ^ f.support.card
| f := λ hf,
let ⟨x, hx⟩ := hf in
calc sign f = sign (swap x (f x) * (swap x (f x) * f)) :
by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl]
... = -(-1) ^ f.support.card :
if h1 : f (f x) = x
then
have h : swap x (f x) * f = 1,
begin
rw hf.eq_swap_of_apply_apply_eq_self hx.1 h1,
simp only [perm.mul_def, perm.one_def, swap_apply_left, swap_swap]
end,
by { rw [sign_mul, sign_swap hx.1.symm, h, sign_one, hf.eq_swap_of_apply_apply_eq_self hx.1 h1,
card_support_swap hx.1.symm], refl }
else
have h : card (support (swap x (f x) * f)) + 1 = card (support f),
by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq h1,
card_insert_of_not_mem (not_mem_erase _ _)],
have wf : card (support (swap x (f x) * f)) < card (support f),
from card_support_swap_mul hx.1,
by { rw [sign_mul, sign_swap hx.1.symm, (hf.swap_mul hx.1 h1).sign, ← h],
simp only [pow_add, mul_one, units.neg_neg, one_mul, units.mul_neg, eq_self_iff_true,
pow_one, units.neg_mul_neg] }
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]}
-- The lemma `support_pow_le` is relevant. It means that `h2` is equivalent to
-- `σ.support = (σ ^ n).support`, as well as to `σ.support.card ≤ (σ ^ n).support.card`.
lemma is_cycle_of_is_cycle_pow {σ : perm α} {n : ℤ}
(h1 : is_cycle (σ ^ n)) (h2 : σ.support ≤ (σ ^ n).support) : is_cycle σ :=
begin
have key : ∀ x : α, (σ ^ n) x ≠ x ↔ σ x ≠ x,
{ simp_rw [←mem_support],
exact finset.ext_iff.mp (le_antisymm (support_pow_le σ n) h2) },
obtain ⟨x, hx1, hx2⟩ := h1,
refine ⟨x, (key x).mp hx1, λ y hy, _⟩,
cases (hx2 y ((key y).mpr hy)) with i _,
exact ⟨n * i, by rwa gpow_mul⟩,
end
end sign_cycle
/-!
### `same_cycle`
-/
/-- The equivalence relation indicating that two points are in the same cycle of a permutation. -/
def same_cycle (f : perm β) (x y : β) : Prop := ∃ i : ℤ, (f ^ i) x = y
@[refl] lemma same_cycle.refl (f : perm β) (x : β) : same_cycle f x x := ⟨0, rfl⟩
@[symm] lemma same_cycle.symm (f : perm β) {x y : β} : same_cycle f x y → same_cycle f y x :=
λ ⟨i, hi⟩, ⟨-i, by rw [gpow_neg, ← hi, inv_apply_self]⟩
@[trans] lemma same_cycle.trans (f : perm β) {x y z : β} :
same_cycle f x y → same_cycle f y z → same_cycle f x z :=
λ ⟨i, hi⟩ ⟨j, hj⟩, ⟨j + i, by rw [gpow_add, mul_apply, hi, hj]⟩
lemma same_cycle.apply_eq_self_iff {f : perm β} {x y : β} :
same_cycle f x y → (f x = x ↔ f y = y) :=
λ ⟨i, hi⟩, by rw [← hi, ← mul_apply, ← gpow_one_add, add_comm, gpow_add_one, mul_apply,
(f ^ i).injective.eq_iff]
lemma is_cycle.same_cycle {f : perm β} (hf : is_cycle f) {x y : β}
(hx : f x ≠ x) (hy : f y ≠ y) : same_cycle f x y :=
hf.exists_gpow_eq hx hy
instance [fintype α] (f : perm α) : decidable_rel (same_cycle f) :=
λ x y, decidable_of_iff (∃ n ∈ list.range (fintype.card (perm α)), (f ^ n) x = y)
⟨λ ⟨n, _, hn⟩, ⟨n, hn⟩, λ ⟨i, hi⟩, ⟨(i % order_of f).nat_abs, list.mem_range.2
(int.coe_nat_lt.1 $
by { rw int.nat_abs_of_nonneg (int.mod_nonneg _
(int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))),
{ apply lt_of_lt_of_le (int.mod_lt _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))),
{ simp [order_of_le_card_univ] },
exact fintype_perm },
exact fintype_perm, }),
by { rw [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _
(int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← gpow_eq_mod_order_of, hi],
exact fintype_perm }⟩⟩
lemma same_cycle_apply {f : perm β} {x y : β} : same_cycle f x (f y) ↔ same_cycle f x y :=
⟨λ ⟨i, hi⟩, ⟨-1 + i, by rw [gpow_add, mul_apply, hi, gpow_neg_one, inv_apply_self]⟩,
λ ⟨i, hi⟩, ⟨1 + i, by rw [gpow_add, mul_apply, hi, gpow_one]⟩⟩
lemma same_cycle_cycle {f : perm β} {x : β} (hx : f x ≠ x) : is_cycle f ↔
(∀ {y}, same_cycle f x y ↔ f y ≠ y) :=
⟨λ hf y, ⟨λ ⟨i, hi⟩ hy, hx $
by { rw [← gpow_apply_eq_self_of_apply_eq_self hy i, (f ^ i).injective.eq_iff] at hi,
rw [hi, hy] },
hf.exists_gpow_eq hx⟩,
λ h, ⟨x, hx, λ y hy, h.2 hy⟩⟩
lemma same_cycle_inv (f : perm β) {x y : β} : same_cycle f⁻¹ x y ↔ same_cycle f x y :=
⟨λ ⟨i, hi⟩, ⟨-i, by rw [gpow_neg, ← inv_gpow, hi]⟩,
λ ⟨i, hi⟩, ⟨-i, by rw [gpow_neg, ← inv_gpow, inv_inv, hi]⟩ ⟩
lemma same_cycle_inv_apply {f : perm β} {x y : β} : same_cycle f x (f⁻¹ y) ↔ same_cycle f x y :=
by rw [← same_cycle_inv, same_cycle_apply, same_cycle_inv]
/-!
### `cycle_of`
-/
/-- `f.cycle_of x` is the cycle of the permutation `f` to which `x` belongs. -/
def cycle_of [fintype α] (f : perm α) (x : α) : perm α :=
of_subtype (@subtype_perm _ f (same_cycle f x) (λ _, same_cycle_apply.symm))
lemma cycle_of_apply [fintype α] (f : perm α) (x y : α) :
cycle_of f x y = if same_cycle f x y then f y else y := rfl
lemma cycle_of_inv [fintype α] (f : perm α) (x : α) :
(cycle_of f x)⁻¹ = cycle_of f⁻¹ x :=
equiv.ext $ λ y, begin
rw [inv_eq_iff_eq, cycle_of_apply, cycle_of_apply],
split_ifs; simp [*, same_cycle_inv, same_cycle_inv_apply] at *
end
@[simp] lemma cycle_of_pow_apply_self [fintype α] (f : perm α) (x : α) :
∀ n : ℕ, (cycle_of f x ^ n) x = (f ^ n) x
| 0 := rfl
| (n+1) := by { rw [pow_succ, mul_apply, cycle_of_apply,
cycle_of_pow_apply_self, if_pos, pow_succ, mul_apply],
exact ⟨n, rfl⟩ }
@[simp] lemma cycle_of_gpow_apply_self [fintype α] (f : perm α) (x : α) :
∀ n : ℤ, (cycle_of f x ^ n) x = (f ^ n) x
| (n : ℕ) := cycle_of_pow_apply_self f x n
| -[1+ n] := by rw [gpow_neg_succ_of_nat, ← inv_pow, cycle_of_inv,
gpow_neg_succ_of_nat, ← inv_pow, cycle_of_pow_apply_self]
lemma same_cycle.cycle_of_apply [fintype α] {f : perm α} {x y : α} (h : same_cycle f x y) :
cycle_of f x y = f y := dif_pos h
lemma cycle_of_apply_of_not_same_cycle [fintype α] {f : perm α} {x y : α} (h : ¬same_cycle f x y) :
cycle_of f x y = y := dif_neg h
@[simp] lemma cycle_of_apply_self [fintype α] (f : perm α) (x : α) :
cycle_of f x x = f x := (same_cycle.refl _ _).cycle_of_apply
lemma is_cycle.cycle_of_eq [fintype α] {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) :
cycle_of f x = f :=
equiv.ext $ λ y,
if h : same_cycle f x y then by rw [h.cycle_of_apply]
else by rw [cycle_of_apply_of_not_same_cycle h, not_not.1 (mt ((same_cycle_cycle hx).1 hf).2 h)]
@[simp] lemma cycle_of_eq_one_iff [fintype α] (f : perm α) {x : α} : cycle_of f x = 1 ↔ f x = x :=
begin
simp_rw [ext_iff, cycle_of_apply, one_apply],
refine ⟨λ h, (if_pos (same_cycle.refl f x)).symm.trans (h x), λ h y, _⟩,
by_cases hy : f y = y,
{ rw [hy, if_t_t] },
{ exact if_neg (mt same_cycle.apply_eq_self_iff (by tauto)) },
end
lemma is_cycle.cycle_of [fintype α] {f : perm α} (hf : is_cycle f) {x : α} :
cycle_of f x = if f x = x then 1 else f :=
begin
by_cases hx : f x = x,
{ rwa [if_pos hx, cycle_of_eq_one_iff] },
{ rwa [if_neg hx, hf.cycle_of_eq] },
end
lemma cycle_of_one [fintype α] (x : α) : cycle_of 1 x = 1 :=
(cycle_of_eq_one_iff 1).mpr rfl
lemma is_cycle_cycle_of [fintype α] (f : perm α) {x : α} (hx : f x ≠ x) : is_cycle (cycle_of f x) :=
have cycle_of f x x ≠ x, by rwa [(same_cycle.refl _ _).cycle_of_apply],
(same_cycle_cycle this).2 $ λ y,
⟨λ h, mt h.apply_eq_self_iff.2 this,
λ h, if hxy : same_cycle f x y then
let ⟨i, hi⟩ := hxy in
⟨i, by rw [cycle_of_gpow_apply_self, hi]⟩
else by { rw [cycle_of_apply_of_not_same_cycle hxy] at h, exact (h rfl).elim }⟩
/-!
### `cycle_factors`
-/
/-- Given a list `l : list α` and a permutation `f : perm α` whose nonfixed points are all in `l`,
recursively factors `f` into cycles. -/
def cycle_factors_aux [fintype α] : Π (l : list α) (f : perm α),
(∀ {x}, f x ≠ x → x ∈ l) →
{l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint}
| [] f h := ⟨[], by { simp only [imp_false, list.pairwise.nil, list.not_mem_nil, forall_const,
and_true, forall_prop_of_false, not_not, not_false_iff, list.prod_nil] at *,
ext, simp * }⟩
| (x::l) f h :=
if hx : f x = x then
cycle_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h, hy (by rwa h)) (h hy))
else let ⟨m, hm₁, hm₂, hm₃⟩ := cycle_factors_aux l ((cycle_of f x)⁻¹ * f)
(λ y hy, list.mem_of_ne_of_mem
(λ h : y = x,
by { rw [h, mul_apply, ne.def, inv_eq_iff_eq, cycle_of_apply_self] at hy, exact hy rfl })
(h (λ h : f y = y, by { rw [mul_apply, h, ne.def, inv_eq_iff_eq, cycle_of_apply] at hy,
split_ifs at hy; cc }))) in
⟨(cycle_of f x) :: m, by { rw [list.prod_cons, hm₁], simp },
λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ hg, hg.symm ▸ is_cycle_cycle_of _ hx)
(hm₂ g),
list.pairwise_cons.2 ⟨λ g hg y,
or_iff_not_imp_left.2 (λ hfy,
have hxy : same_cycle f x y := not_not.1 (mt cycle_of_apply_of_not_same_cycle hfy),
have hgm : g :: m.erase g ~ m := list.cons_perm_iff_perm_erase.2 ⟨hg, list.perm.refl _⟩,
have ∀ h ∈ m.erase g, disjoint g h, from
(list.pairwise_cons.1 ((hgm.pairwise_iff (λ a b (h : disjoint a b), h.symm)).2 hm₃)).1,
classical.by_cases id $ λ hgy : g y ≠ y,
(disjoint_prod_right _ this y).resolve_right $
have hsc : same_cycle f⁻¹ x (f y), by rwa [same_cycle_inv, same_cycle_apply],
by { rw [disjoint_prod_perm hm₃ hgm.symm, list.prod_cons,
← eq_inv_mul_iff_mul_eq] at hm₁,
rwa [hm₁, mul_apply, mul_apply, cycle_of_inv, hsc.cycle_of_apply,
inv_apply_self, inv_eq_iff_eq, eq_comm] }),
hm₃⟩⟩
/-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`. -/
def cycle_factors [fintype α] [linear_order α] (f : perm α) :
{l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} :=
cycle_factors_aux (univ.sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _))
/-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`,
without a linear order. -/
def trunc_cycle_factors [fintype α] (f : perm α) :
trunc {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} :=
quotient.rec_on_subsingleton (@univ α _).1
(λ l h, trunc.mk (cycle_factors_aux l f h))
(show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _)
@[elab_as_eliminator] lemma cycle_induction_on [fintype β] (P : perm β → Prop) (σ : perm β)
(base_one : P 1) (base_cycles : ∀ σ : perm β, σ.is_cycle → P σ)
(induction_disjoint : ∀ σ τ : perm β, disjoint σ τ → is_cycle σ → P σ → P τ → P (σ * τ)) :
P σ :=
begin
suffices :
∀ l : list (perm β), (∀ τ : perm β, τ ∈ l → τ.is_cycle) → l.pairwise disjoint → P l.prod,
{ classical,
let x := σ.trunc_cycle_factors.out,
exact (congr_arg P x.2.1).mp (this x.1 x.2.2.1 x.2.2.2) },
intro l,
induction l with σ l ih,
{ exact λ _ _, base_one },
{ intros h1 h2,
rw list.prod_cons,
exact induction_disjoint σ l.prod
(disjoint_prod_list_of_disjoint (list.pairwise_cons.mp h2).1)
(h1 _ (list.mem_cons_self _ _))
(base_cycles σ (h1 σ (l.mem_cons_self σ)))
(ih (λ τ hτ, h1 τ (list.mem_cons_of_mem σ hτ)) (list.pairwise_of_pairwise_cons h2)) },
end
section generation
variables [fintype α] [fintype β]
open subgroup
lemma closure_is_cycle : closure {σ : perm β | is_cycle σ} = ⊤ :=
begin
classical,
exact top_le_iff.mp (le_trans (ge_of_eq closure_is_swap) (closure_mono (λ _, is_swap.is_cycle))),
end
lemma closure_cycle_adjacent_swap {σ : perm α} (h1 : is_cycle σ) (h2 : σ.support = ⊤) (x : α) :
closure ({σ, swap x (σ x)} : set (perm α)) = ⊤ :=
begin
let H := closure ({σ, swap x (σ x)} : set (perm α)),
have h3 : σ ∈ H := subset_closure (set.mem_insert σ _),
have h4 : swap x (σ x) ∈ H := subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)),
have step1 : ∀ (n : ℕ), swap ((σ ^ n) x) ((σ^(n+1)) x) ∈ H,
{ intro n,
induction n with n ih,
{ exact subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)) },
{ convert H.mul_mem (H.mul_mem h3 ih) (H.inv_mem h3),
rw [mul_swap_eq_swap_mul, mul_inv_cancel_right], refl } },
have step2 : ∀ (n : ℕ), swap x ((σ ^ n) x) ∈ H,
{ intro n,
induction n with n ih,
{ convert H.one_mem,
exact swap_self x },
{ by_cases h5 : x = (σ ^ n) x,
{ rw [pow_succ, mul_apply, ←h5], exact h4 },
by_cases h6 : x = (σ^(n+1)) x,
{ rw [←h6, swap_self], exact H.one_mem },
rw [swap_comm, ←swap_mul_swap_mul_swap h5 h6],
exact H.mul_mem (H.mul_mem (step1 n) ih) (step1 n) } },
have step3 : ∀ (y : α), swap x y ∈ H,
{ intro y,
have hx : x ∈ (⊤ : finset α) := finset.mem_univ x,
rw [←h2, mem_support] at hx,
have hy : y ∈ (⊤ : finset α) := finset.mem_univ y,
rw [←h2, mem_support] at hy,
cases is_cycle.exists_pow_eq h1 hx hy with n hn,
rw ← hn,
exact step2 n },
have step4 : ∀ (y z : α), swap y z ∈ H,
{ intros y z,
by_cases h5 : z = x,
{ rw [h5, swap_comm], exact step3 y },
by_cases h6 : z = y,
{ rw [h6, swap_self], exact H.one_mem },
rw [←swap_mul_swap_mul_swap h5 h6, swap_comm z x],
exact H.mul_mem (H.mul_mem (step3 y) (step3 z)) (step3 y) },
rw [eq_top_iff, ←closure_is_swap, closure_le],
rintros τ ⟨y, z, h5, h6⟩,
rw h6,
exact step4 y z,
end
lemma closure_cycle_coprime_swap {n : ℕ} {σ : perm α} (h0 : nat.coprime n (fintype.card α))
(h1 : is_cycle σ) (h2 : σ.support = finset.univ) (x : α) :
closure ({σ, swap x ((σ ^ n) x)} : set (perm α)) = ⊤ :=
begin
rw [←finset.card_univ, ←h2, ←order_of_is_cycle h1] at h0,
cases exists_pow_eq_self_of_coprime h0 with m hm,
have h2' : (σ ^ n).support = ⊤ := eq.trans (support_pow_coprime h0) h2,
have h1' : is_cycle ((σ ^ n) ^ (m : ℤ)) := by rwa ← hm at h1,
replace h1' : is_cycle (σ ^ n) := is_cycle_of_is_cycle_pow h1'
(le_trans (support_pow_le σ n) (ge_of_eq (congr_arg support hm))),
rw [eq_top_iff, ←closure_cycle_adjacent_swap h1' h2' x, closure_le, set.insert_subset],
exact ⟨subgroup.pow_mem (closure _) (subset_closure (set.mem_insert σ _)) n,
set.singleton_subset_iff.mpr (subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)))⟩,
end
lemma closure_prime_cycle_swap {σ τ : perm α} (h0 : (fintype.card α).prime) (h1 : is_cycle σ)
(h2 : σ.support = finset.univ) (h3 : is_swap τ) : closure ({σ, τ} : set (perm α)) = ⊤ :=
begin
obtain ⟨x, y, h4, h5⟩ := h3,
obtain ⟨i, hi⟩ := h1.exists_pow_eq (mem_support.mp
((finset.ext_iff.mp h2 x).mpr (finset.mem_univ x)))
(mem_support.mp ((finset.ext_iff.mp h2 y).mpr (finset.mem_univ y))),
rw [h5, ←hi],
refine closure_cycle_coprime_swap (nat.coprime.symm
(h0.coprime_iff_not_dvd.mpr (λ h, h4 _))) h1 h2 x,
cases h with m hm,
rwa [hm, pow_mul, ←finset.card_univ, ←h2, ←order_of_is_cycle h1,
pow_order_of_eq_one, one_pow, one_apply] at hi,
end
end generation
section
variables [fintype α] {σ τ : perm α}
noncomputable theory
lemma is_conj_of_support_equiv (f : {x // x ∈ (σ.support : set α)} ≃ {x // x ∈ (τ.support : set α)})
(hf : ∀ (x : α) (hx : x ∈ (σ.support : set α)), (f ⟨σ x, apply_mem_support.2 hx⟩ : α) =
τ ↑(f ⟨x,hx⟩)) :
is_conj σ τ :=
begin
refine is_conj_iff.2 ⟨equiv.extend_subtype f, _⟩,
rw mul_inv_eq_iff_eq_mul,
ext,
simp only [perm.mul_apply],
by_cases hx : x ∈ σ.support,
{ rw [equiv.extend_subtype_apply_of_mem, equiv.extend_subtype_apply_of_mem],
{ exact hf x (finset.mem_coe.2 hx) } },
{ rwa [not_not.1 ((not_congr mem_support).1 (equiv.extend_subtype_not_mem f _ _)),
not_not.1 ((not_congr mem_support).mp hx)] }
end
theorem is_cycle.is_conj (hσ : is_cycle σ) (hτ : is_cycle τ) (h : σ.support.card = τ.support.card) :
is_conj σ τ :=
begin
refine is_conj_of_support_equiv (hσ.gpowers_equiv_support.symm.trans
((gpowers_equiv_gpowers begin
rw [order_of_is_cycle hσ, h, order_of_is_cycle hτ],
end).trans hτ.gpowers_equiv_support)) _,
intros x hx,
simp only [perm.mul_apply, equiv.trans_apply, equiv.sum_congr_apply],
obtain ⟨n, rfl⟩ := hσ.exists_pow_eq (classical.some_spec hσ).1 (mem_support.1 hx),
apply eq.trans _ (congr rfl (congr rfl (congr rfl
(congr rfl (hσ.gpowers_equiv_support_symm_apply n).symm)))),
apply (congr rfl (congr rfl (congr rfl (hσ.gpowers_equiv_support_symm_apply (n + 1))))).trans _,
simp only [ne.def, is_cycle.gpowers_equiv_support_apply,
subtype.coe_mk, gpowers_equiv_gpowers_apply],
rw [pow_succ, perm.mul_apply],
end
theorem is_cycle.is_conj_iff (hσ : is_cycle σ) (hτ : is_cycle τ) :
is_conj σ τ ↔ σ.support.card = τ.support.card :=
⟨begin
intro h,
obtain ⟨π, rfl⟩ := is_conj_iff.1 h,
apply finset.card_congr (λ a ha, π a) (λ _ ha, _) (λ _ _ _ _ ab, π.injective ab) (λ b hb, _),
{ simp [mem_support.1 ha] },
{ refine ⟨π⁻¹ b, ⟨_, π.apply_inv_self b⟩⟩,
contrapose! hb,
rw [mem_support, not_not] at hb,
rw [mem_support, not_not, perm.mul_apply, perm.mul_apply, hb, perm.apply_inv_self] }
end, hσ.is_conj hτ⟩
@[simp]
lemma support_conj : (σ * τ * σ⁻¹).support = τ.support.map σ.to_embedding :=
begin
ext,
simp only [mem_map_equiv, perm.coe_mul, comp_app, ne.def, perm.mem_support, equiv.eq_symm_apply],
refl,
end
lemma card_support_conj : (σ * τ * σ⁻¹).support.card = τ.support.card :=
by simp
end
theorem disjoint.is_conj_mul {α : Type*} [fintype α] {σ τ π ρ : perm α}
(hc1 : is_conj σ π) (hc2 : is_conj τ ρ)
(hd1 : disjoint σ τ) (hd2 : disjoint π ρ) :
is_conj (σ * τ) (π * ρ) :=
begin
classical,
obtain ⟨f, rfl⟩ := is_conj_iff.1 hc1,
obtain ⟨g, rfl⟩ := is_conj_iff.1 hc2,
have hd1' := coe_inj.2 hd1.support_mul,
have hd2' := coe_inj.2 hd2.support_mul,
rw [coe_union] at *,
have hd1'' := disjoint_iff_disjoint_coe.1 (disjoint_iff_disjoint_support.1 hd1),
have hd2'' := disjoint_iff_disjoint_coe.1 (disjoint_iff_disjoint_support.1 hd2),
refine is_conj_of_support_equiv _ _,
{ refine ((equiv.set.of_eq hd1').trans (equiv.set.union hd1'')).trans
((equiv.sum_congr (subtype_equiv f (λ a, _)) (subtype_equiv g (λ a, _))).trans
((equiv.set.of_eq hd2').trans (equiv.set.union hd2'')).symm);
{ simp only [set.mem_image, to_embedding_apply, exists_eq_right,
support_conj, coe_map, apply_eq_iff_eq] } },
{ intros x hx,
simp only [trans_apply, symm_trans_apply, set.of_eq_apply,
set.of_eq_symm_apply, equiv.sum_congr_apply],
rw [hd1', set.mem_union] at hx,
cases hx with hxσ hxτ,
{ rw [mem_coe, mem_support] at hxσ,
rw [set.union_apply_left hd1'' _, set.union_apply_left hd1'' _],
simp only [subtype_equiv_apply, perm.coe_mul, sum.map_inl, comp_app,
set.union_symm_apply_left, subtype.coe_mk, apply_eq_iff_eq],
{ have h := (hd2 (f x)).resolve_left _,
{ rw [mul_apply, mul_apply] at h,
rw [h, inv_apply_self, (hd1 x).resolve_left hxσ] },
{ rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq] } },
{ rwa [subtype.coe_mk, subtype.coe_mk, mem_coe, mem_support] },
{ rwa [subtype.coe_mk, subtype.coe_mk, perm.mul_apply,
(hd1 x).resolve_left hxσ, mem_coe, apply_mem_support, mem_support] } },
{ rw [mem_coe, ← apply_mem_support, mem_support] at hxτ,
rw [set.union_apply_right hd1'' _, set.union_apply_right hd1'' _],
simp only [subtype_equiv_apply, perm.coe_mul, sum.map_inr, comp_app,
set.union_symm_apply_right, subtype.coe_mk, apply_eq_iff_eq],
{ have h := (hd2 (g (τ x))).resolve_right _,
{ rw [mul_apply, mul_apply] at h,
rw [inv_apply_self, h, (hd1 (τ x)).resolve_right hxτ] },
{ rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq] } },
{ rwa [subtype.coe_mk, subtype.coe_mk, mem_coe, ← apply_mem_support, mem_support] },
{ rwa [subtype.coe_mk, subtype.coe_mk, perm.mul_apply,
(hd1 (τ x)).resolve_right hxτ, mem_coe, mem_support] } } }
end
section fixed_points
/-!
### Fixed points
-/
lemma fixed_point_card_lt_of_ne_one [fintype α] {σ : perm α} (h : σ ≠ 1) :
(filter (λ x, σ x = x) univ).card < fintype.card α - 1 :=
begin
rw [nat.lt_sub_left_iff_add_lt, ← nat.lt_sub_right_iff_add_lt, ← finset.card_compl,
finset.compl_filter],
exact one_lt_card_support_of_ne_one h
end
end fixed_points
end equiv.perm
|
f1e5e5c39692b35102ce95f90657bb59eaec9219 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/inner_product_space/lax_milgram.lean | 27354056f5634aa7ba5ecb168c54ab87c1cb634b | [
"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,794 | lean | /-
Copyright (c) 2022 Daniel Roca González. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Roca González
-/
import analysis.inner_product_space.projection
import analysis.inner_product_space.dual
import analysis.normed_space.banach
import analysis.normed_space.operator_norm
import topology.metric_space.antilipschitz
/-!
# The Lax-Milgram Theorem
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We consider an Hilbert space `V` over `ℝ`
equipped with a bounded bilinear form `B : V →L[ℝ] V →L[ℝ] ℝ`.
Recall that a bilinear form `B : V →L[ℝ] V →L[ℝ] ℝ` is *coercive*
iff `∃ C, (0 < C) ∧ ∀ u, C * ‖u‖ * ‖u‖ ≤ B u u`.
Under the hypothesis that `B` is coercive
we prove the Lax-Milgram theorem:
that is, the map `inner_product_space.continuous_linear_map_of_bilin` from
`analysis.inner_product_space.dual` can be upgraded to a continuous equivalence
`is_coercive.continuous_linear_equiv_of_bilin : V ≃L[ℝ] V`.
## References
* We follow the notes of Peter Howard's Spring 2020 *M612: Partial Differential Equations* lecture,
see[howard]
## Tags
dual, Lax-Milgram
-/
noncomputable theory
open is_R_or_C linear_map continuous_linear_map inner_product_space linear_map (ker range)
open_locale real_inner_product_space nnreal
universe u
namespace is_coercive
variables {V : Type u} [normed_add_comm_group V] [inner_product_space ℝ V] [complete_space V]
variables {B : V →L[ℝ] V →L[ℝ] ℝ}
local postfix `♯`:1025 := @continuous_linear_map_of_bilin ℝ V _ _ _ _
lemma bounded_below (coercive : is_coercive B) :
∃ C, 0 < C ∧ ∀ v, C * ‖v‖ ≤ ‖B♯ v‖ :=
begin
rcases coercive with ⟨C, C_ge_0, coercivity⟩,
refine ⟨C, C_ge_0, _⟩,
intro v,
by_cases h : 0 < ‖v‖,
{ refine (mul_le_mul_right h).mp _,
calc C * ‖v‖ * ‖v‖
≤ B v v : coercivity v
... = ⟪B♯ v, v⟫_ℝ : (continuous_linear_map_of_bilin_apply ℝ B v v).symm
... ≤ ‖B♯ v‖ * ‖v‖ : real_inner_le_norm (B♯ v) v, },
{ have : v = 0 := by simpa using h,
simp [this], }
end
lemma antilipschitz (coercive : is_coercive B) :
∃ C : ℝ≥0, 0 < C ∧ antilipschitz_with C B♯ :=
begin
rcases coercive.bounded_below with ⟨C, C_pos, below_bound⟩,
refine ⟨(C⁻¹).to_nnreal, real.to_nnreal_pos.mpr (inv_pos.mpr C_pos), _⟩,
refine continuous_linear_map.antilipschitz_of_bound B♯ _,
simp_rw [real.coe_to_nnreal',
max_eq_left_of_lt (inv_pos.mpr C_pos),
←inv_mul_le_iff (inv_pos.mpr C_pos)],
simpa using below_bound,
end
lemma ker_eq_bot (coercive : is_coercive B) : ker B♯ = ⊥ :=
begin
rw [linear_map_class.ker_eq_bot],
rcases coercive.antilipschitz with ⟨_, _, antilipschitz⟩,
exact antilipschitz.injective,
end
lemma closed_range (coercive : is_coercive B) : is_closed (range B♯ : set V) :=
begin
rcases coercive.antilipschitz with ⟨_, _, antilipschitz⟩,
exact antilipschitz.is_closed_range B♯.uniform_continuous,
end
lemma range_eq_top (coercive : is_coercive B) : range B♯ = ⊤ :=
begin
haveI := coercive.closed_range.complete_space_coe,
rw ← (range B♯).orthogonal_orthogonal,
rw submodule.eq_top_iff',
intros v w mem_w_orthogonal,
rcases coercive with ⟨C, C_pos, coercivity⟩,
obtain rfl : w = 0,
{ rw [←norm_eq_zero, ←mul_self_eq_zero, ←mul_right_inj' C_pos.ne', mul_zero, ←mul_assoc],
apply le_antisymm,
{ calc C * ‖w‖ * ‖w‖
≤ B w w : coercivity w
... = ⟪B♯ w, w⟫_ℝ : (continuous_linear_map_of_bilin_apply ℝ B w w).symm
... = 0 : mem_w_orthogonal _ ⟨w, rfl⟩ },
{ exact mul_nonneg (mul_nonneg C_pos.le (norm_nonneg w)) (norm_nonneg w) } },
exact inner_zero_left _,
end
/--
The Lax-Milgram equivalence of a coercive bounded bilinear operator:
for all `v : V`, `continuous_linear_equiv_of_bilin B v` is the unique element `V`
such that `⟪continuous_linear_equiv_of_bilin B v, w⟫ = B v w`.
The Lax-Milgram theorem states that this is a continuous equivalence.
-/
def continuous_linear_equiv_of_bilin (coercive : is_coercive B) : V ≃L[ℝ] V :=
continuous_linear_equiv.of_bijective
B♯
coercive.ker_eq_bot
coercive.range_eq_top
@[simp]
lemma continuous_linear_equiv_of_bilin_apply (coercive : is_coercive B) (v w : V) :
⟪coercive.continuous_linear_equiv_of_bilin v, w⟫_ℝ = B v w :=
continuous_linear_map_of_bilin_apply ℝ B v w
lemma unique_continuous_linear_equiv_of_bilin (coercive : is_coercive B) {v f : V}
(is_lax_milgram : (∀ w, ⟪f, w⟫_ℝ = B v w)) :
f = coercive.continuous_linear_equiv_of_bilin v :=
unique_continuous_linear_map_of_bilin ℝ B is_lax_milgram
end is_coercive
|
65412edcb88ddae61a2c261202c3d88cb23140f8 | 9c1ad797ec8a5eddb37d34806c543602d9a6bf70 | /monoidal_categories/internal_objects/monoids.lean | baaa0265bd39c48e4b59133b644031bebf6d8682 | [] | no_license | timjb/lean-category-theory | 816eefc3a0582c22c05f4ee1c57ed04e57c0982f | 12916cce261d08bb8740bc85e0175b75fb2a60f4 | refs/heads/master | 1,611,078,926,765 | 1,492,080,000,000 | 1,492,080,000,000 | 88,348,246 | 0 | 0 | null | 1,492,262,499,000 | 1,492,262,498,000 | null | UTF-8 | Lean | false | false | 1,051 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison
import .semigroups
open tqft.categories
open tqft.categories.monoidal_category
namespace tqft.categories.internal_objects
structure MonoidObject { C : Category } ( m : MonoidalStructure C ) extends SemigroupObject m :=
( unit : C.Hom m.tensor_unit object )
( left_identity : C.compose (m.tensorMorphisms unit (C.identity object)) multiplication = C.compose (m.left_unitor object) (C.identity object) )
( right_identity : C.compose (m.tensorMorphisms (C.identity object) unit) multiplication = C.compose (m.right_unitor object) (C.identity object) )
attribute [simp,ematch] MonoidObject.left_identity
attribute [simp,ematch] MonoidObject.right_identity
-- instance MonoidObject_coercion_to_SemigroupObject { C : MonoidalCategory } : has_coe (MonoidObject C) (SemigroupObject C) :=
-- { coe := MonoidObject.to_SemigroupObject }
end tqft.categories.internal_objects |
8707679f7d1a96dcce1e0e940794d0e8da0dc292 | 5749d8999a76f3a8fddceca1f6941981e33aaa96 | /src/linear_algebra/basic.lean | 6c094b260ce59cc72f8a49476bf4ec99be9d0831 | [
"Apache-2.0"
] | permissive | jdsalchow/mathlib | 13ab43ef0d0515a17e550b16d09bd14b76125276 | 497e692b946d93906900bb33a51fd243e7649406 | refs/heads/master | 1,585,819,143,348 | 1,580,072,892,000 | 1,580,072,892,000 | 154,287,128 | 0 | 0 | Apache-2.0 | 1,540,281,610,000 | 1,540,281,609,000 | null | UTF-8 | Lean | false | false | 72,511 | 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, Kevin Buzzard
-/
import algebra.pi_instances data.finsupp data.equiv.algebra order.order_iso
/-!
# Linear algebra
This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of
modules over a ring, submodules, and linear maps. If `p` and `q` are submodules of a module, `p ≤ q`
means that `p ⊆ q`.
Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in
`src/algebra/module.lean`.
## Main definitions
* Many constructors for linear maps, including `pair` and `copair`
* `submodule.span s` is defined to be the smallest submodule containing the set `s`.
* If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`:
that is, elements of `M` are identified if their difference is in `p`. This is itself a module.
* The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain
respectively.
* `linear_equiv M M₂`, the type of linear equivalences between `M` and `M₂`, is a structure that
extends `linear_map` and `equiv`.
* The general linear group is defined to be the group of invertible linear maps from `M` to itself.
## Main statements
* The first and second isomorphism laws for modules are proved as `quot_ker_equiv_range` and
`sup_quotient_equiv_quotient_inf`.
## Notations
* We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the
ring `R`.
* We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the
ring `R` is implicit.
## Implementation notes
We note that, when constructing linear maps, it is convenient to use operations defined on bundled
maps (`pair`, `copair`, arithmetic operations like `+`) instead of defining a function and proving
it is linear.
## Tags
linear algebra, vector space, module
-/
open function lattice
reserve infix ` ≃ₗ `:25
universes u v w x y z u' v' w' y'
variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'}
variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x}
namespace finsupp
lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y}
[has_zero β] [ring R] [add_comm_group M] [module R M]
{v : α →₀ β} {c : R} {h : α → β → M} :
c • (v.sum h) = v.sum (λa b, c • h a b) :=
finset.smul_sum
end finsupp
section
open_locale classical
/-- decomposing `x : ι → R` as a sum along the canonical basis -/
lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) :
x = finset.sum finset.univ (λi:ι, x i • (λj, if i = j then 1 else 0)) :=
begin
ext k,
rw pi.finset_sum_apply,
have : finset.sum finset.univ (λ (x_1 : ι), x x_1 * ite (k = x_1) 1 0) = x k,
by { have := finset.sum_mul_boole finset.univ x k, rwa if_pos (finset.mem_univ _) at this },
rw ← this,
apply finset.sum_congr rfl (λl hl, _),
simp only [smul_eq_mul, mul_ite, pi.smul_apply],
conv_lhs { rw eq_comm }
end
end
namespace linear_map
section
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄]
variables [module R M] [module R M₂] [module R M₃] [module R M₄]
variables (f g : M →ₗ[R] M₂)
include R
@[simp] theorem comp_id : f.comp id = f :=
linear_map.ext $ λ x, rfl
@[simp] theorem id_comp : id.comp f = f :=
linear_map.ext $ λ x, rfl
theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) :=
rfl
/-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a
linear map M₂ → p. -/
def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p :=
by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp
@[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) :
(cod_restrict p f h x : M) = f x := rfl
@[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) :
(cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) :=
ext $ assume b, rfl
@[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) :
p.subtype.comp (cod_restrict p f h) = f :=
ext $ assume b, rfl
/-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/
def inverse (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M :=
by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact
⟨g, λ x y, by rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂],
λ a b, by rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂]⟩
/-- The constant 0 map is linear. -/
instance : has_zero (M →ₗ[R] M₂) := ⟨⟨λ _, 0, by simp, by simp⟩⟩
@[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl
/-- The negation of a linear map is linear. -/
instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, ⟨λ b, - f b, by simp, by simp⟩⟩
@[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl
/-- The sum of two linear maps is linear. -/
instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b + g b, by simp, by simp [smul_add]⟩⟩
@[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl
/-- The type of linear maps is an additive group. -/
instance : add_comm_group (M →ₗ[R] M₂) :=
by refine {zero := 0, add := (+), neg := has_neg.neg, ..};
intros; ext; simp
instance linear_map.is_add_group_hom : is_add_group_hom f :=
{ map_add := f.add }
instance linear_map_apply_is_add_group_hom (a : M) :
is_add_group_hom (λ f : M →ₗ[R] M₂, f a) :=
{ map_add := λ f g, linear_map.add_apply f g a }
lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) :
t.sum f b = t.sum (λd, f d b) :=
(t.sum_hom (λ g : M →ₗ[R] M₂, g b)).symm
@[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl
/-- `λb, f b • x` is a linear map. -/
def smul_right (f : M₂ →ₗ[R] R) (x : M) : M₂ →ₗ[R] M :=
⟨λb, f b • x, by simp [add_smul], by simp [smul_smul]⟩.
@[simp] theorem smul_right_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) :
(smul_right f x : M₂ → M) c = f c • x := rfl
instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩
instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩
@[simp] lemma one_app (x : M) : (1 : M →ₗ[R] M) x = x := rfl
@[simp] lemma mul_app (A B : M →ₗ[R] M) (x : M) : (A * B) x = A (B x) := rfl
@[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 :=
ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero]
@[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 :=
rfl
section
variables (R M)
include M
instance endomorphism_ring : ring (M →ₗ[R] M) :=
by refine {mul := (*), one := 1, ..linear_map.add_comm_group, ..};
{ intros, apply linear_map.ext, simp }
end
section
open_locale classical
/-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements
of the canonical basis. -/
lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) :
f x = finset.sum finset.univ (λi:ι, x i • (f (λj, if i = j then 1 else 0))) :=
begin
conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] },
apply finset.sum_congr rfl (λl hl, _),
rw f.map_smul
end
end
section
variables (R M M₂)
/-- The first projection of a product is a linear map. -/
def fst : M × M₂ →ₗ[R] M := ⟨prod.fst, λ x y, rfl, λ x y, rfl⟩
/-- The second projection of a product is a linear map. -/
def snd : M × M₂ →ₗ[R] M₂ := ⟨prod.snd, λ x y, rfl, λ x y, rfl⟩
end
@[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl
@[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl
/-- The pair of two linear maps is a linear map. -/
def pair (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : M →ₗ[R] M₂ × M₃ :=
⟨λ x, (f x, g x), λ x y, by simp, λ x y, by simp⟩
@[simp] theorem pair_apply (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (x : M) :
pair f g x = (f x, g x) := rfl
@[simp] theorem fst_pair (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) :
(fst R M₂ M₃).comp (pair f g) = f := by ext; refl
@[simp] theorem snd_pair (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) :
(snd R M₂ M₃).comp (pair f g) = g := by ext; refl
@[simp] theorem pair_fst_snd : pair (fst R M M₂) (snd R M M₂) = linear_map.id :=
by ext; refl
section
variables (R M M₂)
/-- The left injection into a product is a linear map. -/
def inl : M →ₗ[R] M × M₂ := by refine ⟨prod.inl, _, _⟩; intros; simp [prod.inl]
/-- The right injection into a product is a linear map. -/
def inr : M₂ →ₗ[R] M × M₂ := by refine ⟨prod.inr, _, _⟩; intros; simp [prod.inr]
end
@[simp] theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl
@[simp] theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl
/-- The copair function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/
def copair (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ :=
⟨λ x, f x.1 + g x.2, λ x y, by simp, λ x y, by simp [smul_add]⟩
@[simp] theorem copair_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M) (y : M₂) :
copair f g (x, y) = f x + g y := rfl
@[simp] theorem copair_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) :
(copair f g).comp (inl R M M₂) = f := by ext; simp
@[simp] theorem copair_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) :
(copair f g).comp (inr R M M₂) = g := by ext; simp
@[simp] theorem copair_inl_inr : copair (inl R M M₂) (inr R M M₂) = linear_map.id :=
by ext ⟨x, y⟩; simp
theorem fst_eq_copair : fst R M M₂ = copair linear_map.id 0 := by ext ⟨x, y⟩; simp
theorem snd_eq_copair : snd R M M₂ = copair 0 linear_map.id := by ext ⟨x, y⟩; simp
theorem inl_eq_pair : inl R M M₂ = pair linear_map.id 0 := rfl
theorem inr_eq_pair : inr R M M₂ = pair 0 linear_map.id := rfl
end
section comm_ring
variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
variables (f g : M →ₗ[R] M₂)
include R
instance : has_scalar R (M →ₗ[R] M₂) := ⟨λ a f,
⟨λ b, a • f b, by simp [smul_add], by simp [smul_smul, mul_comm]⟩⟩
@[simp] lemma smul_apply (a : R) (x : M) : (a • f) x = a • f x := rfl
instance : module R (M →ₗ[R] M₂) :=
module.of_core $ by refine { smul := (•), ..};
intros; ext; simp [smul_add, add_smul, smul_smul]
/-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of
linear maps `M₂ → M₃`. -/
def congr_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) :=
⟨linear_map.comp f,
λ _ _, linear_map.ext $ λ _, f.2 _ _,
λ _ _, linear_map.ext $ λ _, f.3 _ _⟩
theorem smul_comp (g : M₂ →ₗ[R] M₃) (a : R) : (a • g).comp f = a • (g.comp f) :=
rfl
theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) :=
ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl
end comm_ring
end linear_map
namespace submodule
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
variables (p p' : submodule R M) (q q' : submodule R M₂)
variables {r : R} {x y : M}
open set lattice
instance : partial_order (submodule R M) :=
partial_order.lift (coe : submodule R M → set M) (λ a b, ext') (by apply_instance)
variables {p p'}
lemma le_def : p ≤ p' ↔ (p : set M) ⊆ p' := iff.rfl
lemma le_def' : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl
lemma lt_def : p < p' ↔ (p : set M) ⊂ p' := iff.rfl
lemma not_le_iff_exists : ¬ (p ≤ p') ↔ ∃ x ∈ p, x ∉ p' := not_subset
lemma exists_of_lt {p p' : submodule R M} : p < p' → ∃ x ∈ p', x ∉ p := exists_of_ssubset
lemma lt_iff_le_and_exists : p < p' ↔ p ≤ p' ∧ ∃ x ∈ p', x ∉ p :=
by rw [lt_iff_le_not_le, not_le_iff_exists]
/-- If two submodules p and p' satisfy p ⊆ p', then `of_le p p'` is the linear map version of this
inclusion. -/
def of_le (h : p ≤ p') : p →ₗ[R] p' :=
linear_map.cod_restrict _ p.subtype $ λ ⟨x, hx⟩, h hx
@[simp] theorem of_le_apply (h : p ≤ p')
(x : p) : (of_le h x : M) = x := rfl
variables (p p')
lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) :
(submodule.subtype q).comp (of_le h) = submodule.subtype p :=
by ext ⟨b, hb⟩; simp
/-- The set `{0}` is the bottom element of the lattice of submodules. -/
instance : has_bot (submodule R M) :=
⟨by split; try {exact {0}}; simp {contextual := tt}⟩
@[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl
section
variables (R)
@[simp] lemma mem_bot : x ∈ (⊥ : submodule R M) ↔ x = 0 := mem_singleton_iff
end
instance : order_bot (submodule R M) :=
{ bot := ⊥,
bot_le := λ p x, by simp {contextual := tt},
..submodule.partial_order }
/-- The universal set is the top element of the lattice of submodules. -/
instance : has_top (submodule R M) :=
⟨by split; try {exact set.univ}; simp⟩
@[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = univ := rfl
@[simp] lemma mem_top : x ∈ (⊤ : submodule R M) := trivial
lemma eq_bot_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : p = ⊥ :=
by ext x; simp [semimodule.eq_zero_of_zero_eq_one x zero_eq_one]
instance : order_top (submodule R M) :=
{ top := ⊤,
le_top := λ p x _, trivial,
..submodule.partial_order }
instance : has_Inf (submodule R M) :=
⟨λ S, {
carrier := ⋂ s ∈ S, ↑s,
zero := by simp,
add := by simp [add_mem] {contextual := tt},
smul := by simp [smul_mem] {contextual := tt} }⟩
private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p :=
bInter_subset_of_mem
private lemma le_Inf' {S : set (submodule R M)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S :=
subset_bInter
instance : has_inf (submodule R M) :=
⟨λ p p', {
carrier := p ∩ p',
zero := by simp,
add := by simp [add_mem] {contextual := tt},
smul := by simp [smul_mem] {contextual := tt} }⟩
instance : complete_lattice (submodule R M) :=
{ sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x},
le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha,
le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb,
sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩,
inf := (⊓),
le_inf := λ a b c, subset_inter,
inf_le_left := λ a b, inter_subset_left _ _,
inf_le_right := λ a b, inter_subset_right _ _,
Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t},
le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ hs,
Sup_le := λ s p hs, Inf_le' hs,
Inf := Inf,
le_Inf := λ s a, le_Inf',
Inf_le := λ s a, Inf_le',
..submodule.lattice.order_top,
..submodule.lattice.order_bot }
instance : add_comm_monoid (submodule R M) :=
{ add := (⊔),
add_assoc := λ _ _ _, sup_assoc,
zero := ⊥,
zero_add := λ _, bot_sup_eq,
add_zero := λ _, sup_bot_eq,
add_comm := λ _ _, sup_comm }
@[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl
@[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl
lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p :=
eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩
@[simp] theorem inf_coe : (p ⊓ p' : set M) = p ∩ p' := rfl
@[simp] theorem mem_inf {p p' : submodule R M} :
x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
@[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl
@[simp] theorem infi_coe {ι} (p : ι → submodule R M) :
(↑⨅ i, p i : set M) = ⋂ i, ↑(p i) :=
by rw [infi, Inf_coe]; ext a; simp; exact
⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩
@[simp] theorem mem_infi {ι} (p : ι → submodule R M) :
x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i :=
by rw [← mem_coe, infi_coe, mem_Inter]; refl
theorem disjoint_def {p p' : submodule R M} :
disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) :=
show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp
/-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/
def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ :=
{ carrier := f '' p,
zero := ⟨0, p.zero_mem, f.map_zero⟩,
add := by rintro _ _ ⟨b₁, hb₁, rfl⟩ ⟨b₂, hb₂, rfl⟩;
exact ⟨_, p.add_mem hb₁ hb₂, f.map_add _ _⟩,
smul := by rintro a _ ⟨b, hb, rfl⟩;
exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩ }
lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) :
(map f p : set M₂) = f '' p := rfl
@[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} :
x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl
theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p :=
set.mem_image_of_mem _ h
lemma map_id : map linear_map.id p = p :=
submodule.ext $ λ a, by simp
lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) :
map (g.comp f) p = map g (map f p) :=
submodule.ext' $ by simp [map_coe]; rw ← image_comp
lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' :=
image_subset _
@[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ :=
have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩,
ext $ by simp [this, eq_comm]
/-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/
def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M :=
{ carrier := f ⁻¹' p,
zero := by simp,
add := λ x y h₁ h₂, by simp [p.add_mem h₁ h₂],
smul := λ a x h, by simp [p.smul_mem _ h] }
@[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) :
(comap f p : set M) = f ⁻¹' p := rfl
@[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} :
x ∈ comap f p ↔ f x ∈ p := iff.rfl
lemma comap_id : comap linear_map.id p = p :=
submodule.ext' rfl
lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) :
comap (g.comp f) p = comap f (comap g p) := rfl
lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' :=
preimage_mono
lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} :
map f p ≤ q ↔ p ≤ comap f q := image_subset_iff
lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f)
| p q := map_le_iff_le_comap
@[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' :=
(gc_map_comap f).l_sup
@[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) :
map f (⨆i, p i) = (⨆i, map f (p i)) :=
(gc_map_comap f).l_supr
@[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl
@[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl
@[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) :
comap f (⨅i, p i) = (⨅i, comap f (p i)) :=
(gc_map_comap f).u_infi
@[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ :=
ext $ by simp
lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q :=
(gc_map_comap f).l_u_le _
lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) :=
(gc_map_comap f).le_u_l _
--TODO(Mario): is there a way to prove this from order properties?
lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂}
{p : submodule R M} {p' : submodule R M₂} :
map f p ⊓ p' = map f (p ⊓ comap f p') :=
le_antisymm
(by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩)
(le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right))
lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' :=
ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩
lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0
| ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb
section
variables (R)
/-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/
def span (s : set M) : submodule R M := Inf {p | s ⊆ p}
end
variables {s t : set M}
lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p :=
mem_bInter_iff
lemma subset_span : s ⊆ span R s :=
λ x h, mem_span.2 $ λ p hp, hp h
lemma span_le {p} : span R s ≤ p ↔ s ⊆ p :=
⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩
lemma span_mono (h : s ⊆ t) : span R s ≤ span R t :=
span_le.2 $ subset.trans h subset_span
lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p :=
le_antisymm (span_le.2 h₁) h₂
@[simp] lemma span_eq : span R (p : set M) = p :=
span_eq_of_le _ (subset.refl _) subset_span
/-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is
preserved under addition and scalar multiplication, then `p` holds for all elements of the span of
`s`. -/
@[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0)
(H1 : ∀ x y, p x → p y → p (x + y))
(H2 : ∀ (a:R) x, p x → p (a • x)) : p x :=
(@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h
section
variables (R M)
/-- `span` forms a Galois insertion with the coercion from submodule to set. -/
protected def gi : galois_insertion (@span R M _ _ _) coe :=
{ choice := λ s _, span R s,
gc := λ s t, span_le,
le_l_u := λ s, subset_span,
choice_eq := λ s h, rfl }
end
@[simp] lemma span_empty : span R (∅ : set M) = ⊥ :=
(submodule.gi R M).gc.l_bot
@[simp] lemma span_univ : span R (univ : set M) = ⊤ :=
eq_top_iff.2 $ le_def.2 $ subset_span
lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t :=
(submodule.gi R M).gc.l_sup
lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) :=
(submodule.gi R M).gc.l_supr
@[simp] theorem Union_coe_of_directed {ι} (hι : nonempty ι)
(S : ι → submodule R M)
(H : ∀ i j, ∃ k, S i ≤ S k ∧ S j ≤ S k) :
((supr S : submodule R M) : set M) = ⋃ i, S i :=
begin
refine subset.antisymm _ (Union_subset $ le_supr S),
rw [show supr S = ⨆ i, span R (S i), by simp, ← span_Union],
unfreezeI,
refine λ x hx, span_induction hx (λ _, id) _ _ _,
{ cases hι with i, exact mem_Union.2 ⟨i, by simp⟩ },
{ simp, intros x y i hi j hj,
rcases H i j with ⟨k, ik, jk⟩,
exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ },
{ simp [-mem_coe]; exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ },
end
lemma mem_supr_of_mem {ι : Sort*} {b : M} (p : ι → submodule R M) (i : ι) (h : b ∈ p i) :
b ∈ (⨆i, p i) :=
have p i ≤ (⨆i, p i) := le_supr p i,
@this b h
@[simp] theorem mem_supr_of_directed {ι} (hι : nonempty ι)
(S : ι → submodule R M)
(H : ∀ i j, ∃ k, S i ≤ S k ∧ S j ≤ S k) {x} :
x ∈ supr S ↔ ∃ i, x ∈ S i :=
by rw [← mem_coe, Union_coe_of_directed hι S H, mem_Union]; refl
theorem mem_Sup_of_directed {s : set (submodule R M)}
{z} (hzs : z ∈ Sup s) (x ∈ s)
(hdir : ∀ i ∈ s, ∀ j ∈ s, ∃ k ∈ s, i ≤ k ∧ j ≤ k) :
∃ y ∈ s, z ∈ y :=
begin
haveI := classical.dec, rw Sup_eq_supr at hzs,
have : ∃ (i : submodule R M), z ∈ ⨆ (H : i ∈ s), i,
{ refine (mem_supr_of_directed ⟨⊥⟩ _ (λ i j, _)).1 hzs,
by_cases his : i ∈ s; by_cases hjs : j ∈ s,
{ rcases hdir i his j hjs with ⟨k, hks, hik, hjk⟩,
exact ⟨k, le_supr_of_le hks (supr_le $ λ _, hik),
le_supr_of_le hks (supr_le $ λ _, hjk)⟩ },
{ exact ⟨i, le_refl _, supr_le $ hjs.elim⟩ },
{ exact ⟨j, supr_le $ his.elim, le_refl _⟩ },
{ exact ⟨⊥, supr_le $ his.elim, supr_le $ hjs.elim⟩ } },
cases this with N hzn, by_cases hns : N ∈ s,
{ have : (⨆ (H : N ∈ s), N) ≤ N := supr_le (λ _, le_refl _),
exact ⟨N, hns, this hzn⟩ },
{ have : (⨆ (H : N ∈ s), N) ≤ ⊥ := supr_le hns.elim,
cases (mem_bot R).1 (this hzn), exact ⟨x, H, x.zero_mem⟩ }
end
section
variables {p p'}
lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x :=
⟨λ h, begin
rw [← span_eq p, ← span_eq p', ← span_union] at h,
apply span_induction h,
{ rintro y (h | h),
{ exact ⟨y, h, 0, by simp, by simp⟩ },
{ exact ⟨0, by simp, y, h, by simp⟩ } },
{ exact ⟨0, by simp, 0, by simp⟩ },
{ rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩,
exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp⟩ },
{ rintro a _ ⟨y, hy, z, hz, rfl⟩,
exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ }
end,
by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _
((le_sup_left : p ≤ p ⊔ p') hy)
((le_sup_right : p' ≤ p ⊔ p') hz)⟩
end
lemma mem_span_singleton {y : M} : x ∈ span R ({y} : set M) ↔ ∃ a:R, a • y = x :=
⟨λ h, begin
apply span_induction h,
{ rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ },
{ exact ⟨0, by simp⟩ },
{ rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩,
exact ⟨a + b, by simp [add_smul]⟩ },
{ rintro a _ ⟨b, rfl⟩,
exact ⟨a * b, by simp [smul_smul]⟩ }
end,
by rintro ⟨a, y, rfl⟩; exact
smul_mem _ _ (subset_span $ by simp)⟩
lemma span_singleton_eq_range (y : M) : (span R ({y} : set M) : set M) = range ((• y) : R → M) :=
set.ext $ λ x, mem_span_singleton
lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z :=
begin
rw [← union_singleton, span_union, mem_sup],
simp [mem_span_singleton], split,
{ rintro ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩, exact ⟨a, z, hz, rfl⟩ },
{ rintro ⟨a, z, hz, rfl⟩, exact ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩ }
end
lemma mem_span_insert' {y} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s :=
begin
rw mem_span_insert, split,
{ rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz]⟩ },
{ rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp⟩ }
end
lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s :=
span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _)
lemma span_span : span R (span R s : set M) = span R s := span_eq _
lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 :=
eq_bot_iff.trans ⟨
λ H x h, (mem_bot R).1 $ H $ subset_span h,
λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩
lemma span_singleton_eq_bot : span R ({x} : set M) = ⊥ ↔ x = 0 :=
span_eq_bot.trans $ by simp
@[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) :=
span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $
span_le.2 $ image_subset_iff.1 subset_span
lemma linear_eq_on (s : set M) {f g : M →ₗ[R] M₂} (H : ∀x∈s, f x = g x) {x} (h : x ∈ span R s) :
f x = g x :=
by apply span_induction h H; simp {contextual := tt}
/-- The product of two submodules is a submodule. -/
def prod : submodule R (M × M₂) :=
{ carrier := set.prod p q,
zero := ⟨zero_mem _, zero_mem _⟩,
add := by rintro ⟨x₁, y₁⟩ ⟨x₂, y₂⟩ ⟨hx₁, hy₁⟩ ⟨hx₂, hy₂⟩;
exact ⟨add_mem _ hx₁ hx₂, add_mem _ hy₁ hy₂⟩,
smul := by rintro a ⟨x, y⟩ ⟨hx, hy⟩;
exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩ }
@[simp] lemma prod_coe :
(prod p q : set (M × M₂)) = set.prod p q := rfl
@[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} :
x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod
lemma span_prod_le (s : set M) (t : set M₂) :
span R (set.prod s t) ≤ prod (span R s) (span R t) :=
span_le.2 $ set.prod_mono subset_span subset_span
@[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ :=
by ext; simp
@[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ :=
by ext ⟨x, y⟩; simp [prod.zero_eq_mk]
lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} :
p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono
@[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') :=
ext' set.prod_inter_prod
@[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') :=
begin
refine le_antisymm (sup_le
(prod_mono le_sup_left le_sup_left)
(prod_mono le_sup_right le_sup_right)) _,
simp [le_def'], intros xx yy hxx hyy,
rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩,
rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩,
refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩
end
-- TODO(Mario): Factor through add_subgroup
/-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/
def quotient_rel : setoid M :=
⟨λ x y, x - y ∈ p, λ x, by simp,
λ x y h, by simpa using neg_mem _ h,
λ x y z h₁ h₂, by simpa using add_mem _ h₁ h₂⟩
/-- The quotient of a module `M` by a submodule `p ⊆ M`. -/
def quotient : Type* := quotient (quotient_rel p)
namespace quotient
/-- Map associating to an element of `M` the corresponding element of `M/p`,
when `p` is a submodule of `M`. -/
def mk {p : submodule R M} : M → quotient p := quotient.mk'
@[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl
@[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl
@[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl
protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq'
instance : has_zero (quotient p) := ⟨mk 0⟩
@[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl
@[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p :=
by simpa using (quotient.eq p : mk x = 0 ↔ _)
instance : has_add (quotient p) :=
⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $
λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa using add_mem p h₁ h₂⟩
@[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl
instance : has_neg (quotient p) :=
⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $
λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩
@[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl
instance : add_comm_group (quotient p) :=
by refine {zero := 0, add := (+), neg := has_neg.neg, ..};
repeat {rintro ⟨⟩};
simp [-mk_zero, (mk_zero p).symm, -mk_add, (mk_add p).symm, -mk_neg, (mk_neg p).symm]
instance : has_scalar R (quotient p) :=
⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $
λ x y h, (quotient.eq p).2 $ by simpa [smul_add] using smul_mem p a h⟩
@[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl
instance : module R (quotient p) :=
module.of_core $ by refine {smul := (•), ..};
repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul,
-mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm]
end quotient
end submodule
namespace submodule
variables [discrete_field K]
variables [add_comm_group V] [vector_space K V]
variables [add_comm_group V₂] [vector_space K V₂]
lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) :
p.comap (a • f) = p.comap f :=
by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply]
lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) :
p.map (a • f) = p.map f :=
le_antisymm
begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end
begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end
set_option class.instance_max_depth 40
lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) :
p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) :=
by by_cases a = 0; simp [h, comap_smul]
lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) :
p.map (a • f) = (⨆ h : a ≠ 0, p.map f) :=
by by_cases a = 0; simp [h, map_smul]
end submodule
namespace linear_map
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
include R
open submodule
@[simp] lemma finsupp_sum {R M M₂ γ} [ring R] [add_comm_group M] [module R M]
[add_comm_group M₂] [module R M₂] [has_zero γ]
(f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} :
f (t.sum g) = t.sum (λi d, f (g i d)) := f.map_sum
theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') :
submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) :=
submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.coe_ext]
theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') :
submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') :=
submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩
/-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. -/
def range (f : M →ₗ[R] M₂) : submodule R M₂ := map f ⊤
theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := set.image_univ
@[simp] theorem mem_range {f : M →ₗ[R] M₂} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x :=
(set.ext_iff _ _).1 (range_coe f).
@[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := map_id _
theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) :=
map_comp _ _ _
theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g :=
by rw range_comp; exact map_mono le_top
theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f :=
by rw [← submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective]
lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ :=
by rw [range, map_le_iff_le_comap, eq_top_iff]
lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f :=
map_mono le_top
lemma sup_range_inl_inr :
(inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ :=
begin
refine eq_top_iff'.2 (λ x, mem_sup.2 _),
rcases x with ⟨x₁, x₂⟩ ,
have h₁ : prod.mk x₁ (0 : M₂) ∈ (inl R M M₂).range,
by simp,
have h₂ : prod.mk (0 : M) x₂ ∈ (inr R M M₂).range,
by simp,
use [⟨x₁, 0⟩, h₁, ⟨0, x₂⟩, h₂],
simp
end
/-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the
set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/
def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥
@[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R
@[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl
theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl
theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) :=
by rw ker_comp; exact comap_mono bot_le
theorem sub_mem_ker_iff {f : M →ₗ[R] M₂} {x y} : x - y ∈ f.ker ↔ f x = f y :=
by rw [mem_ker, map_sub, sub_eq_zero]
theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} :
disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 :=
by simp [disjoint_def]
theorem disjoint_ker' {f : M →ₗ[R] M₂} {p : submodule R M} :
disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y :=
disjoint_ker.trans
⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]),
λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩
theorem inj_of_disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M}
{s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) :
∀ x y ∈ s, f x = f y → x = y :=
λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy)
lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range :=
by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl
theorem ker_eq_bot {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ injective f :=
by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤
theorem ker_eq_bot' {f : M →ₗ[R] M₂} :
ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) :=
have h : (∀ m ∈ (⊤ : submodule R M), f m = 0 → m = 0) ↔ (∀ m, f m = 0 → m = 0),
from ⟨λ h m, h m mem_top, λ h m _, h m⟩,
by simpa [h, disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤
lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ :=
by rw [ker, eq_bot_iff, map_le_iff_le_comap]
lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) :
ker (cod_restrict p f hf) = ker f :=
by rw [ker, comap_cod_restrict, map_bot]; refl
lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) :
range (cod_restrict p f hf) = comap p.subtype f.range :=
map_cod_restrict _ _ _ _
lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) :
map f (comap f q) = range f ⊓ q :=
le_antisymm (le_inf (map_mono le_top) (map_comap_le _ _)) $
by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩
lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) :
map f (comap f q) = q :=
by rw [map_comap_eq, inf_of_le_right h]
lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) :
comap f (map f p) = p ⊔ ker f :=
begin
refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)),
rintro x ⟨y, hy, e⟩,
exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩
end
lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) :
comap f (map f p) = p :=
by rw [comap_map_eq, sup_of_le_left h]
@[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ :=
eq_top_iff'.2 $ λ x, by simp
@[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ :=
submodule.map_zero _
theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 :=
⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩
lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 :=
by rw [range_le_iff_comap]; exact ker_eq_top
theorem map_le_map_iff {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' :=
⟨λ H x hx, let ⟨y, hy, e⟩ := H ⟨x, hx, rfl⟩ in ker_eq_bot.1 hf e ▸ hy, map_mono⟩
theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) :=
λ p p' h, le_antisymm ((map_le_map_iff hf).1 (le_of_eq h)) ((map_le_map_iff hf).1 (ge_of_eq h))
theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' :=
⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩
theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) :=
λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h))
theorem map_copair_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) :
map (copair f g) (p.prod q) = map f p ⊔ map g q :=
begin
refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)),
{ rw le_def', rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩,
exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ },
{ exact λ x hx, ⟨(x, 0), by simp [hx]⟩ },
{ exact λ x hx, ⟨(0, x), by simp [hx]⟩ }
end
theorem comap_pair_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) :
comap (pair f g) (p.prod q) = comap f p ⊓ comap g q :=
submodule.ext $ λ x, iff.rfl
theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) :
p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) :=
submodule.ext $ λ x, iff.rfl
theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) :
p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) :=
by rw [← map_copair_prod, copair_inl_inr, map_id]
lemma span_inl_union_inr {s : set M} {t : set M₂} :
span R (prod.inl '' s ∪ prod.inr '' t) = (span R s).prod (span R t) :=
by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image]; refl
lemma ker_pair (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) :
ker (pair f g) = ker f ⊓ ker g :=
by rw [ker, ← prod_bot, comap_pair_prod]; refl
end linear_map
namespace linear_map
variables [discrete_field K]
variables [add_comm_group V] [vector_space K V]
variables [add_comm_group V₂] [vector_space K V₂]
lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f :=
submodule.comap_smul f _ a h
lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f :=
submodule.comap_smul' f _ a
lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f :=
submodule.map_smul f _ a h
lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f :=
submodule.map_smul' f _ a
end linear_map
namespace is_linear_map
lemma is_linear_map_add {R M : Type*} [ring R] [add_comm_group M] [module R M]:
is_linear_map R (λ (x : M × M), x.1 + x.2) :=
begin
apply is_linear_map.mk,
{ intros x y,
simp },
{ intros x y,
simp [smul_add] }
end
lemma is_linear_map_sub {R M : Type*} [ring R] [add_comm_group M] [module R M]:
is_linear_map R (λ (x : M × M), x.1 - x.2) :=
begin
apply is_linear_map.mk,
{ intros x y,
simp },
{ intros x y,
simp [smul_add] }
end
end is_linear_map
namespace submodule
variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂]
variables (p p' : submodule R M) (q : submodule R M₂)
include T
open linear_map
@[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := rfl
@[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl
@[simp] theorem ker_subtype : p.subtype.ker = ⊥ :=
ker_eq_bot.2 $ λ x y, subtype.eq'
@[simp] theorem range_subtype : p.subtype.range = p :=
by simpa using map_comap_subtype p ⊤
lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p :=
by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range)
/-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the
maximal submodule of `p` is just `p `. -/
@[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p :=
by simp
@[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ :=
by rw [of_le, ker_cod_restrict, ker_subtype]
lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p :=
by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype]
lemma disjoint_iff_comap_eq_bot (p q : submodule R M) :
disjoint p q ↔ comap p.subtype q = ⊥ :=
by rw [eq_bot_iff, ← map_le_map_iff p.ker_subtype, map_bot, map_comap_subtype]; refl
/-- If N ⊆ M then submodules of N are the same as submodules of M contained in N -/
def map_subtype.order_iso :
((≤) : submodule R p → submodule R p → Prop) ≃o
((≤) : {p' : submodule R M // p' ≤ p} → {p' : submodule R M // p' ≤ p} → Prop) :=
{ to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩,
inv_fun := λ q, comap p.subtype q,
left_inv := λ p', comap_map_eq_self $ by simp,
right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [map_comap_subtype p, inf_of_le_right hq],
ord := λ p₁ p₂, (map_le_map_iff $ ker_subtype _).symm }
/-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of
submodules of M. -/
def map_subtype.le_order_embedding :
((≤) : submodule R p → submodule R p → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) :=
(order_iso.to_order_embedding $ map_subtype.order_iso p).trans (subtype.order_embedding _ _)
@[simp] lemma map_subtype_embedding_eq (p' : submodule R p) :
map_subtype.le_order_embedding p p' = map p.subtype p' := rfl
/-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of
submodules of M. -/
def map_subtype.lt_order_embedding :
((<) : submodule R p → submodule R p → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) :=
(map_subtype.le_order_embedding p).lt_embedding_of_le_embedding
@[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ :=
by ext ⟨x, y⟩; simp [and.left_comm, eq_comm]
@[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q :=
by ext ⟨x, y⟩; simp [and.left_comm, eq_comm]
@[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ :=
by ext ⟨x, y⟩; simp
@[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q :=
by ext ⟨x, y⟩; simp
@[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp
@[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp
@[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p :=
by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)]
@[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q :=
by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)]
@[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ :=
by rw [ker, ← prod_bot, prod_comap_inl]
@[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ :=
by rw [ker, ← prod_bot, prod_comap_inr]
@[simp] theorem range_fst : (fst R M M₂).range = ⊤ :=
by rw [range, ← prod_top, prod_map_fst]
@[simp] theorem range_snd : (snd R M M₂).range = ⊤ :=
by rw [range, ← prod_top, prod_map_snd]
/-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/
def mkq : M →ₗ[R] p.quotient := ⟨quotient.mk, by simp, by simp⟩
@[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl
/-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂`
vanishing on `p`, as a linear map. -/
def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ :=
⟨λ x, _root_.quotient.lift_on' x f $
λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab,
by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y,
by rintro a ⟨x⟩; exact f.map_smul a x⟩
@[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) :
p.liftq f h (quotient.mk x) = f x := rfl
@[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f :=
by ext; refl
@[simp] theorem range_mkq : p.mkq.range = ⊤ :=
eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, trivial, rfl⟩
@[simp] theorem ker_mkq : p.mkq.ker = p :=
by ext; simp
lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' :=
by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p')
@[simp] theorem mkq_map_self : map p.mkq p = ⊥ :=
by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _
@[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' :=
by simp [comap_map_eq, sup_comm]
/-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along
`f : M → M₂` is linear. -/
def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient :=
p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h
@[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) :
mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl
theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f :=
by ext x; refl
theorem comap_liftq (f : M →ₗ[R] M₂) (h) :
q.comap (p.liftq f h) = (q.comap f).map (mkq p) :=
le_antisymm
(by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩)
(by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _)
theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) :
q.map (p.liftq f h) = (q.comap p.mkq).map f :=
le_antisymm
(by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩)
(by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩)
theorem ker_liftq (f : M →ₗ[R] M₂) (h) :
ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _
theorem range_liftq (f : M →ₗ[R] M₂) (h) :
range (p.liftq f h) = range f := map_liftq _ _ _ _
theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ :=
by rw [ker_liftq, le_antisymm h h', mkq_map_self]
/-- The correspondence theorem for modules: there is an order isomorphism between submodules of the
quotient of `M` by `p`, and submodules of `M` larger than `p`. -/
def comap_mkq.order_iso :
((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≃o
((≤) : {p' : submodule R M // p ≤ p'} → {p' : submodule R M // p ≤ p'} → Prop) :=
{ to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩,
inv_fun := λ q, map p.mkq q,
left_inv := λ p', map_comap_eq_self $ by simp,
right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [comap_map_mkq p, sup_of_le_right hq],
ord := λ p₁ p₂, (comap_le_comap_iff $ range_mkq _).symm }
/-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules
of `M`. -/
def comap_mkq.le_order_embedding :
((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) :=
(order_iso.to_order_embedding $ comap_mkq.order_iso p).trans (subtype.order_embedding _ _)
@[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) :
comap_mkq.le_order_embedding p p' = comap p.mkq p' := rfl
/-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules
of `M`. -/
def comap_mkq.lt_order_embedding :
((<) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) :=
(comap_mkq.le_order_embedding p).lt_embedding_of_le_embedding
end submodule
section
set_option old_structure_cmd true
/-- A linear equivalence is an invertible linear map. -/
structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w)
[ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂]
extends M →ₗ[R] M₂, M ≃ M₂
end
infix ` ≃ₗ ` := linear_equiv _
notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂
namespace linear_equiv
section ring
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
include R
instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩
@[simp] theorem coe_apply (e : M ≃ₗ[R] M₂) (b : M) : (e : M →ₗ[R] M₂) b = e b := rfl
lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) :=
λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h)
@[ext] lemma ext {f g : M ≃ₗ[R] M₂} (h : (f : M → M₂) = g) : f = g :=
to_equiv_injective (equiv.eq_of_to_fun_eq h)
section
variable (M)
/-- The identity map is a linear equivalence. -/
@[refl] def refl : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M }
end
/-- Linear equivalences are symmetric. -/
@[symm] def symm (e : M ≃ₗ[R] M₂) : M₂ ≃ₗ[R] M :=
{ .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv,
.. e.to_equiv.symm }
/-- Linear equivalences are transitive. -/
@[trans] def trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : M ≃ₗ[R] M₃ :=
{ .. e₂.to_linear_map.comp e₁.to_linear_map,
.. e₁.to_equiv.trans e₂.to_equiv }
/-- A linear equivalence is an additive equivalence. -/
def to_add_equiv (e : M ≃ₗ[R] M₂) : M ≃+ M₂ := { map_add' := e.add, .. e }
@[simp] theorem apply_symm_apply (e : M ≃ₗ[R] M₂) (c : M₂) : e (e.symm c) = c := e.6 c
@[simp] theorem symm_apply_apply (e : M ≃ₗ[R] M₂) (b : M) : e.symm (e b) = b := e.5 b
@[simp] theorem map_add (e : M ≃ₗ[R] M₂) (a b : M) : e (a + b) = e a + e b := e.add a b
@[simp] theorem map_zero (e : M ≃ₗ[R] M₂) : e 0 = 0 := e.to_linear_map.map_zero
@[simp] theorem map_neg (e : M ≃ₗ[R] M₂) (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a
@[simp] theorem map_sub (e : M ≃ₗ[R] M₂) (a b : M) : e (a - b) = e a - e b :=
e.to_linear_map.map_sub a b
@[simp] theorem map_smul (e : M ≃ₗ[R] M₂) (c : R) (x : M) : e (c • x) = c • e x := e.smul c x
@[simp] theorem map_eq_zero_iff (e : M ≃ₗ[R] M₂) {x : M} : e x = 0 ↔ x = 0 :=
e.to_add_equiv.map_eq_zero_iff
@[simp] theorem map_ne_zero_iff (e : M ≃ₗ[R] M₂) {x : M} : e x ≠ 0 ↔ x ≠ 0 :=
e.to_add_equiv.map_ne_zero_iff
/-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that
the kernel of `f` is `{0}` and the range is the universal set. -/
noncomputable def of_bijective
(f : M →ₗ[R] M₂) (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ :=
{ ..f, ..@equiv.of_bijective _ _ f
⟨linear_map.ker_eq_bot.1 hf₁, linear_map.range_eq_top.1 hf₂⟩ }
@[simp] theorem of_bijective_apply (f : M →ₗ[R] M₂) {hf₁ hf₂} (x : M) :
of_bijective f hf₁ hf₂ x = f x := rfl
/-- If a linear map has an inverse, it is a linear equivalence. -/
def of_linear (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M)
(h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ :=
{ inv_fun := g,
left_inv := linear_map.ext_iff.1 h₂,
right_inv := linear_map.ext_iff.1 h₁,
..f }
@[simp] theorem of_linear_apply (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) {h₁ h₂}
(x : M) : of_linear f g h₁ h₂ x = f x := rfl
@[simp] theorem of_linear_symm_apply (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) {h₁ h₂}
(x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl
@[simp] protected theorem ker (f : M ≃ₗ[R] M₂) : (f : M →ₗ[R] M₂).ker = ⊥ :=
linear_map.ker_eq_bot.2 f.to_equiv.injective
@[simp] protected theorem range (f : M ≃ₗ[R] M₂) : (f : M →ₗ[R] M₂).range = ⊤ :=
linear_map.range_eq_top.2 f.to_equiv.surjective
/-- The top submodule of `M` is linearly equivalent to `M`. -/
def of_top (p : submodule R M) (h : p = ⊤) : p ≃ₗ[R] M :=
{ inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩,
left_inv := λ ⟨x, h⟩, rfl,
right_inv := λ x, rfl,
.. p.subtype }
@[simp] theorem of_top_apply (p : submodule R M) {h} (x : p) :
of_top p h x = x := rfl
@[simp] theorem of_top_symm_apply (p : submodule R M) {h} (x : M) :
↑((of_top p h).symm x) = x := rfl
lemma eq_bot_of_equiv (p : submodule R M) (e : p ≃ₗ[R] (⊥ : submodule R M₂)) :
p = ⊥ :=
begin
refine bot_unique (submodule.le_def'.2 $ assume b hb, (submodule.mem_bot R).2 _),
have := e.symm_apply_apply ⟨b, hb⟩,
rw [← e.coe_apply, submodule.eq_zero_of_bot_submodule ((e : p →ₗ[R] (⊥ : submodule R M₂)) ⟨b, hb⟩),
← e.symm.coe_apply, linear_map.map_zero] at this,
exact congr_arg (coe : p → M) this.symm
end
end ring
section comm_ring
variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
include R
open linear_map
set_option class.instance_max_depth 39
/-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/
def smul_of_unit (a : units R) : M ≃ₗ[R] M :=
of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M)
(by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl)
(by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl)
/-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a
linear isomorphism between the two function spaces. -/
def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R]
[add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂]
[module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂]
(e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) :
(M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) :=
{ to_fun := λ f, e₂.to_linear_map.comp $ f.comp e₁.symm.to_linear_map,
inv_fun := λ f, e₂.symm.to_linear_map.comp $ f.comp e₁.to_linear_map,
left_inv := λ f, by { ext x, unfold_coes,
change e₂.inv_fun (e₂.to_fun $ f.to_fun $ e₁.inv_fun $ e₁.to_fun x) = _,
rw [e₁.left_inv, e₂.left_inv] },
right_inv := λ f, by { ext x, unfold_coes,
change e₂.to_fun (e₂.inv_fun $ f.to_fun $ e₁.to_fun $ e₁.inv_fun x) = _,
rw [e₁.right_inv, e₂.right_inv] },
add := λ f g, by { ext x, change e₂.to_fun ((f + g) (e₁.inv_fun x)) = _,
rw [linear_map.add_apply, e₂.add], refl },
smul := λ c f, by { ext x, change e₂.to_fun ((c • f) (e₁.inv_fun x)) = _,
rw [linear_map.smul_apply, e₂.smul], refl } }
/-- If M₂ and M₃ are linearly isomorphic then the two spaces of linear maps from M into M₂ and
M into M₃ are linearly isomorphic. -/
def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl M) f
/-- If M and M₂ are linearly isomorphic then the two spaces of linear maps from M and M₂ to themselves
are linearly isomorphic. -/
def conj (e : M ≃ₗ[R] M₂) : (M →ₗ[R] M) ≃ₗ[R] (M₂ →ₗ[R] M₂) := arrow_congr e e
end comm_ring
section field
variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module K M] [module K M₂] [module K M₃]
variable (M)
open linear_map
/-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/
def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M :=
smul_of_unit $ units.mk0 a ha
end field
end linear_equiv
namespace equiv
variables [ring R] [add_comm_group M] [module R M] [add_comm_group M₂] [module R M₂]
/-- An equivalence whose underlying function is linear is a linear equivalence. -/
def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ :=
{ add := h.add, smul := h.smul, .. e}
end equiv
namespace linear_map
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
variables (f : M →ₗ[R] M₂)
/-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly
equivalent to the range of `f`. -/
noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range :=
have hr : ∀ x : f.range, ∃ y, f y = ↑x := λ x, x.2.imp $ λ _, and.right,
let F : f.ker.quotient →ₗ[R] f.range :=
f.ker.liftq (cod_restrict f.range f $ λ x, ⟨x, trivial, rfl⟩)
(λ x hx, by simp; apply subtype.coe_ext.2; simpa using hx) in
{ inv_fun := λx, submodule.quotient.mk (classical.some (hr x)),
left_inv := by rintro ⟨x⟩; exact
(submodule.quotient.eq _).2 (sub_mem_ker_iff.2 $
classical.some_spec $ hr $ F $ submodule.quotient.mk x),
right_inv := λ x : range f, subtype.eq $ classical.some_spec (hr x),
.. F }
open submodule
/--
Canonical linear map from the quotient p/(p ∩ p') to (p+p')/p', mapping x + (p ∩ p') to x + p',
where p and p' are submodules of an ambient module.
-/
def sup_quotient_to_quotient_inf (p p' : submodule R M) :
(comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient :=
(comap p.subtype (p ⊓ p')).liftq
((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin
rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype],
exact comap_mono (inf_le_inf le_sup_left (le_refl _)) end
set_option class.instance_max_depth 41
/--
Second Isomorphism Law : the canonical map from p/(p ∩ p') to (p+p')/p' as a linear isomorphism.
-/
noncomputable def sup_quotient_equiv_quotient_inf (p p' : submodule R M) :
(comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient :=
{ .. sup_quotient_to_quotient_inf p p',
.. show (comap p.subtype (p ⊓ p')).quotient ≃ (comap (p ⊔ p').subtype p').quotient, from
@equiv.of_bijective _ _ (sup_quotient_to_quotient_inf p p') begin
constructor,
{ rw [← ker_eq_bot, sup_quotient_to_quotient_inf, ker_liftq_eq_bot],
rw [ker_comp, ker_mkq],
rintros ⟨x, hx1⟩ hx2, exact ⟨hx1, hx2⟩ },
rw [← range_eq_top, sup_quotient_to_quotient_inf, range_liftq, eq_top_iff'],
rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩,
use [⟨y, hy⟩, trivial], apply (submodule.quotient.eq _).2,
change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff]
end }
section prod
/-- The cartesian product of two linear maps as a linear map. -/
def prod {R M M₂ M₃ : Type*} [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
[module R M] [module R M₂] [module R M₃]
(f₁ : M →ₗ[R] M₂) (f₂ : M →ₗ[R] M₃) : M →ₗ[R] (M₂ × M₃) :=
{ to_fun := λx, (f₁ x, f₂ x),
add := λx y, begin
change (f₁ (x + y), f₂ (x+y)) = (f₁ x, f₂ x) + (f₁ y, f₂ y),
simp only [linear_map.map_add],
refl
end,
smul := λc x, by simp only [linear_map.map_smul] }
lemma is_linear_map_prod_iso {R M M₂ M₃ : Type*} [comm_ring R] [add_comm_group M] [add_comm_group M₂]
[add_comm_group M₃] [module R M] [module R M₂] [module R M₃] :
is_linear_map R (λ(p : (M →ₗ[R] M₂) × (M →ₗ[R] M₃)), (linear_map.prod p.1 p.2 : (M →ₗ[R] (M₂ × M₃)))) :=
⟨λu v, rfl, λc u, rfl⟩
end prod
section pi
universe i
variables {φ : ι → Type i}
variables [∀i, add_comm_group (φ i)] [∀i, module R (φ i)]
/-- `pi` construction for linear functions. From a family of linear functions it produces a linear
function into a family of modules. -/
def pi (f : Πi, M₂ →ₗ[R] φ i) : M₂ →ₗ[R] (Πi, φ i) :=
⟨λc i, f i c,
assume c d, funext $ assume i, (f i).add _ _, assume c d, funext $ assume i, (f i).smul _ _⟩
@[simp] lemma pi_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i : ι) :
pi f c i = f i c := rfl
lemma ker_pi (f : Πi, M₂ →ₗ[R] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) :=
by ext c; simp [funext_iff]; refl
lemma pi_eq_zero (f : Πi, M₂ →ₗ[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) :=
by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩
lemma pi_zero : pi (λi, 0 : Πi, M₂ →ₗ[R] φ i) = 0 :=
by ext; refl
lemma pi_comp (f : Πi, M₂ →ₗ[R] φ i) (g : M₃ →ₗ[R] M₂) : (pi f).comp g = pi (λi, (f i).comp g) :=
rfl
/-- The projections from a family of modules are linear maps. -/
def proj (i : ι) : (Πi, φ i) →ₗ[R] φ i :=
⟨ λa, a i, assume f g, rfl, assume c f, rfl ⟩
@[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[R] φ i) b = b i := rfl
lemma proj_pi (f : Πi, M₂ →ₗ[R] φ i) (i : ι) : (proj i).comp (pi f) = f i :=
ext $ assume c, rfl
lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ :=
bot_unique $ submodule.le_def'.2 $ assume a h,
begin
simp only [mem_infi, mem_ker, proj_apply] at h,
exact (mem_bot _).2 (funext $ assume i, h i)
end
section
variables (R φ)
/-- If `I` and `J` are disjoint index sets, the product of the kernels of the `J`th projections of
`φ` is linearly equivalent to the product over `I`. -/
def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)]
(hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) :
(⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃ₗ[R] (Πi:I, φ i) :=
begin
refine linear_equiv.of_linear
(pi $ λi, (proj (i:ι)).comp (submodule.subtype _))
(cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _,
{ assume b,
simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply],
assume j hjJ,
have : j ∉ I := assume hjI, hd ⟨hjI, hjJ⟩,
rw [dif_neg this, zero_apply] },
{ simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, dif_pos, subtype.val_prop'],
ext b ⟨j, hj⟩, refl },
{ ext ⟨b, hb⟩,
apply subtype.coe_ext.2,
ext j,
have hb : ∀i ∈ J, b i = 0,
{ simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb },
simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply],
split_ifs,
{ rw [dif_pos h], refl },
{ rw [dif_neg h],
exact (hb _ $ (hu trivial).resolve_left h).symm } }
end
end
section
variable [decidable_eq ι]
/-- `diag i j` is the identity map if `i = j`. Otherwise it is the constant 0 map. -/
def diag (i j : ι) : φ i →ₗ[R] φ j :=
@function.update ι (λj, φ i →ₗ[R] φ j) _ 0 i id j
lemma update_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i j : ι) (b : M₂ →ₗ[R] φ i) :
(update f i b j) c = update (λi, f i c) i (b c) j :=
begin
by_cases j = i,
{ rw [h, update_same, update_same] },
{ rw [update_noteq h, update_noteq h] }
end
end
section
variable [decidable_eq ι]
variables (R φ)
/-- The standard basis of the product of `φ`. -/
def std_basis (i : ι) : φ i →ₗ[R] (Πi, φ i) := pi (diag i)
lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ i b = update 0 i b :=
by ext j; rw [std_basis, pi_apply, diag, update_apply]; refl
@[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis R φ i b i = b :=
by rw [std_basis_apply, update_same]
lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 :=
by rw [std_basis_apply, update_noteq h]; refl
lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ :=
ker_eq_bot.2 $ assume f g hfg,
have std_basis R φ i f i = std_basis R φ i g i := hfg ▸ rfl,
by simpa only [std_basis_same]
lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i :=
by rw [std_basis, proj_pi]
lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id :=
by ext b; simp
lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 :=
by ext b; simp [std_basis_ne R φ _ _ h]
lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) :
(⨆i∈I, range (std_basis R φ i)) ≤ (⨅i∈J, ker (proj i)) :=
begin
refine (supr_le $ assume i, supr_le $ assume hi, range_le_iff_comap.2 _),
simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi],
assume b hb j hj,
have : i ≠ j := assume eq, h ⟨hi, eq.symm ▸ hj⟩,
rw [proj_std_basis_ne R φ j i this.symm, zero_apply]
end
lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) :
(⨅ i∈J, ker (proj i)) ≤ (⨆i∈I, range (std_basis R φ i)) :=
submodule.le_def'.2
begin
assume b hb,
simp only [mem_infi, mem_ker, proj_apply] at hb,
rw ← show I.sum (λi, std_basis R φ i (b i)) = b,
{ ext i,
rw [pi.finset_sum_apply, ← std_basis_same R φ i (b i)],
refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _,
assume hiI,
rw [std_basis_same],
exact hb _ ((hu trivial).resolve_left hiI) },
exact sum_mem _ (assume i hiI, mem_supr_of_mem _ i $ mem_supr_of_mem _ hiI $
linear_map.mem_range.2 ⟨_, rfl⟩)
end
lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι}
(hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) :
(⨆i∈I, range (std_basis R φ i)) = (⨅i∈J, ker (proj i)) :=
begin
refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _,
have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [finset.coe_to_finset] },
refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_le_supr $ assume i, _),
rw [← finset.mem_coe, finset.coe_to_finset],
exact le_refl _
end
lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis R φ i)) = ⊤ :=
have (set.univ : set ι) ⊆ ↑(finset.univ : finset ι) ∪ ∅ := by rw [finset.coe_univ, set.union_empty],
begin
apply top_unique,
convert (infi_ker_proj_le_supr_range_std_basis R φ this),
exact infi_emptyset.symm,
exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis R φ i)) $ finset.mem_univ i).symm)
end
lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) :
disjoint (⨆i∈I, range (std_basis R φ i)) (⨆i∈J, range (std_basis R φ i)) :=
begin
refine disjoint_mono
(supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl I)
(supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl J) _,
simp only [disjoint, submodule.le_def', mem_infi, mem_inf, mem_ker, mem_bot, proj_apply,
funext_iff],
rintros b ⟨hI, hJ⟩ i,
classical,
by_cases hiI : i ∈ I,
{ by_cases hiJ : i ∈ J,
{ exact (h ⟨hiI, hiJ⟩).elim },
{ exact hJ i hiJ } },
{ exact hI i hiI }
end
lemma std_basis_eq_single {a : R} :
(λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) :=
begin
ext i j,
rw [std_basis_apply, finsupp.single_apply],
split_ifs,
{ rw [h, function.update_same] },
{ rw [function.update_noteq (ne.symm h)], refl },
end
end
end pi
variables (R M)
instance automorphism_group : group (M ≃ₗ[R] M) :=
{ mul := λ f g, g.trans f,
one := linear_equiv.refl M,
inv := λ f, f.symm,
mul_assoc := λ f g h, by {ext, refl},
mul_one := λ f, by {ext, refl},
one_mul := λ f, by {ext, refl},
mul_left_inv := λ f, by {ext, exact f.left_inv x} }
instance automorphism_group.to_linear_map_is_monoid_hom :
is_monoid_hom (linear_equiv.to_linear_map : (M ≃ₗ[R] M) → (M →ₗ[R] M)) :=
{ map_one := rfl,
map_mul := λ f g, rfl }
/-- The group of invertible linear maps from `M` to itself -/
def general_linear_group := units (M →ₗ[R] M)
namespace general_linear_group
variables {R M}
instance : group (general_linear_group R M) := by delta general_linear_group; apply_instance
/-- An invertible linear map `f` determines an equivalence from `M` to itself. -/
def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) :=
{ inv_fun := f.inv.to_fun,
left_inv := λ m, show (f.inv * f.val) m = m,
by erw f.inv_val; simp,
right_inv := λ m, show (f.val * f.inv) m = m,
by erw f.val_inv; simp,
..f.val }
/-- An equivalence from `M` to itself determines an invertible linear map. -/
def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M :=
{ val := f,
inv := f.symm,
val_inv := linear_map.ext $ λ _, f.apply_symm_apply _,
inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ }
variables (R M)
/-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear
equivalences between `M` and itself. -/
def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) :=
{ to_fun := to_linear_equiv,
inv_fun := of_linear_equiv,
left_inv := λ f,
begin
delta to_linear_equiv of_linear_equiv,
cases f with f f_inv, cases f, cases f_inv,
congr
end,
right_inv := λ f,
begin
delta to_linear_equiv of_linear_equiv,
cases f,
congr
end,
map_mul' := λ x y, by {ext, refl} }
@[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) :
((general_linear_equiv R M).to_equiv f).to_linear_map = f.val :=
by {ext, refl}
end general_linear_group
end linear_map
|
0bbc31f2f7191c785b9906d5a28bac2f211246ae | 92b50235facfbc08dfe7f334827d47281471333b | /library/data/quotient/classical.lean | bbf89c2cfd73b96e13b9cd8207ab46ebf9ef30ed | [
"Apache-2.0"
] | permissive | htzh/lean | 24f6ed7510ab637379ec31af406d12584d31792c | d70c79f4e30aafecdfc4a60b5d3512199200ab6e | refs/heads/master | 1,607,677,731,270 | 1,437,089,952,000 | 1,437,089,952,000 | 37,078,816 | 0 | 0 | null | 1,433,780,956,000 | 1,433,780,955,000 | null | UTF-8 | Lean | false | false | 2,040 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
A classical treatment of quotients, using Hilbert choice.
-/
import algebra.relation data.subtype logic.axioms.classical logic.axioms.hilbert
import .basic
namespace quotient
open relation nonempty subtype
/- abstract quotient -/
definition prelim_map {A : Type} (R : A → A → Prop) (a : A) :=
-- TODO: it is interesting how the elaborator fails here
-- epsilon (fun b, R a b)
@epsilon _ (nonempty.intro a) (fun b, R a b)
-- TODO: only needed R reflexive (or weaker: R a a)
theorem prelim_map_rel {A : Type} {R : A → A → Prop} (H : is_equivalence R) (a : A)
: R a (prelim_map R a) :=
have reflR : reflexive R, from is_equivalence.refl R,
epsilon_spec (exists.intro a (reflR a))
-- TODO: only needed: R PER
theorem prelim_map_congr {A : Type} {R : A → A → Prop} (H1 : is_equivalence R) {a b : A}
(H2 : R a b) : prelim_map R a = prelim_map R b :=
have symmR : relation.symmetric R, from is_equivalence.symm R,
have transR : relation.transitive R, from is_equivalence.trans R,
have H3 : ∀c, R a c ↔ R b c, from
take c,
iff.intro
(assume H4 : R a c, transR (symmR H2) H4)
(assume H4 : R b c, transR H2 H4),
have H4 : (fun c, R a c) = (fun c, R b c), from
funext (take c, eq.of_iff (H3 c)),
assert H5 : nonempty A, from
nonempty.intro a,
show epsilon (λc, R a c) = epsilon (λc, R b c), from
congr_arg _ H4
definition quotient {A : Type} (R : A → A → Prop) : Type := image (prelim_map R)
definition quotient_abs {A : Type} (R : A → A → Prop) : A → quotient R :=
fun_image (prelim_map R)
definition quotient_elt_of {A : Type} (R : A → A → Prop) : quotient R → A := elt_of
theorem quotient_is_quotient {A : Type} (R : A → A → Prop) (H : is_equivalence R)
: is_quotient R (quotient_abs R) (quotient_elt_of R) :=
representative_map_to_quotient_equiv
H
(prelim_map_rel H)
(@prelim_map_congr _ _ H)
end quotient
|
dc27fb0f74bc8e90f447b0433e4ce3734cee0d33 | 07c76fbd96ea1786cc6392fa834be62643cea420 | /hott/cubical/square.hlean | d8a028250ddc54de9308c71c72eb364f85b3596f | [
"Apache-2.0"
] | permissive | fpvandoorn/lean2 | 5a430a153b570bf70dc8526d06f18fc000a60ad9 | 0889cf65b7b3cebfb8831b8731d89c2453dd1e9f | refs/heads/master | 1,592,036,508,364 | 1,545,093,958,000 | 1,545,093,958,000 | 75,436,854 | 0 | 0 | null | 1,480,718,780,000 | 1,480,718,780,000 | null | UTF-8 | Lean | false | false | 37,866 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Jakob von Raumer
Squares in a type
-/
import types.eq
open eq equiv is_equiv sigma
namespace eq
variables {A B C : Type} {a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ a₁ a₂ a₃ a₄ : A}
/-a₀₀-/ {p₁₀ p₁₀' : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/
/-a₀₂-/ {p₁₂ p₁₂' : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/
/-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/
{p₀₁ p₀₁' : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ p₂₁' : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂}
{p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄}
{b : B} {c : C}
inductive square {A : Type} {a₀₀ : A}
: Π{a₂₀ a₀₂ a₂₂ : A}, a₀₀ = a₂₀ → a₀₂ = a₂₂ → a₀₀ = a₀₂ → a₂₀ = a₂₂ → Type :=
ids : square idp idp idp idp
/- square top bottom left right -/
variables {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁}
{s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃}
definition ids [reducible] [constructor] := @square.ids
definition idsquare [reducible] [constructor] (a : A) := @square.ids A a
definition hrefl [unfold 4] (p : a = a') : square idp idp p p :=
by induction p; exact ids
definition vrefl [unfold 4] (p : a = a') : square p p idp idp :=
by induction p; exact ids
definition hrfl [reducible] [unfold 4] {p : a = a'} : square idp idp p p :=
!hrefl
definition vrfl [reducible] [unfold 4] {p : a = a'} : square p p idp idp :=
!vrefl
definition hdeg_square [unfold 6] {p q : a = a'} (r : p = q) : square idp idp p q :=
by induction r;apply hrefl
definition vdeg_square [unfold 6] {p q : a = a'} (r : p = q) : square p q idp idp :=
by induction r;apply vrefl
definition hdeg_square_idp (p : a = a') : hdeg_square (refl p) = hrfl :=
by reflexivity
definition vdeg_square_idp (p : a = a') : vdeg_square (refl p) = vrfl :=
by reflexivity
definition hconcat [unfold 16] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁)
: square (p₁₀ ⬝ p₃₀) (p₁₂ ⬝ p₃₂) p₀₁ p₄₁ :=
by induction s₃₁; exact s₁₁
definition vconcat [unfold 16] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃)
: square p₁₀ p₁₄ (p₀₁ ⬝ p₀₃) (p₂₁ ⬝ p₂₃) :=
by induction s₁₃; exact s₁₁
definition dconcat [unfold 14] {p₀₀ : a₀₀ = a} {p₂₂ : a = a₂₂}
(s₂₁ : square p₀₀ p₁₂ p₀₁ p₂₂) (s₁₂ : square p₁₀ p₂₂ p₀₀ p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction s₁₂; exact s₂₁
definition hinverse [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀⁻¹ p₁₂⁻¹ p₂₁ p₀₁ :=
by induction s₁₁;exact ids
definition vinverse [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₂ p₁₀ p₀₁⁻¹ p₂₁⁻¹ :=
by induction s₁₁;exact ids
definition eq_vconcat [unfold 11] {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) :
square p p₁₂ p₀₁ p₂₁ :=
by induction r; exact s₁₁
definition vconcat_eq [unfold 12] {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) :
square p₁₀ p p₀₁ p₂₁ :=
by induction r; exact s₁₁
definition eq_hconcat [unfold 11] {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) :
square p₁₀ p₁₂ p p₂₁ :=
by induction r; exact s₁₁
definition hconcat_eq [unfold 12] {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) :
square p₁₀ p₁₂ p₀₁ p :=
by induction r; exact s₁₁
infix ` ⬝h `:69 := hconcat --type using \tr
infix ` ⬝v `:70 := vconcat --type using \tr
infixl ` ⬝hp `:71 := hconcat_eq --type using \tr
infixl ` ⬝vp `:73 := vconcat_eq --type using \tr
infixr ` ⬝ph `:72 := eq_hconcat --type using \tr
infixr ` ⬝pv `:74 := eq_vconcat --type using \tr
postfix `⁻¹ʰ`:(max+1) := hinverse --type using \-1h
postfix `⁻¹ᵛ`:(max+1) := vinverse --type using \-1v
definition transpose [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₀₁ p₂₁ p₁₀ p₁₂ :=
by induction s₁₁;exact ids
definition aps [unfold 12] (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square (ap f p₁₀) (ap f p₁₂) (ap f p₀₁) (ap f p₂₁) :=
by induction s₁₁;exact ids
/- canceling, whiskering and moving thinks along the sides of the square -/
definition whisker_tl (p : a = a₀₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁ :=
by induction s₁₁;induction p;constructor
definition whisker_br (p : a₂₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p) :=
by induction p;exact s₁₁
definition whisker_rt (p : a = a₂₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁) :=
by induction s₁₁;induction p;constructor
definition whisker_tr (p : a₂₀ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁) :=
by induction s₁₁;induction p;constructor
definition whisker_bl (p : a = a₀₂) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁ :=
by induction s₁₁;induction p;constructor
definition whisker_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁ :=
by induction s₁₁;induction p;constructor
definition cancel_tl (p : a = a₀₀) (s₁₁ : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁)
: square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p; rewrite +idp_con at s₁₁; exact s₁₁
definition cancel_br (p : a₂₂ = a) (s₁₁ : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p))
: square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p;exact s₁₁
definition cancel_rt (p : a = a₂₀) (s₁₁ : square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁))
: square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p; rewrite idp_con at s₁₁; exact s₁₁
definition cancel_tr (p : a₂₀ = a) (s₁₁ : square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁))
: square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p; rewrite [▸* at s₁₁,idp_con at s₁₁]; exact s₁₁
definition cancel_bl (p : a = a₀₂) (s₁₁ : square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁)
: square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p; rewrite idp_con at s₁₁; exact s₁₁
definition cancel_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁)
: square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p; rewrite [▸* at s₁₁,idp_con at s₁₁]; exact s₁₁
definition move_top_of_left {p : a₀₀ = a} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p ⬝ q) p₂₁)
: square (p⁻¹ ⬝ p₁₀) p₁₂ q p₂₁ :=
by apply cancel_tl p; rewrite con_inv_cancel_left; exact s
definition move_top_of_left' {p : a = a₀₀} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p⁻¹ ⬝ q) p₂₁)
: square (p ⬝ p₁₀) p₁₂ q p₂₁ :=
by apply cancel_tl p⁻¹; rewrite inv_con_cancel_left; exact s
definition move_left_of_top {p : a₀₀ = a} {q : a = a₂₀} (s : square (p ⬝ q) p₁₂ p₀₁ p₂₁)
: square q p₁₂ (p⁻¹ ⬝ p₀₁) p₂₁ :=
by apply cancel_tl p; rewrite con_inv_cancel_left; exact s
definition move_left_of_top' {p : a = a₀₀} {q : a = a₂₀} (s : square (p⁻¹ ⬝ q) p₁₂ p₀₁ p₂₁)
: square q p₁₂ (p ⬝ p₀₁) p₂₁ :=
by apply cancel_tl p⁻¹; rewrite inv_con_cancel_left; exact s
definition move_bot_of_right {p : a₂₀ = a} {q : a = a₂₂} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q))
: square p₁₀ (p₁₂ ⬝ q⁻¹) p₀₁ p :=
by apply cancel_br q; rewrite inv_con_cancel_right; exact s
definition move_bot_of_right' {p : a₂₀ = a} {q : a₂₂ = a} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q⁻¹))
: square p₁₀ (p₁₂ ⬝ q) p₀₁ p :=
by apply cancel_br q⁻¹; rewrite con_inv_cancel_right; exact s
definition move_right_of_bot {p : a₀₂ = a} {q : a = a₂₂} (s : square p₁₀ (p ⬝ q) p₀₁ p₂₁)
: square p₁₀ p p₀₁ (p₂₁ ⬝ q⁻¹) :=
by apply cancel_br q; rewrite inv_con_cancel_right; exact s
definition move_right_of_bot' {p : a₀₂ = a} {q : a₂₂ = a} (s : square p₁₀ (p ⬝ q⁻¹) p₀₁ p₂₁)
: square p₁₀ p p₀₁ (p₂₁ ⬝ q) :=
by apply cancel_br q⁻¹; rewrite con_inv_cancel_right; exact s
definition move_top_of_right {p : a₂₀ = a} {q : a = a₂₂} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q))
: square (p₁₀ ⬝ p) p₁₂ p₀₁ q :=
by apply cancel_rt p; rewrite con_inv_cancel_right; exact s
definition move_right_of_top {p : a₀₀ = a} {q : a = a₂₀} (s : square (p ⬝ q) p₁₂ p₀₁ p₂₁)
: square p p₁₂ p₀₁ (q ⬝ p₂₁) :=
by apply cancel_tr q; rewrite inv_con_cancel_left; exact s
definition move_bot_of_left {p : a₀₀ = a} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p ⬝ q) p₂₁)
: square p₁₀ (q ⬝ p₁₂) p p₂₁ :=
by apply cancel_lb q; rewrite inv_con_cancel_left; exact s
definition move_left_of_bot {p : a₀₂ = a} {q : a = a₂₂} (s : square p₁₀ (p ⬝ q) p₀₁ p₂₁)
: square p₁₀ q (p₀₁ ⬝ p) p₂₁ :=
by apply cancel_bl p; rewrite con_inv_cancel_right; exact s
/- some higher ∞-groupoid operations -/
definition vconcat_vrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: s₁₁ ⬝v vrefl p₁₂ = s₁₁ :=
by induction s₁₁; reflexivity
definition hconcat_hrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: s₁₁ ⬝h hrefl p₂₁ = s₁₁ :=
by induction s₁₁; reflexivity
/- equivalences -/
definition eq_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂ :=
by induction s₁₁; apply idp
definition square_of_eq (r : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p₁₂; esimp at r; induction r; induction p₂₁; induction p₁₀; exact ids
definition eq_top_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹ :=
by induction s₁₁; apply idp
definition square_of_eq_top (r : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹) : square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p₂₁; induction p₁₂; esimp at r;induction r;induction p₁₀;exact ids
definition eq_bot_of_square [unfold 10] (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: p₁₂ = p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ :=
by induction s₁₁; apply idp
definition square_of_eq_bot (r : p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ = p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ :=
by induction p₂₁; induction p₁₀; esimp at r; induction r; induction p₀₁; exact ids
definition square_equiv_eq [constructor] (t : a₀₀ = a₀₂) (b : a₂₀ = a₂₂)
(l : a₀₀ = a₂₀) (r : a₀₂ = a₂₂) : square t b l r ≃ t ⬝ r = l ⬝ b :=
begin
fapply equiv.MK,
{ exact eq_of_square},
{ exact square_of_eq},
{ intro s, induction b, esimp [concat] at s, induction s, induction r, induction t, apply idp},
{ intro s, induction s, apply idp},
end
definition hdeg_square_equiv' [constructor] (p q : a = a') : square idp idp p q ≃ p = q :=
by transitivity _;apply square_equiv_eq;transitivity _;apply eq_equiv_eq_symm;
apply equiv_eq_closed_right;apply idp_con
definition vdeg_square_equiv' [constructor] (p q : a = a') : square p q idp idp ≃ p = q :=
by transitivity _;apply square_equiv_eq;apply equiv_eq_closed_right; apply idp_con
definition eq_of_hdeg_square [reducible] {p q : a = a'} (s : square idp idp p q) : p = q :=
to_fun !hdeg_square_equiv' s
definition eq_of_vdeg_square [reducible] {p q : a = a'} (s : square p q idp idp) : p = q :=
to_fun !vdeg_square_equiv' s
definition top_deg_square (l : a₁ = a₂) (b : a₂ = a₃) (r : a₄ = a₃)
: square (l ⬝ b ⬝ r⁻¹) b l r :=
by induction r;induction b;induction l;constructor
definition bot_deg_square (l : a₁ = a₂) (t : a₁ = a₃) (r : a₃ = a₄)
: square t (l⁻¹ ⬝ t ⬝ r) l r :=
by induction r;induction t;induction l;constructor
/-
the following two equivalences have as underlying inverse function the functions
hdeg_square and vdeg_square, respectively.
See example below the definition
-/
definition hdeg_square_equiv [constructor] (p q : a = a') :
square idp idp p q ≃ p = q :=
begin
fapply equiv_change_fun,
{ fapply equiv_change_inv, apply hdeg_square_equiv', exact hdeg_square,
intro s, induction s, induction p, reflexivity},
{ exact eq_of_hdeg_square},
{ reflexivity}
end
definition vdeg_square_equiv [constructor] (p q : a = a') :
square p q idp idp ≃ p = q :=
begin
fapply equiv_change_fun,
{ fapply equiv_change_inv, apply vdeg_square_equiv',exact vdeg_square,
intro s, induction s, induction p, reflexivity},
{ exact eq_of_vdeg_square},
{ reflexivity}
end
example (p q : a = a') : to_inv (hdeg_square_equiv p q) = hdeg_square := idp
/-
characterization of pathovers in a equality type. The type B of the equality is fixed here.
A version where B may also varies over the path p is given in the file squareover
-/
definition eq_pathover [unfold 7] {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'}
(s : square q r (ap f p) (ap g p)) : q =[p] r :=
begin induction p, apply pathover_idp_of_eq, exact eq_of_vdeg_square s end
definition eq_pathover_constant_left {g : A → B} {p : a = a'} {b : B} {q : b = g a} {r : b = g a'}
(s : square q r idp (ap g p)) : q =[p] r :=
eq_pathover (ap_constant p b ⬝ph s)
definition eq_pathover_id_left {g : A → A} {p : a = a'} {q : a = g a} {r : a' = g a'}
(s : square q r p (ap g p)) : q =[p] r :=
eq_pathover (ap_id p ⬝ph s)
definition eq_pathover_constant_right {f : A → B} {p : a = a'} {b : B} {q : f a = b} {r : f a' = b}
(s : square q r (ap f p) idp) : q =[p] r :=
eq_pathover (s ⬝hp (ap_constant p b)⁻¹)
definition eq_pathover_id_right {f : A → A} {p : a = a'} {q : f a = a} {r : f a' = a'}
(s : square q r (ap f p) p) : q =[p] r :=
eq_pathover (s ⬝hp (ap_id p)⁻¹)
definition square_of_pathover [unfold 7]
{f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'}
(s : q =[p] r) : square q r (ap f p) (ap g p) :=
by induction p;apply vdeg_square;exact eq_of_pathover_idp s
definition eq_pathover_constant_left_id_right {p : a = a'} {a₀ : A} {q : a₀ = a} {r : a₀ = a'}
(s : square q r idp p) : q =[p] r :=
eq_pathover (ap_constant p a₀ ⬝ph s ⬝hp (ap_id p)⁻¹)
definition eq_pathover_id_left_constant_right {p : a = a'} {a₀ : A} {q : a = a₀} {r : a' = a₀}
(s : square q r p idp) : q =[p] r :=
eq_pathover (ap_id p ⬝ph s ⬝hp (ap_constant p a₀)⁻¹)
definition loop_pathover {p : a = a'} {q : a = a} {r : a' = a'} (s : square q r p p) : q =[p] r :=
eq_pathover (ap_id p ⬝ph s ⬝hp (ap_id p)⁻¹)
/- interaction of equivalences with operations on squares -/
definition eq_pathover_equiv_square [constructor] {f g : A → B}
(p : a = a') (q : f a = g a) (r : f a' = g a') : q =[p] r ≃ square q r (ap f p) (ap g p) :=
equiv.MK square_of_pathover
eq_pathover
begin
intro s, induction p, esimp [square_of_pathover,eq_pathover],
exact ap vdeg_square (to_right_inv !pathover_idp (eq_of_vdeg_square s))
⬝ to_left_inv !vdeg_square_equiv s
end
begin
intro s, induction p, esimp [square_of_pathover,eq_pathover],
exact ap pathover_idp_of_eq (to_right_inv !vdeg_square_equiv (eq_of_pathover_idp s))
⬝ to_left_inv !pathover_idp s
end
definition square_of_pathover_eq_concato {f g : A → B} {p : a = a'} {q q' : f a = g a}
{r : f a' = g a'} (s' : q = q') (s : q' =[p] r)
: square_of_pathover (s' ⬝po s) = s' ⬝pv square_of_pathover s :=
by induction s;induction s';reflexivity
definition square_of_pathover_concato_eq {f g : A → B} {p : a = a'} {q : f a = g a}
{r r' : f a' = g a'} (s' : r = r') (s : q =[p] r)
: square_of_pathover (s ⬝op s') = square_of_pathover s ⬝vp s' :=
by induction s;induction s';reflexivity
definition square_of_pathover_concato {f g : A → B} {p : a = a'} {p' : a' = a''} {q : f a = g a}
{q' : f a' = g a'} {q'' : f a'' = g a''} (s : q =[p] q') (s' : q' =[p'] q'')
: square_of_pathover (s ⬝o s')
= ap_con f p p' ⬝ph (square_of_pathover s ⬝v square_of_pathover s') ⬝hp (ap_con g p p')⁻¹ :=
by induction s';induction s;esimp [ap_con,hconcat_eq];exact !vconcat_vrfl⁻¹
definition eq_of_square_hrfl [unfold 4] (p : a = a') : eq_of_square hrfl = idp_con p :=
by induction p;reflexivity
definition eq_of_square_vrfl [unfold 4] (p : a = a') : eq_of_square vrfl = (idp_con p)⁻¹ :=
by induction p;reflexivity
definition eq_of_square_hdeg_square {p q : a = a'} (r : p = q)
: eq_of_square (hdeg_square r) = !idp_con ⬝ r⁻¹ :=
by induction r;induction p;reflexivity
definition eq_of_square_vdeg_square {p q : a = a'} (r : p = q)
: eq_of_square (vdeg_square r) = r ⬝ !idp_con⁻¹ :=
by induction r;induction p;reflexivity
definition eq_of_square_eq_vconcat {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: eq_of_square (r ⬝pv s₁₁) = whisker_right p₂₁ r ⬝ eq_of_square s₁₁ :=
by induction s₁₁;cases r;reflexivity
definition eq_of_square_eq_hconcat {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
: eq_of_square (r ⬝ph s₁₁) = eq_of_square s₁₁ ⬝ (whisker_right p₁₂ r)⁻¹ :=
by induction r;reflexivity
definition eq_of_square_vconcat_eq {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p)
: eq_of_square (s₁₁ ⬝vp r) = eq_of_square s₁₁ ⬝ whisker_left p₀₁ r :=
by induction r;reflexivity
definition eq_of_square_hconcat_eq {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p)
: eq_of_square (s₁₁ ⬝hp r) = (whisker_left p₁₀ r)⁻¹ ⬝ eq_of_square s₁₁ :=
by induction s₁₁; induction r;reflexivity
definition change_path_eq_pathover {A B : Type} {a a' : A} {f g : A → B}
{p p' : a = a'} (r : p = p')
{q : f a = g a} {q' : f a' = g a'}
(s : square q q' (ap f p) (ap g p)) :
change_path r (eq_pathover s) = eq_pathover ((ap02 f r)⁻¹ ⬝ph s ⬝hp (ap02 g r)) :=
by induction r; reflexivity
definition eq_hconcat_hdeg_square {A : Type} {a a' : A} {p₁ p₂ p₃ : a = a'} (q₁ : p₁ = p₂)
(q₂ : p₂ = p₃) : q₁ ⬝ph hdeg_square q₂ = hdeg_square (q₁ ⬝ q₂) :=
by induction q₁; induction q₂; reflexivity
definition hdeg_square_hconcat_eq {A : Type} {a a' : A} {p₁ p₂ p₃ : a = a'} (q₁ : p₁ = p₂)
(q₂ : p₂ = p₃) : hdeg_square q₁ ⬝hp q₂ = hdeg_square (q₁ ⬝ q₂) :=
by induction q₁; induction q₂; reflexivity
definition eq_hconcat_eq_hdeg_square {A : Type} {a a' : A} {p₁ p₂ p₃ p₄ : a = a'} (q₁ : p₁ = p₂)
(q₂ : p₂ = p₃) (q₃ : p₃ = p₄) : q₁ ⬝ph hdeg_square q₂ ⬝hp q₃ = hdeg_square (q₁ ⬝ q₂ ⬝ q₃) :=
by induction q₃; apply eq_hconcat_hdeg_square
-- definition vconcat_eq [unfold 11] {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) :
-- square p₁₀ p p₀₁ p₂₁ :=
-- by induction r; exact s₁₁
-- definition eq_hconcat [unfold 11] {p : a₀₀ = a₀₂} (r : p = p₀₁)
-- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ :=
-- by induction r; exact s₁₁
-- definition hconcat_eq [unfold 11] {p : a₂₀ = a₂₂}
-- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p :=
-- by induction r; exact s₁₁
-- the following definition is very slow, maybe it's interesting to see why?
-- definition eq_pathover_equiv_square' {f g : A → B}(p : a = a') (q : f a = g a) (r : f a' = g a')
-- : square q r (ap f p) (ap g p) ≃ q =[p] r :=
-- equiv.MK eq_pathover
-- square_of_pathover
-- (λs, begin
-- induction p, rewrite [↑[square_of_pathover,eq_pathover],
-- to_right_inv !vdeg_square_equiv (eq_of_pathover_idp s),
-- to_left_inv !pathover_idp s]
-- end)
-- (λs, begin
-- induction p, rewrite [↑[square_of_pathover,eq_pathover],▸*,
-- to_right_inv !(@pathover_idp A) (eq_of_vdeg_square s),
-- to_left_inv !vdeg_square_equiv s]
-- end)
/- recursors for squares where some sides are reflexivity -/
definition rec_on_b [recursor] {a₀₀ : A}
{P : Π{a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂}, square t idp l r → Type}
{a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂}
(s : square t idp l r) (H : P ids) : P s :=
have H2 : P (square_of_eq (eq_of_square s)),
from eq.rec_on (eq_of_square s : t ⬝ r = l) (by induction r; induction t; exact H),
left_inv (to_fun !square_equiv_eq) s ▸ H2
definition rec_on_r [recursor] {a₀₀ : A}
{P : Π{a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂}, square t b l idp → Type}
{a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂}
(s : square t b l idp) (H : P ids) : P s :=
let p : l ⬝ b = t := (eq_of_square s)⁻¹ in
have H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹),
from @eq.rec_on _ _ (λx p, P (square_of_eq p⁻¹)) _ p (by induction b; induction l; exact H),
left_inv (to_fun !square_equiv_eq) s ▸ !inv_inv ▸ H2
definition rec_on_l [recursor] {a₀₁ : A}
{P : Π {a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂},
square t b idp r → Type}
{a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂}
(s : square t b idp r) (H : P ids) : P s :=
let p : t ⬝ r = b := eq_of_square s ⬝ !idp_con in
have H2 : P (square_of_eq (p ⬝ !idp_con⁻¹)),
from eq.rec_on p (by induction r; induction t; exact H),
left_inv (to_fun !square_equiv_eq) s ▸ !con_inv_cancel_right ▸ H2
definition rec_on_t [recursor] {a₁₀ : A}
{P : Π {a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂}, square idp b l r → Type}
{a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂}
(s : square idp b l r) (H : P ids) : P s :=
let p : l ⬝ b = r := (eq_of_square s)⁻¹ ⬝ !idp_con in
have H2 : P (square_of_eq ((p ⬝ !idp_con⁻¹)⁻¹)),
from eq.rec_on p (by induction b; induction l; exact H),
have H3 : P (square_of_eq ((eq_of_square s)⁻¹⁻¹)),
from eq.rec_on !con_inv_cancel_right H2,
have H4 : P (square_of_eq (eq_of_square s)),
from eq.rec_on !inv_inv H3,
proof
left_inv (to_fun !square_equiv_eq) s ▸ H4
qed
definition rec_on_tb [recursor] {a : A}
{P : Π{b : A} {l : a = b} {r : a = b}, square idp idp l r → Type}
{b : A} {l : a = b} {r : a = b}
(s : square idp idp l r) (H : P ids) : P s :=
have H2 : P (square_of_eq (eq_of_square s)),
from eq.rec_on (eq_of_square s : idp ⬝ r = l) (by induction r; exact H),
left_inv (to_fun !square_equiv_eq) s ▸ H2
definition rec_on_lr [recursor] {a : A}
{P : Π{a' : A} {t : a = a'} {b : a = a'}, square t b idp idp → Type}
{a' : A} {t : a = a'} {b : a = a'}
(s : square t b idp idp) (H : P ids) : P s :=
let p : idp ⬝ b = t := (eq_of_square s)⁻¹ in
have H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹),
from @eq.rec_on _ _ (λx q, P (square_of_eq q⁻¹)) _ p (by induction b; exact H),
to_left_inv (!square_equiv_eq) s ▸ !inv_inv ▸ H2
--we can also do the other recursors (tl, tr, bl, br, tbl, tbr, tlr, blr), but let's postpone this until they are needed
definition whisker_square [unfold 14 15 16 17] (r₁₀ : p₁₀ = p₁₀') (r₁₂ : p₁₂ = p₁₂')
(r₀₁ : p₀₁ = p₀₁') (r₂₁ : p₂₁ = p₂₁') (s : square p₁₀ p₁₂ p₀₁ p₂₁)
: square p₁₀' p₁₂' p₀₁' p₂₁' :=
by induction r₁₀; induction r₁₂; induction r₀₁; induction r₂₁; exact s
/- squares commute with some operations on 2-paths -/
definition square_inv2 {p₁ p₂ p₃ p₄ : a = a'}
{t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄} (s : square t b l r)
: square (inverse2 t) (inverse2 b) (inverse2 l) (inverse2 r) :=
by induction s;constructor
definition square_con2 {p₁ p₂ p₃ p₄ : a₁ = a₂} {q₁ q₂ q₃ q₄ : a₂ = a₃}
{t₁ : p₁ = p₂} {b₁ : p₃ = p₄} {l₁ : p₁ = p₃} {r₁ : p₂ = p₄}
{t₂ : q₁ = q₂} {b₂ : q₃ = q₄} {l₂ : q₁ = q₃} {r₂ : q₂ = q₄}
(s₁ : square t₁ b₁ l₁ r₁) (s₂ : square t₂ b₂ l₂ r₂)
: square (t₁ ◾ t₂) (b₁ ◾ b₂) (l₁ ◾ l₂) (r₁ ◾ r₂) :=
by induction s₂;induction s₁;constructor
open is_trunc
definition is_set.elims [H : is_set A] : square p₁₀ p₁₂ p₀₁ p₂₁ :=
square_of_eq !is_set.elim
definition is_trunc_square [instance] (n : trunc_index) [H : is_trunc n .+2 A]
: is_trunc n (square p₁₀ p₁₂ p₀₁ p₂₁) :=
is_trunc_equiv_closed_rev n !square_equiv_eq _
-- definition square_of_con_inv_hsquare {p₁ p₂ p₃ p₄ : a₁ = a₂}
-- {t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄}
-- (s : square (con_inv_eq_idp t) (con_inv_eq_idp b) (l ◾ r⁻²) idp)
-- : square t b l r :=
-- sorry --by induction s
/- Square fillers -/
-- TODO replace by "more algebraic" fillers?
variables (p₁₀ p₁₂ p₀₁ p₂₁)
definition square_fill_t : Σ (p : a₀₀ = a₂₀), square p p₁₂ p₀₁ p₂₁ :=
by induction p₀₁; induction p₂₁; exact ⟨_, !vrefl⟩
definition square_fill_b : Σ (p : a₀₂ = a₂₂), square p₁₀ p p₀₁ p₂₁ :=
by induction p₀₁; induction p₂₁; exact ⟨_, !vrefl⟩
definition square_fill_l : Σ (p : a₀₀ = a₀₂), square p₁₀ p₁₂ p p₂₁ :=
by induction p₁₀; induction p₁₂; exact ⟨_, !hrefl⟩
definition square_fill_r : Σ (p : a₂₀ = a₂₂) , square p₁₀ p₁₂ p₀₁ p :=
by induction p₁₀; induction p₁₂; exact ⟨_, !hrefl⟩
variables {p₁₀ p₁₂ p₀₁ p₂₁}
/- Squares having an 'ap' term on one face -/
--TODO find better names
definition square_Flr_ap_idp {c : B} {f : A → B} (p : Π a, f a = c)
{a b : A} (q : a = b) : square (p a) (p b) (ap f q) idp :=
by induction q; apply vrfl
definition square_Flr_idp_ap {c : B} {f : A → B} (p : Π a, c = f a)
{a b : A} (q : a = b) : square (p a) (p b) idp (ap f q) :=
by induction q; apply vrfl
definition square_ap_idp_Flr {b : B} {f : A → B} (p : Π a, f a = b)
{a b : A} (q : a = b) : square (ap f q) idp (p a) (p b) :=
by induction q; apply hrfl
/- Matching eq_hconcat with hconcat etc. -/
-- TODO maybe rename hconcat_eq and the like?
variable (s₁₁)
definition ph_eq_pv_h_vp {p : a₀₀ = a₀₂} (r : p = p₀₁) :
r ⬝ph s₁₁ = !idp_con⁻¹ ⬝pv ((hdeg_square r) ⬝h s₁₁) ⬝vp !idp_con :=
by cases r; cases s₁₁; esimp
definition hdeg_h_eq_pv_ph_vp {p : a₀₀ = a₀₂} (r : p = p₀₁) :
hdeg_square r ⬝h s₁₁ = !idp_con ⬝pv (r ⬝ph s₁₁) ⬝vp !idp_con⁻¹ :=
by cases r; cases s₁₁; esimp
definition hp_eq_h {p : a₂₀ = a₂₂} (r : p₂₁ = p) :
s₁₁ ⬝hp r = s₁₁ ⬝h hdeg_square r :=
by cases r; cases s₁₁; esimp
definition pv_eq_ph_vdeg_v_vh {p : a₀₀ = a₂₀} (r : p = p₁₀) :
r ⬝pv s₁₁ = !idp_con⁻¹ ⬝ph ((vdeg_square r) ⬝v s₁₁) ⬝hp !idp_con :=
by cases r; cases s₁₁; esimp
definition vdeg_v_eq_ph_pv_hp {p : a₀₀ = a₂₀} (r : p = p₁₀) :
vdeg_square r ⬝v s₁₁ = !idp_con ⬝ph (r ⬝pv s₁₁) ⬝hp !idp_con⁻¹ :=
by cases r; cases s₁₁; esimp
definition vp_eq_v {p : a₀₂ = a₂₂} (r : p₁₂ = p) :
s₁₁ ⬝vp r = s₁₁ ⬝v vdeg_square r :=
by cases r; cases s₁₁; esimp
definition natural_square [unfold 8] {f g : A → B} (p : f ~ g) (q : a = a') :
square (p a) (p a') (ap f q) (ap g q) :=
square_of_pathover (apd p q)
definition natural_square_tr [unfold 8] {f g : A → B} (p : f ~ g) (q : a = a') :
square (ap f q) (ap g q) (p a) (p a') :=
transpose (natural_square p q)
definition natural_square011 {A A' : Type} {B : A → Type}
{a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b')
{l r : Π⦃a⦄, B a → A'} (g : Π⦃a⦄ (b : B a), l b = r b)
: square (apd011 l p q) (apd011 r p q) (g b) (g b') :=
begin
induction q, exact hrfl
end
definition natural_square0111' {A A' : Type} {B : A → Type} (C : Π⦃a⦄, B a → Type)
{a a' : A} {p : a = a'} {b : B a} {b' : B a'} {q : b =[p] b'}
{c : C b} {c' : C b'} (s : c =[apd011 C p q] c')
{l r : Π⦃a⦄ {b : B a}, C b → A'}
(g : Π⦃a⦄ {b : B a} (c : C b), l c = r c)
: square (apd0111 l p q s) (apd0111 r p q s) (g c) (g c') :=
begin
induction q, esimp at s, induction s using idp_rec_on, exact hrfl
end
-- this can be generalized a bit, by making the domain and codomain of k different, and also have
-- a function at the RHS of s (similar to m)
definition natural_square0111 {A A' : Type} {B : A → Type} (C : Π⦃a⦄, B a → Type)
{a a' : A} {p : a = a'} {b : B a} {b' : B a'} {q : b =[p] b'}
{c : C b} {c' : C b'} (r : c =[apd011 C p q] c')
{k : A → A} {l : Π⦃a⦄, B a → B (k a)} (m : Π⦃a⦄ {b : B a}, C b → C (l b))
{f : Π⦃a⦄ {b : B a}, C b → A'}
(s : Π⦃a⦄ {b : B a} (c : C b), f (m c) = f c)
: square (apd0111 (λa b c, f (m c)) p q r) (apd0111 f p q r) (s c) (s c') :=
begin
induction q, esimp at r, induction r using idp_rec_on, exact hrfl
end
definition natural_square2 {A B X : Type} {C : A → B → Type}
{a a₂ : A} {b b₂ : B} {c : C a b} {c₂ : C a₂ b₂} {f : A → X} {g : B → X}
(h : Πa b, C a b → f a = g b) (p : a = a₂) (q : b = b₂) (r : transport11 C p q c = c₂) :
square (h a b c) (h a₂ b₂ c₂) (ap f p) (ap g q) :=
by induction p; induction q; induction r; exact vrfl
/- some higher coherence conditions -/
theorem whisker_bl_whisker_tl_eq (p : a = a')
: whisker_bl p (whisker_tl p ids) = con.right_inv p ⬝ph vrfl :=
by induction p; reflexivity
theorem ap_is_constant_natural_square {g : B → C} {f : A → B} (H : Πa, g (f a) = c) (p : a = a') :
(ap_is_constant H p)⁻¹ ⬝ph natural_square H p ⬝hp ap_constant p c =
whisker_bl (H a') (whisker_tl (H a) ids) :=
begin induction p, esimp, rewrite inv_inv, rewrite whisker_bl_whisker_tl_eq end
definition inv_ph_eq_of_eq_ph {p : a₀₀ = a₀₂} {r : p₀₁ = p} {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁}
{s₁₁' : square p₁₀ p₁₂ p p₂₁} (t : s₁₁ = r ⬝ph s₁₁') : r⁻¹ ⬝ph s₁₁ = s₁₁' :=
by induction r; exact t
-- the following is used for torus.elim_surf
theorem whisker_square_aps_eq {f : A → B}
{q₁₀ : f a₀₀ = f a₂₀} {q₀₁ : f a₀₀ = f a₀₂} {q₂₁ : f a₂₀ = f a₂₂} {q₁₂ : f a₀₂ = f a₂₂}
{r₁₀ : ap f p₁₀ = q₁₀} {r₀₁ : ap f p₀₁ = q₀₁} {r₂₁ : ap f p₂₁ = q₂₁} {r₁₂ : ap f p₁₂ = q₁₂}
{s₁₁ : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} {t₁₁ : square q₁₀ q₁₂ q₀₁ q₂₁}
(u : square (ap02 f s₁₁) (eq_of_square t₁₁)
(ap_con f p₁₀ p₂₁ ⬝ (r₁₀ ◾ r₂₁)) (ap_con f p₀₁ p₁₂ ⬝ (r₀₁ ◾ r₁₂)))
: whisker_square r₁₀ r₁₂ r₀₁ r₂₁ (aps f (square_of_eq s₁₁)) = t₁₁ :=
begin
induction r₁₀, induction r₀₁, induction r₁₂, induction r₂₁,
induction p₁₂, induction p₁₀, induction p₂₁, esimp at *, induction s₁₁, esimp at *,
esimp [square_of_eq],
apply inj !square_equiv_eq, esimp,
exact (eq_bot_of_square u)⁻¹
end
definition natural_square_eq {A B : Type} {a a' : A} {f g : A → B} (p : f ~ g) (q : a = a')
: natural_square p q = square_of_pathover (apd p q) :=
idp
definition eq_of_square_hrfl_hconcat_eq {A : Type} {a a' : A} {p p' : a = a'} (q : p = p')
: eq_of_square (hrfl ⬝hp q⁻¹) = !idp_con ⬝ q :=
by induction q; induction p; reflexivity
definition aps_vrfl {A B : Type} {a a' : A} (f : A → B) (p : a = a') :
aps f (vrefl p) = vrefl (ap f p) :=
by induction p; reflexivity
definition aps_hrfl {A B : Type} {a a' : A} (f : A → B) (p : a = a') :
aps f (hrefl p) = hrefl (ap f p) :=
by induction p; reflexivity
-- should the following two equalities be cubes?
definition natural_square_ap_fn {A B C : Type} {a a' : A} {g h : A → B} (f : B → C) (p : g ~ h)
(q : a = a') : natural_square (λa, ap f (p a)) q =
ap_compose f g q ⬝ph (aps f (natural_square p q) ⬝hp (ap_compose f h q)⁻¹) :=
begin
induction q, exact !aps_vrfl⁻¹
end
definition natural_square_compose {A B C : Type} {a a' : A} {g g' : B → C}
(p : g ~ g') (f : A → B) (q : a = a') : natural_square (λa, p (f a)) q =
ap_compose g f q ⬝ph (natural_square p (ap f q) ⬝hp (ap_compose g' f q)⁻¹) :=
by induction q; reflexivity
definition natural_square_eq2 {A B : Type} {a a' : A} {f f' : A → B} (p : f ~ f') {q q' : a = a'}
(r : q = q') : natural_square p q = ap02 f r ⬝ph (natural_square p q' ⬝hp (ap02 f' r)⁻¹) :=
by induction r; reflexivity
definition natural_square_refl {A B : Type} {a a' : A} (f : A → B) (q : a = a')
: natural_square (homotopy.refl f) q = hrfl :=
by induction q; reflexivity
definition aps_eq_hconcat {p₀₁'} (f : A → B) (q : p₀₁' = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) :
aps f (q ⬝ph s₁₁) = ap02 f q ⬝ph aps f s₁₁ :=
by induction q; reflexivity
definition aps_hconcat_eq {p₂₁'} (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁' = p₂₁) :
aps f (s₁₁ ⬝hp r⁻¹) = aps f s₁₁ ⬝hp (ap02 f r)⁻¹ :=
by induction r; reflexivity
definition aps_hconcat_eq' {p₂₁'} (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p₂₁') :
aps f (s₁₁ ⬝hp r) = aps f s₁₁ ⬝hp ap02 f r :=
by induction r; reflexivity
definition aps_square_of_eq (f : A → B) (s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂) :
aps f (square_of_eq s) = square_of_eq ((ap_con f p₁₀ p₂₁)⁻¹ ⬝ ap02 f s ⬝ ap_con f p₀₁ p₁₂) :=
by induction p₁₂; esimp at *; induction s; induction p₂₁; induction p₁₀; reflexivity
definition aps_eq_hconcat_eq {p₀₁' p₂₁'} (f : A → B) (q : p₀₁' = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁)
(r : p₂₁' = p₂₁) : aps f (q ⬝ph s₁₁ ⬝hp r⁻¹) = ap02 f q ⬝ph aps f s₁₁ ⬝hp (ap02 f r)⁻¹ :=
by induction q; induction r; reflexivity
definition eq_hconcat_equiv [constructor] {p : a₀₀ = a₀₂} (r : p = p₀₁) :
square p₁₀ p₁₂ p p₂₁ ≃ square p₁₀ p₁₂ p₀₁ p₂₁ :=
equiv.MK (eq_hconcat r⁻¹) (eq_hconcat r)
begin intro s, induction r, reflexivity end begin intro s, induction r, reflexivity end
definition hconcat_eq_equiv [constructor] {p : a₂₀ = a₂₂} (r : p₂₁ = p) :
square p₁₀ p₁₂ p₀₁ p₂₁ ≃ square p₁₀ p₁₂ p₀₁ p :=
equiv.MK (λs, hconcat_eq s r) (λs, hconcat_eq s r⁻¹)
begin intro s, induction r, reflexivity end begin intro s, induction r, reflexivity end
end eq
|
c2b71c62ee3caa36eed6401c2ef9848f4801e75f | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/linear_algebra/matrix.lean | 45fc8b7406c3d0fb91746ddd7ac72f83e796a922 | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 11,291 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl, Casper Putz
The equivalence between matrices and linear maps.
-/
import data.matrix.basic
import linear_algebra.dimension linear_algebra.tensor_product
/-!
# Linear maps and matrices
This file defines the maps to send matrices to a linear map,
and to send linear maps between modules with a finite bases
to matrices. This defines a linear equivalence between linear maps
between finite-dimensional vector spaces and matrices indexed by
the respective bases.
Some results are proved about the linear map corresponding to a
diagonal matrix (range, ker and rank).
## Main definitions
to_lin, to_matrix, linear_equiv_matrix
## Tags
linear_map, matrix, linear_equiv, diagonal
-/
noncomputable theory
open set submodule
universes u v w
variables {l m n : Type u} [fintype l] [fintype m] [fintype n]
namespace matrix
variables {R : Type v} [comm_ring R]
instance [decidable_eq m] [decidable_eq n] (R) [fintype R] : fintype (matrix m n R) :=
by unfold matrix; apply_instance
/-- Evaluation of matrices gives a linear map from matrix m n R to
linear maps (n → R) →ₗ[R] (m → R). -/
def eval : (matrix m n R) →ₗ[R] ((n → R) →ₗ[R] (m → R)) :=
begin
refine linear_map.mk₂ R mul_vec _ _ _ _,
{ assume M N v, funext x,
change finset.univ.sum (λy:n, (M x y + N x y) * v y) = _,
simp only [_root_.add_mul, finset.sum_add_distrib],
refl },
{ assume c M v, funext x,
change finset.univ.sum (λy:n, (c * M x y) * v y) = _,
simp only [_root_.mul_assoc, finset.mul_sum.symm],
refl },
{ assume M v w, funext x,
change finset.univ.sum (λy:n, M x y * (v y + w y)) = _,
simp [_root_.mul_add, finset.sum_add_distrib],
refl },
{ assume c M v, funext x,
change finset.univ.sum (λy:n, M x y * (c * v y)) = _,
rw [show (λy:n, M x y * (c * v y)) = (λy:n, c * (M x y * v y)), { funext n, ac_refl },
← finset.mul_sum],
refl }
end
/-- Evaluation of matrices gives a map from matrix m n R to
linear maps (n → R) →ₗ[R] (m → R). -/
def to_lin : matrix m n R → (n → R) →ₗ[R] (m → R) := eval.to_fun
lemma to_lin_add (M N : matrix m n R) : (M + N).to_lin = M.to_lin + N.to_lin :=
matrix.eval.map_add M N
@[simp] lemma to_lin_zero : (0 : matrix m n R).to_lin = 0 :=
matrix.eval.map_zero
instance to_lin.is_linear_map :
@is_linear_map R (matrix m n R) ((n → R) →ₗ[R] (m → R)) _ _ _ _ _ to_lin :=
matrix.eval.is_linear
instance to_lin.is_add_monoid_hom :
@is_add_monoid_hom (matrix m n R) ((n → R) →ₗ[R] (m → R)) _ _ to_lin :=
{ map_zero := to_lin_zero, map_add := to_lin_add }
@[simp] lemma to_lin_apply (M : matrix m n R) (v : n → R) :
(M.to_lin : (n → R) → (m → R)) v = mul_vec M v := rfl
lemma mul_to_lin [decidable_eq l] (M : matrix m n R) (N : matrix n l R) :
(M.mul N).to_lin = M.to_lin.comp N.to_lin :=
begin
ext v x,
simp [to_lin_apply, mul_vec, matrix.mul, finset.sum_mul, finset.mul_sum],
rw [finset.sum_comm],
congr, funext x, congr, funext y,
rw [mul_assoc]
end
@[simp] lemma to_lin_one [decidable_eq n] : (1 : matrix n n R).to_lin = linear_map.id :=
by { ext, simp }
end matrix
namespace linear_map
variables {R : Type v} [comm_ring R]
/-- The linear map from linear maps (n → R) →ₗ[R] (m → R) to matrix m n R. -/
def to_matrixₗ [decidable_eq n] : ((n → R) →ₗ[R] (m → R)) →ₗ[R] matrix m n R :=
begin
refine linear_map.mk (λ f i j, f (λ n, ite (j = n) 1 0) i) _ _,
{ assume f g, simp only [add_apply], refl },
{ assume f g, simp only [smul_apply], refl }
end
/-- The map from linear maps (n → R) →ₗ[R] (m → R) to matrix m n R. -/
def to_matrix [decidable_eq n] : ((n → R) →ₗ[R] (m → R)) → matrix m n R := to_matrixₗ.to_fun
end linear_map
section linear_equiv_matrix
variables {R : Type v} [comm_ring R] [decidable_eq n]
open finsupp matrix linear_map
/-- to_lin is the left inverse of to_matrix. -/
lemma to_matrix_to_lin {f : (n → R) →ₗ[R] (m → R)} :
to_lin (to_matrix f) = f :=
begin
ext : 1,
-- Show that the two sides are equal by showing that they are equal on a basis
convert linear_eq_on (set.range _) _ (is_basis.mem_span (@pi.is_basis_fun R n _ _) _),
assume e he,
rw [@std_basis_eq_single R _ _ _ 1] at he,
cases (set.mem_range.mp he) with i h,
ext j,
change finset.univ.sum (λ k, (f.to_fun (λ l, ite (k = l) 1 0)) j * (e k)) = _,
rw [←h],
conv_lhs { congr, skip, funext,
rw [mul_comm, ←smul_eq_mul, ←pi.smul_apply, ←linear_map.smul],
rw [show _ = ite (i = k) (1:R) 0, by convert single_apply],
rw [show f.to_fun (ite (i = k) (1:R) 0 • (λ l, ite (k = l) 1 0)) = ite (i = k) (f.to_fun _) 0,
{ split_ifs, { rw [one_smul] }, { rw [zero_smul], exact linear_map.map_zero f } }] },
convert finset.sum_eq_single i _ _,
{ rw [if_pos rfl], convert rfl, ext, congr },
{ assume _ _ hbi, rw [if_neg $ ne.symm hbi], refl },
{ assume hi, exact false.elim (hi $ finset.mem_univ i) }
end
/-- to_lin is the right inverse of to_matrix. -/
lemma to_lin_to_matrix {M : matrix m n R} : to_matrix (to_lin M) = M :=
begin
ext,
change finset.univ.sum (λ y, M i y * ite (j = y) 1 0) = M i j,
have h1 : (λ y, M i y * ite (j = y) 1 0) = (λ y, ite (j = y) (M i y) 0),
{ ext, split_ifs, exact mul_one _, exact ring.mul_zero _ },
have h2 : finset.univ.sum (λ y, ite (j = y) (M i y) 0) = (finset.singleton j).sum (λ y, ite (j = y) (M i y) 0),
{ refine (finset.sum_subset _ _).symm,
{ intros _ H, rwa finset.mem_singleton.1 H, exact finset.mem_univ _ },
{ exact λ _ _ H, if_neg (mt (finset.mem_singleton.2 ∘ eq.symm) H) } },
rw [h1, h2, finset.sum_singleton],
exact if_pos rfl
end
/-- Linear maps (n → R) →ₗ[R] (m → R) are linearly equivalent to matrix m n R. -/
def linear_equiv_matrix' : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] matrix m n R :=
{ to_fun := to_matrix,
inv_fun := to_lin,
right_inv := λ _, to_lin_to_matrix,
left_inv := λ _, to_matrix_to_lin,
add := to_matrixₗ.add,
smul := to_matrixₗ.smul }
/-- Given a basis of two modules M₁ and M₂ over a commutative ring R, we get a linear equivalence
between linear maps M₁ →ₗ M₂ and matrices over R indexed by the bases. -/
def linear_equiv_matrix {ι κ M₁ M₂ : Type*}
[add_comm_group M₁] [module R M₁]
[add_comm_group M₂] [module R M₂]
[fintype ι] [decidable_eq ι] [fintype κ] [decidable_eq κ]
{v₁ : ι → M₁} {v₂ : κ → M₂} (hv₁ : is_basis R v₁) (hv₂ : is_basis R v₂) :
(M₁ →ₗ[R] M₂) ≃ₗ[R] matrix κ ι R :=
linear_equiv.trans (linear_equiv.arrow_congr (equiv_fun_basis hv₁) (equiv_fun_basis hv₂)) linear_equiv_matrix'
end linear_equiv_matrix
namespace matrix
open_locale matrix
section trace
variables {R : Type v} {M : Type w} [ring R] [add_comm_group M] [module R M]
/--
The diagonal of a square matrix.
-/
def diag (n : Type u) (R : Type v) (M : Type w)
[ring R] [add_comm_group M] [module R M] [fintype n] : (matrix n n M) →ₗ[R] n → M := {
to_fun := λ A i, A i i,
add := by { intros, ext, refl, },
smul := by { intros, ext, refl, } }
@[simp] lemma diag_one [decidable_eq n] :
diag n R R 1 = λ i, 1 := by { dunfold diag, ext, simp [one_val_eq] }
@[simp] lemma diag_transpose (A : matrix n n M) : diag n R M Aᵀ = diag n R M A := rfl
/--
The trace of a square matrix.
-/
def trace (n : Type u) (R : Type v) (M : Type w)
[ring R] [add_comm_group M] [module R M] [fintype n] : (matrix n n M) →ₗ[R] M := {
to_fun := finset.univ.sum ∘ (diag n R M),
add := by { intros, apply finset.sum_add_distrib, },
smul := by { intros, simp [finset.smul_sum], } }
@[simp] lemma trace_one [decidable_eq n] :
trace n R R 1 = fintype.card n :=
have h : trace n R R 1 = finset.univ.sum (diag n R R 1) := rfl,
by rw [h, diag_one, finset.sum_const, add_monoid.smul_one]; refl
@[simp] lemma trace_transpose (A : matrix n n M) : trace n R M Aᵀ = trace n R M A := rfl
@[simp] lemma trace_transpose_mul [decidable_eq n] (A : matrix m n R) (B : matrix n m R) :
trace n R R (Aᵀ ⬝ Bᵀ) = trace m R R (A ⬝ B) := finset.sum_comm
lemma trace_mul_comm {S : Type v} [comm_ring S] [decidable_eq n]
(A : matrix m n S) (B : matrix n m S) :
trace n S S (B ⬝ A) = trace m S S (A ⬝ B) :=
by rw [←trace_transpose, ←trace_transpose_mul, transpose_mul]
end trace
section ring
variables {R : Type v} [comm_ring R]
open linear_map matrix
lemma proj_diagonal [decidable_eq m] (i : m) (w : m → R) :
(proj i).comp (to_lin (diagonal w)) = (w i) • proj i :=
by ext j; simp [mul_vec_diagonal]
lemma diagonal_comp_std_basis [decidable_eq n] (w : n → R) (i : n) :
(diagonal w).to_lin.comp (std_basis R (λ_:n, R) i) = (w i) • std_basis R (λ_:n, R) i :=
begin
ext a j,
simp only [linear_map.comp_apply, smul_apply, to_lin_apply, mul_vec_diagonal, smul_apply,
pi.smul_apply, smul_eq_mul],
by_cases i = j,
{ subst h },
{ rw [std_basis_ne R (λ_:n, R) _ _ (ne.symm h), _root_.mul_zero, _root_.mul_zero] }
end
end ring
section vector_space
variables {K : Type u} [field K] -- maybe try to relax the universe constraint
open linear_map matrix
lemma rank_vec_mul_vec [decidable_eq n] (w : m → K) (v : n → K) :
rank (vec_mul_vec w v).to_lin ≤ 1 :=
begin
rw [vec_mul_vec_eq, mul_to_lin],
refine le_trans (rank_comp_le1 _ _) _,
refine le_trans (rank_le_domain _) _,
rw [dim_fun', ← cardinal.fintype_card],
exact le_refl _
end
set_option class.instance_max_depth 100
lemma diagonal_to_lin [decidable_eq m] (w : m → K) :
(diagonal w).to_lin = linear_map.pi (λi, w i • linear_map.proj i) :=
by ext v j; simp [mul_vec_diagonal]
lemma ker_diagonal_to_lin [decidable_eq m] (w : m → K) :
ker (diagonal w).to_lin = (⨆i∈{i | w i = 0 }, range (std_basis K (λi, K) i)) :=
begin
rw [← comap_bot, ← infi_ker_proj],
simp only [comap_infi, (ker_comp _ _).symm, proj_diagonal, ker_smul'],
have : univ ⊆ {i : m | w i = 0} ∪ -{i : m | w i = 0}, { rw set.union_compl_self },
exact (supr_range_std_basis_eq_infi_ker_proj K (λi:m, K)
(disjoint_compl {i | w i = 0}) this (finite.of_fintype _)).symm
end
lemma range_diagonal [decidable_eq m] (w : m → K) :
(diagonal w).to_lin.range = (⨆ i ∈ {i | w i ≠ 0}, (std_basis K (λi, K) i).range) :=
begin
dsimp only [mem_set_of_eq],
rw [← map_top, ← supr_range_std_basis, map_supr],
congr, funext i,
rw [← linear_map.range_comp, diagonal_comp_std_basis, range_smul'],
end
lemma rank_diagonal [decidable_eq m] [decidable_eq K] (w : m → K) :
rank (diagonal w).to_lin = fintype.card { i // w i ≠ 0 } :=
begin
have hu : univ ⊆ - {i : m | w i = 0} ∪ {i : m | w i = 0}, { rw set.compl_union_self },
have hd : disjoint {i : m | w i ≠ 0} {i : m | w i = 0} := (disjoint_compl {i | w i = 0}).symm,
have h₁ := supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) hd hu (finite.of_fintype _),
have h₂ := @infi_ker_proj_equiv K _ _ (λi:m, K) _ _ _ _ (by simp; apply_instance) hd hu,
rw [rank, range_diagonal, h₁, ←@dim_fun' K],
apply linear_equiv.dim_eq,
apply h₂,
end
end vector_space
end matrix
|
9a7d66911dabc6287be59a9f3d833d30bd7c5cae | c86b74188c4b7a462728b1abd659ab4e5828dd61 | /src/Lean/Compiler/IR/EmitC.lean | 98c2d5823eb1dfb1a24722f29210032d7125e245 | [
"Apache-2.0"
] | permissive | cwb96/lean4 | 75e1f92f1ba98bbaa6b34da644b3dfab2ce7bf89 | b48831cda76e64f13dd1c0edde7ba5fb172ed57a | refs/heads/master | 1,686,347,881,407 | 1,624,483,842,000 | 1,624,483,842,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 25,244 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Runtime
import Lean.Compiler.NameMangling
import Lean.Compiler.ExportAttr
import Lean.Compiler.InitAttr
import Lean.Compiler.IR.CompilerM
import Lean.Compiler.IR.EmitUtil
import Lean.Compiler.IR.NormIds
import Lean.Compiler.IR.SimpCase
import Lean.Compiler.IR.Boxing
namespace Lean.IR.EmitC
open ExplicitBoxing (requiresBoxedVersion mkBoxedName isBoxedName)
def leanMainFn := "_lean_main"
structure Context where
env : Environment
modName : Name
jpMap : JPParamsMap := {}
mainFn : FunId := arbitrary
mainParams : Array Param := #[]
abbrev M := ReaderT Context (EStateM String String)
def getEnv : M Environment := Context.env <$> read
def getModName : M Name := Context.modName <$> read
def getDecl (n : Name) : M Decl := do
let env ← getEnv
match findEnvDecl env n with
| some d => pure d
| none => throw s!"unknown declaration '{n}'"
@[inline] def emit {α : Type} [ToString α] (a : α) : M Unit :=
modify fun out => out ++ toString a
@[inline] def emitLn {α : Type} [ToString α] (a : α) : M Unit := do
emit a; emit "\n"
def emitLns {α : Type} [ToString α] (as : List α) : M Unit :=
as.forM fun a => emitLn a
def argToCString (x : Arg) : String :=
match x with
| Arg.var x => toString x
| _ => "lean_box(0)"
def emitArg (x : Arg) : M Unit :=
emit (argToCString x)
def toCType : IRType → String
| IRType.float => "double"
| IRType.uint8 => "uint8_t"
| IRType.uint16 => "uint16_t"
| IRType.uint32 => "uint32_t"
| IRType.uint64 => "uint64_t"
| IRType.usize => "size_t"
| IRType.object => "lean_object*"
| IRType.tobject => "lean_object*"
| IRType.irrelevant => "lean_object*"
| IRType.struct _ _ => panic! "not implemented yet"
| IRType.union _ _ => panic! "not implemented yet"
def throwInvalidExportName {α : Type} (n : Name) : M α :=
throw s!"invalid export name '{n}'"
def toCName (n : Name) : M String := do
let env ← getEnv;
-- TODO: we should support simple export names only
match getExportNameFor env n with
| some (Name.str Name.anonymous s _) => pure s
| some _ => throwInvalidExportName n
| none => if n == `main then pure leanMainFn else pure n.mangle
def emitCName (n : Name) : M Unit :=
toCName n >>= emit
def toCInitName (n : Name) : M String := do
let env ← getEnv;
-- TODO: we should support simple export names only
match getExportNameFor env n with
| some (Name.str Name.anonymous s _) => pure $ "_init_" ++ s
| some _ => throwInvalidExportName n
| none => pure ("_init_" ++ n.mangle)
def emitCInitName (n : Name) : M Unit :=
toCInitName n >>= emit
def emitFnDeclAux (decl : Decl) (cppBaseName : String) (addExternForConsts : Bool) : M Unit := do
let ps := decl.params
let env ← getEnv
if ps.isEmpty then
if isClosedTermName env decl.name then emit "static "
else if addExternForConsts then emit "extern "
emit (toCType decl.resultType ++ " " ++ cppBaseName)
unless ps.isEmpty do
emit "("
-- We omit irrelevant parameters for extern constants
let ps := if isExternC env decl.name then ps.filter (fun p => !p.ty.isIrrelevant) else ps
if ps.size > closureMaxArgs && isBoxedName decl.name then
emit "lean_object**"
else
ps.size.forM fun i => do
if i > 0 then emit ", "
emit (toCType ps[i].ty)
emit ")"
emitLn ";"
def emitFnDecl (decl : Decl) (addExternForConsts : Bool) : M Unit := do
let cppBaseName ← toCName decl.name
emitFnDeclAux decl cppBaseName addExternForConsts
def emitExternDeclAux (decl : Decl) (cNameStr : String) : M Unit := do
let cName := Name.mkSimple cNameStr
let env ← getEnv
let extC := isExternC env decl.name
emitFnDeclAux decl cNameStr (!extC)
def emitFnDecls : M Unit := do
let env ← getEnv
let decls := getDecls env
let modDecls : NameSet := decls.foldl (fun s d => s.insert d.name) {}
let usedDecls : NameSet := decls.foldl (fun s d => collectUsedDecls env d (s.insert d.name)) {}
let usedDecls := usedDecls.toList
usedDecls.forM fun n => do
let decl ← getDecl n;
match getExternNameFor env `c decl.name with
| some cName => emitExternDeclAux decl cName
| none => emitFnDecl decl (!modDecls.contains n)
def emitMainFn : M Unit := do
let d ← getDecl `main
match d with
| Decl.fdecl (f := f) (xs := xs) (type := t) (body := b) .. => do
unless xs.size == 2 || xs.size == 1 do throw "invalid main function, incorrect arity when generating code"
let env ← getEnv
let usesLeanAPI := usesModuleFrom env `Lean
if usesLeanAPI then
emitLn "void lean_initialize();"
else
emitLn "void lean_initialize_runtime_module();";
emitLn "
#if defined(WIN32) || defined(_WIN32)
#include <windows.h>
#endif
int main(int argc, char ** argv) {
#if defined(WIN32) || defined(_WIN32)
SetErrorMode(SEM_FAILCRITICALERRORS);
#endif
lean_object* in; lean_object* res;";
if usesLeanAPI then
emitLn "lean_initialize();"
else
emitLn "lean_initialize_runtime_module();"
let modName ← getModName
emitLn ("res = " ++ mkModuleInitializationFunctionName modName ++ "(lean_io_mk_world());")
emitLns ["lean_io_mark_end_initialization();",
"if (lean_io_result_is_ok(res)) {",
"lean_dec_ref(res);",
"lean_init_task_manager();"];
if xs.size == 2 then
emitLns ["in = lean_box(0);",
"int i = argc;",
"while (i > 1) {",
" lean_object* n;",
" i--;",
" n = lean_alloc_ctor(1,2,0); lean_ctor_set(n, 0, lean_mk_string(argv[i])); lean_ctor_set(n, 1, in);",
" in = n;",
"}"]
emitLn ("res = " ++ leanMainFn ++ "(in, lean_io_mk_world());")
else
emitLn ("res = " ++ leanMainFn ++ "(lean_io_mk_world());")
emitLn "}"
emitLns ["if (lean_io_result_is_ok(res)) {",
" int ret = lean_unbox(lean_io_result_get_value(res));",
" lean_dec_ref(res);",
" return ret;",
"} else {",
" lean_io_result_show_error(res);",
" lean_dec_ref(res);",
" return 1;",
"}"]
emitLn "}"
| other => throw "function declaration expected"
def hasMainFn : M Bool := do
let env ← getEnv
let decls := getDecls env
pure $ decls.any (fun d => d.name == `main)
def emitMainFnIfNeeded : M Unit := do
if (← hasMainFn) then emitMainFn
def emitFileHeader : M Unit := do
let env ← getEnv
let modName ← getModName
emitLn "// Lean compiler output"
emitLn ("// Module: " ++ toString modName)
emit "// Imports:"
env.imports.forM fun m => emit (" " ++ toString m)
emitLn ""
emitLn "#include <lean/lean.h>"
emitLns [
"#if defined(__clang__)",
"#pragma clang diagnostic ignored \"-Wunused-parameter\"",
"#pragma clang diagnostic ignored \"-Wunused-label\"",
"#elif defined(__GNUC__) && !defined(__CLANG__)",
"#pragma GCC diagnostic ignored \"-Wunused-parameter\"",
"#pragma GCC diagnostic ignored \"-Wunused-label\"",
"#pragma GCC diagnostic ignored \"-Wunused-but-set-variable\"",
"#endif",
"#ifdef __cplusplus",
"extern \"C\" {",
"#endif"
]
def emitFileFooter : M Unit :=
emitLns [
"#ifdef __cplusplus",
"}",
"#endif"
]
def throwUnknownVar {α : Type} (x : VarId) : M α :=
throw s!"unknown variable '{x}'"
def getJPParams (j : JoinPointId) : M (Array Param) := do
let ctx ← read;
match ctx.jpMap.find? j with
| some ps => pure ps
| none => throw "unknown join point"
def declareVar (x : VarId) (t : IRType) : M Unit := do
emit (toCType t); emit " "; emit x; emit "; "
def declareParams (ps : Array Param) : M Unit :=
ps.forM fun p => declareVar p.x p.ty
partial def declareVars : FnBody → Bool → M Bool
| e@(FnBody.vdecl x t _ b), d => do
let ctx ← read
if isTailCallTo ctx.mainFn e then
pure d
else
declareVar x t; declareVars b true
| FnBody.jdecl j xs _ b, d => do declareParams xs; declareVars b (d || xs.size > 0)
| e, d => if e.isTerminal then pure d else declareVars e.body d
def emitTag (x : VarId) (xType : IRType) : M Unit := do
if xType.isObj then do
emit "lean_obj_tag("; emit x; emit ")"
else
emit x
def isIf (alts : Array Alt) : Option (Nat × FnBody × FnBody) :=
if alts.size != 2 then none
else match alts[0] with
| Alt.ctor c b => some (c.cidx, b, alts[1].body)
| _ => none
def emitInc (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do
emit $
if checkRef then (if n == 1 then "lean_inc" else "lean_inc_n")
else (if n == 1 then "lean_inc_ref" else "lean_inc_ref_n")
emit "("; emit x
if n != 1 then emit ", "; emit n
emitLn ");"
def emitDec (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do
emit (if checkRef then "lean_dec" else "lean_dec_ref");
emit "("; emit x;
if n != 1 then emit ", "; emit n
emitLn ");"
def emitDel (x : VarId) : M Unit := do
emit "lean_free_object("; emit x; emitLn ");"
def emitSetTag (x : VarId) (i : Nat) : M Unit := do
emit "lean_ctor_set_tag("; emit x; emit ", "; emit i; emitLn ");"
def emitSet (x : VarId) (i : Nat) (y : Arg) : M Unit := do
emit "lean_ctor_set("; emit x; emit ", "; emit i; emit ", "; emitArg y; emitLn ");"
def emitOffset (n : Nat) (offset : Nat) : M Unit := do
if n > 0 then
emit "sizeof(void*)*"; emit n;
if offset > 0 then emit " + "; emit offset
else
emit offset
def emitUSet (x : VarId) (n : Nat) (y : VarId) : M Unit := do
emit "lean_ctor_set_usize("; emit x; emit ", "; emit n; emit ", "; emit y; emitLn ");"
def emitSSet (x : VarId) (n : Nat) (offset : Nat) (y : VarId) (t : IRType) : M Unit := do
match t with
| IRType.float => emit "lean_ctor_set_float"
| IRType.uint8 => emit "lean_ctor_set_uint8"
| IRType.uint16 => emit "lean_ctor_set_uint16"
| IRType.uint32 => emit "lean_ctor_set_uint32"
| IRType.uint64 => emit "lean_ctor_set_uint64"
| _ => throw "invalid instruction";
emit "("; emit x; emit ", "; emitOffset n offset; emit ", "; emit y; emitLn ");"
def emitJmp (j : JoinPointId) (xs : Array Arg) : M Unit := do
let ps ← getJPParams j
unless xs.size == ps.size do throw "invalid goto"
xs.size.forM fun i => do
let p := ps[i]
let x := xs[i]
emit p.x; emit " = "; emitArg x; emitLn ";"
emit "goto "; emit j; emitLn ";"
def emitLhs (z : VarId) : M Unit := do
emit z; emit " = "
def emitArgs (ys : Array Arg) : M Unit :=
ys.size.forM fun i => do
if i > 0 then emit ", "
emitArg ys[i]
def emitCtorScalarSize (usize : Nat) (ssize : Nat) : M Unit := do
if usize == 0 then emit ssize
else if ssize == 0 then emit "sizeof(size_t)*"; emit usize
else emit "sizeof(size_t)*"; emit usize; emit " + "; emit ssize
def emitAllocCtor (c : CtorInfo) : M Unit := do
emit "lean_alloc_ctor("; emit c.cidx; emit ", "; emit c.size; emit ", "
emitCtorScalarSize c.usize c.ssize; emitLn ");"
def emitCtorSetArgs (z : VarId) (ys : Array Arg) : M Unit :=
ys.size.forM fun i => do
emit "lean_ctor_set("; emit z; emit ", "; emit i; emit ", "; emitArg ys[i]; emitLn ");"
def emitCtor (z : VarId) (c : CtorInfo) (ys : Array Arg) : M Unit := do
emitLhs z;
if c.size == 0 && c.usize == 0 && c.ssize == 0 then do
emit "lean_box("; emit c.cidx; emitLn ");"
else do
emitAllocCtor c; emitCtorSetArgs z ys
def emitReset (z : VarId) (n : Nat) (x : VarId) : M Unit := do
emit "if (lean_is_exclusive("; emit x; emitLn ")) {";
n.forM fun i => do
emit " lean_ctor_release("; emit x; emit ", "; emit i; emitLn ");"
emit " "; emitLhs z; emit x; emitLn ";";
emitLn "} else {";
emit " lean_dec_ref("; emit x; emitLn ");";
emit " "; emitLhs z; emitLn "lean_box(0);";
emitLn "}"
def emitReuse (z : VarId) (x : VarId) (c : CtorInfo) (updtHeader : Bool) (ys : Array Arg) : M Unit := do
emit "if (lean_is_scalar("; emit x; emitLn ")) {";
emit " "; emitLhs z; emitAllocCtor c;
emitLn "} else {";
emit " "; emitLhs z; emit x; emitLn ";";
if updtHeader then emit " lean_ctor_set_tag("; emit z; emit ", "; emit c.cidx; emitLn ");"
emitLn "}";
emitCtorSetArgs z ys
def emitProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do
emitLhs z; emit "lean_ctor_get("; emit x; emit ", "; emit i; emitLn ");"
def emitUProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do
emitLhs z; emit "lean_ctor_get_usize("; emit x; emit ", "; emit i; emitLn ");"
def emitSProj (z : VarId) (t : IRType) (n offset : Nat) (x : VarId) : M Unit := do
emitLhs z;
match t with
| IRType.float => emit "lean_ctor_get_float"
| IRType.uint8 => emit "lean_ctor_get_uint8"
| IRType.uint16 => emit "lean_ctor_get_uint16"
| IRType.uint32 => emit "lean_ctor_get_uint32"
| IRType.uint64 => emit "lean_ctor_get_uint64"
| _ => throw "invalid instruction"
emit "("; emit x; emit ", "; emitOffset n offset; emitLn ");"
def toStringArgs (ys : Array Arg) : List String :=
ys.toList.map argToCString
def emitSimpleExternalCall (f : String) (ps : Array Param) (ys : Array Arg) : M Unit := do
emit f; emit "("
-- We must remove irrelevant arguments to extern calls.
discard <| ys.size.foldM
(fun i (first : Bool) =>
if ps[i].ty.isIrrelevant then
pure first
else do
unless first do emit ", "
emitArg ys[i]
pure false)
true
emitLn ");"
pure ()
def emitExternCall (f : FunId) (ps : Array Param) (extData : ExternAttrData) (ys : Array Arg) : M Unit :=
match getExternEntryFor extData `c with
| some (ExternEntry.standard _ extFn) => emitSimpleExternalCall extFn ps ys
| some (ExternEntry.inline _ pat) => do emit (expandExternPattern pat (toStringArgs ys)); emitLn ";"
| some (ExternEntry.foreign _ extFn) => emitSimpleExternalCall extFn ps ys
| _ => throw s!"failed to emit extern application '{f}'"
def emitFullApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do
emitLhs z
let decl ← getDecl f
match decl with
| Decl.extern _ ps _ extData => emitExternCall f ps extData ys
| _ =>
emitCName f
if ys.size > 0 then emit "("; emitArgs ys; emit ")"
emitLn ";"
def emitPartialApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do
let decl ← getDecl f
let arity := decl.params.size;
emitLhs z; emit "lean_alloc_closure((void*)("; emitCName f; emit "), "; emit arity; emit ", "; emit ys.size; emitLn ");";
ys.size.forM fun i => do
let y := ys[i]
emit "lean_closure_set("; emit z; emit ", "; emit i; emit ", "; emitArg y; emitLn ");"
def emitApp (z : VarId) (f : VarId) (ys : Array Arg) : M Unit :=
if ys.size > closureMaxArgs then do
emit "{ lean_object* _aargs[] = {"; emitArgs ys; emitLn "};";
emitLhs z; emit "lean_apply_m("; emit f; emit ", "; emit ys.size; emitLn ", _aargs); }"
else do
emitLhs z; emit "lean_apply_"; emit ys.size; emit "("; emit f; emit ", "; emitArgs ys; emitLn ");"
def emitBoxFn (xType : IRType) : M Unit :=
match xType with
| IRType.usize => emit "lean_box_usize"
| IRType.uint32 => emit "lean_box_uint32"
| IRType.uint64 => emit "lean_box_uint64"
| IRType.float => emit "lean_box_float"
| other => emit "lean_box"
def emitBox (z : VarId) (x : VarId) (xType : IRType) : M Unit := do
emitLhs z; emitBoxFn xType; emit "("; emit x; emitLn ");"
def emitUnbox (z : VarId) (t : IRType) (x : VarId) : M Unit := do
emitLhs z;
match t with
| IRType.usize => emit "lean_unbox_usize"
| IRType.uint32 => emit "lean_unbox_uint32"
| IRType.uint64 => emit "lean_unbox_uint64"
| IRType.float => emit "lean_unbox_float"
| other => emit "lean_unbox";
emit "("; emit x; emitLn ");"
def emitIsShared (z : VarId) (x : VarId) : M Unit := do
emitLhs z; emit "!lean_is_exclusive("; emit x; emitLn ");"
def emitIsTaggedPtr (z : VarId) (x : VarId) : M Unit := do
emitLhs z; emit "!lean_is_scalar("; emit x; emitLn ");"
def toHexDigit (c : Nat) : String :=
String.singleton c.digitChar
def quoteString (s : String) : String :=
let q := "\"";
let q := s.foldl
(fun q c => q ++
if c == '\n' then "\\n"
else if c == '\n' then "\\t"
else if c == '\\' then "\\\\"
else if c == '\"' then "\\\""
else if c.toNat <= 31 then
"\\x" ++ toHexDigit (c.toNat / 16) ++ toHexDigit (c.toNat % 16)
-- TODO(Leo): we should use `\unnnn` for escaping unicode characters.
else String.singleton c)
q;
q ++ "\""
def emitNumLit (t : IRType) (v : Nat) : M Unit := do
if t.isObj then
if v < UInt32.size then
emit "lean_unsigned_to_nat("; emit v; emit "u)"
else
emit "lean_cstr_to_nat(\""; emit v; emit "\")"
else
emit v
def emitLit (z : VarId) (t : IRType) (v : LitVal) : M Unit := do
emitLhs z;
match v with
| LitVal.num v => emitNumLit t v; emitLn ";"
| LitVal.str v => emit "lean_mk_string("; emit (quoteString v); emitLn ");"
def emitVDecl (z : VarId) (t : IRType) (v : Expr) : M Unit :=
match v with
| Expr.ctor c ys => emitCtor z c ys
| Expr.reset n x => emitReset z n x
| Expr.reuse x c u ys => emitReuse z x c u ys
| Expr.proj i x => emitProj z i x
| Expr.uproj i x => emitUProj z i x
| Expr.sproj n o x => emitSProj z t n o x
| Expr.fap c ys => emitFullApp z c ys
| Expr.pap c ys => emitPartialApp z c ys
| Expr.ap x ys => emitApp z x ys
| Expr.box t x => emitBox z x t
| Expr.unbox x => emitUnbox z t x
| Expr.isShared x => emitIsShared z x
| Expr.isTaggedPtr x => emitIsTaggedPtr z x
| Expr.lit v => emitLit z t v
def isTailCall (x : VarId) (v : Expr) (b : FnBody) : M Bool := do
let ctx ← read;
match v, b with
| Expr.fap f _, FnBody.ret (Arg.var y) => pure $ f == ctx.mainFn && x == y
| _, _ => pure false
def paramEqArg (p : Param) (x : Arg) : Bool :=
match x with
| Arg.var x => p.x == x
| _ => false
/-
Given `[p_0, ..., p_{n-1}]`, `[y_0, ..., y_{n-1}]`, representing the assignments
```
p_0 := y_0,
...
p_{n-1} := y_{n-1}
```
Return true iff we have `(i, j)` where `j > i`, and `y_j == p_i`.
That is, we have
```
p_i := y_i,
...
p_j := p_i, -- p_i was overwritten above
```
-/
def overwriteParam (ps : Array Param) (ys : Array Arg) : Bool :=
let n := ps.size;
n.any $ fun i =>
let p := ps[i]
(i+1, n).anyI fun j => paramEqArg p ys[j]
def emitTailCall (v : Expr) : M Unit :=
match v with
| Expr.fap _ ys => do
let ctx ← read
let ps := ctx.mainParams
unless ps.size == ys.size do throw "invalid tail call"
if overwriteParam ps ys then
emitLn "{"
ps.size.forM fun i => do
let p := ps[i]
let y := ys[i]
unless paramEqArg p y do
emit (toCType p.ty); emit " _tmp_"; emit i; emit " = "; emitArg y; emitLn ";"
ps.size.forM fun i => do
let p := ps[i]
let y := ys[i]
unless paramEqArg p y do emit p.x; emit " = _tmp_"; emit i; emitLn ";"
emitLn "}"
else
ys.size.forM fun i => do
let p := ps[i]
let y := ys[i]
unless paramEqArg p y do emit p.x; emit " = "; emitArg y; emitLn ";"
emitLn "goto _start;"
| _ => throw "bug at emitTailCall"
mutual
partial def emitIf (x : VarId) (xType : IRType) (tag : Nat) (t : FnBody) (e : FnBody) : M Unit := do
emit "if ("; emitTag x xType; emit " == "; emit tag; emitLn ")";
emitFnBody t;
emitLn "else";
emitFnBody e
partial def emitCase (x : VarId) (xType : IRType) (alts : Array Alt) : M Unit :=
match isIf alts with
| some (tag, t, e) => emitIf x xType tag t e
| _ => do
emit "switch ("; emitTag x xType; emitLn ") {";
let alts := ensureHasDefault alts;
alts.forM fun alt => do
match alt with
| Alt.ctor c b => emit "case "; emit c.cidx; emitLn ":"; emitFnBody b
| Alt.default b => emitLn "default: "; emitFnBody b
emitLn "}"
partial def emitBlock (b : FnBody) : M Unit := do
match b with
| FnBody.jdecl j xs v b => emitBlock b
| d@(FnBody.vdecl x t v b) =>
let ctx ← read
if isTailCallTo ctx.mainFn d then
emitTailCall v
else
emitVDecl x t v
emitBlock b
| FnBody.inc x n c p b =>
unless p do emitInc x n c
emitBlock b
| FnBody.dec x n c p b =>
unless p do emitDec x n c
emitBlock b
| FnBody.del x b => emitDel x; emitBlock b
| FnBody.setTag x i b => emitSetTag x i; emitBlock b
| FnBody.set x i y b => emitSet x i y; emitBlock b
| FnBody.uset x i y b => emitUSet x i y; emitBlock b
| FnBody.sset x i o y t b => emitSSet x i o y t; emitBlock b
| FnBody.mdata _ b => emitBlock b
| FnBody.ret x => emit "return "; emitArg x; emitLn ";"
| FnBody.case _ x xType alts => emitCase x xType alts
| FnBody.jmp j xs => emitJmp j xs
| FnBody.unreachable => emitLn "lean_internal_panic_unreachable();"
partial def emitJPs : FnBody → M Unit
| FnBody.jdecl j xs v b => do emit j; emitLn ":"; emitFnBody v; emitJPs b
| e => do unless e.isTerminal do emitJPs e.body
partial def emitFnBody (b : FnBody) : M Unit := do
emitLn "{"
let declared ← declareVars b false
if declared then emitLn ""
emitBlock b
emitJPs b
emitLn "}"
end
def emitDeclAux (d : Decl) : M Unit := do
let env ← getEnv
let (vMap, jpMap) := mkVarJPMaps d
withReader (fun ctx => { ctx with jpMap := jpMap }) do
unless hasInitAttr env d.name do
match d with
| Decl.fdecl (f := f) (xs := xs) (type := t) (body := b) .. =>
let baseName ← toCName f;
if xs.size == 0 then
emit "static "
emit (toCType t); emit " ";
if xs.size > 0 then
emit baseName;
emit "(";
if xs.size > closureMaxArgs && isBoxedName d.name then
emit "lean_object** _args"
else
xs.size.forM fun i => do
if i > 0 then emit ", "
let x := xs[i]
emit (toCType x.ty); emit " "; emit x.x
emit ")"
else
emit ("_init_" ++ baseName ++ "()")
emitLn " {";
if xs.size > closureMaxArgs && isBoxedName d.name then
xs.size.forM fun i => do
let x := xs[i]
emit "lean_object* "; emit x.x; emit " = _args["; emit i; emitLn "];"
emitLn "_start:";
withReader (fun ctx => { ctx with mainFn := f, mainParams := xs }) (emitFnBody b);
emitLn "}"
| _ => pure ()
def emitDecl (d : Decl) : M Unit := do
let d := d.normalizeIds; -- ensure we don't have gaps in the variable indices
try
emitDeclAux d
catch err =>
throw s!"{err}\ncompiling:\n{d}"
def emitFns : M Unit := do
let env ← getEnv;
let decls := getDecls env;
decls.reverse.forM emitDecl
def emitMarkPersistent (d : Decl) (n : Name) : M Unit := do
if d.resultType.isObj then
emit "lean_mark_persistent("
emitCName n
emitLn ");"
def emitDeclInit (d : Decl) : M Unit := do
let env ← getEnv
let n := d.name
if isIOUnitInitFn env n then
emit "res = "; emitCName n; emitLn "(lean_io_mk_world());"
emitLn "if (lean_io_result_is_error(res)) return res;"
emitLn "lean_dec_ref(res);"
else if d.params.size == 0 then
match getInitFnNameFor? env d.name with
| some initFn =>
emit "res = "; emitCName initFn; emitLn "(lean_io_mk_world());"
emitLn "if (lean_io_result_is_error(res)) return res;"
emitCName n; emitLn " = lean_io_result_get_value(res);"
emitMarkPersistent d n
emitLn "lean_dec_ref(res);"
| _ =>
emitCName n; emit " = "; emitCInitName n; emitLn "();"; emitMarkPersistent d n
def emitInitFn : M Unit := do
let env ← getEnv
let modName ← getModName
env.imports.forM fun imp => emitLn ("lean_object* " ++ mkModuleInitializationFunctionName imp.module ++ "(lean_object*);")
emitLns [
"static bool _G_initialized = false;",
"lean_object* " ++ mkModuleInitializationFunctionName modName ++ "(lean_object* w) {",
"lean_object * res;",
"if (_G_initialized) return lean_io_result_mk_ok(lean_box(0));",
"_G_initialized = true;"
]
env.imports.forM fun imp => emitLns [
"res = " ++ mkModuleInitializationFunctionName imp.module ++ "(lean_io_mk_world());",
"if (lean_io_result_is_error(res)) return res;",
"lean_dec_ref(res);"]
let decls := getDecls env
decls.reverse.forM emitDeclInit
emitLns ["return lean_io_result_mk_ok(lean_box(0));", "}"]
def main : M Unit := do
emitFileHeader
emitFnDecls
emitFns
emitInitFn
emitMainFnIfNeeded
emitFileFooter
end EmitC
@[export lean_ir_emit_c]
def emitC (env : Environment) (modName : Name) : Except String String :=
match (EmitC.main { env := env, modName := modName }).run "" with
| EStateM.Result.ok _ s => Except.ok s
| EStateM.Result.error err _ => Except.error err
end Lean.IR
|
1b72490b9a38f2d6ea7b3e2ce3005343f359ef38 | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /algebra/archimedean.lean | a3846ece88d1883d4619dbdebc8c53781435531c | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 8,688 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
Archimedean groups and fields.
-/
import algebra.group_power data.rat data.int.order
local infix ` • ` := add_monoid.smul
variables {α : Type*}
class floor_ring (α) extends linear_ordered_ring α :=
(floor : α → ℤ)
(le_floor : ∀ (z : ℤ) (x : α), z ≤ floor x ↔ (z : α) ≤ x)
instance : floor_ring ℤ :=
{ floor := id, le_floor := by simp,
..linear_ordered_comm_ring.to_linear_ordered_ring ℤ }
instance : floor_ring ℚ :=
{ floor := rat.floor, le_floor := @rat.le_floor,
..linear_ordered_comm_ring.to_linear_ordered_ring ℚ }
section
variable [floor_ring α]
def floor : α → ℤ := floor_ring.floor
notation `⌊` x `⌋` := floor x
theorem le_floor : ∀ {z : ℤ} {x : α}, z ≤ ⌊x⌋ ↔ (z : α) ≤ x :=
floor_ring.le_floor
theorem floor_lt {x : α} {z : ℤ} : ⌊x⌋ < z ↔ x < z :=
le_iff_le_iff_lt_iff_lt.1 le_floor
theorem floor_le (x : α) : (⌊x⌋ : α) ≤ x :=
le_floor.1 (le_refl _)
theorem floor_nonneg {x : α} : 0 ≤ ⌊x⌋ ↔ 0 ≤ x :=
by simpa using @le_floor _ _ 0 x
theorem lt_succ_floor (x : α) : x < ⌊x⌋.succ :=
floor_lt.1 $ int.lt_succ_self _
theorem lt_floor_add_one (x : α) : x < ⌊x⌋ + 1 :=
by simpa [int.succ] using lt_succ_floor x
theorem sub_one_lt_floor (x : α) : x - 1 < ⌊x⌋ :=
sub_lt_iff_lt_add.2 (lt_floor_add_one x)
@[simp] theorem floor_coe (z : ℤ) : ⌊(z:α)⌋ = z :=
eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le]
@[simp] theorem floor_zero : ⌊(0:α)⌋ = 0 := floor_coe 0
@[simp] theorem floor_one : ⌊(1:α)⌋ = 1 :=
by rw [← int.cast_one, floor_coe]
theorem floor_mono {a b : α} (h : a ≤ b) : ⌊a⌋ ≤ ⌊b⌋ :=
le_floor.2 (le_trans (floor_le _) h)
@[simp] theorem floor_add_int (x : α) (z : ℤ) : ⌊x + z⌋ = ⌊x⌋ + z :=
eq_of_forall_le_iff $ λ a, by rw [le_floor,
← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub]
theorem floor_sub_int (x : α) (z : ℤ) : ⌊x - z⌋ = ⌊x⌋ - z :=
eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _)
/-- `ceil x` is the smallest integer `z` such that `x ≤ z` -/
def ceil (x : α) : ℤ := -⌊-x⌋
notation `⌈` x `⌉` := ceil x
theorem ceil_le {z : ℤ} {x : α} : ⌈x⌉ ≤ z ↔ x ≤ z :=
by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff]
theorem lt_ceil {x : α} {z : ℤ} : z < ⌈x⌉ ↔ (z:α) < x :=
le_iff_le_iff_lt_iff_lt.1 ceil_le
theorem le_ceil (x : α) : x ≤ ⌈x⌉ :=
ceil_le.1 (le_refl _)
@[simp] theorem ceil_coe (z : ℤ) : ⌈(z:α)⌉ = z :=
by rw [ceil, ← int.cast_neg, floor_coe, neg_neg]
theorem ceil_mono {a b : α} (h : a ≤ b) : ⌈a⌉ ≤ ⌈b⌉ :=
ceil_le.2 (le_trans h (le_ceil _))
@[simp] theorem ceil_add_int (x : α) (z : ℤ) : ⌈x + z⌉ = ⌈x⌉ + z :=
by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl
theorem ceil_sub_int (x : α) (z : ℤ) : ⌈x - z⌉ = ⌈x⌉ - z :=
eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _)
theorem ceil_lt_add_one (x : α) : (⌈x⌉ : α) < x + 1 :=
by rw [← lt_ceil, ← int.cast_one, ceil_add_int]; apply lt_add_one
end
class archimedean (α) [ordered_comm_monoid α] : Prop :=
(arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y)
theorem exists_nat_gt [linear_ordered_semiring α] [archimedean α]
(x : α) : ∃ n : ℕ, x < n :=
let ⟨n, h⟩ := archimedean.arch x zero_lt_one in
⟨n+1, lt_of_le_of_lt (by simpa using h)
(nat.cast_lt.2 (nat.lt_succ_self _))⟩
section linear_ordered_ring
variables [linear_ordered_ring α] [archimedean α]
lemma pow_unbounded_of_gt_one (x : α) {y : α}
(hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n :=
have hy0 : 0 < y - 1 := sub_pos_of_lt hy1,
let ⟨n, h⟩ := archimedean.arch x hy0 in
⟨n, calc x ≤ n • (y - 1) : h
... < 1 + n • (y - 1) : by rw add_comm; exact lt_add_one _
... ≤ y ^ n : pow_ge_one_add_sub_mul (le_of_lt hy1) _⟩
theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n :=
let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by simp [h]⟩
theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x :=
let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by simp [neg_lt.1 h]⟩
theorem exists_floor (x : α) :
∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x :=
begin
haveI := classical.prop_decidable,
have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub :=
int.exists_greatest_of_bdd
(let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h',
int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩)
(let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩),
refine this.imp (λ fl h z, _),
cases h with h₁ h₂,
exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩,
end
end linear_ordered_ring
instance : archimedean ℕ :=
⟨λ n m m0, ⟨n, by simpa using nat.mul_le_mul_left n m0⟩⟩
instance : archimedean ℤ :=
⟨λ n m m0, ⟨n.to_nat, begin
simp [add_monoid.smul_eq_mul],
refine le_trans (int.le_to_nat _) _,
simpa using mul_le_mul_of_nonneg_left
(int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat),
end⟩⟩
noncomputable def archimedean.floor_ring (α)
[linear_ordered_ring α] [archimedean α] : floor_ring α :=
{ floor := λ x, classical.some (exists_floor x),
le_floor := λ z x, classical.some_spec (exists_floor x) z }
section linear_ordered_field
variables [linear_ordered_field α]
theorem archimedean_iff_nat_lt :
archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n :=
⟨@exists_nat_gt α _, λ H, ⟨λ x y y0,
(H (x / y)).imp $ λ n h, le_of_lt $
by rwa [div_lt_iff y0, ← add_monoid.smul_eq_mul] at h⟩⟩
theorem archimedean_iff_nat_le :
archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n :=
archimedean_iff_nat_lt.trans
⟨λ H x, (H x).imp $ λ _, le_of_lt,
λ H x, let ⟨n, h⟩ := H x in ⟨n+1,
lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩
theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q :=
let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by simp [h]⟩
theorem archimedean_iff_rat_lt :
archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q :=
⟨@exists_rat_gt α _,
λ H, archimedean_iff_nat_lt.2 $ λ x,
let ⟨q, h⟩ := H x in
⟨rat.nat_ceil q, lt_of_lt_of_le h $
by simpa using (@rat.cast_le α _ _ _).2 (rat.le_nat_ceil _)⟩⟩
theorem archimedean_iff_rat_le :
archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q :=
archimedean_iff_rat_lt.trans
⟨λ H x, (H x).imp $ λ _, le_of_lt,
λ H x, let ⟨n, h⟩ := H x in ⟨n+1,
lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩
variable [archimedean α]
theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x :=
let ⟨n, h⟩ := exists_int_lt x in ⟨n, by simp [h]⟩
theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x :=
let ⟨n, h⟩ := exists_nat_gt x⁻¹ in begin
have n0 := nat.cast_pos.1 (lt_trans (inv_pos x0) h),
refine ⟨n⁻¹, inv_pos (nat.cast_pos.2 n0), _⟩,
simpa [rat.cast_inv_of_ne_zero, ne_of_gt n0] using
(inv_lt x0 (nat.cast_pos.2 n0)).1 h
end
theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y :=
begin
cases exists_nat_gt (y - x)⁻¹ with n nh,
cases exists_floor (x * n) with z zh,
refine ⟨(z + 1 : ℤ) / n, _⟩,
have n0 := nat.cast_pos.1 (lt_trans (inv_pos (sub_pos.2 h)) nh),
simp [rat.cast_div_of_ne_zero, -int.cast_add, ne_of_gt n0],
have n0' := (@nat.cast_pos α _ _).2 n0,
refine ⟨(lt_div_iff n0').2 $
(le_iff_le_iff_lt_iff_lt.1 (zh _)).1 (lt_add_one _), _⟩,
simp [div_lt_iff n0', -add_comm],
refine lt_of_le_of_lt (add_le_add_right ((zh _).1 (le_refl _)) _) _,
rwa [← lt_sub_iff_add_lt', ← sub_mul,
← div_lt_iff' (sub_pos.2 h), one_div_eq_inv]
end
include α
@[simp] theorem rat.cast_floor (x : ℚ) :
by haveI := archimedean.floor_ring α; exact ⌊(x:α)⌋ = ⌊x⌋ :=
begin
haveI := archimedean.floor_ring α,
apply le_antisymm,
{ rw [le_floor, ← @rat.cast_le α, rat.cast_coe_int],
apply floor_le },
{ rw [le_floor, ← rat.cast_coe_int, rat.cast_le],
apply floor_le }
end
end linear_ordered_field
section
variables [discrete_linear_ordered_field α] [archimedean α]
theorem exists_rat_near (x : α) {ε : α} (ε0 : ε > 0) :
∃ q : ℚ, abs (x - q) < ε :=
let ⟨q, h₁, h₂⟩ := exists_rat_btwn $
lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in
⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩
end
instance : archimedean ℚ :=
archimedean_iff_rat_le.2 $ λ q, ⟨q, by simp⟩
|
2836b3c4cf10a2f5e9278e5070527d85917db826 | 4c630d016e43ace8c5f476a5070a471130c8a411 | /data/int/basic.lean | ec5e1cab838d622e0b885314e95910cc9fbe45ee | [
"Apache-2.0"
] | permissive | ngamt/mathlib | 9a510c391694dc43eec969914e2a0e20b272d172 | 58909bd424209739a2214961eefaa012fb8a18d2 | refs/heads/master | 1,585,942,993,674 | 1,540,739,585,000 | 1,540,916,815,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 47,451 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
The integers, with addition, multiplication, and subtraction.
-/
import data.nat.basic data.list.basic algebra.char_zero algebra.order_functions
open nat
namespace int
instance : inhabited ℤ := ⟨0⟩
meta instance : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-("++↑k++"+1)")⟩
attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ
@[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl
@[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl
@[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl
theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n
theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n
theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n
@[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n :=
by rw [← int.coe_nat_zero, coe_nat_lt]
@[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 :=
by rw [← int.coe_nat_zero, coe_nat_inj']
@[simp] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 :=
not_congr coe_nat_eq_zero
lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _)
lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n :=
⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h),
λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩
lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n)
/- succ and pred -/
/-- Immediate successor of an integer: `succ n = n + 1` -/
def succ (a : ℤ) := a + 1
/-- Immediate predecessor of an integer: `pred n = n - 1` -/
def pred (a : ℤ) := a - 1
theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl
theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _
theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _
theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _
theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a :=
by rw [neg_succ, succ_pred]
theorem neg_pred (a : ℤ) : -pred a = succ (-a) :=
by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg]
theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a :=
by rw [neg_pred, pred_succ]
theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n
theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n
theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n
theorem lt_succ_self (a : ℤ) : a < succ a :=
lt_add_of_pos_right _ zero_lt_one
theorem pred_self_lt (a : ℤ) : pred a < a :=
sub_lt_self _ zero_lt_one
theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl
theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b :=
@add_le_add_iff_right _ _ a b 1
theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b :=
sub_lt_iff_lt_add.trans lt_add_one_iff
theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b :=
le_sub_iff_add_le
@[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop}
(i : ℤ) (hz : p 0) (hp : ∀i, p i → p (i + 1)) (hn : ∀i, p i → p (i - 1)) : p i :=
begin
induction i,
{ induction i,
{ exact hz },
{ exact hp _ i_ih } },
{ have : ∀n:ℕ, p (- n),
{ intro n, induction n,
{ simp [hz] },
{ have := hn _ n_ih, simpa } },
exact this (i + 1) }
end
/- nat abs -/
attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one
theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b :=
begin
have, {
refine (λ a b : ℕ, sub_nat_nat_elim a b.succ
(λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl);
intros i n e,
{ subst e, rw [add_comm _ i, add_assoc],
exact nat.le_add_right i (b.succ + b).succ },
{ apply succ_le_succ,
rw [← succ_inj e, ← add_assoc, add_comm],
apply nat.le_add_right } },
cases a; cases b with b b; simp [nat_abs, nat.succ_add];
try {refl}; [skip, rw add_comm a b]; apply this
end
theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n :=
by cases n; refl
theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) :=
by cases a; cases b; simp [(*), int.mul, nat_abs_neg_of_nat]
theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 :=
by simp [neg_succ_of_nat_eq]
lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 :=
λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h
/- / -/
@[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl
@[simp] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl
theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : b > 0) :
-[1+m] / b = -(m / b + 1) :=
match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end
@[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b)
| (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl
| (m : ℕ) (n+1:ℕ) := rfl
| 0 -[1+ n] := rfl
| (m+1:ℕ) -[1+ n] := (neg_neg _).symm
| -[1+ m] 0 := rfl
| -[1+ m] (n+1:ℕ) := rfl
| -[1+ m] -[1+ n] := rfl
theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b = -((-a - 1) / b + 1) :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ :=
by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl
end
protected theorem div_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a / b ≥ 0 :=
match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _
end
protected theorem div_nonpos {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≤ 0) : a / b ≤ 0 :=
nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb)
theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b < 0 :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _
end
@[simp] protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0
| 0 := rfl
| (n+1:ℕ) := rfl
| -[1+ n] := rfl
@[simp] protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0
| 0 := rfl
| (n+1:ℕ) := rfl
| -[1+ n] := rfl
@[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a
| 0 := rfl
| (n+1:ℕ) := congr_arg of_nat (nat.div_one _)
| -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _)
theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 :=
match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 :=
congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2
end
theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 :=
match b, abs b, abs_eq_nat_abs b, H2 with
| (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2
| -[1+ n], ._, rfl, H2 := neg_inj $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2
end
protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) :
(a + b * c) / c = a / c + b :=
have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from
λ k n a, match a with
| (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos
| -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ =
n - (m / k.succ + 1 : ℕ), begin
cases lt_or_ge m (n*k.succ) with h h,
{ rw [← int.coe_nat_sub h,
← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)],
apply congr_arg of_nat,
rw [mul_comm, nat.mul_sub_div], rwa mul_comm },
{ change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) =
↑n - ((m / nat.succ k : ℕ) + 1),
rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ),
← int.coe_nat_sub h,
← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h),
← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'],
{ apply congr_arg neg_succ_of_nat,
rw [mul_comm, nat.sub_mul_div], rwa mul_comm } }
end
end,
have ∀ {a b c : ℤ}, c > 0 → (a + b * c) / c = a / c + b, from
λ a b c H, match c, eq_succ_of_zero_lt H, b with
| ._, ⟨k, rfl⟩, (n : ℕ) := this
| ._, ⟨k, rfl⟩, -[1+ n] :=
show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from
eq_sub_of_add_eq $ by rw [← this, sub_add_cancel]
end,
match lt_trichotomy c 0 with
| or.inl hlt := neg_inj $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg];
apply this (neg_pos_of_neg hlt)
| or.inr (or.inl heq) := absurd heq H
| or.inr (or.inr hgt) := this hgt
end
protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) :
(a + b * c) / b = a / b + c :=
by rw [mul_comm, int.add_mul_div_right _ _ H]
@[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a :=
by have := int.add_mul_div_right 0 a H;
rwa [zero_add, int.zero_div, zero_add] at this
@[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b :=
by rw [mul_comm, int.mul_div_cancel _ H]
@[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 :=
by have := int.mul_div_cancel 1 H; rwa one_mul at this
/- mod -/
theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl
@[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl
theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : b > 0) :
-[1+m] % b = b - 1 - m % b :=
by rw [sub_sub, add_comm]; exact
match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end
@[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b
| (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _)
@[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b :=
abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _)
@[simp] theorem zero_mod (b : ℤ) : 0 % b = 0 :=
congr_arg of_nat $ nat.zero_mod _
@[simp] theorem mod_zero : ∀ (a : ℤ), a % 0 = a
| (m : ℕ) := congr_arg of_nat $ nat.mod_zero _
| -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _
@[simp] theorem mod_one : ∀ (a : ℤ), a % 1 = 0
| (m : ℕ) := congr_arg of_nat $ nat.mod_one _
| -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl
theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a :=
match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 :=
congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2)
end
theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → a % b ≥ 0
| (m : ℕ) n H := coe_zero_le _
| -[1+ m] n H :=
sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H)
theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : b > 0) : a % b < b :=
match a, b, eq_succ_of_zero_lt H with
| (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _))
| -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _)
end
theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b :=
by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H)
theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] :=
begin
rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)],
apply eq_neg_of_eq_neg,
rw [neg_sub, sub_sub_self, add_right_comm],
exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm
end
theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a
| (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _)
| (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _)
| 0 -[1+ n] := rfl
| (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _,
by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _)
| -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl
| -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ
| -[1+ m] -[1+ n] := mod_add_div_aux m n.succ
theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) :=
eq_sub_of_add_eq (mod_add_div _ _)
@[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c :=
if cz : c = 0 then by rw [cz, mul_zero, add_zero] else
by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz,
mul_add, mul_comm, add_sub_add_right_eq_sub]
@[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b :=
by rw [mul_comm, add_mul_mod_self]
@[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b :=
by have := add_mul_mod_self_left a b 1; rwa mul_one at this
@[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a :=
by rw [add_comm, add_mod_self]
@[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n :=
by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm;
rwa [add_right_comm, mod_add_div] at this
@[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k :=
by rw [add_comm, mod_add_mod, add_comm]
theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) :
(m + i) % n = (k + i) % n :=
by rw [← mod_add_mod, ← mod_add_mod k, H]
theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) :
(i + m) % n = (i + k) % n :=
by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm]
theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔
m % n = k % n :=
⟨λ H, by have := add_mod_eq_add_mod_right (-i) H;
rwa [add_neg_cancel_right, add_neg_cancel_right] at this,
add_mod_eq_add_mod_right _⟩
theorem mod_add_cancel_left {m n k i : ℤ} :
(i + m) % n = (i + k) % n ↔ m % n = k % n :=
by rw [add_comm, add_comm i, mod_add_cancel_right]
theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔
m % n = k % n :=
mod_add_cancel_right _
theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 :=
(mod_sub_cancel_right k).symm.trans $ by simp
@[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 :=
by rw [← zero_add (a * b), add_mul_mod_self, zero_mod]
@[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 :=
by rw [mul_comm, mul_mod_left]
@[simp] theorem mod_self {a : ℤ} : a % a = 0 :=
by have := mul_mod_left 1 a; rwa one_mul at this
@[simp] lemma mod_mod (a b : ℤ) : a % b % b = a % b :=
by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]}
/- properties of / and % -/
@[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b / (a * c) = b / c :=
suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from
match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with
| ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _
| ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ :=
by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg];
apply congr_arg has_neg.neg; apply this
end,
λ m k b, match b, k with
| (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos)
| -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero]
| -[1+ n], k+1 := congr_arg neg_succ_of_nat $
show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin
apply nat.div_eq_of_lt_le,
{ refine le_trans _ (nat.le_add_right _ _),
rw [← nat.mul_div_mul _ _ m.succ_pos],
apply nat.div_mul_le_self },
{ change m.succ * n.succ ≤ _,
rw [mul_left_comm],
apply nat.mul_le_mul_left,
apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1,
apply nat.lt_succ_self }
end
end
@[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b > 0) :
a * b / (c * b) = a / c :=
by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H]
@[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b % (a * c) = a * (b % c) :=
by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc]
theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : b > 0) : a < (a / b + 1) * b :=
by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt;
rw [← mod_def]; apply mod_lt_of_pos _ H
theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a :=
suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from
λ a b, match b, eq_coe_or_neg b with
| ._, ⟨n, or.inl rfl⟩ := this _ _
| ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this
end,
λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact
coe_nat_le_coe_nat_of_le (match a, n with
| (m : ℕ), n := nat.div_le_self _ _
| -[1+ m], 0 := nat.zero_le _
| -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _)
end)
theorem div_le_self {a : ℤ} (b : ℤ) (Ha : a ≥ 0) : a / b ≤ a :=
by have := le_trans (le_abs_self _) (abs_div_le_abs a b);
rwa [abs_of_nonneg Ha] at this
theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a :=
by have := mod_add_div a b; rwa [H, zero_add] at this
theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a :=
by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H]
lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 :=
have h : n % 2 < 2 := abs_of_nonneg (show (2 : ℤ) ≥ 0, from dec_trivial) ▸ int.mod_lt _ dec_trivial,
have h₁ : n % 2 ≥ 0 := int.mod_nonneg _ dec_trivial,
match (n % 2), h, h₁ with
| (0 : ℕ) := λ _ _, or.inl rfl
| (1 : ℕ) := λ _ _, or.inr rfl
| (k + 2 : ℕ) := λ h _, absurd h dec_trivial
| -[1+ a] := λ _ h₁, absurd h₁ dec_trivial
end
/- dvd -/
theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n :=
⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim
(λm0, by simp [m0] at ae; simp [ae, m0])
(λm0l, by {
cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a
(by simp [ae.symm]) (by simpa using m0l)) with k e,
subst a, exact ⟨k, int.coe_nat_inj ae⟩ }),
λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩
theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem dvd_antisymm {a b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a ∣ b → b ∣ a → a = b :=
begin
rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs],
rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'],
apply nat.dvd_antisymm
end
theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b :=
⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩
theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0
| a ._ ⟨c, rfl⟩ := mul_mod_right _ _
theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 :=
⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b :=
(nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e])
theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b :=
(nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e])
instance decidable_dvd : @decidable_rel ℤ (∣) :=
assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm
protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a :=
div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H)
protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b :=
by rw [mul_comm, int.div_mul_cancel H]
protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c)
| ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else
by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz]
theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a
| a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else
by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az];
apply dvd_mul_right
protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) :
a = b * c :=
by rw [← H2, int.mul_div_cancel' H1]
protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) :
a / b = c :=
by rw [H2, int.mul_div_cancel_left _ H1]
protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) :
a / b = c ↔ a = b * c :=
⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩
protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) :
a / b = c ↔ a = c * b :=
by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H'
protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) :
a = c * b :=
by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2]
protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) :
a / b = c :=
int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2])
theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b)
| ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else
by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz]
theorem div_sign : ∀ a b, a / sign b = a * sign b
| a (n+1:ℕ) := by unfold sign; simp
| a 0 := by simp [sign]
| a -[1+ n] := by simp [sign]
@[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b
| a 0 := by simp
| 0 b := by simp
| (m+1:ℕ) (n+1:ℕ) := rfl
| (m+1:ℕ) -[1+ n] := rfl
| -[1+ m] (n+1:ℕ) := rfl
| -[1+ m] -[1+ n] := rfl
protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) :=
if az : a = 0 then by simp [az] else
(int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az)
(sign_mul_abs _).symm).symm
theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i
| (n+1:ℕ) := mul_one _
| 0 := mul_zero _
| -[1+ n] := mul_neg_one _
theorem le_of_dvd {a b : ℤ} (bpos : b > 0) (H : a ∣ b) : a ≤ b :=
match a, b, eq_succ_of_zero_lt bpos, H with
| (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $
nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H
| -[1+ m], ._, ⟨n, rfl⟩, _ :=
le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _)
end
theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 :=
match a, eq_coe_of_zero_le H, H' with
| ._, ⟨n, rfl⟩, H' := congr_arg coe $
nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H'
end
theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 :=
eq_one_of_dvd_one H ⟨b, H'.symm⟩
theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : b ≥ 0) (H' : a * b = 1) : b = 1 :=
eq_one_of_mul_eq_one_right H (by rw [mul_comm, H'])
lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z
| (int.of_nat _) haz := int.coe_nat_dvd.2 haz
| -[1+k] haz :=
begin
change ↑a ∣ -(k+1 : ℤ),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
exact haz
end
lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs
| (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz)
| -[1+k] haz :=
have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz,
int.coe_nat_dvd.1 haz'
lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) :
↑(p ^ m) ∣ k :=
begin
induction k,
{ apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1 hdiv },
{ change -[1+k] with -(↑(k+1) : ℤ),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1,
apply dvd_of_dvd_neg,
exact hdiv }
end
lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m :=
by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk
/- / and ordering -/
protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a :=
le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H
protected theorem div_le_of_le_mul {a b c : ℤ} (H : c > 0) (H' : a ≤ b * c) : a / c ≤ b :=
le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H
protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : c > 0) (H3 : a < b / c) : a * c < b :=
lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3)
protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : c > 0) (H2 : a ≤ b / c) : a * c ≤ b :=
le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1))
protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : c > 0) (H2 : a * c ≤ b) : a ≤ b / c :=
le_of_lt_add_one $ lt_of_mul_lt_mul_right
(lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1)
protected theorem le_div_iff_mul_le {a b c : ℤ} (H : c > 0) : a ≤ b / c ↔ a * c ≤ b :=
⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩
protected theorem div_le_div {a b c : ℤ} (H : c > 0) (H' : a ≤ b) : a / c ≤ b / c :=
int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H')
protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : c > 0) (H' : a < b * c) : a / c < b :=
lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H')
protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : c > 0) (H2 : a / c < b) : a < b * c :=
lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2)
protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : c > 0) : a / c < b ↔ a < b * c :=
⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩
protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ a) (H3 : a / b ≤ c) :
a ≤ c * b :=
by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1
protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ c) (H3 : a * b < c) :
a < c / b :=
lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3)
protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : c > 0) (H' : c ∣ b) :
a < b / c ↔ a * c < b :=
⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩
theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : a > 0) (H2 : b ≥ 0) (H3 : b ∣ a) : a / b > 0 :=
int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul)
theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H1 : b ∣ a) (H2 : d ∣ c) (H3 : b ≠ 0)
(H4 : d ≠ 0) (H5 : a * d = b * c) :
a / b = c / d :=
int.div_eq_of_eq_mul_right H3 $
by rw [← int.mul_div_assoc _ H2]; exact
(int.div_eq_of_eq_mul_left H4 H5.symm).symm
theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0) (hbc : b ∣ c)
(h : b * a = c * d) : a = c / b * d :=
begin
cases hbc with k hk,
subst hk,
rw int.mul_div_cancel_left, rw mul_assoc at h,
apply _root_.eq_of_mul_eq_mul_left _ h,
repeat {assumption}
end
theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ}
(h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = (n - m).succ,
apply succ_sub,
apply le_of_lt_succ h,
simp [*, sub_nat_nat]
end
theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ}
(h : m ≥ n.succ) : of_nat m + -[1+n] = of_nat (m - n.succ) :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = 0,
apply sub_eq_zero_of_le h,
simp [*, sub_nat_nat]
end
@[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl
/- to_nat -/
theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0
| (n : ℕ) := (max_eq_left (coe_zero_le n)).symm
| -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm
@[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a :=
by rw [to_nat_eq_max, max_eq_left h]
@[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl
theorem le_to_nat (a : ℤ) : a ≤ to_nat a :=
by rw [to_nat_eq_max]; apply le_max_left
@[simp] theorem to_nat_le (a : ℤ) (n : ℕ) : to_nat a ≤ n ↔ a ≤ n :=
by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff];
exact and_iff_left (coe_zero_le _)
def to_nat' : ℤ → option ℕ
| (n : ℕ) := some n
| -[1+ n] := none
theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n
| (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm
| -[1+ m] n := by split; intro h; cases h
/- units -/
@[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 :=
units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹,
by rw [← nat_abs_mul, units.mul_inv]; refl,
by rw [← nat_abs_mul, units.inv_mul]; refl⟩
theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 :=
by simpa [units.ext_iff, units_nat_abs] using nat_abs_eq u
lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u :=
(units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl)
/- bitwise ops -/
@[simp] lemma bodd_zero : bodd 0 = ff := rfl
@[simp] lemma bodd_one : bodd 1 = tt := rfl
@[simp] lemma bodd_two : bodd 2 = ff := rfl
@[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd :=
by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd);
intros i m; simp [bodd]; cases i.bodd; cases m.bodd; refl
@[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd :=
by cases n; simp; refl
@[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n :=
by cases n; unfold has_neg.neg; simp [int.coe_nat_eq, int.neg, bodd]
@[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) :=
by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, bodd];
cases m.bodd; cases n.bodd; refl
@[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n :=
by cases m with m m; cases n with n n; unfold has_mul.mul; simp [int.mul, bodd];
cases m.bodd; cases n.bodd; refl
theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n
| (n : ℕ) :=
by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ),
by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2
| -[1+ n] := begin
refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2),
dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul],
{ change -[1+ 2 * nat.div2 n] = _, rw zero_add },
{ rw [zero_add, add_comm], refl }
end
theorem div2_val : ∀ n, div2 n = n / 2
| (n : ℕ) := congr_arg of_nat n.div2_val
| -[1+ n] := congr_arg neg_succ_of_nat n.div2_val
lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm
lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _)
lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 :=
by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val }
lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n :=
(bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _
def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n :=
by rw [← bit_decomp n]; apply h
@[simp] lemma bit_zero : bit ff 0 = 0 := rfl
@[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bodd_bit (b n) : bodd (bit b n) = b :=
by rw bit_val; simp; cases b; cases bodd n; refl
@[simp] lemma div2_bit (b n) : div2 (bit b n) = n :=
begin
rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add],
cases b, all_goals {exact dec_trivial}
end
@[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero];
clear test_bit_zero; cases b; refl
@[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ]
private meta def bitwise_tac : tactic unit := `[
funext m,
funext n,
cases m with m m; cases n with n n; try {refl},
all_goals {
apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat,
try {dsimp [nat.land, nat.ldiff, nat.lor]},
try {rw [
show nat.bitwise (λ a b, a && bnot b) n m =
nat.bitwise (λ a b, b && bnot a) m n, from
congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]},
apply congr_arg (λ f, nat.bitwise f m n),
funext a,
funext b,
cases a; cases b; refl
},
all_goals {unfold nat.land nat.ldiff nat.lor}
]
theorem bitwise_or : bitwise bor = lor := by bitwise_tac
theorem bitwise_and : bitwise band = land := by bitwise_tac
theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac
theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac
@[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) :
bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) :=
begin
cases m with m m; cases n with n n;
repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ };
unfold bitwise nat_bitwise bnot;
[ induction h : f ff ff,
induction h : f ff tt,
induction h : f tt ff,
induction h : f tt tt ],
all_goals {
unfold cond, rw nat.bitwise_bit,
repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } },
all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl }
end
@[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) :=
by rw [← bitwise_or, bitwise_bit]
@[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) :=
by rw [← bitwise_and, bitwise_bit]
@[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) :=
by rw [← bitwise_diff, bitwise_bit]
@[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) :=
by rw [← bitwise_xor, bitwise_bit]
@[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n)
| (n : ℕ) := by simp [lnot]
| -[1+ n] := by simp [lnot]
@[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) :
test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) :=
begin
induction k with k IH generalizing m n;
apply bit_cases_on m; intros a m';
apply bit_cases_on n; intros b n';
rw bitwise_bit,
{ simp [test_bit_zero] },
{ simp [test_bit_succ, IH] }
end
@[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k :=
by rw [← bitwise_or, test_bit_bitwise]
@[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k :=
by rw [← bitwise_and, test_bit_bitwise]
@[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) :=
by rw [← bitwise_diff, test_bit_bitwise]
@[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) :=
by rw [← bitwise_xor, test_bit_bitwise]
@[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k)
| (n : ℕ) k := by simp [lnot, test_bit]
| -[1+ n] k := by simp [lnot, test_bit]
lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k
| (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _)
| -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _)
| (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k)
(λ i n, congr_arg coe $
by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg coe $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl)
| -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k])
(λ i n, congr_arg neg_succ_of_nat $
by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg neg_succ_of_nat $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl)
lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k :=
shiftl_add _ _ _
@[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl
@[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg]
@[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl
@[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl
@[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl
@[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl
lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k
| (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat,
← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add]
| -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ,
← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add]
lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n)
| (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _)
lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n)
| (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _)
| -[1+ m] n := begin
rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl,
exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial)
end
lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) :=
congr_arg coe (nat.one_shiftl _)
@[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0
| (n : ℕ) := congr_arg coe (nat.zero_shiftl _)
| -[1+ n] := congr_arg coe (nat.zero_shiftr _)
@[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _
/- Least upper bound property for integers -/
theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P]
(Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z)
(Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) :=
let ⟨b, Hb⟩ := Hbdd in
have EX : ∃ n : ℕ, P (b + n), from
let ⟨elt, Helt⟩ := Hinh in
match elt, le.dest (Hb _ Helt), Helt with
| ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩
end,
⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h,
match z, le.dest (Hb _ h), h with
| ._, ⟨n, rfl⟩, h := add_le_add_left
(int.coe_nat_le.2 $ nat.find_min' _ h) _
end⟩
theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P]
(Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b)
(Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) :=
have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from
let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩,
have Hinh' : ∃ z : ℤ, P (-z), from
let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩,
let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in
⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩
/- cast (injection into groups with one) -/
@[simp] theorem nat_cast_eq_coe_nat : ∀ n,
@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n =
@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n
| 0 := rfl
| (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n)
section cast
variables {α : Type*}
section
variables [has_zero α] [has_one α] [has_add α] [has_neg α]
/-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/
protected def cast : ℤ → α
| (n : ℕ) := n
| -[1+ n] := -(n+1)
@[priority 0] instance cast_coe : has_coe ℤ α := ⟨int.cast⟩
@[simp] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl
@[simp] theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl
@[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl
@[simp] theorem cast_coe_nat' (n : ℕ) :
(@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n : α) = n :=
by simp
@[simp] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl
end
@[simp] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one
@[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n :=
begin
unfold sub_nat_nat, cases e : n - m,
{ simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] },
{ rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e,
nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] },
end
@[simp] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n
| 0 := neg_zero.symm
| (n+1) := rfl
@[simp] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n
| (m : ℕ) (n : ℕ) := nat.cast_add _ _
| (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _
| -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $
show (n:α) = -(m+1) + n + (m+1),
by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm,
nat.cast_add, cast_succ, neg_add_cancel_left]
| -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1),
by rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add];
apply congr_arg (λ x:ℕ, -(x:α)); simp
@[simp] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n
| (n : ℕ) := cast_neg_of_nat _
| -[1+ n] := (neg_neg _).symm
theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n :=
by simp
@[simp] theorem cast_eq_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 :=
⟨λ h, begin cases n,
{ exact congr_arg coe (nat.cast_eq_zero.1 h) },
{ rw [cast_neg_succ_of_nat, neg_eq_zero, ← cast_succ, nat.cast_eq_zero] at h,
contradiction }
end, λ h, by rw [h, cast_zero]⟩
@[simp] theorem cast_inj [add_group α] [has_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n :=
by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero]
theorem cast_injective [add_group α] [has_one α] [char_zero α] : function.injective (coe : ℤ → α)
| m n := cast_inj.1
@[simp] theorem cast_ne_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
@[simp] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n
| (m : ℕ) (n : ℕ) := nat.cast_mul _ _
| (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $
show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1),
by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg]
| -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $
show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n,
by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul]
| -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1),
by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg]
theorem mul_cast_comm [ring α] (a : α) (n : ℤ) : a * n = n * a :=
by cases n; simp [nat.mul_cast_comm, left_distrib, right_distrib, *]
@[simp] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _
@[simp] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp
theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n
| (n : ℕ) := by simp
| -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using
show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one
@[simp] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
@[simp] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n :=
by simpa [-cast_le] using not_congr (@cast_le α _ n m)
@[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
theorem eq_cast [add_group α] [has_one α] (f : ℤ → α)
(H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (n : ℤ) : f n = n :=
begin
have H : ∀ (n : ℕ), f n = n :=
nat.eq_cast' (λ n, f n) H1 (λ x y, Hadd x y),
cases n, {apply H},
apply eq_neg_of_add_eq_zero,
rw [← nat.cast_zero, ← H 0, int.coe_nat_zero,
← show -[1+ n] + (↑n + 1) = 0, from neg_add_self (↑n+1),
Hadd, show f (n+1) = n+1, from H (n+1)]
end
@[simp] theorem cast_id (n : ℤ) : ↑n = n :=
(eq_cast id rfl (λ _ _, rfl) n).symm
@[simp] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [h, min]
@[simp] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b :=
by by_cases a ≤ b; simp [h, max]
@[simp] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q :=
by simp [abs]
end cast
section decidable
def range (m n : ℤ) : list ℤ :=
(list.range (to_nat (n-m))).map $ λ r, m+r
theorem mem_range_iff {m n r : ℤ} : r ∈ range m n ↔ m ≤ r ∧ r < n :=
⟨λ H, let ⟨s, h1, h2⟩ := list.mem_map.1 H in h2 ▸
⟨le_add_of_nonneg_right trivial,
add_lt_of_lt_sub_left $ match n-m, h1 with
| (k:ℕ), h1 := by rwa [list.mem_range, to_nat_coe_nat, ← coe_nat_lt] at h1
end⟩,
λ ⟨h1, h2⟩, list.mem_map.2 ⟨to_nat (r-m),
list.mem_range.2 $ by rw [← coe_nat_lt, to_nat_of_nonneg (sub_nonneg_of_le h1),
to_nat_of_nonneg (sub_nonneg_of_le (le_of_lt (lt_of_le_of_lt h1 h2)))];
exact sub_lt_sub_right h2 _,
show m + _ = _, by rw [to_nat_of_nonneg (sub_nonneg_of_le h1), add_sub_cancel'_right]⟩⟩
instance decidable_le_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r < n → P r) :=
decidable_of_iff (∀ r ∈ range m n, P r) $ by simp only [mem_range_iff, and_imp]
instance decidable_le_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r ≤ n → P r) :=
decidable_of_iff (∀ r ∈ range m (n+1), P r) $ by simp only [mem_range_iff, and_imp, lt_add_one_iff]
instance decidable_lt_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r < n → P r) :=
int.decidable_le_lt P _ _
instance decidable_lt_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r ≤ n → P r) :=
int.decidable_le_le P _ _
end decidable
end int
|
aa4da737bf9ca108eed392c771a36909f75ecbab | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/topology/alexandroff.lean | f8bccb1640ac835684d2529b9c6884350330a4f0 | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,559 | lean | /-
Copyright (c) 2021 Yourong Zang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yourong Zang, Yury Kudryashov
-/
import topology.separation
import topology.opens
/-!
# The Alexandroff Compactification
We construct the Alexandroff compactification (the one-point compactification) of an arbitrary
topological space `X` and prove some properties inherited from `X`.
## Main definitions
* `alexandroff`: the Alexandroff compactification, we use coercion for the canonical embedding
`X → alexandroff X`; when `X` is already compact, the compactification adds an isolated point
to the space.
* `alexandroff.infty`: the extra point
## Main results
* The topological structure of `alexandroff X`
* The connectedness of `alexandroff X` for a noncompact, preconnected `X`
* `alexandroff X` is `T₀` for a T₀ space `X`
* `alexandroff X` is `T₁` for a T₁ space `X`
* `alexandroff X` is normal if `X` is a locally compact Hausdorff space
## Tags
one-point compactification, compactness
-/
open set filter
open_locale classical topological_space filter
/-!
### Definition and basic properties
In this section we define `alexandroff X` to be the disjoint union of `X` and `∞`, implemented as
`option X`. Then we restate some lemmas about `option X` for `alexandroff X`.
-/
/-- The Alexandroff extension of an arbitrary topological space `X` -/
def alexandroff (X : Type*) := option X
namespace alexandroff
variables {X : Type*}
/-- The point at infinity -/
def infty : alexandroff X := none
localized "notation `∞` := alexandroff.infty" in alexandroff
instance : has_coe_t X (alexandroff X) := ⟨option.some⟩
instance : inhabited (alexandroff X) := ⟨∞⟩
lemma coe_injective : function.injective (coe : X → alexandroff X) :=
option.some_injective X
@[norm_cast] lemma coe_eq_coe {x y : X} : (x : alexandroff X) = y ↔ x = y :=
coe_injective.eq_iff
@[simp] lemma coe_ne_infty (x : X) : (x : alexandroff X) ≠ ∞ .
@[simp] lemma infty_ne_coe (x : X) : ∞ ≠ (x : alexandroff X) .
/-- Recursor for `alexandroff` using the preferred forms `∞` and `↑x`. -/
@[elab_as_eliminator]
protected def rec (C : alexandroff X → Sort*) (h₁ : C ∞) (h₂ : Π x : X, C x) :
Π (z : alexandroff X), C z :=
option.rec h₁ h₂
lemma is_compl_range_coe_infty : is_compl (range (coe : X → alexandroff X)) {∞} :=
is_compl_range_some_none X
@[simp] lemma range_coe_union_infty : (range (coe : X → alexandroff X) ∪ {∞}) = univ :=
range_some_union_none X
@[simp] lemma range_coe_inter_infty : (range (coe : X → alexandroff X) ∩ {∞}) = ∅ :=
range_some_inter_none X
@[simp] lemma compl_range_coe : (range (coe : X → alexandroff X))ᶜ = {∞} :=
compl_range_some X
lemma compl_infty : ({∞}ᶜ : set (alexandroff X)) = range (coe : X → alexandroff X) :=
(@is_compl_range_coe_infty X).symm.compl_eq
lemma compl_image_coe (s : set X) : (coe '' s : set (alexandroff X))ᶜ = coe '' sᶜ ∪ {∞} :=
by rw [coe_injective.compl_image_eq, compl_range_coe]
lemma ne_infty_iff_exists {x : alexandroff X} :
x ≠ ∞ ↔ ∃ (y : X), (y : alexandroff X) = x :=
by induction x using alexandroff.rec; simp
instance : can_lift (alexandroff X) X :=
{ coe := coe,
cond := λ x, x ≠ ∞,
prf := λ x, ne_infty_iff_exists.1 }
lemma not_mem_range_coe_iff {x : alexandroff X} :
x ∉ range (coe : X → alexandroff X) ↔ x = ∞ :=
by rw [← mem_compl_iff, compl_range_coe, mem_singleton_iff]
lemma infty_not_mem_range_coe : ∞ ∉ range (coe : X → alexandroff X) :=
not_mem_range_coe_iff.2 rfl
lemma infty_not_mem_image_coe {s : set X} : ∞ ∉ (coe : X → alexandroff X) '' s :=
not_mem_subset (image_subset_range _ _) infty_not_mem_range_coe
@[simp] lemma coe_preimage_infty : (coe : X → alexandroff X) ⁻¹' {∞} = ∅ :=
by { ext, simp }
/-!
### Topological space structure on `alexandroff X`
We define a topological space structure on `alexandroff X` so that `s` is open if and only if
* `coe ⁻¹' s` is open in `X`;
* if `∞ ∈ s`, then `(coe ⁻¹' s)ᶜ` is compact.
Then we reformulate this definition in a few different ways, and prove that
`coe : X → alexandroff X` is an open embedding. If `X` is not a compact space, then we also prove
that `coe` has dense range, so it is a dense embedding.
-/
variables [topological_space X]
instance : topological_space (alexandroff X) :=
{ is_open := λ s, (∞ ∈ s → is_compact ((coe : X → alexandroff X) ⁻¹' s)ᶜ) ∧
is_open ((coe : X → alexandroff X) ⁻¹' s),
is_open_univ := by simp,
is_open_inter := λ s t,
begin
rintros ⟨hms, hs⟩ ⟨hmt, ht⟩,
refine ⟨_, hs.inter ht⟩,
rintros ⟨hms', hmt'⟩,
simpa [compl_inter] using (hms hms').union (hmt hmt')
end,
is_open_sUnion := λ S ho,
begin
suffices : is_open (coe ⁻¹' ⋃₀ S : set X),
{ refine ⟨_, this⟩,
rintro ⟨s, hsS : s ∈ S, hs : ∞ ∈ s⟩,
refine compact_of_is_closed_subset ((ho s hsS).1 hs) this.is_closed_compl _,
exact compl_subset_compl.mpr (preimage_mono $ subset_sUnion_of_mem hsS) },
rw [preimage_sUnion],
exact is_open_bUnion (λ s hs, (ho s hs).2)
end }
variables {s : set (alexandroff X)} {t : set X}
lemma is_open_def :
is_open s ↔ (∞ ∈ s → is_compact (coe ⁻¹' s : set X)ᶜ) ∧ is_open (coe ⁻¹' s : set X) :=
iff.rfl
lemma is_open_iff_of_mem' (h : ∞ ∈ s) :
is_open s ↔ is_compact (coe ⁻¹' s : set X)ᶜ ∧ is_open (coe ⁻¹' s : set X) :=
by simp [is_open_def, h]
lemma is_open_iff_of_mem (h : ∞ ∈ s) :
is_open s ↔ is_closed (coe ⁻¹' s : set X)ᶜ ∧ is_compact (coe ⁻¹' s : set X)ᶜ :=
by simp only [is_open_iff_of_mem' h, is_closed_compl_iff, and.comm]
lemma is_open_iff_of_not_mem (h : ∞ ∉ s) :
is_open s ↔ is_open (coe ⁻¹' s : set X) :=
by simp [is_open_def, h]
lemma is_closed_iff_of_mem (h : ∞ ∈ s) :
is_closed s ↔ is_closed (coe ⁻¹' s : set X) :=
have ∞ ∉ sᶜ, from λ H, H h,
by rw [← is_open_compl_iff, is_open_iff_of_not_mem this, ← is_open_compl_iff, preimage_compl]
lemma is_closed_iff_of_not_mem (h : ∞ ∉ s) :
is_closed s ↔ is_closed (coe ⁻¹' s : set X) ∧ is_compact (coe ⁻¹' s : set X) :=
by rw [← is_open_compl_iff, is_open_iff_of_mem (mem_compl h), ← preimage_compl, compl_compl]
@[simp] lemma is_open_image_coe {s : set X} :
is_open (coe '' s : set (alexandroff X)) ↔ is_open s :=
by rw [is_open_iff_of_not_mem infty_not_mem_image_coe, preimage_image_eq _ coe_injective]
lemma is_open_compl_image_coe {s : set X} :
is_open (coe '' s : set (alexandroff X))ᶜ ↔ is_closed s ∧ is_compact s :=
begin
rw [is_open_iff_of_mem, ← preimage_compl, compl_compl, preimage_image_eq _ coe_injective],
exact infty_not_mem_image_coe
end
@[simp] lemma is_closed_image_coe {s : set X} :
is_closed (coe '' s : set (alexandroff X)) ↔ is_closed s ∧ is_compact s :=
by rw [← is_open_compl_iff, is_open_compl_image_coe]
/-- An open set in `alexandroff X` constructed from a closed compact set in `X` -/
def opens_of_compl (s : set X) (h₁ : is_closed s) (h₂ : is_compact s) :
topological_space.opens (alexandroff X) :=
⟨(coe '' s)ᶜ, is_open_compl_image_coe.2 ⟨h₁, h₂⟩⟩
lemma infty_mem_opens_of_compl {s : set X} (h₁ : is_closed s) (h₂ : is_compact s) :
∞ ∈ opens_of_compl s h₁ h₂ :=
mem_compl infty_not_mem_image_coe
@[continuity] lemma continuous_coe : continuous (coe : X → alexandroff X) :=
continuous_def.mpr (λ s hs, hs.right)
lemma is_open_map_coe : is_open_map (coe : X → alexandroff X) :=
λ s, is_open_image_coe.2
lemma open_embedding_coe : open_embedding (coe : X → alexandroff X) :=
open_embedding_of_continuous_injective_open continuous_coe coe_injective is_open_map_coe
lemma is_open_range_coe : is_open (range (coe : X → alexandroff X)) :=
open_embedding_coe.open_range
lemma is_closed_infty : is_closed ({∞} : set (alexandroff X)) :=
by { rw [← compl_range_coe, is_closed_compl_iff], exact is_open_range_coe }
lemma nhds_coe_eq (x : X) : 𝓝 ↑x = map (coe : X → alexandroff X) (𝓝 x) :=
(open_embedding_coe.map_nhds_eq x).symm
lemma nhds_within_coe_image (s : set X) (x : X) :
𝓝[coe '' s] (x : alexandroff X) = map coe (𝓝[s] x) :=
(open_embedding_coe.to_embedding.map_nhds_within_eq _ _).symm
lemma nhds_within_coe (s : set (alexandroff X)) (x : X) :
𝓝[s] ↑x = map coe (𝓝[coe ⁻¹' s] x) :=
(open_embedding_coe.map_nhds_within_preimage_eq _ _).symm
lemma comap_coe_nhds (x : X) : comap (coe : X → alexandroff X) (𝓝 x) = 𝓝 x :=
(open_embedding_coe.to_inducing.nhds_eq_comap x).symm
/-- If `x` is not an isolated point of `X`, then `x : alexandroff X` is not an isolated point
of `alexandroff X`. -/
instance nhds_within_compl_coe_ne_bot (x : X) [h : ne_bot (𝓝[{x}ᶜ] x)] :
ne_bot (𝓝[{x}ᶜ] (x : alexandroff X)) :=
by simpa [nhds_within_coe, preimage, coe_eq_coe] using h.map coe
lemma nhds_within_compl_infty_eq : 𝓝[{∞}ᶜ] (∞ : alexandroff X) = map coe (coclosed_compact X) :=
begin
refine (nhds_within_basis_open ∞ _).ext (has_basis_coclosed_compact.map _) _ _,
{ rintro s ⟨hs, hso⟩,
refine ⟨_, (is_open_iff_of_mem hs).mp hso, _⟩,
simp },
{ rintro s ⟨h₁, h₂⟩,
refine ⟨_, ⟨mem_compl infty_not_mem_image_coe, is_open_compl_image_coe.2 ⟨h₁, h₂⟩⟩, _⟩,
simp [compl_image_coe, ← diff_eq, subset_preimage_image] }
end
/-- If `X` is a non-compact space, then `∞` is not an isolated point of `alexandroff X`. -/
instance nhds_within_compl_infty_ne_bot [ne_bot (cocompact X)] :
ne_bot (𝓝[{∞}ᶜ] (∞ : alexandroff X)) :=
by { rw nhds_within_compl_infty_eq, apply_instance }
@[priority 900]
instance nhds_within_compl_ne_bot [∀ x : X, ne_bot (𝓝[{x}ᶜ] x)] [ne_bot (cocompact X)]
(x : alexandroff X) : ne_bot (𝓝[{x}ᶜ] x) :=
alexandroff.rec _ alexandroff.nhds_within_compl_infty_ne_bot
(λ y, alexandroff.nhds_within_compl_coe_ne_bot y) x
lemma nhds_infty_eq : 𝓝 (∞ : alexandroff X) = map coe (coclosed_compact X) ⊔ pure ∞ :=
by rw [← nhds_within_compl_infty_eq, nhds_within_compl_singleton_sup_pure]
lemma has_basis_nhds_infty :
(𝓝 (∞ : alexandroff X)).has_basis (λ s : set X, is_closed s ∧ is_compact s)
(λ s, coe '' sᶜ ∪ {∞}) :=
begin
rw nhds_infty_eq,
exact (has_basis_coclosed_compact.map _).sup_pure _
end
@[simp] lemma comap_coe_nhds_infty : comap (coe : X → alexandroff X) (𝓝 ∞) = coclosed_compact X :=
by simp [nhds_infty_eq, comap_sup, comap_map coe_injective]
lemma le_nhds_infty {f : filter (alexandroff X)} :
f ≤ 𝓝 ∞ ↔ ∀ s : set X, is_closed s → is_compact s → coe '' sᶜ ∪ {∞} ∈ f :=
by simp only [has_basis_nhds_infty.ge_iff, and_imp]
lemma ultrafilter_le_nhds_infty {f : ultrafilter (alexandroff X)} :
(f : filter (alexandroff X)) ≤ 𝓝 ∞ ↔ ∀ s : set X, is_closed s → is_compact s → coe '' s ∉ f :=
by simp only [le_nhds_infty, ← compl_image_coe, ultrafilter.mem_coe,
ultrafilter.compl_mem_iff_not_mem]
lemma tendsto_nhds_infty' {α : Type*} {f : alexandroff X → α} {l : filter α} :
tendsto f (𝓝 ∞) l ↔ tendsto f (pure ∞) l ∧ tendsto (f ∘ coe) (coclosed_compact X) l :=
by simp [nhds_infty_eq, and_comm]
lemma tendsto_nhds_infty {α : Type*} {f : alexandroff X → α} {l : filter α} :
tendsto f (𝓝 ∞) l ↔
∀ s ∈ l, f ∞ ∈ s ∧ ∃ t : set X, is_closed t ∧ is_compact t ∧ maps_to (f ∘ coe) tᶜ s :=
tendsto_nhds_infty'.trans $ by simp only [tendsto_pure_left,
has_basis_coclosed_compact.tendsto_left_iff, forall_and_distrib, and_assoc, exists_prop]
lemma continuous_at_infty' {Y : Type*} [topological_space Y] {f : alexandroff X → Y} :
continuous_at f ∞ ↔ tendsto (f ∘ coe) (coclosed_compact X) (𝓝 (f ∞)) :=
tendsto_nhds_infty'.trans $ and_iff_right (tendsto_pure_nhds _ _)
lemma continuous_at_infty {Y : Type*} [topological_space Y] {f : alexandroff X → Y} :
continuous_at f ∞ ↔
∀ s ∈ 𝓝 (f ∞), ∃ t : set X, is_closed t ∧ is_compact t ∧ maps_to (f ∘ coe) tᶜ s :=
continuous_at_infty'.trans $
by simp only [has_basis_coclosed_compact.tendsto_left_iff, exists_prop, and_assoc]
lemma continuous_at_coe {Y : Type*} [topological_space Y] {f : alexandroff X → Y} {x : X} :
continuous_at f x ↔ continuous_at (f ∘ coe) x :=
by rw [continuous_at, nhds_coe_eq, tendsto_map'_iff, continuous_at]
/-- If `X` is not a compact space, then the natural embedding `X → alexandroff X` has dense range.
-/
lemma dense_range_coe [ne_bot (cocompact X)] :
dense_range (coe : X → alexandroff X) :=
begin
rw [dense_range, ← compl_infty],
exact dense_compl_singleton _
end
lemma dense_embedding_coe [ne_bot (cocompact X)] :
dense_embedding (coe : X → alexandroff X) :=
{ dense := dense_range_coe, .. open_embedding_coe }
/-!
### Compactness and separation properties
In this section we prove that `alexandroff X` is a compact space; it is a T₀ (resp., T₁) space if
the original space satisfies the same separation axiom. If the original space is a locally compact
Hausdorff space, then `alexandroff X` is a normal (hence, regular and Hausdorff) space.
Finally, if the original space `X` is *not* compact and is a preconnected space, then
`alexandroff X` is a connected space.
-/
/-- For any topological space `X`, its one point compactification is a compact space. -/
instance : compact_space (alexandroff X) :=
{ compact_univ :=
begin
refine is_compact_iff_ultrafilter_le_nhds.2 (λ f hf, _), clear hf,
by_cases hf : (f : filter (alexandroff X)) ≤ 𝓝 ∞,
{ exact ⟨∞, mem_univ _, hf⟩ },
{ simp only [ultrafilter_le_nhds_infty, not_forall, not_not] at hf,
rcases hf with ⟨s, h₁, h₂, hsf⟩,
have hf : range (coe : X → alexandroff X) ∈ f,
from mem_of_superset hsf (image_subset_range _ _),
have hsf' : s ∈ f.comap coe_injective hf, from (f.mem_comap _ _).2 hsf,
rcases h₂.ultrafilter_le_nhds _ (le_principal_iff.2 hsf') with ⟨a, has, hle⟩,
rw [ultrafilter.coe_comap, ← comap_coe_nhds, comap_le_comap_iff hf] at hle,
exact ⟨a, mem_univ _, hle⟩ }
end }
/-- The one point compactification of a `t0_space` space is a `t0_space`. -/
instance [t0_space X] : t0_space (alexandroff X) :=
begin
refine ⟨λ x y hxy, _⟩,
induction x using alexandroff.rec; induction y using alexandroff.rec,
{ exact (hxy rfl).elim },
{ use {∞}ᶜ, simp [is_closed_infty] },
{ use {∞}ᶜ, simp [is_closed_infty] },
{ rcases t0_space.t0 x y (mt coe_eq_coe.mpr hxy) with ⟨U, hUo, hU⟩,
refine ⟨coe '' U, is_open_image_coe.2 hUo, _⟩,
simpa [coe_eq_coe] }
end
/-- The one point compactification of a `t1_space` space is a `t1_space`. -/
instance [t1_space X] : t1_space (alexandroff X) :=
{ t1 := λ z,
begin
induction z using alexandroff.rec,
{ exact is_closed_infty },
{ simp only [← image_singleton, is_closed_image_coe],
exact ⟨is_closed_singleton, is_compact_singleton⟩ }
end }
/-- The one point compactification of a locally compact Hausdorff space is a normal (hence,
Hausdorff and regular) topological space. -/
instance [locally_compact_space X] [t2_space X] : normal_space (alexandroff X) :=
begin
have key : ∀ z : X,
∃ u v : set (alexandroff X), is_open u ∧ is_open v ∧ ↑z ∈ u ∧ ∞ ∈ v ∧ u ∩ v = ∅,
{ intro z,
rcases exists_open_with_compact_closure z with ⟨u, hu, huy', Hu⟩,
refine ⟨coe '' u, (coe '' closure u)ᶜ, is_open_image_coe.2 hu,
is_open_compl_image_coe.2 ⟨is_closed_closure, Hu⟩, mem_image_of_mem _ huy',
mem_compl infty_not_mem_image_coe, _⟩,
rw [← subset_compl_iff_disjoint, compl_compl],
exact image_subset _ subset_closure },
refine @normal_of_compact_t2 _ _ _ ⟨λ x y hxy, _⟩,
induction x using alexandroff.rec; induction y using alexandroff.rec,
{ exact (hxy rfl).elim },
{ rcases key y with ⟨u, v, hu, hv, hxu, hyv, huv⟩,
exact ⟨v, u, hv, hu, hyv, hxu, (inter_comm u v) ▸ huv⟩ },
{ exact key x },
{ exact separated_by_open_embedding open_embedding_coe (mt coe_eq_coe.mpr hxy) }
end
/-- If `X` is not a compact space, then `alexandroff X` is a connected space. -/
instance [preconnected_space X] [ne_bot (cocompact X)] : connected_space (alexandroff X) :=
{ to_preconnected_space := dense_embedding_coe.to_dense_inducing.preconnected_space,
to_nonempty := infer_instance }
end alexandroff
|
492fac2df912a87fc1770770ef96c42ad31c4a17 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/combinatorics/quiver/connected_component.lean | c70c11e89199538cbe352d41fea67acd013b5f61 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,386 | lean | /-
Copyright (c) 2021 David Wärn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Wärn
-/
import combinatorics.quiver.subquiver
import combinatorics.quiver.path
import combinatorics.quiver.symmetric
/-!
## Weakly connected components
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
For a quiver `V`, we define the type `weakly_connected_component V` as the quotient of `V`
by the relation which identifies `a` with `b` if there is a path from `a` to `b` in `symmetrify V`.
(These zigzags can be seen as a proof-relevant analogue of `eqv_gen`.)
Strongly connected components have not yet been defined.
-/
universes u
namespace quiver
variables (V : Type*) [quiver.{u+1} V]
/-- Two vertices are related in the zigzag setoid if there is a
zigzag of arrows from one to the other. -/
def zigzag_setoid : setoid V :=
⟨λ a b, nonempty (@path (symmetrify V) _ a b),
λ a, ⟨path.nil⟩,
λ a b ⟨p⟩, ⟨p.reverse⟩,
λ a b c ⟨p⟩ ⟨q⟩, ⟨p.comp q⟩⟩
/-- The type of weakly connected components of a directed graph. Two vertices are
in the same weakly connected component if there is a zigzag of arrows from one
to the other. -/
def weakly_connected_component : Type* := quotient (zigzag_setoid V)
namespace weakly_connected_component
variable {V}
/-- The weakly connected component corresponding to a vertex. -/
protected def mk : V → weakly_connected_component V := quotient.mk'
instance : has_coe_t V (weakly_connected_component V) := ⟨weakly_connected_component.mk⟩
instance [inhabited V] : inhabited (weakly_connected_component V) := ⟨show V, from default⟩
protected lemma eq (a b : V) :
(a : weakly_connected_component V) = b ↔ nonempty (@path (symmetrify V) _ a b) :=
quotient.eq'
end weakly_connected_component
variable {V}
/-- A wide subquiver `H` of `G.symmetrify` determines a wide subquiver of `G`, containing an
an arrow `e` if either `e` or its reversal is in `H`. -/
-- Without the explicit universe level in `quiver.{v+1}` Lean comes up with
-- `quiver.{max u_2 u_3 + 1}`. This causes problems elsewhere, so we write `quiver.{v+1}`.
def wide_subquiver_symmetrify (H : wide_subquiver (symmetrify V)) : wide_subquiver V :=
λ a b, { e | sum.inl e ∈ H a b ∨ sum.inr e ∈ H b a }
end quiver
|
33580cb891b1cf16eb4fbbf2cde9840e8ee8471d | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/Term.lean | e2d699aa316ad7763858638f903bb2fff57f92ec | [
"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 | 75,370 | 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, Sebastian Ullrich
-/
import Lean.Meta.AppBuilder
import Lean.Meta.CollectMVars
import Lean.Meta.Coe
import Lean.Linter.Deprecated
import Lean.Elab.Config
import Lean.Elab.Level
import Lean.Elab.DeclModifiers
namespace Lean.Elab
namespace Term
/-- Saved context for postponed terms and tactics to be executed. -/
structure SavedContext where
declName? : Option Name
options : Options
openDecls : List OpenDecl
macroStack : MacroStack
errToSorry : Bool
levelNames : List Name
/-- We use synthetic metavariables as placeholders for pending elaboration steps. -/
inductive SyntheticMVarKind where
/-- Use typeclass resolution to synthesize value for metavariable. -/
| typeClass
/-- Use coercion to synthesize value for the metavariable.
if `f?` is `some f`, we produce an application type mismatch error message.
Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)`
Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/
| coe (header? : Option String) (expectedType : Expr) (e : Expr) (f? : Option Expr)
/-- Use tactic to synthesize value for metavariable. -/
| tactic (tacticCode : Syntax) (ctx : SavedContext)
/-- Metavariable represents a hole whose elaboration has been postponed. -/
| postponed (ctx : SavedContext)
deriving Inhabited
instance : ToString SyntheticMVarKind where
toString
| .typeClass => "typeclass"
| .coe .. => "coe"
| .tactic .. => "tactic"
| .postponed .. => "postponed"
structure SyntheticMVarDecl where
stx : Syntax
kind : SyntheticMVarKind
deriving Inhabited
/--
We can optionally associate an error context with a metavariable (see `MVarErrorInfo`).
We have three different kinds of error context.
-/
inductive MVarErrorKind where
/-- Metavariable for implicit arguments. `ctx` is the parent application. -/
| implicitArg (ctx : Expr)
/-- Metavariable for explicit holes provided by the user (e.g., `_` and `?m`) -/
| hole
/-- "Custom", `msgData` stores the additional error messages. -/
| custom (msgData : MessageData)
deriving Inhabited
instance : ToString MVarErrorKind where
toString
| .implicitArg _ => "implicitArg"
| .hole => "hole"
| .custom _ => "custom"
/--
We can optionally associate an error context with metavariables.
-/
structure MVarErrorInfo where
mvarId : MVarId
ref : Syntax
kind : MVarErrorKind
argName? : Option Name := none
deriving Inhabited
/--
Nested `let rec` expressions are eagerly lifted by the elaborator.
We store the information necessary for performing the lifting here.
-/
structure LetRecToLift where
ref : Syntax
fvarId : FVarId
attrs : Array Attribute
shortDeclName : Name
declName : Name
lctx : LocalContext
localInstances : LocalInstances
type : Expr
val : Expr
mvarId : MVarId
deriving Inhabited
/--
State of the `TermElabM` monad.
-/
structure State where
levelNames : List Name := []
syntheticMVars : MVarIdMap SyntheticMVarDecl := {}
pendingMVars : List MVarId := {}
mvarErrorInfos : MVarIdMap MVarErrorInfo := {}
letRecsToLift : List LetRecToLift := []
deriving Inhabited
end Term
namespace Tactic
/--
State of the `TacticM` monad.
-/
structure State where
goals : List MVarId
deriving Inhabited
/--
Snapshots are used to implement the `save` tactic.
This tactic caches the state of the system, and allows us to "replay"
expensive proofs efficiently. This is only relevant implementing the
LSP server.
-/
structure Snapshot where
core : Core.State
meta : Meta.State
term : Term.State
tactic : Tactic.State
stx : Syntax
/--
Key for the cache used to implement the `save` tactic.
-/
structure CacheKey where
mvarId : MVarId -- TODO: should include all goals
pos : String.Pos
deriving BEq, Hashable, Inhabited
/--
Cache for the `save` tactic.
-/
structure Cache where
pre : PHashMap CacheKey Snapshot := {}
post : PHashMap CacheKey Snapshot := {}
deriving Inhabited
end Tactic
namespace Term
structure Context where
declName? : Option Name := none
/--
Map `.auxDecl` local declarations used to encode recursive declarations to their full-names.
-/
auxDeclToFullName : FVarIdMap Name := {}
macroStack : MacroStack := []
/--
When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`.
The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in
the list of pending synthetic metavariables, and returns `?m`. -/
mayPostpone : Bool := true
/--
When `errToSorry` is set to true, the method `elabTerm` catches
exceptions and converts them into synthetic `sorry`s.
The implementation of choice nodes and overloaded symbols rely on the fact
that when `errToSorry` is set to false for an elaboration function `F`, then
`errToSorry` remains `false` for all elaboration functions invoked by `F`.
That is, it is safe to transition `errToSorry` from `true` to `false`, but
we must not set `errToSorry` to `true` when it is currently set to `false`. -/
errToSorry : Bool := true
/--
When `autoBoundImplicit` is set to true, instead of producing
an "unknown identifier" error for unbound variables, we generate an
internal exception. This exception is caught at `elabBinders` and
`elabTypeWithUnboldImplicit`. Both methods add implicit declarations
for the unbound variable and try again. -/
autoBoundImplicit : Bool := false
autoBoundImplicits : PArray Expr := {}
/--
A name `n` is only eligible to be an auto implicit name if `autoBoundImplicitForbidden n = false`.
We use this predicate to disallow `f` to be considered an auto implicit name in a definition such
as
```
def f : f → Bool := fun _ => true
```
-/
autoBoundImplicitForbidden : Name → Bool := fun _ => false
/-- Map from user name to internal unique name -/
sectionVars : NameMap Name := {}
/-- Map from internal name to fvar -/
sectionFVars : NameMap Expr := {}
/-- Enable/disable implicit lambdas feature. -/
implicitLambda : Bool := true
/-- Noncomputable sections automatically add the `noncomputable` modifier to any declaration we cannot generate code for. -/
isNoncomputableSection : Bool := false
/-- When `true` we skip TC failures. We use this option when processing patterns. -/
ignoreTCFailures : Bool := false
/-- `true` when elaborating patterns. It affects how we elaborate named holes. -/
inPattern : Bool := false
/-- Cache for the `save` tactic. It is only `some` in the LSP server. -/
tacticCache? : Option (IO.Ref Tactic.Cache) := none
/--
If `true`, we store in the `Expr` the `Syntax` for recursive applications (i.e., applications
of free variables tagged with `isAuxDecl`). We store the `Syntax` using `mkRecAppWithSyntax`.
We use the `Syntax` object to produce better error messages at `Structural.lean` and `WF.lean`. -/
saveRecAppSyntax : Bool := true
/--
If `holesAsSyntheticOpaque` is `true`, then we mark metavariables associated
with `_`s as `synthethicOpaque` if they do not occur in patterns.
This option is useful when elaborating terms in tactics such as `refine'` where
we want holes there to become new goals. See issue #1681, we have
`refine' (fun x => _)
-/
holesAsSyntheticOpaque : Bool := false
abbrev TermElabM := ReaderT Context $ StateRefT State MetaM
abbrev TermElab := Syntax → Option Expr → TermElabM Expr
/-
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`.
-/
@[always_inline]
instance : Monad TermElabM :=
let i := inferInstanceAs (Monad TermElabM)
{ pure := i.pure, bind := i.bind }
open Meta
instance : Inhabited (TermElabM α) where
default := throw default
/--
Backtrackable state for the `TermElabM` monad.
-/
structure SavedState where
meta : Meta.SavedState
«elab» : State
deriving Nonempty
protected def saveState : TermElabM SavedState :=
return { meta := (← Meta.saveState), «elab» := (← get) }
def SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do
let traceState ← getTraceState -- We never backtrack trace message
let infoState ← getInfoState -- We also do not backtrack the info nodes when `restoreInfo == false`
s.meta.restore
set s.elab
setTraceState traceState
unless restoreInfo do
setInfoState infoState
instance : MonadBacktrack SavedState TermElabM where
saveState := Term.saveState
restoreState b := b.restore
abbrev TermElabResult (α : Type) := EStateM.Result Exception SavedState α
/--
Execute `x`, save resulting expression and new state.
We remove any `Info` created by `x`.
The info nodes are committed when we execute `applyResult`.
We use `observing` to implement overloaded notation and decls.
We want to save `Info` nodes for the chosen alternative.
-/
def observing (x : TermElabM α) : TermElabM (TermElabResult α) := do
let s ← saveState
try
let e ← x
let sNew ← saveState
s.restore (restoreInfo := true)
return EStateM.Result.ok e sNew
catch
| ex@(.error ..) =>
let sNew ← saveState
s.restore (restoreInfo := true)
return .error ex sNew
| ex@(.internal id _) =>
if id == postponeExceptionId then
s.restore (restoreInfo := true)
throw ex
/--
Apply the result/exception and state captured with `observing`.
We use this method to implement overloaded notation and symbols. -/
def applyResult (result : TermElabResult α) : TermElabM α := do
match result with
| .ok a r => r.restore (restoreInfo := true); return a
| .error ex r => r.restore (restoreInfo := true); throw ex
/--
Execute `x`, but keep state modifications only if `x` did not postpone.
This method is useful to implement elaboration functions that cannot decide whether
they need to postpone or not without updating the state. -/
def commitIfDidNotPostpone (x : TermElabM α) : TermElabM α := do
-- We just reuse the implementation of `observing` and `applyResult`.
let r ← observing x
applyResult r
/--
Return the universe level names explicitly provided by the user.
-/
def getLevelNames : TermElabM (List Name) :=
return (← get).levelNames
/--
Given a free variable `fvar`, return its declaration.
This function panics if `fvar` is not a free variable.
-/
def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do
match (← getLCtx).find? fvar.fvarId! with
| some d => pure d
| none => unreachable!
instance : AddErrorMessageContext TermElabM where
add ref msg := do
let ctx ← read
let ref := getBetterRef ref ctx.macroStack
let msg ← addMessageContext msg
let msg ← addMacroStack msg ctx.macroStack
pure (ref, msg)
/--
Execute `x` but discard changes performed at `Term.State` and `Meta.State`.
Recall that the `Environment` and `InfoState` are at `Core.State`. Thus, any updates to it will
be preserved. This method is useful for performing computations where all
metavariable must be resolved or discarded.
The `InfoTree`s are not discarded, however, and wrapped in `InfoTree.Context`
to store their metavariable context. -/
def withoutModifyingElabMetaStateWithInfo (x : TermElabM α) : TermElabM α := do
let s ← get
let sMeta ← getThe Meta.State
try
withSaveInfoContext x
finally
set s
set sMeta
/--
Execute `x` but discard changes performed to the state.
However, the info trees and messages are not discarded. -/
private def withoutModifyingStateWithInfoAndMessagesImpl (x : TermElabM α) : TermElabM α := do
let saved ← saveState
try
withSaveInfoContext x
finally
let saved := { saved with meta.core.infoState := (← getInfoState), meta.core.messages := (← getThe Core.State).messages }
restoreState saved
/--
Execute `x` without storing `Syntax` for recursive applications. See `saveRecAppSyntax` field at `Context`.
-/
def withoutSavingRecAppSyntax (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with saveRecAppSyntax := false }) x
unsafe def mkTermElabAttributeUnsafe (ref : Name) : IO (KeyedDeclsAttribute TermElab) :=
mkElabAttribute TermElab `builtin_term_elab `term_elab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term" ref
@[implemented_by mkTermElabAttributeUnsafe]
opaque mkTermElabAttribute (ref : Name) : IO (KeyedDeclsAttribute TermElab)
builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab ← mkTermElabAttribute decl_name%
/--
Auxiliary datatype for presenting a Lean lvalue modifier.
We represent an unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`.
Example: `a.foo.1` is represented as the `Syntax` `a` and the list
`[LVal.fieldName "foo", LVal.fieldIdx 1]`.
-/
inductive LVal where
| fieldIdx (ref : Syntax) (i : Nat)
/-- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierarchical/composite name.
`ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/
| fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax)
def LVal.getRef : LVal → Syntax
| .fieldIdx ref _ => ref
| .fieldName ref .. => ref
def LVal.isFieldName : LVal → Bool
| .fieldName .. => true
| _ => false
instance : ToString LVal where
toString
| .fieldIdx _ i => toString i
| .fieldName _ n .. => n
/-- Return the name of the declaration being elaborated if available. -/
def getDeclName? : TermElabM (Option Name) := return (← read).declName?
/-- Return the list of nested `let rec` declarations that need to be lifted. -/
def getLetRecsToLift : TermElabM (List LetRecToLift) := return (← get).letRecsToLift
/-- Return the declaration of the given metavariable -/
def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (← getMCtx).getDecl mvarId
/-- Execute `x` with `declName? := name`. See `getDeclName?`. -/
def withDeclName (name : Name) (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with declName? := name }) x
/-- Update the universe level parameter names. -/
def setLevelNames (levelNames : List Name) : TermElabM Unit :=
modify fun s => { s with levelNames := levelNames }
/-- Execute `x` using `levelNames` as the universe level parameter names. See `getLevelNames`. -/
def withLevelNames (levelNames : List Name) (x : TermElabM α) : TermElabM α := do
let levelNamesSaved ← getLevelNames
setLevelNames levelNames
try x finally setLevelNames levelNamesSaved
/--
Declare an auxiliary local declaration `shortDeclName : type` for elaborating recursive declaration `declName`,
update the mapping `auxDeclToFullName`, and then execute `k`.
-/
def withAuxDecl (shortDeclName : Name) (type : Expr) (declName : Name) (k : Expr → TermElabM α) : TermElabM α :=
withLocalDecl shortDeclName .default (kind := .auxDecl) type fun x =>
withReader (fun ctx => { ctx with auxDeclToFullName := ctx.auxDeclToFullName.insert x.fvarId! declName }) do
k x
def withoutErrToSorryImp (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with errToSorry := false }) x
/--
Execute `x` without converting errors (i.e., exceptions) to `sorry` applications.
Recall that when `errToSorry = true`, the method `elabTerm` catches exceptions and converts them into `sorry` applications.
-/
def withoutErrToSorry [MonadFunctorT TermElabM m] : m α → m α :=
monadMap (m := TermElabM) withoutErrToSorryImp
/-- For testing `TermElabM` methods. The #eval command will sign the error. -/
def throwErrorIfErrors : TermElabM Unit := do
if (← MonadLog.hasErrors) then
throwError "Error(s)"
def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit :=
withRef Syntax.missing <| trace cls msg
def ppGoal (mvarId : MVarId) : TermElabM Format :=
Meta.ppGoal mvarId
open Level (LevelElabM)
def liftLevelM (x : LevelElabM α) : TermElabM α := do
let ctx ← read
let mctx ← getMCtx
let ngen ← getNGen
let lvlCtx : Level.Context := { options := (← getOptions), ref := (← getRef), autoBoundImplicit := ctx.autoBoundImplicit }
match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (← getLevelNames) } with
| .ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a
| .error ex _ => throw ex
def elabLevel (stx : Syntax) : TermElabM Level :=
liftLevelM <| Level.elabLevel stx
/-- Elaborate `x` with `stx` on the macro stack -/
def withPushMacroExpansionStack (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x
/-- Elaborate `x` with `stx` on the macro stack and produce macro expansion info -/
def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α :=
withMacroExpansionInfo beforeStx afterStx do
withPushMacroExpansionStack beforeStx afterStx x
/--
Add the given metavariable to the list of pending synthetic metavariables.
The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/
def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do
modify fun s => { s with syntheticMVars := s.syntheticMVars.insert mvarId { stx, kind }, pendingMVars := mvarId :: s.pendingMVars }
def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do
registerSyntheticMVar (← getRef) mvarId kind
def registerMVarErrorInfo (mvarErrorInfo : MVarErrorInfo) : TermElabM Unit :=
modify fun s => { s with mvarErrorInfos := s.mvarErrorInfos.insert mvarErrorInfo.mvarId mvarErrorInfo }
def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit :=
registerMVarErrorInfo { mvarId, ref, kind := .hole }
def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do
registerMVarErrorInfo { mvarId, ref, kind := .implicitArg app }
def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do
registerMVarErrorInfo { mvarId, ref, kind := .custom msgData }
def getMVarErrorInfo? (mvarId : MVarId) : TermElabM (Option MVarErrorInfo) := do
return (← get).mvarErrorInfos.find? mvarId
def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit :=
match e.getAppFn with
| Expr.mvar mvarId => registerMVarErrorCustomInfo mvarId ref msgData
| _ => pure ()
/--
Auxiliary method for reporting errors of the form "... contains metavariables ...".
This kind of error is thrown, for example, at `Match.lean` where elaboration
cannot continue if there are metavariables in patterns.
We only want to log it if we haven't logged any errors so far. -/
def throwMVarError (m : MessageData) : TermElabM α := do
if (← MonadLog.hasErrors) then
throwAbortTerm
else
throwError m
def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do
match mvarErrorInfo.kind with
| MVarErrorKind.implicitArg app => do
let app ← instantiateMVars app
let msg := addArgName "don't know how to synthesize implicit argument"
let msg := msg ++ m!"{indentExpr app.setAppPPExplicitForExposingMVars}" ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId
logErrorAt mvarErrorInfo.ref (appendExtra msg)
| MVarErrorKind.hole => do
let msg := addArgName "don't know how to synthesize placeholder" " for argument"
let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId
logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg)
| MVarErrorKind.custom msg =>
logErrorAt mvarErrorInfo.ref (appendExtra msg)
where
/-- Append `mvarErrorInfo` argument name (if available) to the message.
Remark: if the argument name contains macro scopes we do not append it. -/
addArgName (msg : MessageData) (extra : String := "") : MessageData :=
match mvarErrorInfo.argName? with
| none => msg
| some argName => if argName.hasMacroScopes then msg else msg ++ extra ++ m!" '{argName}'"
appendExtra (msg : MessageData) : MessageData :=
match extraMsg? with
| none => msg
| some extraMsg => msg ++ extraMsg
/--
Try to log errors for the unassigned metavariables `pendingMVarIds`.
Return `true` if there were "unfilled holes", and we should "abort" declaration.
TODO: try to fill "all" holes using synthetic "sorry's"
Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/
def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do
if pendingMVarIds.isEmpty then
return false
else
let hasOtherErrors ← MonadLog.hasErrors
let mut hasNewErrors := false
let mut alreadyVisited : MVarIdSet := {}
let mut errors : Array MVarErrorInfo := #[]
for (_, mvarErrorInfo) in (← get).mvarErrorInfos do
let mvarId := mvarErrorInfo.mvarId
unless alreadyVisited.contains mvarId do
alreadyVisited := alreadyVisited.insert mvarId
/- The metavariable `mvarErrorInfo.mvarId` may have been assigned or
delayed assigned to another metavariable that is unassigned. -/
let mvarDeps ← getMVars (mkMVar mvarId)
if mvarDeps.any pendingMVarIds.contains then do
unless hasOtherErrors do
errors := errors.push mvarErrorInfo
hasNewErrors := true
-- To sort the errors by position use
-- let sortedErrors := errors.qsort fun e₁ e₂ => e₁.ref.getPos?.getD 0 < e₂.ref.getPos?.getD 0
for error in errors do
error.mvarId.withContext do
error.logError extraMsg?
return hasNewErrors
/-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/
def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do
let pendingMVarIds ← getMVarsAtDecl decl
if (← logUnassignedUsingErrorInfos pendingMVarIds) then
throwAbortCommand
/--
Execute `x` without allowing it to postpone elaboration tasks.
That is, `tryPostpone` is a noop. -/
def withoutPostponing (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with mayPostpone := false }) x
/-- Creates syntax for `(` <ident> `:` <type> `)` -/
def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax :=
mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"]
/--
Convert unassigned universe level metavariables into parameters.
The new parameter names are fresh names of the form `u_i` with regard to `ctx.levelNames`, which is updated with the new names. -/
def levelMVarToParam (e : Expr) (except : LMVarId → Bool := fun _ => false) : TermElabM Expr := do
let levelNames ← getLevelNames
let r := (← getMCtx).levelMVarToParam (fun n => levelNames.elem n) except e `u 1
setLevelNames (levelNames ++ r.newParamNames.toList)
setMCtx r.mctx
return r.expr
/--
Auxiliary method for creating fresh binder names.
Do not confuse with the method for creating fresh free/meta variable ids. -/
def mkFreshBinderName [Monad m] [MonadQuotation m] : m Name :=
withFreshMacroScope <| MonadQuotation.addMacroScope `x
/--
Auxiliary method for creating a `Syntax.ident` containing
a fresh name. This method is intended for creating fresh binder names.
It is just a thin layer on top of `mkFreshUserName`. -/
def mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) (canonical := false) : m Ident :=
return mkIdentFrom ref (← mkFreshBinderName) canonical
private def applyAttributesCore
(declName : Name) (attrs : Array Attribute)
(applicationTime? : Option AttributeApplicationTime) : TermElabM Unit := do profileitM Exception "attribute application" (← getOptions) do
for attr in attrs do
withRef attr.stx do withLogging do
let env ← getEnv
match getAttributeImpl env attr.name with
| Except.error errMsg => throwError errMsg
| Except.ok attrImpl =>
let runAttr := attrImpl.add declName attr.stx attr.kind
let runAttr := do
-- not truly an elaborator, but a sensible target for go-to-definition
let elaborator := attrImpl.ref
if (← getInfoState).enabled && (← getEnv).contains elaborator then
withInfoContext (mkInfo := return .ofCommandInfo { elaborator, stx := attr.stx }) do
try runAttr
finally if attr.stx[0].isIdent || attr.stx[0].isAtom then
-- Add an additional node over the leading identifier if there is one to make it look more function-like.
-- Do this last because we want user-created infos to take precedence
pushInfoLeaf <| .ofCommandInfo { elaborator, stx := attr.stx[0] }
else
runAttr
match applicationTime? with
| none => runAttr
| some applicationTime =>
if applicationTime == attrImpl.applicationTime then
runAttr
/-- Apply given attributes **at** a given application time -/
def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit :=
applyAttributesCore declName attrs applicationTime
def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit :=
applyAttributesCore declName attrs none
def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do
let header : MessageData := match header? with
| some header => m!"{header} "
| none => m!"type mismatch{indentExpr e}\n"
return m!"{header}{← mkHasTypeButIsExpectedMsg eType expectedType}"
def throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr)
(f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := do
/-
We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was
always of the form:
```
failed to synthesize instance
CoeT <eType> <e> <expectedType>
```
We should revisit this decision in the future and decide whether it may contain useful information
or not. -/
let extraMsg := Format.nil
/-
let extraMsg : MessageData := match extraMsg? with
| none => Format.nil
| some extraMsg => Format.line ++ extraMsg;
-/
match f? with
| none => throwError "{← mkTypeMismatchError header? e eType expectedType}{extraMsg}"
| some f => Meta.throwAppTypeMismatch f e
def withoutMacroStackAtErr (x : TermElabM α) : TermElabM α :=
withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x
namespace ContainsPendingMVar
abbrev M := MonadCacheT Expr Unit (OptionT MetaM)
/-- See `containsPostponedTerm` -/
partial def visit (e : Expr) : M Unit := do
checkCache e fun _ => do
match e with
| .forallE _ d b _ => visit d; visit b
| .lam _ d b _ => visit d; visit b
| .letE _ t v b _ => visit t; visit v; visit b
| .app f a => visit f; visit a
| .mdata _ b => visit b
| .proj _ _ b => visit b
| .fvar fvarId .. =>
match (← fvarId.getDecl) with
| .cdecl .. => return ()
| .ldecl (value := v) .. => visit v
| .mvar mvarId .. =>
let e' ← instantiateMVars e
if e' != e then
visit e'
else
match (← getDelayedMVarAssignment? mvarId) with
| some d => visit (mkMVar d.mvarIdPending)
| none => failure
| _ => return ()
end ContainsPendingMVar
/-- Return `true` if `e` contains a pending metavariable. Remark: it also visits let-declarations. -/
def containsPendingMVar (e : Expr) : MetaM Bool := do
match (← ContainsPendingMVar.visit e |>.run.run) with
| some _ => return false
| none => return true
/--
Try to synthesize metavariable using type class resolution.
This method assumes the local context and local instances of `instMVar` coincide
with the current local context and local instances.
Return `true` if the instance was synthesized successfully, and `false` if
the instance contains unassigned metavariables that are blocking the type class
resolution procedure. Throw an exception if resolution or assignment irrevocably fails.
-/
def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do
let instMVarDecl ← getMVarDecl instMVar
let type := instMVarDecl.type
let type ← instantiateMVars type
let result ← trySynthInstance type maxResultSize?
match result with
| LOption.some val =>
if (← instMVar.isAssigned) then
let oldVal ← instantiateMVars (mkMVar instMVar)
unless (← isDefEq oldVal val) do
if (← containsPendingMVar oldVal <||> containsPendingMVar val) then
/- If `val` or `oldVal` contains metavariables directly or indirectly (e.g., in a let-declaration),
we return `false` to indicate we should try again later. This is very coarse grain since
the metavariable may not be responsible for the failure. We should refine the test in the future if needed.
This check has been added to address dependencies between postponed metavariables. The following
example demonstrates the issue fixed by this test.
```
structure Point where
x : Nat
y : Nat
def Point.compute (p : Point) : Point :=
let p := { p with x := 1 }
let p := { p with y := 0 }
if (p.x - p.y) > p.x then p else p
```
The `isDefEq` test above fails for `Decidable (p.x - p.y ≤ p.x)` when the structure instance assigned to
`p` has not been elaborated yet.
-/
return false -- we will try again later
let oldValType ← inferType oldVal
let valType ← inferType val
unless (← isDefEq oldValType valType) do
throwError "synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\nhas type{indentExpr valType}\nexpected{indentExpr oldValType}"
throwError "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}"
else
unless (← isDefEq (mkMVar instMVar) val) do
throwError "failed to assign synthesized type class instance{indentExpr val}"
return true
| .undef => return false -- we will try later
| .none =>
if (← read).ignoreTCFailures then
return false
else
throwError "failed to synthesize instance{indentExpr type}"
def mkCoe (expectedType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do
withTraceNode `Elab.coe (fun _ => return m!"adding coercion for {e} : {← inferType e} =?= {expectedType}") do
try
withoutMacroStackAtErr do
match ← coerce? e expectedType with
| .some eNew => return eNew
| .none => failure
| .undef =>
let mvarAux ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque
registerSyntheticMVarWithCurrRef mvarAux.mvarId! (.coe errorMsgHeader? expectedType e f?)
return mvarAux
catch
| .error _ msg => throwTypeMismatchError errorMsgHeader? expectedType (← inferType e) e f? msg
| _ => throwTypeMismatchError errorMsgHeader? expectedType (← inferType e) e f?
/--
If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal.
If they are not, then try coercions.
Argument `f?` is used only for generating error messages. -/
def ensureHasType (expectedType? : Option Expr) (e : Expr)
(errorMsgHeader? : Option String := none) (f? : Option Expr := none) : TermElabM Expr := do
let some expectedType := expectedType? | return e
if (← isDefEq (← inferType e) expectedType) then
return e
else
mkCoe expectedType e f? errorMsgHeader?
/--
Create a synthetic sorry for the given expected type. If `expectedType? = none`, then a fresh
metavariable is created to represent the type.
-/
private def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do
let expectedType ← match expectedType? with
| none => mkFreshTypeMVar
| some expectedType => pure expectedType
mkSyntheticSorry expectedType
/--
Log the given exception, and create a synthetic sorry for representing the failed
elaboration step with exception `ex`.
-/
def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do
let syntheticSorry ← mkSyntheticSorryFor expectedType?
logException ex
pure syntheticSorry
/-- If `mayPostpone == true`, throw `Expection.postpone`. -/
def tryPostpone : TermElabM Unit := do
if (← read).mayPostpone then
throwPostpone
/-- Return `true` if `e` reduces (by unfolding only `[reducible]` declarations) to `?m ...` -/
def isMVarApp (e : Expr) : TermElabM Bool :=
return (← whnfR e).getAppFn.isMVar
/-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/
def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do
if (← isMVarApp e) then
tryPostpone
/-- If `e? = some e`, then `tryPostponeIfMVar e`, otherwise it is just `tryPostpone`. -/
def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit :=
match e? with
| some e => tryPostponeIfMVar e
| none => tryPostpone
/--
Throws `Exception.postpone`, if `expectedType?` contains unassigned metavariables.
It is a noop if `mayPostpone == false`.
-/
def tryPostponeIfHasMVars? (expectedType? : Option Expr) : TermElabM (Option Expr) := do
tryPostponeIfNoneOrMVar expectedType?
let some expectedType := expectedType? | return none
let expectedType ← instantiateMVars expectedType
if expectedType.hasExprMVar then
tryPostpone
return none
return some expectedType
/--
Throws `Exception.postpone`, if `expectedType?` contains unassigned metavariables.
If `mayPostpone == false`, it throws error `msg`.
-/
def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do
let some expectedType ← tryPostponeIfHasMVars? expectedType? |
throwError "{msg}, expected type contains metavariables{indentD expectedType?}"
return expectedType
/--
Save relevant context for term elaboration postponement.
-/
def saveContext : TermElabM SavedContext :=
return {
macroStack := (← read).macroStack
declName? := (← read).declName?
options := (← getOptions)
openDecls := (← getOpenDecls)
errToSorry := (← read).errToSorry
levelNames := (← get).levelNames
}
/--
Execute `x` with the context saved using `saveContext`.
-/
def withSavedContext (savedCtx : SavedContext) (x : TermElabM α) : TermElabM α := do
withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <|
withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls }) <|
withLevelNames savedCtx.levelNames x
/--
Delay the elaboration of `stx`, and return a fresh metavariable that works a placeholder.
Remark: the caller is responsible for making sure the info tree is properly updated.
This method is used only at `elabUsingElabFnsAux`.
-/
private def postponeElabTermCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
trace[Elab.postpone] "{stx} : {expectedType?}"
let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque
registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (← saveContext))
return mvar
def getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) :=
return (← get).syntheticMVars.find? mvarId
/--
Create an auxiliary annotation to make sure we create an `Info` even if `e` is a metavariable.
See `mkTermInfo`.
We use this function because some elaboration functions elaborate subterms that may not be immediately
part of the resulting term. Example:
```
let_mvar% ?m := b; wait_if_type_mvar% ?m; body
```
If the type of `b` is not known, then `wait_if_type_mvar% ?m; body` is postponed and just returns a fresh
metavariable `?n`. The elaborator for
```
let_mvar% ?m := b; wait_if_type_mvar% ?m; body
```
returns `mkSaveInfoAnnotation ?n` to make sure the info nodes created when elaborating `b` are "saved".
This is a bit hackish, but elaborators like `let_mvar%` are rare.
-/
def mkSaveInfoAnnotation (e : Expr) : Expr :=
if e.isMVar then
mkAnnotation `save_info e
else
e
def isSaveInfoAnnotation? (e : Expr) : Option Expr :=
annotation? `save_info e
partial def removeSaveInfoAnnotation (e : Expr) : Expr :=
match isSaveInfoAnnotation? e with
| some e => removeSaveInfoAnnotation e
| _ => e
/--
Return `some mvarId` if `e` corresponds to a hole that is going to be filled "later" by executing a tactic or resuming elaboration.
We do not save `ofTermInfo` for this kind of node in the `InfoTree`.
-/
def isTacticOrPostponedHole? (e : Expr) : TermElabM (Option MVarId) := do
match e with
| Expr.mvar mvarId =>
match (← getSyntheticMVarDecl? mvarId) with
| some { kind := .tactic .., .. } => return mvarId
| some { kind := .postponed .., .. } => return mvarId
| _ => return none
| _ => pure none
def mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (isBinder := false) : TermElabM (Sum Info MVarId) := do
match (← isTacticOrPostponedHole? e) with
| some mvarId => return Sum.inr mvarId
| none =>
let e := removeSaveInfoAnnotation e
return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (← getLCtx), expr := e, stx, expectedType?, isBinder }
/--
Pushes a new leaf node to the info tree associating the expression `e` to the syntax `stx`.
As a result, when the user hovers over `stx` they will see the type of `e`, and if `e`
is a constant they will see the constant's doc string.
* `expectedType?`: the expected type of `e` at the point of elaboration, if available
* `lctx?`: the local context in which to interpret `e` (otherwise it will use `← getLCtx`)
* `elaborator`: a declaration name used as an alternative target for go-to-definition
* `isBinder`: if true, this will be treated as defining `e` (which should be a local constant)
for the purpose of go-to-definition on local variables
* `force`: In patterns, the effect of `addTermInfo` is usually suppressed and replaced
by a `patternWithRef?` annotation which will be turned into a term info on the
post-match-elaboration expression. This flag overrides that behavior and adds the term
info immediately. (See https://github.com/leanprover/lean4/pull/1664.)
-/
def addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none)
(lctx? : Option LocalContext := none) (elaborator := Name.anonymous)
(isBinder := false) (force := false) : TermElabM Expr := do
if (← read).inPattern && !force then
return mkPatternWithRef e stx
else
withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx? isBinder) |> discard
return e
def addTermInfo' (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) : TermElabM Unit :=
discard <| addTermInfo stx e expectedType? lctx? elaborator isBinder
def withInfoContext' (stx : Syntax) (x : TermElabM Expr) (mkInfo : Expr → TermElabM (Sum Info MVarId)) : TermElabM Expr := do
if (← read).inPattern then
let e ← x
return mkPatternWithRef e stx
else
Elab.withInfoContext' x mkInfo
/--
Postpone the elaboration of `stx`, return a metavariable that acts as a placeholder, and
ensures the info tree is updated and a hole id is introduced.
When `stx` is elaborated, new info nodes are created and attached to the new hole id in the info tree.
-/
def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
withInfoContext' stx (mkInfo := mkTermInfo .anonymous (expectedType? := expectedType?) stx) do
postponeElabTermCore stx expectedType?
/--
Helper function for `elabTerm` that tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or
an error is found. -/
private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool)
: List (KeyedDeclsAttribute.AttributeEntry TermElab) → TermElabM Expr
| [] => do throwError "unexpected syntax{indentD stx}"
| (elabFn::elabFns) =>
try
-- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`)
withInfoContext' stx (mkInfo := mkTermInfo elabFn.declName (expectedType? := expectedType?) stx)
(try
elabFn.value stx expectedType?
catch ex => match ex with
| .error .. =>
if (← read).errToSorry then
exceptionToSorry ex expectedType?
else
throw ex
| .internal id _ =>
if (← read).errToSorry && id == abortTermExceptionId then
exceptionToSorry ex expectedType?
else if id == unsupportedSyntaxExceptionId then
throw ex -- to outer try
else if catchExPostpone && id == postponeExceptionId then
/- If `elab` threw `Exception.postpone`, we reset any state modifications.
For example, we want to make sure pending synthetic metavariables created by `elab` before
it threw `Exception.postpone` are discarded.
Note that we are also discarding the messages created by `elab`.
For example, consider the expression.
`((f.x a1).x a2).x a3`
Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`.
Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone`
because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and
finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would
keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is
wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch
and new metavariables are created for the nested functions. -/
s.restore
postponeElabTermCore stx expectedType?
else
throw ex)
catch ex => match ex with
| .internal id _ =>
if id == unsupportedSyntaxExceptionId then
s.restore -- also removes the info tree created above
elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns
else
throw ex
| _ => throw ex
private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do
let s ← saveState
let k := stx.getKind
match termElabAttribute.getEntries (← getEnv) k with
| [] => throwError "elaboration function for '{k}' has not been implemented{indentD stx}"
| elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns
instance : MonadMacroAdapter TermElabM where
getCurrMacroScope := getCurrMacroScope
getNextMacroScope := return (← getThe Core.State).nextMacroScope
setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next }
private def isExplicit (stx : Syntax) : Bool :=
match stx with
| `(@$_) => true
| _ => false
private def isExplicitApp (stx : Syntax) : Bool :=
stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0]
/--
Return true if `stx` is a lambda abstraction containing a `{}` or `[]` binder annotation.
Example: `fun {α} (a : α) => a` -/
private def isLambdaWithImplicit (stx : Syntax) : Bool :=
match stx with
| `(fun $binders* => $_) => binders.raw.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder
| _ => false
private partial def dropTermParens : Syntax → Syntax := fun stx =>
match stx with
| `(($stx)) => dropTermParens stx
| _ => stx
private def isHole (stx : Syntax) : Bool :=
match stx with
| `(_) => true
| `(? _) => true
| `(? $_:ident) => true
| _ => false
private def isTacticBlock (stx : Syntax) : Bool :=
match stx with
| `(by $_:tacticSeq) => true
| _ => false
private def isNoImplicitLambda (stx : Syntax) : Bool :=
match stx with
| `(no_implicit_lambda% $_:term) => true
| _ => false
private def isTypeAscription (stx : Syntax) : Bool :=
match stx with
| `(($_ : $_)) => true
| _ => false
def hasNoImplicitLambdaAnnotation (type : Expr) : Bool :=
annotation? `noImplicitLambda type |>.isSome
def mkNoImplicitLambdaAnnotation (type : Expr) : Expr :=
if hasNoImplicitLambdaAnnotation type then
type
else
mkAnnotation `noImplicitLambda type
/-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/
def blockImplicitLambda (stx : Syntax) : Bool :=
let stx := dropTermParens stx
-- TODO: make it extensible
isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx ||
isNoImplicitLambda stx || isTypeAscription stx
def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do
let lctx ← getLCtx
let auxDeclToFullName := (← read).auxDeclToFullName
let currNamespace ← getCurrNamespace
let view := extractMacroScopes n
/- Simple case. "Match" function for regular local declarations. -/
let matchLocalDecl? (localDecl : LocalDecl) (givenName : Name) : Option LocalDecl := do
guard (localDecl.userName == givenName)
return localDecl
/-
"Match" function for auxiliary declarations that correspond to recursive definitions being defined.
This function is used in the first-pass.
Note that we do not check for `localDecl.userName == givenName` in this pass as we do for regular local declarations.
Reason: consider the following example
```
mutual
inductive Foo
| somefoo : Foo | bar : Bar → Foo → Foo
inductive Bar
| somebar : Bar| foobar : Foo → Bar → Bar
end
mutual
private def Foo.toString : Foo → String
| Foo.somefoo => go 2 ++ toString.go 2 ++ Foo.toString.go 2
| Foo.bar b f => toString f ++ Bar.toString b
where
go (x : Nat) := s!"foo {x}"
private def _root_.Ex2.Bar.toString : Bar → String
| Bar.somebar => "bar"
| Bar.foobar f b => Foo.toString f ++ Bar.toString b
end
```
In the example above, we have two local declarations named `toString` in the local context, and
we want the `toString f` to be resolved to `Foo.toString f`.
-/
let matchAuxRecDecl? (localDecl : LocalDecl) (fullDeclName : Name) (givenNameView : MacroScopesView) : Option LocalDecl := do
let fullDeclView := extractMacroScopes fullDeclName
/- First cleanup private name annotations -/
let fullDeclView := { fullDeclView with name := (privateToUserName? fullDeclView.name).getD fullDeclView.name }
let fullDeclName := fullDeclView.review
let localDeclNameView := extractMacroScopes localDecl.userName
/- If the current namespace is a prefix of the full declaration name,
we use a relaxed matching test where we must satisfy the following conditions
- The local declaration is a suffix of the given name.
- The given name is a suffix of the full declaration.
Recall the `let rec`/`where` declaration naming convention. For example, suppose we have
```
def Foo.Bla.f ... :=
... go ...
where
go ... := ...
```
The current namespace is `Foo.Bla`, and the full name for `go` is `Foo.Bla.f.g`, but we want to
refer to it using just `go`. It is also accepted to refer to it using `f.go`, `Bla.f.go`, etc.
-/
if currNamespace.isPrefixOf fullDeclName then
/- Relaxed mode that allows us to access `let rec` declarations using shorter names -/
guard (localDeclNameView.isSuffixOf givenNameView)
guard (givenNameView.isSuffixOf fullDeclView)
return localDecl
else
/-
It is the standard algorithm we are using at `resolveGlobalName` for processing namespaces.
The current solution also has a limitation when using `def _root_` in a mutual block.
The non `def _root_` declarations may update the namespace. See the following example:
```
mutual
def Foo.f ... := ...
def _root_.g ... := ...
let rec h := ...
...
end
```
`def Foo.f` updates the namespace. Then, even when processing `def _root_.g ...`
the condition `currNamespace.isPrefixOf fullDeclName` does not hold.
This is not a big problem because we are planning to modify how we handle the mutual block in the future.
Note that we don't check for `localDecl.userName == givenName` here.
-/
let rec go (ns : Name) : Option LocalDecl := do
if { givenNameView with name := ns ++ givenNameView.name }.review == fullDeclName then
return localDecl
match ns with
| .str pre .. => go pre
| _ => failure
return (← go currNamespace)
/- Traverse the local context backwards looking for match `givenNameView`.
If `skipAuxDecl` we ignore `auxDecl` local declarations. -/
let findLocalDecl? (givenNameView : MacroScopesView) (skipAuxDecl : Bool) : Option LocalDecl :=
let givenName := givenNameView.review
let localDecl? := lctx.decls.findSomeRev? fun localDecl? => do
let localDecl ← localDecl?
if localDecl.isAuxDecl then
guard (not skipAuxDecl)
if let some fullDeclName := auxDeclToFullName.find? localDecl.fvarId then
matchAuxRecDecl? localDecl fullDeclName givenNameView
else
matchLocalDecl? localDecl givenName
else
matchLocalDecl? localDecl givenName
if localDecl?.isSome || skipAuxDecl then
localDecl?
else
-- Search auxDecls again trying an exact match of the given name
lctx.decls.findSomeRev? fun localDecl? => do
let localDecl ← localDecl?
guard localDecl.isAuxDecl
matchLocalDecl? localDecl givenName
/-
We use the parameter `globalDeclFound` to decide whether we should skip auxiliary declarations or not.
We set it to true if we found a global declaration `n` as we iterate over the `loop`.
Without this workaround, we would not be able to elaborate an example such as
```
def foo.aux := 1
def foo : Nat → Nat
| n => foo.aux -- should not be interpreted as `(foo).bar`
```
See test `aStructPerfIssue.lean` for another example.
We skip auxiliary declarations when `projs` is not empty and `globalDeclFound` is true.
Remark: we did not use to have the `globalDeclFound` parameter. Without this extra check we failed
to elaborate
```
example : Nat :=
let n := 0
n.succ + (m |>.succ) + m.succ
where
m := 1
```
See issue #1850.
-/
let rec loop (n : Name) (projs : List String) (globalDeclFound : Bool) := do
let givenNameView := { view with name := n }
let mut globalDeclFound := globalDeclFound
unless globalDeclFound do
let r ← resolveGlobalName givenNameView.review
let r := r.filter fun (_, fieldList) => fieldList.isEmpty
unless r.isEmpty do
globalDeclFound := true
match findLocalDecl? givenNameView (skipAuxDecl := globalDeclFound && not projs.isEmpty) with
| some decl => return some (decl.toExpr, projs)
| none => match n with
| .str pre s => loop pre (s::projs) globalDeclFound
| _ => return none
loop view.name [] (globalDeclFound := false)
/-- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/
def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) :=
match stx with
| Syntax.ident _ _ val _ => do
let r? ← resolveLocalName val
match r? with
| some (fvar, []) => return some fvar
| _ => return none
| _ => return none
inductive UseImplicitLambdaResult where
| no
| yes (expectedType : Expr)
| postpone
/--
Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and
`blockImplicitLambda stx` is not true, else return `none`.
Remark: implicit lambdas are not triggered by the strict implicit binder annotation `{{a : α}} → β`
-/
private def useImplicitLambda (stx : Syntax) (expectedType? : Option Expr) : TermElabM UseImplicitLambdaResult := do
if blockImplicitLambda stx then
return .no
let some expectedType := expectedType? | return .no
if hasNoImplicitLambdaAnnotation expectedType then
return .no
let expectedType ← whnfForall expectedType
let .forallE _ _ _ c := expectedType | return .no
unless c.isImplicit || c.isInstImplicit do
return .no
if let some x ← isLocalIdent? stx then
if (← isMVarApp (← inferType x)) then
/-
If `stx` is a local variable without type information, then adding implicit lambdas makes elaboration fail.
We should try to postpone elaboration until the type of the local variable becomes available, or disable
implicit lambdas if we cannot postpone anymore.
Here is an example where this special case is useful.
```
def foo2mk (_ : ∀ {α : Type} (a : α), a = a) : nat := 37
example (x) : foo2mk x = foo2mk x := rfl
```
The example about would fail without this special case.
The expected type would be `(a : α✝) → a = a`, where `α✝` is a new free variable introduced by the implicit lambda.
Now, let `?m` be the type of `x`. Then, the constraint `?m =?= (a : α✝) → a = a` cannot be solved using the
assignment `?m := (a : α✝) → a = a` since `α✝` is not in the scope of `?m`.
Note that, this workaround does not prevent the following example from failing.
```
example (x) : foo2mk (id x) = 37 := rfl
```
The user can write
```
example (x) : foo2mk (id @x) = 37 := rfl
```
-/
return .postpone
return .yes expectedType
private def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do
match ex with
| .error ref msg =>
if impFVars.isEmpty then
return Exception.error ref msg
else
let mut msg := m!"{msg}\nthe following variables have been introduced by the implicit lambda feature"
for impFVar in impFVars do
let auxMsg := m!"{impFVar} : {← inferType impFVar}"
let auxMsg ← addMessageContext auxMsg
msg := m!"{msg}{indentD auxMsg}"
msg := m!"{msg}\nyou can disable implicit lambdas using `@` or writing a lambda expression with `\{}` or `[]` binder annotations."
return Exception.error ref msg
| _ => return ex
private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do
let body ← elabUsingElabFns stx expectedType catchExPostpone
try
let body ← ensureHasType expectedType body
let r ← mkLambdaFVars impFVars body
trace[Elab.implicitForall] r
return r
catch ex =>
throw (← decorateErrorMessageWithLambdaImplicitVars ex impFVars)
private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr :=
loop type #[]
where
loop (type : Expr) (fvars : Array Expr) : TermElabM Expr := do
match (← whnfForall type) with
| .forallE n d b c =>
if c.isExplicit then
elabImplicitLambdaAux stx catchExPostpone type fvars
else withFreshMacroScope do
let n ← MonadQuotation.addMacroScope n
withLocalDecl n c d fun fvar => do
let type := b.instantiate1 fvar
loop type (fvars.push fvar)
| _ =>
elabImplicitLambdaAux stx catchExPostpone type fvars
/-- Main loop for `elabTerm` -/
private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr
| .missing => mkSyntheticSorryFor expectedType?
| stx => withFreshMacroScope <| withIncRecDepth do
withTraceNode `Elab.step (fun _ => return m!"expected type: {expectedType?}, term\n{stx}") do
checkMaxHeartbeats "elaborator"
let env ← getEnv
let result ← match (← liftMacroM (expandMacroImpl? env stx)) with
| some (decl, stxNew?) =>
let stxNew ← liftMacroM <| liftExcept stxNew?
withInfoContext' stx (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <|
withMacroExpansion stx stxNew <|
withRef stxNew <|
elabTermAux expectedType? catchExPostpone implicitLambda stxNew
| _ =>
let useImplicitResult ← if implicitLambda && (← read).implicitLambda then useImplicitLambda stx expectedType? else pure .no
match useImplicitResult with
| .yes expectedType => elabImplicitLambda stx catchExPostpone expectedType
| .no => elabUsingElabFns stx expectedType? catchExPostpone
| .postpone =>
/-
Try to postpone elaboration, and if we cannot postpone anymore disable implicit lambdas.
See comment at `useImplicitLambda`.
-/
if (← read).mayPostpone then
if catchExPostpone then
postponeElabTerm stx expectedType?
else
throwPostpone
else
elabUsingElabFns stx expectedType? catchExPostpone
trace[Elab.step.result] result
pure result
/-- Store in the `InfoTree` that `e` is a "dot"-completion target. -/
def addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do
addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (← getLCtx), elaborator := .anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?)
/--
Main function for elaborating terms.
It extracts the elaboration methods from the environment using the node kind.
Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods.
It creates a fresh macro scope for executing the elaboration method.
All unlogged trace messages produced by the elaboration method are logged using
the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`,
the error is logged and a synthetic sorry expression is returned.
If the elaboration throws `Exception.postpone` and `catchExPostpone == true`,
a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered,
and returned.
The option `catchExPostpone == false` is used to implement `resumeElabTerm`
to prevent the creation of another synthetic metavariable when resuming the elaboration.
If `implicitLambda == false`, then disable implicit lambdas feature for the given syntax, but not for its subterms.
We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect.
-/
def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr :=
withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx
def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do
let e ← elabTerm stx expectedType? catchExPostpone implicitLambda
withRef stx <| ensureHasType expectedType? e errorMsgHeader?
/-- Execute `x` and return `some` if no new errors were recorded or exceptions were thrown. Otherwise, return `none`. -/
def commitIfNoErrors? (x : TermElabM α) : TermElabM (Option α) := do
let saved ← saveState
Core.resetMessageLog
try
let a ← x
if (← MonadLog.hasErrors) then
restoreState saved
return none
else
Core.setMessageLog (saved.meta.core.messages ++ (← Core.getMessageLog))
return a
catch _ =>
restoreState saved
return none
/-- Adapt a syntax transformation to a regular, term-producing elaborator. -/
def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do
let stx' ← exp stx
withMacroExpansion stx stx' <| elabTerm stx' expectedType?
/--
Create a new metavariable with the given type, and try to synthesize it.
If type class resolution cannot be executed (e.g., it is stuck because of metavariables in `type`),
register metavariable as a pending one.
-/
def mkInstMVar (type : Expr) : TermElabM Expr := do
let mvar ← mkFreshExprMVar type MetavarKind.synthetic
let mvarId := mvar.mvarId!
unless (← synthesizeInstMVarCore mvarId) do
registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass
return mvar
/--
Make sure `e` is a type by inferring its type and making sure it is an `Expr.sort`
or is unifiable with `Expr.sort`, or can be coerced into one. -/
def ensureType (e : Expr) : TermElabM Expr := do
if (← isType e) then
return e
else
let eType ← inferType e
let u ← mkFreshLevelMVar
if (← isDefEq eType (mkSort u)) then
return e
else if let some coerced ← coerceToSort? e then
return coerced
else
if (← instantiateMVars e).hasSyntheticSorry then
throwAbortTerm
throwError "type expected, got\n ({← instantiateMVars e} : {← instantiateMVars eType})"
/-- Elaborate `stx` and ensure result is a type. -/
def elabType (stx : Syntax) : TermElabM Expr := do
let u ← mkFreshLevelMVar
let type ← elabTerm stx (mkSort u)
withRef stx <| ensureType type
/--
Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught,
a new local declaration is created, registered, and `k` is tried to be executed again. -/
partial def withAutoBoundImplicit (k : TermElabM α) : TermElabM α := do
let flag := autoImplicit.get (← getOptions)
if flag then
withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do
let rec loop (s : SavedState) : TermElabM α := do
try
k
catch
| ex => match isAutoBoundImplicitLocalException? ex with
| some n =>
-- Restore state, declare `n`, and try again
s.restore
withLocalDecl n .implicit (← mkFreshTypeMVar) fun x =>
withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do
loop (← saveState)
| none => throw ex
loop (← saveState)
else
k
def withoutAutoBoundImplicit (k : TermElabM α) : TermElabM α := do
withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k
partial def withAutoBoundImplicitForbiddenPred (p : Name → Bool) (x : TermElabM α) : TermElabM α := do
withReader (fun ctx => { ctx with autoBoundImplicitForbidden := fun n => p n || ctx.autoBoundImplicitForbidden n }) x
/--
Collect unassigned metavariables in `type` that are not already in `init` and not satisfying `except`.
-/
partial def collectUnassignedMVars (type : Expr) (init : Array Expr := #[]) (except : MVarId → Bool := fun _ => false)
: TermElabM (Array Expr) := do
let mvarIds ← getMVars type
if mvarIds.isEmpty then
return init
else
go mvarIds.toList init init
where
go (mvarIds : List MVarId) (result visited : Array Expr) : TermElabM (Array Expr) := do
match mvarIds with
| [] => return result
| mvarId :: mvarIds => do
let visited := visited.push (mkMVar mvarId)
if (← mvarId.isAssigned) then
go mvarIds result visited
else if result.contains (mkMVar mvarId) || except mvarId then
go mvarIds result visited
else
let mvarType := (← getMVarDecl mvarId).type
let mvarIdsNew ← getMVars mvarType
let mvarIdsNew := mvarIdsNew.filter fun mvarId => !visited.contains (mkMVar mvarId)
if mvarIdsNew.isEmpty then
go mvarIds (result.push (mkMVar mvarId)) visited
else
go (mvarIdsNew.toList ++ mvarId :: mvarIds) result visited
/--
Return `autoBoundImplicits ++ xs`
This method throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs`.
The `autoBoundImplicits` may contain free variables created by the auto-implicit feature, and unassigned free variables.
It avoids the hack used at `autoBoundImplicitsOld`.
Remark: we cannot simply replace every occurrence of `addAutoBoundImplicitsOld` with this one because a particular
use-case may not be able to handle the metavariables in the array being given to `k`.
-/
def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do
let autos := (← read).autoBoundImplicits
go autos.toList #[]
where
go (todo : List Expr) (autos : Array Expr) : TermElabM (Array Expr) := do
match todo with
| [] =>
for auto in autos do
if auto.isFVar then
let localDecl ← auto.fvarId!.getDecl
for x in xs do
if (← localDeclDependsOn localDecl x.fvarId!) then
throwError "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'"
return autos ++ xs
| auto :: todo =>
let autos ← collectUnassignedMVars (← inferType auto) autos
go todo (autos.push auto)
/--
Similar to `autoBoundImplicits`, but immediately if the resulting array of expressions contains metavariables,
it immediately uses `mkForallFVars` + `forallBoundedTelescope` to convert them into free variables.
The type `type` is modified during the process if type depends on `xs`.
We use this method to simplify the conversion of code using `autoBoundImplicitsOld` to `autoBoundImplicits`.
-/
def addAutoBoundImplicits' (xs : Array Expr) (type : Expr) (k : Array Expr → Expr → TermElabM α) : TermElabM α := do
let xs ← addAutoBoundImplicits xs
if xs.all (·.isFVar) then
k xs type
else
forallBoundedTelescope (← mkForallFVars xs type) xs.size fun xs type => k xs type
def mkAuxName (suffix : Name) : TermElabM Name := do
match (← read).declName? with
| none => throwError "auxiliary declaration cannot be created when declaration name is not available"
| some declName => Lean.mkAuxName (declName ++ suffix) 1
builtin_initialize registerTraceClass `Elab.letrec
/-- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it
is delayed assigned to one. -/
def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do
trace[Elab.letrec] "mvarId: {mkMVar mvarId} letrecMVars: {(← get).letRecsToLift.map (mkMVar $ ·.mvarId)}"
let mvarId ← getDelayedMVarRoot mvarId
trace[Elab.letrec] "mvarId root: {mkMVar mvarId}"
return (← get).letRecsToLift.any (·.mvarId == mvarId)
/--
Create an `Expr.const` using the given name and explicit levels.
Remark: fresh universe metavariables are created if the constant has more universe
parameters than `explicitLevels`. -/
def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do
let cinfo ← getConstInfo constName
if explicitLevels.length > cinfo.levelParams.length then
throwError "too many explicit universe levels for '{constName}'"
else
let numMissingLevels := cinfo.levelParams.length - explicitLevels.length
let us ← mkFreshLevelMVars numMissingLevels
return Lean.mkConst constName (explicitLevels ++ us)
private def mkConsts (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do
candidates.foldlM (init := []) fun result (declName, projs) => do
-- TODO: better support for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail.
Linter.checkDeprecated declName -- TODO: check is occurring too early if there are multiple alternatives. Fix if it is not ok in practice
let const ← mkConst declName explicitLevels
return (const, projs) :: result
def resolveName (stx : Syntax) (n : Name) (preresolved : List Syntax.Preresolved) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × List String)) := do
addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType?
if let some (e, projs) ← resolveLocalName n then
unless explicitLevels.isEmpty do
throwError "invalid use of explicit universe parameters, '{e}' is a local"
return [(e, projs)]
let preresolved := preresolved.filterMap fun
| .decl n projs => some (n, projs)
| _ => none
-- check for section variable capture by a quotation
let ctx ← read
if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (·, projs) then
return [(e, projs)] -- section variables should shadow global decls
if preresolved.isEmpty then
process (← resolveGlobalName n)
else
process preresolved
where
process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do
if candidates.isEmpty then
if (← read).autoBoundImplicit &&
!(← read).autoBoundImplicitForbidden n &&
isValidAutoBoundImplicitName n (relaxedAutoImplicit.get (← getOptions)) then
throwAutoBoundImplicitLocal n
else
throwError "unknown identifier '{Lean.mkConst n}'"
mkConsts candidates explicitLevels
/--
Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`.
Example: Assume resolveName `v.head.bla.boo` produces `(v.head, ["bla", "boo"])`, then this method produces
`(v.head, id, [f₁, f₂])` where `id` is an identifier for `v.head`, and `f₁` and `f₂` are identifiers for fields `"bla"` and `"boo"`. -/
def resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × Syntax × List Syntax)) := do
match ident with
| .ident _ _ n preresolved =>
let r ← resolveName ident n preresolved explicitLevels expectedType?
r.mapM fun (c, fields) => do
let ids := ident.identComponents (nFields? := fields.length)
return (c, ids.head!, ids.tail!)
| _ => throwError "identifier expected"
def resolveId? (stx : Syntax) (kind := "term") (withInfo := false) : TermElabM (Option Expr) :=
match stx with
| .ident _ _ val preresolved => do
let rs ← try resolveName stx val preresolved [] catch _ => pure []
let rs := rs.filter fun ⟨_, projs⟩ => projs.isEmpty
let fs := rs.map fun (f, _) => f
match fs with
| [] => return none
| [f] =>
let f ← if withInfo then addTermInfo stx f else pure f
return some f
| _ => throwError "ambiguous {kind}, use fully qualified name, possible interpretations {fs}"
| _ => throwError "identifier expected"
def TermElabM.run (x : TermElabM α) (ctx : Context := {}) (s : State := {}) : MetaM (α × State) :=
withConfig setElabConfig (x ctx |>.run s)
@[inline] def TermElabM.run' (x : TermElabM α) (ctx : Context := {}) (s : State := {}) : MetaM α :=
(·.1) <$> x.run ctx s
def TermElabM.toIO (x : TermElabM α)
(ctxCore : Core.Context) (sCore : Core.State)
(ctxMeta : Meta.Context) (sMeta : Meta.State)
(ctx : Context) (s : State) : IO (α × Core.State × Meta.State × State) := do
let ((a, s), sCore, sMeta) ← (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta
return (a, sCore, sMeta, s)
instance [MetaEval α] : MetaEval (TermElabM α) where
eval env opts x _ := do
let x : TermElabM α := do
try x finally
(← Core.getMessageLog).forM fun msg => do IO.println (← msg.toString)
MetaEval.eval env opts (hideUnit := true) <| x.run' {}
/--
Execute `x` and then tries to solve pending universe constraints.
Note that, stuck constraints will not be discarded.
-/
def universeConstraintsCheckpoint (x : TermElabM α) : TermElabM α := do
let a ← x
discard <| processPostponed (mayPostpone := true) (exceptionOnFailure := true)
return a
def expandDeclId (currNamespace : Name) (currLevelNames : List Name) (declId : Syntax) (modifiers : Modifiers) : TermElabM ExpandDeclIdResult := do
let r ← Elab.expandDeclId currNamespace currLevelNames declId modifiers
if (← read).sectionVars.contains r.shortName then
throwError "invalid declaration name '{r.shortName}', there is a section variable with the same name"
return r
/--
Helper function for "embedding" an `Expr` in `Syntax`.
It creates a named hole `?m` and immediately assigns `e` to it.
Examples:
```lean
let e := mkConst ``Nat.zero
`(Nat.succ $(← exprToSyntax e))
```
-/
def exprToSyntax (e : Expr) : TermElabM Term := withFreshMacroScope do
let result ← `(?m)
let eType ← inferType e
let mvar ← elabTerm result eType
mvar.mvarId!.assign e
return result
end Term
open Term in
def withoutModifyingStateWithInfoAndMessages [MonadControlT TermElabM m] [Monad m] (x : m α) : m α := do
controlAt TermElabM fun runInBase => withoutModifyingStateWithInfoAndMessagesImpl <| runInBase x
builtin_initialize
registerTraceClass `Elab.postpone
registerTraceClass `Elab.coe
registerTraceClass `Elab.debug
export Term (TermElabM)
end Lean.Elab
|
193de2f4104da2d2d48856a19bf5c8d4e20b8f0c | 8e381650eb2c1c5361be64ff97e47d956bf2ab9f | /src/sheaves/presheaf_maps.lean | 44a39f13bae109872f1dd5d97f9c6c0ab5fc5b9f | [] | no_license | alreadydone/lean-scheme | 04c51ab08eca7ccf6c21344d45d202780fa667af | 52d7624f57415eea27ed4dfa916cd94189221a1c | refs/heads/master | 1,599,418,221,423 | 1,562,248,559,000 | 1,562,248,559,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,145 | lean | /-
Continuous maps and presheaves.
https://stacks.math.columbia.edu/tag/008C
-/
import to_mathlib.opens
import sheaves.presheaf
universes u v w
open topological_space
variables {α : Type u} [topological_space α]
variables {β : Type v} [topological_space β]
variables {f : α → β} (Hf : continuous f)
-- f induces a functor PSh(α) ⟶ PSh(β).
namespace presheaf
section pushforward
def pushforward (F : presheaf α) : presheaf β :=
{ F := λ U, F (opens.comap Hf U),
res := λ U V HVU, F.res (opens.comap Hf U) (opens.comap Hf V) (opens.comap_mono Hf V U HVU),
Hid := λ U, F.Hid (opens.comap Hf U),
Hcomp := λ U V W HWV HVU,
F.Hcomp (opens.comap Hf U) (opens.comap Hf V) (opens.comap Hf W)
(opens.comap_mono Hf W V HWV) (opens.comap_mono Hf V U HVU), }
def pushforward.morphism (F G : presheaf α) (φ : F ⟶ G)
: pushforward Hf F ⟶ pushforward Hf G :=
{ map := λ U, φ.map (opens.comap Hf U),
commutes := λ U V HVU,
φ.commutes (opens.comap Hf U) (opens.comap Hf V) (opens.comap_mono Hf V U HVU), }
end pushforward
-- f induces a functor PSh(β) ⟶ PSh(α). Simplified to the case when f is 'nice'.
section pullback
variable (Hf' : ∀ (U : opens α), is_open (f '' U))
def pullback (F : presheaf β) : presheaf α :=
{ F := λ U, F (opens.map Hf' U),
res := λ U V HVU, F.res (opens.map Hf' U) (opens.map Hf' V) (opens.map_mono Hf' V U HVU),
Hid := λ U, F.Hid (opens.map Hf' U),
Hcomp := λ U V W HWV HVU,
F.Hcomp (opens.map Hf' U) (opens.map Hf' V) (opens.map Hf' W)
(opens.map_mono Hf' W V HWV) (opens.map_mono Hf' V U HVU), }
def pullback.morphism (F G : presheaf β) (φ : F ⟶ G) : pullback Hf' F ⟶ pullback Hf' G :=
{ map := λ U, φ.map (opens.map Hf' U),
commutes := λ U V HVU,
φ.commutes (opens.map Hf' U) (opens.map Hf' V) (opens.map_mono Hf' V U HVU), }
end pullback
-- f induces a `map` from a presheaf on β to a presheaf on α.
structure fmap (F : presheaf α) (G : presheaf β) :=
(map : ∀ (U), G U → F (opens.comap Hf U))
(commutes : ∀ (U V) (HVU : V ⊆ U),
(map V) ∘ (G.res U V HVU)
= (F.res (opens.comap Hf U) (opens.comap Hf V) (opens.comap_mono Hf V U HVU)) ∘ (map U))
namespace fmap
variables {γ : Type w} [topological_space γ]
variables {g : β → γ} {Hg : continuous g}
variable {Hf}
def comp {F : presheaf α} {G : presheaf β} {H : presheaf γ}
(f_ : fmap Hf F G) (g_ : fmap Hg G H) : fmap (continuous.comp Hf Hg) F H :=
{ map := λ U, (f_.map (opens.comap Hg U)) ∘ (g_.map U),
commutes :=
begin
intros U V HVU,
rw function.comp.assoc _ _ (H.res _ _ _),
rw g_.commutes,
rw ←function.comp.assoc _ _ (g_.map _),
rw f_.commutes,
refl,
end, }
def id (F : presheaf α) : fmap continuous_id F F :=
{ map := λ U,
begin
have HUU : opens.comap continuous_id U ⊆ U,
intros x Hx,
dsimp [opens.comap] at Hx,
exact Hx,
exact (F.res U (opens.comap continuous_id U) HUU),
end,
commutes :=
begin
intros U V HUV,
iterate 2 { rw ←F.Hcomp, },
end, }
end fmap
end presheaf
|
b223b1d5a353fb2fa3f8f2f885d57a17b64478a0 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/direct_sum/ring.lean | b8c27d87566bc0f6e4eb5d951a55d25d5c7851a8 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 22,807 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import group_theory.subgroup.basic
import algebra.graded_monoid
import algebra.direct_sum.basic
import algebra.big_operators.pi
/-!
# Additively-graded multiplicative structures on `⨁ i, A i`
This module provides a set of heterogeneous typeclasses for defining a multiplicative structure
over `⨁ i, A i` such that `(*) : A i → A j → A (i + j)`; that is to say, `A` forms an
additively-graded ring. The typeclasses are:
* `direct_sum.gnon_unital_non_assoc_semiring A`
* `direct_sum.gsemiring A`
* `direct_sum.gring A`
* `direct_sum.gcomm_semiring A`
* `direct_sum.gcomm_ring A`
Respectively, these imbue the external direct sum `⨁ i, A i` with:
* `direct_sum.non_unital_non_assoc_semiring`, `direct_sum.non_unital_non_assoc_ring`
* `direct_sum.semiring`
* `direct_sum.ring`
* `direct_sum.comm_semiring`
* `direct_sum.comm_ring`
the base ring `A 0` with:
* `direct_sum.grade_zero.non_unital_non_assoc_semiring`,
`direct_sum.grade_zero.non_unital_non_assoc_ring`
* `direct_sum.grade_zero.semiring`
* `direct_sum.grade_zero.ring`
* `direct_sum.grade_zero.comm_semiring`
* `direct_sum.grade_zero.comm_ring`
and the `i`th grade `A i` with `A 0`-actions (`•`) defined as left-multiplication:
* `direct_sum.grade_zero.has_smul (A 0)`, `direct_sum.grade_zero.smul_with_zero (A 0)`
* `direct_sum.grade_zero.module (A 0)`
* (nothing)
* (nothing)
* (nothing)
Note that in the presence of these instances, `⨁ i, A i` itself inherits an `A 0`-action.
`direct_sum.of_zero_ring_hom : A 0 →+* ⨁ i, A i` provides `direct_sum.of A 0` as a ring
homomorphism.
`direct_sum.to_semiring` extends `direct_sum.to_add_monoid` to produce a `ring_hom`.
## Direct sums of subobjects
Additionally, this module provides helper functions to construct `gsemiring` and `gcomm_semiring`
instances for:
* `A : ι → submonoid S`:
`direct_sum.gsemiring.of_add_submonoids`, `direct_sum.gcomm_semiring.of_add_submonoids`.
* `A : ι → subgroup S`:
`direct_sum.gsemiring.of_add_subgroups`, `direct_sum.gcomm_semiring.of_add_subgroups`.
* `A : ι → submodule S`:
`direct_sum.gsemiring.of_submodules`, `direct_sum.gcomm_semiring.of_submodules`.
If `complete_lattice.independent (set.range A)`, these provide a gradation of `⨆ i, A i`, and the
mapping `⨁ i, A i →+ ⨆ i, A i` can be obtained as
`direct_sum.to_monoid (λ i, add_submonoid.inclusion $ le_supr A i)`.
## tags
graded ring, filtered ring, direct sum, add_submonoid
-/
set_option old_structure_cmd true
variables {ι : Type*} [decidable_eq ι]
namespace direct_sum
open_locale direct_sum
/-! ### Typeclasses -/
section defs
variables (A : ι → Type*)
/-- A graded version of `non_unital_non_assoc_semiring`. -/
class gnon_unital_non_assoc_semiring [has_add ι] [Π i, add_comm_monoid (A i)] extends
graded_monoid.ghas_mul A :=
(mul_zero : ∀ {i j} (a : A i), mul a (0 : A j) = 0)
(zero_mul : ∀ {i j} (b : A j), mul (0 : A i) b = 0)
(mul_add : ∀ {i j} (a : A i) (b c : A j), mul a (b + c) = mul a b + mul a c)
(add_mul : ∀ {i j} (a b : A i) (c : A j), mul (a + b) c = mul a c + mul b c)
end defs
section defs
variables (A : ι → Type*)
/-- A graded version of `semiring`. -/
class gsemiring [add_monoid ι] [Π i, add_comm_monoid (A i)] extends
gnon_unital_non_assoc_semiring A, graded_monoid.gmonoid A :=
(nat_cast : ℕ → A 0)
(nat_cast_zero : nat_cast 0 = 0)
(nat_cast_succ : ∀ n : ℕ, nat_cast (n + 1) = nat_cast n + graded_monoid.ghas_one.one)
/-- A graded version of `comm_semiring`. -/
class gcomm_semiring [add_comm_monoid ι] [Π i, add_comm_monoid (A i)] extends
gsemiring A, graded_monoid.gcomm_monoid A
/-- A graded version of `ring`. -/
class gring [add_monoid ι] [Π i, add_comm_group (A i)] extends gsemiring A :=
(int_cast : ℤ → A 0)
(int_cast_of_nat : ∀ n : ℕ, int_cast n = nat_cast n)
(int_cast_neg_succ_of_nat : ∀ n : ℕ, int_cast (-(n+1 : ℕ)) = -nat_cast (n+1 : ℕ))
/-- A graded version of `comm_ring`. -/
class gcomm_ring [add_comm_monoid ι] [Π i, add_comm_group (A i)] extends
gring A, gcomm_semiring A
end defs
lemma of_eq_of_graded_monoid_eq {A : ι → Type*} [Π (i : ι), add_comm_monoid (A i)]
{i j : ι} {a : A i} {b : A j} (h : graded_monoid.mk i a = graded_monoid.mk j b) :
direct_sum.of A i a = direct_sum.of A j b :=
dfinsupp.single_eq_of_sigma_eq h
variables (A : ι → Type*)
/-! ### Instances for `⨁ i, A i` -/
section one
variables [has_zero ι] [graded_monoid.ghas_one A] [Π i, add_comm_monoid (A i)]
instance : has_one (⨁ i, A i) :=
{ one := direct_sum.of (λ i, A i) 0 graded_monoid.ghas_one.one }
end one
section mul
variables [has_add ι] [Π i, add_comm_monoid (A i)] [gnon_unital_non_assoc_semiring A]
open add_monoid_hom (flip_apply coe_comp comp_hom_apply_apply)
/-- The piecewise multiplication from the `has_mul` instance, as a bundled homomorphism. -/
@[simps]
def gmul_hom {i j} : A i →+ A j →+ A (i + j) :=
{ to_fun := λ a,
{ to_fun := λ b, graded_monoid.ghas_mul.mul a b,
map_zero' := gnon_unital_non_assoc_semiring.mul_zero _,
map_add' := gnon_unital_non_assoc_semiring.mul_add _ },
map_zero' := add_monoid_hom.ext $ λ a, gnon_unital_non_assoc_semiring.zero_mul a,
map_add' := λ a₁ a₂, add_monoid_hom.ext $ λ b, gnon_unital_non_assoc_semiring.add_mul _ _ _}
/-- The multiplication from the `has_mul` instance, as a bundled homomorphism. -/
def mul_hom : (⨁ i, A i) →+ (⨁ i, A i) →+ ⨁ i, A i :=
direct_sum.to_add_monoid $ λ i,
add_monoid_hom.flip $ direct_sum.to_add_monoid $ λ j, add_monoid_hom.flip $
(direct_sum.of A _).comp_hom.comp $ gmul_hom A
instance : non_unital_non_assoc_semiring (⨁ i, A i) :=
{ mul := λ a b, mul_hom A a b,
zero := 0,
add := (+),
zero_mul := λ a, by simp only [add_monoid_hom.map_zero, add_monoid_hom.zero_apply],
mul_zero := λ a, by simp only [add_monoid_hom.map_zero],
left_distrib := λ a b c, by simp only [add_monoid_hom.map_add],
right_distrib := λ a b c, by simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply],
.. direct_sum.add_comm_monoid _ _}
variables {A}
lemma mul_hom_of_of {i j} (a : A i) (b : A j) :
mul_hom A (of _ i a) (of _ j b) = of _ (i + j) (graded_monoid.ghas_mul.mul a b) :=
begin
unfold mul_hom,
rw [to_add_monoid_of, flip_apply, to_add_monoid_of, flip_apply, coe_comp, function.comp_app,
comp_hom_apply_apply, coe_comp, function.comp_app, gmul_hom_apply_apply],
end
lemma of_mul_of {i j} (a : A i) (b : A j) :
of _ i a * of _ j b = of _ (i + j) (graded_monoid.ghas_mul.mul a b) :=
mul_hom_of_of a b
end mul
section semiring
variables [Π i, add_comm_monoid (A i)] [add_monoid ι] [gsemiring A]
open add_monoid_hom (flip_hom coe_comp comp_hom_apply_apply flip_apply flip_hom_apply)
private lemma one_mul (x : ⨁ i, A i) : 1 * x = x :=
suffices mul_hom A 1 = add_monoid_hom.id (⨁ i, A i),
from add_monoid_hom.congr_fun this x,
begin
apply add_hom_ext, intros i xi,
unfold has_one.one,
rw mul_hom_of_of,
exact of_eq_of_graded_monoid_eq (one_mul $ graded_monoid.mk i xi),
end
private lemma mul_one (x : ⨁ i, A i) : x * 1 = x :=
suffices (mul_hom A).flip 1 = add_monoid_hom.id (⨁ i, A i),
from add_monoid_hom.congr_fun this x,
begin
apply add_hom_ext, intros i xi,
unfold has_one.one,
rw [flip_apply, mul_hom_of_of],
exact of_eq_of_graded_monoid_eq (mul_one $ graded_monoid.mk i xi),
end
private lemma mul_assoc (a b c : ⨁ i, A i) : a * b * c = a * (b * c) :=
suffices (mul_hom A).comp_hom.comp (mul_hom A) -- `λ a b c, a * b * c` as a bundled hom
= (add_monoid_hom.comp_hom flip_hom $ -- `λ a b c, a * (b * c)` as a bundled hom
(mul_hom A).flip.comp_hom.comp (mul_hom A)).flip,
from add_monoid_hom.congr_fun (add_monoid_hom.congr_fun (add_monoid_hom.congr_fun this a) b) c,
begin
ext ai ax bi bx ci cx : 6,
dsimp only [coe_comp, function.comp_app, comp_hom_apply_apply, flip_apply, flip_hom_apply],
rw [mul_hom_of_of, mul_hom_of_of, mul_hom_of_of, mul_hom_of_of],
exact of_eq_of_graded_monoid_eq (mul_assoc (graded_monoid.mk ai ax) ⟨bi, bx⟩ ⟨ci, cx⟩),
end
/-- The `semiring` structure derived from `gsemiring A`. -/
instance semiring : semiring (⨁ i, A i) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
one_mul := one_mul A,
mul_one := mul_one A,
mul_assoc := mul_assoc A,
nat_cast := λ n, of _ _ (gsemiring.nat_cast n),
nat_cast_zero := by rw [gsemiring.nat_cast_zero, map_zero],
nat_cast_succ := λ n, by { rw [gsemiring.nat_cast_succ, map_add], refl },
..direct_sum.non_unital_non_assoc_semiring _, }
lemma of_pow {i} (a : A i) (n : ℕ) :
of _ i a ^ n = of _ (n • i) (graded_monoid.gmonoid.gnpow _ a) :=
begin
induction n with n,
{ exact of_eq_of_graded_monoid_eq (pow_zero $ graded_monoid.mk _ a).symm, },
{ rw [pow_succ, n_ih, of_mul_of],
exact of_eq_of_graded_monoid_eq (pow_succ (graded_monoid.mk _ a) n).symm, },
end
lemma of_list_dprod {α} (l : list α) (fι : α → ι) (fA : Π a, A (fι a)) :
of A _ (l.dprod fι fA) = (l.map $ λ a, of A (fι a) (fA a)).prod :=
begin
induction l,
{ simp only [list.map_nil, list.prod_nil, list.dprod_nil],
refl },
{ simp only [list.map_cons, list.prod_cons, list.dprod_cons, ←l_ih, direct_sum.of_mul_of],
refl },
end
lemma list_prod_of_fn_of_eq_dprod (n : ℕ) (fι : fin n → ι) (fA : Π a, A (fι a)) :
(list.of_fn $ λ a, of A (fι a) (fA a)).prod = of A _ ((list.fin_range n).dprod fι fA) :=
by rw [list.of_fn_eq_map, of_list_dprod]
open_locale big_operators
/-- A heavily unfolded version of the definition of multiplication -/
lemma mul_eq_sum_support_ghas_mul
[Π (i : ι) (x : A i), decidable (x ≠ 0)] (a a' : ⨁ i, A i) :
a * a' =
∑ ij in dfinsupp.support a ×ˢ dfinsupp.support a',
direct_sum.of _ _ (graded_monoid.ghas_mul.mul (a ij.fst) (a' ij.snd)) :=
begin
change direct_sum.mul_hom _ a a' = _,
dsimp [direct_sum.mul_hom, direct_sum.to_add_monoid, dfinsupp.lift_add_hom_apply],
simp only [dfinsupp.sum_add_hom_apply, dfinsupp.sum, dfinsupp.finset_sum_apply,
add_monoid_hom.coe_finset_sum, finset.sum_apply, add_monoid_hom.flip_apply,
add_monoid_hom.comp_hom_apply_apply, add_monoid_hom.comp_apply,
direct_sum.gmul_hom_apply_apply],
rw finset.sum_product,
end
end semiring
section comm_semiring
variables [Π i, add_comm_monoid (A i)] [add_comm_monoid ι] [gcomm_semiring A]
private lemma mul_comm (a b : ⨁ i, A i) : a * b = b * a :=
suffices mul_hom A = (mul_hom A).flip,
from add_monoid_hom.congr_fun (add_monoid_hom.congr_fun this a) b,
begin
apply add_hom_ext, intros ai ax, apply add_hom_ext, intros bi bx,
rw [add_monoid_hom.flip_apply, mul_hom_of_of, mul_hom_of_of],
exact of_eq_of_graded_monoid_eq (gcomm_semiring.mul_comm ⟨ai, ax⟩ ⟨bi, bx⟩),
end
/-- The `comm_semiring` structure derived from `gcomm_semiring A`. -/
instance comm_semiring : comm_semiring (⨁ i, A i) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
mul_comm := mul_comm A,
..direct_sum.semiring _, }
end comm_semiring
section non_unital_non_assoc_ring
variables [Π i, add_comm_group (A i)] [has_add ι] [gnon_unital_non_assoc_semiring A]
/-- The `ring` derived from `gsemiring A`. -/
instance non_assoc_ring : non_unital_non_assoc_ring (⨁ i, A i) :=
{ mul := (*),
zero := 0,
add := (+),
neg := has_neg.neg,
..(direct_sum.non_unital_non_assoc_semiring _),
..(direct_sum.add_comm_group _), }
end non_unital_non_assoc_ring
section ring
variables [Π i, add_comm_group (A i)] [add_monoid ι] [gring A]
/-- The `ring` derived from `gsemiring A`. -/
instance ring : ring (⨁ i, A i) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
neg := has_neg.neg,
int_cast := λ z, of _ _ (gring.int_cast z),
int_cast_of_nat := λ z, congr_arg _ $ gring.int_cast_of_nat _,
int_cast_neg_succ_of_nat := λ z,
(congr_arg _ $ gring.int_cast_neg_succ_of_nat _).trans (map_neg _ _),
..(direct_sum.semiring _),
..(direct_sum.add_comm_group _), }
end ring
section comm_ring
variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gcomm_ring A]
/-- The `comm_ring` derived from `gcomm_semiring A`. -/
instance comm_ring : comm_ring (⨁ i, A i) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
neg := has_neg.neg,
..(direct_sum.ring _),
..(direct_sum.comm_semiring _), }
end comm_ring
/-! ### Instances for `A 0`
The various `g*` instances are enough to promote the `add_comm_monoid (A 0)` structure to various
types of multiplicative structure.
-/
section grade_zero
section one
variables [has_zero ι] [graded_monoid.ghas_one A] [Π i, add_comm_monoid (A i)]
@[simp] lemma of_zero_one : of _ 0 (1 : A 0) = 1 := rfl
end one
section mul
variables [add_zero_class ι] [Π i, add_comm_monoid (A i)] [gnon_unital_non_assoc_semiring A]
@[simp] lemma of_zero_smul {i} (a : A 0) (b : A i) : of _ _ (a • b) = of _ _ a * of _ _ b :=
(of_eq_of_graded_monoid_eq (graded_monoid.mk_zero_smul a b)).trans (of_mul_of _ _).symm
@[simp] lemma of_zero_mul (a b : A 0) : of _ 0 (a * b) = of _ 0 a * of _ 0 b:=
of_zero_smul A a b
instance grade_zero.non_unital_non_assoc_semiring : non_unital_non_assoc_semiring (A 0) :=
function.injective.non_unital_non_assoc_semiring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of A 0).map_add (of_zero_mul A) (λ x n, dfinsupp.single_smul n x)
instance grade_zero.smul_with_zero (i : ι) : smul_with_zero (A 0) (A i) :=
begin
letI := smul_with_zero.comp_hom (⨁ i, A i) (of A 0).to_zero_hom,
refine dfinsupp.single_injective.smul_with_zero (of A i).to_zero_hom (of_zero_smul A),
end
end mul
section semiring
variables [Π i, add_comm_monoid (A i)] [add_monoid ι] [gsemiring A]
@[simp] lemma of_zero_pow (a : A 0) : ∀ n : ℕ, of _ 0 (a ^ n) = of _ 0 a ^ n
| 0 := by rw [pow_zero, pow_zero, direct_sum.of_zero_one]
| (n + 1) := by rw [pow_succ, pow_succ, of_zero_mul, of_zero_pow]
instance : has_nat_cast (A 0) := ⟨gsemiring.nat_cast⟩
@[simp] lemma of_nat_cast (n : ℕ) : of A 0 n = n :=
rfl
/-- The `semiring` structure derived from `gsemiring A`. -/
instance grade_zero.semiring : semiring (A 0) :=
function.injective.semiring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A)
(of A 0).map_nsmul (λ x n, of_zero_pow _ _ _) (of_nat_cast A)
/-- `of A 0` is a `ring_hom`, using the `direct_sum.grade_zero.semiring` structure. -/
def of_zero_ring_hom : A 0 →+* (⨁ i, A i) :=
{ map_one' := of_zero_one A, map_mul' := of_zero_mul A, ..(of _ 0) }
/-- Each grade `A i` derives a `A 0`-module structure from `gsemiring A`. Note that this results
in an overall `module (A 0) (⨁ i, A i)` structure via `direct_sum.module`.
-/
instance grade_zero.module {i} : module (A 0) (A i) :=
begin
letI := module.comp_hom (⨁ i, A i) (of_zero_ring_hom A),
exact dfinsupp.single_injective.module (A 0) (of A i) (λ a, of_zero_smul A a),
end
end semiring
section comm_semiring
variables [Π i, add_comm_monoid (A i)] [add_comm_monoid ι] [gcomm_semiring A]
/-- The `comm_semiring` structure derived from `gcomm_semiring A`. -/
instance grade_zero.comm_semiring : comm_semiring (A 0) :=
function.injective.comm_semiring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A)
(λ x n, dfinsupp.single_smul n x) (λ x n, of_zero_pow _ _ _) (of_nat_cast A)
end comm_semiring
section ring
variables [Π i, add_comm_group (A i)] [add_zero_class ι] [gnon_unital_non_assoc_semiring A]
/-- The `non_unital_non_assoc_ring` derived from `gnon_unital_non_assoc_semiring A`. -/
instance grade_zero.non_unital_non_assoc_ring : non_unital_non_assoc_ring (A 0) :=
function.injective.non_unital_non_assoc_ring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of A 0).map_add (of_zero_mul A)
(of A 0).map_neg (of A 0).map_sub
(λ x n, begin
letI : Π i, distrib_mul_action ℕ (A i) := λ i, infer_instance,
exact dfinsupp.single_smul n x
end)
(λ x n, begin
letI : Π i, distrib_mul_action ℤ (A i) := λ i, infer_instance,
exact dfinsupp.single_smul n x
end)
end ring
section ring
variables [Π i, add_comm_group (A i)] [add_monoid ι] [gring A]
instance : has_int_cast (A 0) := ⟨gring.int_cast⟩
@[simp] lemma of_int_cast (n : ℤ) : of A 0 n = n :=
rfl
/-- The `ring` derived from `gsemiring A`. -/
instance grade_zero.ring : ring (A 0) :=
function.injective.ring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A)
(of A 0).map_neg (of A 0).map_sub
(λ x n, begin
letI : Π i, distrib_mul_action ℕ (A i) := λ i, infer_instance,
exact dfinsupp.single_smul n x
end)
(λ x n, begin
letI : Π i, distrib_mul_action ℤ (A i) := λ i, infer_instance,
exact dfinsupp.single_smul n x
end) (λ x n, of_zero_pow _ _ _)
(of_nat_cast A) (of_int_cast A)
end ring
section comm_ring
variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gcomm_ring A]
/-- The `comm_ring` derived from `gcomm_semiring A`. -/
instance grade_zero.comm_ring : comm_ring (A 0) :=
function.injective.comm_ring (of A 0) dfinsupp.single_injective
(of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A)
(of A 0).map_neg (of A 0).map_sub
(λ x n, begin
letI : Π i, distrib_mul_action ℕ (A i) := λ i, infer_instance,
exact dfinsupp.single_smul n x
end)
(λ x n, begin
letI : Π i, distrib_mul_action ℤ (A i) := λ i, infer_instance,
exact dfinsupp.single_smul n x
end) (λ x n, of_zero_pow _ _ _)
(of_nat_cast A) (of_int_cast A)
end comm_ring
end grade_zero
section to_semiring
variables {R : Type*} [Π i, add_comm_monoid (A i)] [add_monoid ι] [gsemiring A] [semiring R]
variables {A}
/-- If two ring homomorphisms from `⨁ i, A i` are equal on each `of A i y`,
then they are equal.
See note [partially-applied ext lemmas]. -/
@[ext]
lemma ring_hom_ext' ⦃F G : (⨁ i, A i) →+* R⦄
(h : ∀ i, (↑F : _ →+ R).comp (of A i) = (↑G : _ →+ R).comp (of A i)) : F = G :=
ring_hom.coe_add_monoid_hom_injective $ direct_sum.add_hom_ext' h
/-- Two `ring_hom`s out of a direct sum are equal if they agree on the generators. -/
lemma ring_hom_ext ⦃f g : (⨁ i, A i) →+* R⦄ (h : ∀ i x, f (of A i x) = g (of A i x)) :
f = g :=
ring_hom_ext' $ λ i, add_monoid_hom.ext $ h i
/-- A family of `add_monoid_hom`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul`
describes a `ring_hom`s on `⨁ i, A i`. This is a stronger version of `direct_sum.to_monoid`.
Of particular interest is the case when `A i` are bundled subojects, `f` is the family of
coercions such as `add_submonoid.subtype (A i)`, and the `[gsemiring A]` structure originates from
`direct_sum.gsemiring.of_add_submonoids`, in which case the proofs about `ghas_one` and `ghas_mul`
can be discharged by `rfl`. -/
@[simps]
def to_semiring
(f : Π i, A i →+ R) (hone : f _ (graded_monoid.ghas_one.one) = 1)
(hmul : ∀ {i j} (ai : A i) (aj : A j), f _ (graded_monoid.ghas_mul.mul ai aj) = f _ ai * f _ aj) :
(⨁ i, A i) →+* R :=
{ to_fun := to_add_monoid f,
map_one' := begin
change (to_add_monoid f) (of _ 0 _) = 1,
rw to_add_monoid_of,
exact hone
end,
map_mul' := begin
rw (to_add_monoid f).map_mul_iff,
ext xi xv yi yv : 4,
show to_add_monoid f (of A xi xv * of A yi yv) =
to_add_monoid f (of A xi xv) * to_add_monoid f (of A yi yv),
rw [of_mul_of, to_add_monoid_of, to_add_monoid_of, to_add_monoid_of],
exact hmul _ _,
end,
.. to_add_monoid f}
@[simp] lemma to_semiring_of (f : Π i, A i →+ R) (hone hmul) (i : ι) (x : A i) :
to_semiring f hone hmul (of _ i x) = f _ x :=
to_add_monoid_of f i x
@[simp] lemma to_semiring_coe_add_monoid_hom (f : Π i, A i →+ R) (hone hmul):
(to_semiring f hone hmul : (⨁ i, A i) →+ R) = to_add_monoid f := rfl
/-- Families of `add_monoid_hom`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul`
are isomorphic to `ring_hom`s on `⨁ i, A i`. This is a stronger version of `dfinsupp.lift_add_hom`.
-/
@[simps]
def lift_ring_hom :
{f : Π {i}, A i →+ R //
f (graded_monoid.ghas_one.one) = 1 ∧
∀ {i j} (ai : A i) (aj : A j), f (graded_monoid.ghas_mul.mul ai aj) = f ai * f aj} ≃
((⨁ i, A i) →+* R) :=
{ to_fun := λ f, to_semiring (λ _, f.1) f.2.1 (λ _ _, f.2.2),
inv_fun := λ F,
⟨λ i, (F : (⨁ i, A i) →+ R).comp (of _ i), begin
simp only [add_monoid_hom.comp_apply, ring_hom.coe_add_monoid_hom],
rw ←F.map_one,
refl
end, λ i j ai aj, begin
simp only [add_monoid_hom.comp_apply, ring_hom.coe_add_monoid_hom],
rw [←F.map_mul, of_mul_of],
end⟩,
left_inv := λ f, begin
ext xi xv,
exact to_add_monoid_of (λ _, f.1) xi xv,
end,
right_inv := λ F, begin
apply ring_hom.coe_add_monoid_hom_injective,
ext xi xv,
simp only [ring_hom.coe_add_monoid_hom_mk,
direct_sum.to_add_monoid_of,
add_monoid_hom.mk_coe,
add_monoid_hom.comp_apply, to_semiring_coe_add_monoid_hom],
end}
end to_semiring
end direct_sum
/-! ### Concrete instances -/
section uniform
variables (ι)
/-- A direct sum of copies of a `semiring` inherits the multiplication structure. -/
instance non_unital_non_assoc_semiring.direct_sum_gnon_unital_non_assoc_semiring
{R : Type*} [add_monoid ι] [non_unital_non_assoc_semiring R] :
direct_sum.gnon_unital_non_assoc_semiring (λ i : ι, R) :=
{ mul_zero := λ i j, mul_zero,
zero_mul := λ i j, zero_mul,
mul_add := λ i j, mul_add,
add_mul := λ i j, add_mul,
..has_mul.ghas_mul ι }
/-- A direct sum of copies of a `semiring` inherits the multiplication structure. -/
instance semiring.direct_sum_gsemiring {R : Type*} [add_monoid ι] [semiring R] :
direct_sum.gsemiring (λ i : ι, R) :=
{ nat_cast := λ n, n,
nat_cast_zero := nat.cast_zero,
nat_cast_succ := nat.cast_succ,
..non_unital_non_assoc_semiring.direct_sum_gnon_unital_non_assoc_semiring ι,
..monoid.gmonoid ι }
open_locale direct_sum
-- To check `has_mul.ghas_mul_mul` matches
example {R : Type*} [add_monoid ι] [semiring R] (i j : ι) (a b : R) :
(direct_sum.of _ i a * direct_sum.of _ j b : ⨁ i, R) = direct_sum.of _ (i + j) (by exact a * b) :=
by rw [direct_sum.of_mul_of, has_mul.ghas_mul_mul]
/-- A direct sum of copies of a `comm_semiring` inherits the commutative multiplication structure.
-/
instance comm_semiring.direct_sum_gcomm_semiring {R : Type*} [add_comm_monoid ι] [comm_semiring R] :
direct_sum.gcomm_semiring (λ i : ι, R) :=
{ ..comm_monoid.gcomm_monoid ι, ..semiring.direct_sum_gsemiring ι }
end uniform
|
aad7375a4cb42643f5cbfb5715082a00c4b1e33e | a523fc1740c8cb84cd0fa0f4b52a760da4e32a5c | /src/missing_mathlib/field_thoery/algebraic_closure.lean | 8e4ea88c39ce9f30190647398642aa860146c953 | [] | no_license | abentkamp/spectral | a1aff51e85d30b296a81d256ced1d382345d3396 | 751645679ef1cb6266316349de9e492eff85484c | refs/heads/master | 1,669,994,798,064 | 1,597,591,646,000 | 1,597,591,646,000 | 287,544,072 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 470 | lean | import field_theory.algebraic_closure
import missing_mathlib.field_thoery.splitting_field
universes u v w
noncomputable theory
open_locale classical big_operators
open polynomial
variables (k : Type u) [field k]
namespace is_alg_closed
variables [is_alg_closed k]
lemma degree_eq_one_of_irreducible {p : polynomial k} (h_nz : p ≠ 0) (hp : irreducible p) :
p.degree = 1 :=
degree_eq_one_of_irreducible_of_splits h_nz hp (polynomial.splits' _)
end is_alg_closed |
6a76b5002f96480360b82f26914eaea9ab70efaf | 842b7df4a999c5c50bbd215b8617dd705e43c2e1 | /nat_num_game/src/Advanced_Proposition_World.lean/adv_prop_wrld10.lean | 4018a55842a5a9ee2a1087ec0bc8484a14c1549a | [] | no_license | Samyak-Surti/LeanCode | 1c245631f74b00057d20483c8ac75916e8643b14 | 944eac3e5f43e2614ed246083b97fbdf24181d83 | refs/heads/master | 1,669,023,730,828 | 1,595,534,784,000 | 1,595,534,784,000 | 282,037,186 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 85 | lean | lemma contrapositive2 (P Q : Prop) : (¬ Q → ¬ P) → (P → Q) :=
begin
end
|
3b493fc8f5322a9a3ca30c6fa7966e7d319e49a4 | cc060cf567f81c404a13ee79bf21f2e720fa6db0 | /lean/two_function_coercions.lean | 96c21626c184a0e08a2d27198801a7b7a1b21309 | [
"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 | 400 | lean | structure foo (A B : Type) :=
(bar : A → Type)
(baz : B → Type)
instance FunctionA {A B : Type} : has_coe_to_fun (foo A B) :=
{ F := λ f, A → Type,
coe := foo.bar }
instance FunctionB {A B : Type} : has_coe_to_fun (foo A B) :=
{ F := λ f, B → Type,
coe := foo.baz }
def X : foo unit bool :=
{ bar := λ a, unit,
baz := λ a, bool }
eval (X ())
eval (X tt)
eval (X ff)
|
c97c0ddb58f6e9893244399ce4e3891d747daa55 | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /library/init/algebra/order.lean | 694451ecde959e74d1ee82998014c5be1f0db7c2 | [
"Apache-2.0"
] | permissive | pacchiano/lean | 9324b33f3ac3b5c5647285160f9f6ea8d0d767dc | fdadada3a970377a6df8afcd629a6f2eab6e84e8 | refs/heads/master | 1,611,357,380,399 | 1,489,870,101,000 | 1,489,870,101,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,763 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.logic
/- Make sure instances defined in this file have lower priority than the ones
defined for concrete structures -/
set_option default_priority 100
universe u
variables {α : Type u}
class weak_order (α : Type u) extends has_le α :=
(le_refl : ∀ a : α, a ≤ a)
(le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c)
(le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b)
class linear_weak_order (α : Type u) extends weak_order α :=
(le_total : ∀ a b : α, a ≤ b ∨ b ≤ a)
class strict_order (α : Type u) extends has_lt α :=
(lt_irrefl : ∀ a : α, ¬ a < a)
(lt_trans : ∀ a b c : α, a < b → b < c → a < c)
/- structures with a weak and a strict order -/
class order_pair (α : Type u) extends weak_order α, has_lt α :=
(le_of_lt : ∀ a b : α, a < b → a ≤ b)
(lt_of_lt_of_le : ∀ a b c : α, a < b → b ≤ c → a < c)
(lt_of_le_of_lt : ∀ a b c : α, a ≤ b → b < c → a < c)
(lt_irrefl : ∀ a : α, ¬ a < a)
class strong_order_pair (α : Type u) extends weak_order α, has_lt α :=
(le_iff_lt_or_eq : ∀ a b : α, a ≤ b ↔ a < b ∨ a = b)
(lt_irrefl : ∀ a : α, ¬ a < a)
class linear_order_pair (α : Type u) extends order_pair α, linear_weak_order α
class linear_strong_order_pair (α : Type u) extends strong_order_pair α, linear_weak_order α
@[refl] lemma le_refl [weak_order α] : ∀ a : α, a ≤ a :=
weak_order.le_refl
@[trans] lemma le_trans [weak_order α] : ∀ {a b c : α}, a ≤ b → b ≤ c → a ≤ c :=
weak_order.le_trans
lemma le_antisymm [weak_order α] : ∀ {a b : α}, a ≤ b → b ≤ a → a = b :=
weak_order.le_antisymm
lemma le_of_eq [weak_order α] {a b : α} : a = b → a ≤ b :=
λ h, h ▸ le_refl a
@[trans] lemma ge_trans [weak_order α] : ∀ {a b c : α}, a ≥ b → b ≥ c → a ≥ c :=
λ a b c h₁ h₂, le_trans h₂ h₁
lemma le_total [linear_weak_order α] : ∀ a b : α, a ≤ b ∨ b ≤ a :=
linear_weak_order.le_total
lemma le_of_not_ge [linear_weak_order α] {a b : α} : ¬ a ≥ b → a ≤ b :=
or.resolve_left (le_total b a)
lemma le_of_not_le [linear_weak_order α] {a b : α} : ¬ a ≤ b → b ≤ a :=
or.resolve_left (le_total a b)
lemma lt_irrefl [strict_order α] : ∀ a : α, ¬ a < a :=
strict_order.lt_irrefl
lemma gt_irrefl [strict_order α] : ∀ a : α, ¬ a > a :=
lt_irrefl
@[trans] lemma lt_trans [strict_order α] : ∀ {a b c : α}, a < b → b < c → a < c :=
strict_order.lt_trans
def lt.trans := @lt_trans
@[trans] lemma gt_trans [strict_order α] : ∀ {a b c : α}, a > b → b > c → a > c :=
λ a b c h₁ h₂, lt_trans h₂ h₁
def gt.trans := @gt_trans
lemma ne_of_lt [strict_order α] {a b : α} (h : a < b) : a ≠ b :=
λ he, absurd h (he ▸ lt_irrefl a)
lemma ne_of_gt [strict_order α] {a b : α} (h : a > b) : a ≠ b :=
λ he, absurd h (he ▸ lt_irrefl a)
lemma lt_asymm [strict_order α] {a b : α} (h : a < b) : ¬ b < a :=
λ h1 : b < a, lt_irrefl a (lt_trans h h1)
lemma not_lt_of_gt [strict_order α] {a b : α} (h : a > b) : ¬ a < b :=
lt_asymm h
lemma le_of_lt [order_pair α] : ∀ {a b : α}, a < b → a ≤ b :=
order_pair.le_of_lt
@[trans] lemma lt_of_lt_of_le [order_pair α] : ∀ {a b c : α}, a < b → b ≤ c → a < c :=
order_pair.lt_of_lt_of_le
@[trans] lemma lt_of_le_of_lt [order_pair α] : ∀ {a b c : α}, a ≤ b → b < c → a < c :=
order_pair.lt_of_le_of_lt
@[trans] lemma gt_of_gt_of_ge [order_pair α] {a b c : α} (h₁ : a > b) (h₂ : b ≥ c) : a > c :=
lt_of_le_of_lt h₂ h₁
@[trans] lemma gt_of_ge_of_gt [order_pair α] {a b c : α} (h₁ : a ≥ b) (h₂ : b > c) : a > c :=
lt_of_lt_of_le h₂ h₁
instance order_pair.to_strict_order [s : order_pair α] : strict_order α :=
{ s with
lt_irrefl := order_pair.lt_irrefl,
lt_trans := λ a b c h₁ h₂, lt_of_lt_of_le h₁ (le_of_lt h₂) }
lemma not_le_of_gt [order_pair α] {a b : α} (h : a > b) : ¬ a ≤ b :=
λ h₁, lt_irrefl b (lt_of_lt_of_le h h₁)
lemma not_lt_of_ge [order_pair α] {a b : α} (h : a ≥ b) : ¬ a < b :=
λ h₁, lt_irrefl b (lt_of_le_of_lt h h₁)
lemma le_iff_lt_or_eq [strong_order_pair α] : ∀ {a b : α}, a ≤ b ↔ a < b ∨ a = b :=
strong_order_pair.le_iff_lt_or_eq
lemma lt_or_eq_of_le [strong_order_pair α] : ∀ {a b : α}, a ≤ b → a < b ∨ a = b :=
λ a b h, iff.mp le_iff_lt_or_eq h
lemma le_of_lt_or_eq [strong_order_pair α] : ∀ {a b : α}, (a < b ∨ a = b) → a ≤ b :=
λ a b h, iff.mpr le_iff_lt_or_eq h
lemma lt_of_le_of_ne [strong_order_pair α] {a b : α} : a ≤ b → a ≠ b → a < b :=
λ h₁ h₂, or.resolve_right (lt_or_eq_of_le h₁) h₂
private lemma lt_irrefl' [strong_order_pair α] : ∀ a : α, ¬ a < a :=
strong_order_pair.lt_irrefl
private lemma le_of_lt' [strong_order_pair α] ⦃a b : α⦄ (h : a < b) : a ≤ b :=
le_of_lt_or_eq (or.inl h)
private lemma lt_of_lt_of_le' [strong_order_pair α] (a b c : α) (h₁ : a < b) (h₂ : b ≤ c) : a < c :=
have a ≤ c, from le_trans (le_of_lt' h₁) h₂,
or.elim (lt_or_eq_of_le this)
(λ h : a < c, h)
(λ h : a = c,
have b ≤ a, from h^.symm ▸ h₂,
have a = b, from le_antisymm (le_of_lt' h₁) this,
absurd h₁ (this ▸ lt_irrefl' a))
private lemma lt_of_le_of_lt' [strong_order_pair α] (a b c : α) (h₁ : a ≤ b) (h₂ : b < c) : a < c :=
have a ≤ c, from le_trans h₁ (le_of_lt' h₂),
or.elim (lt_or_eq_of_le this)
(λ h : a < c, h)
(λ h : a = c,
have c ≤ b, from h ▸ h₁,
have c = b, from le_antisymm this (le_of_lt' h₂),
absurd h₂ (this ▸ lt_irrefl' c))
instance strong_order_pair.to_order_pair [s : strong_order_pair α] : order_pair α :=
{ s with
lt_irrefl := lt_irrefl',
le_of_lt := le_of_lt',
lt_of_le_of_lt := lt_of_le_of_lt',
lt_of_lt_of_le := lt_of_lt_of_le'}
instance linear_strong_order_pair.to_linear_order_pair [s : linear_strong_order_pair α] : linear_order_pair α :=
{ s with
lt_irrefl := lt_irrefl',
le_of_lt := le_of_lt',
lt_of_le_of_lt := lt_of_le_of_lt',
lt_of_lt_of_le := lt_of_lt_of_le'}
lemma lt_trichotomy [linear_strong_order_pair α] (a b : α) : a < b ∨ a = b ∨ b < a :=
or.elim (le_total a b)
(λ h : a ≤ b, or.elim (lt_or_eq_of_le h)
(λ h : a < b, or.inl h)
(λ h : a = b, or.inr (or.inl h)))
(λ h : b ≤ a, or.elim (lt_or_eq_of_le h)
(λ h : b < a, or.inr (or.inr h))
(λ h : b = a, or.inr (or.inl h^.symm)))
lemma le_of_not_gt [linear_strong_order_pair α] {a b : α} (h : ¬ a > b) : a ≤ b :=
match lt_trichotomy a b with
| or.inl hlt := le_of_lt hlt
| or.inr (or.inl heq) := heq ▸ le_refl a
| or.inr (or.inr hgt) := absurd hgt h
end
lemma lt_of_not_ge [linear_strong_order_pair α] {a b : α} (h : ¬ a ≥ b) : a < b :=
match lt_trichotomy a b with
| or.inl hlt := hlt
| or.inr (or.inl heq) := absurd (heq ▸ le_refl a : a ≥ b) h
| or.inr (or.inr hgt) := absurd (le_of_lt hgt) h
end
lemma lt_or_ge [linear_strong_order_pair α] (a b : α) : a < b ∨ a ≥ b :=
match lt_trichotomy a b with
| or.inl hlt := or.inl hlt
| or.inr (or.inl heq) := or.inr (heq ▸ le_refl a)
| or.inr (or.inr hgt) := or.inr (le_of_lt hgt)
end
lemma le_or_gt [linear_strong_order_pair α] (a b : α) : a ≤ b ∨ a > b :=
or.swap (lt_or_ge b a)
lemma lt_or_gt_of_ne [linear_strong_order_pair α] {a b : α} (h : a ≠ b) : a < b ∨ a > b :=
match lt_trichotomy a b with
| or.inl hlt := or.inl hlt
| or.inr (or.inl heq) := absurd heq h
| or.inr (or.inr hgt) := or.inr hgt
end
lemma lt_iff_not_ge [linear_strong_order_pair α] (x y : α) : x < y ↔ ¬ x ≥ y :=
⟨not_le_of_gt, lt_of_not_ge⟩
/- The following lemma can be used when defining a decidable_linear_order instance, and the concrete structure
does not have its own definition for decidable le -/
def decidable_le_of_decidable_lt [linear_strong_order_pair α] [∀ a b : α, decidable (a < b)] (a b : α) : decidable (a ≤ b) :=
if h₁ : a < b then is_true (le_of_lt h₁)
else if h₂ : b < a then is_false (not_le_of_gt h₂)
else is_true (le_of_not_gt h₂)
/- The following lemma can be used when defining a decidable_linear_order instance, and the concrete structure
does not have its own definition for decidable le -/
def decidable_eq_of_decidable_lt [linear_strong_order_pair α] [∀ a b : α, decidable (a < b)] (a b : α) : decidable (a = b) :=
match decidable_le_of_decidable_lt a b with
| is_true h₁ :=
match decidable_le_of_decidable_lt b a with
| is_true h₂ := is_true (le_antisymm h₁ h₂)
| is_false h₂ := is_false (λ he : a = b, h₂ (he ▸ le_refl a))
end
| is_false h₁ := is_false (λ he : a = b, h₁ (he ▸ le_refl a))
end
class decidable_linear_order (α : Type u) extends linear_strong_order_pair α :=
(decidable_lt : decidable_rel lt)
(decidable_le : decidable_rel le) -- TODO(Leo): add default value using decidable_le_of_decidable_lt
(decidable_eq : decidable_eq α) -- TODO(Leo): add default value using decidable_eq_of_decidable_lt
instance [decidable_linear_order α] (a b : α) : decidable (a < b) :=
decidable_linear_order.decidable_lt α a b
instance [decidable_linear_order α] (a b : α) : decidable (a ≤ b) :=
decidable_linear_order.decidable_le α a b
instance [decidable_linear_order α] (a b : α) : decidable (a = b) :=
decidable_linear_order.decidable_eq α a b
lemma eq_or_lt_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ a < b) : a = b ∨ b < a :=
if h₁ : a = b then or.inl h₁
else or.inr (lt_of_not_ge (λ hge, h (lt_of_le_of_ne hge h₁)))
|
e2c068a921ba751cab48281631420b407a175275 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/algebra/pi_instances.lean | 9bd4f5caa53dfc2fb9344276708f073f7584c3e8 | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 19,255 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
Pi instances for algebraic structures.
-/
import order.basic
import algebra.module algebra.group
import data.finset
import ring_theory.subring
import tactic.pi_instances
namespace pi
universes u v w
variable {I : Type u} -- The indexing type
variable {f : I → Type v} -- The family of types already equiped with instances
variables (x y : Π i, f i) (i : I)
instance has_zero [∀ i, has_zero $ f i] : has_zero (Π i : I, f i) := ⟨λ i, 0⟩
@[simp] lemma zero_apply [∀ i, has_zero $ f i] : (0 : Π i, f i) i = 0 := rfl
instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ i, 1⟩
@[simp] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl
attribute [to_additive] pi.has_one
attribute [to_additive] pi.one_apply
instance has_add [∀ i, has_add $ f i] : has_add (Π i : I, f i) := ⟨λ x y, λ i, x i + y i⟩
@[simp] lemma add_apply [∀ i, has_add $ f i] : (x + y) i = x i + y i := rfl
instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ x y, λ i, x i * y i⟩
@[simp] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl
attribute [to_additive] pi.has_mul
attribute [to_additive] pi.mul_apply
instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ x, λ i, (x i)⁻¹⟩
@[simp] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl
instance has_neg [∀ i, has_neg $ f i] : has_neg (Π i : I, f i) := ⟨λ x, λ i, -(x i)⟩
@[simp] lemma neg_apply [∀ i, has_neg $ f i] : (-x) i = -x i := rfl
attribute [to_additive] pi.has_inv
attribute [to_additive] pi.inv_apply
instance has_scalar {α : Type*} [∀ i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩
@[simp] lemma smul_apply {α : Type*} [∀ i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl
instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by pi_instance
instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by pi_instance
instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by pi_instance
instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by pi_instance
instance group [∀ i, group $ f i] : group (Π i : I, f i) := by pi_instance
instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by pi_instance
instance add_semigroup [∀ i, add_semigroup $ f i] : add_semigroup (Π i : I, f i) := by pi_instance
instance add_comm_semigroup [∀ i, add_comm_semigroup $ f i] : add_comm_semigroup (Π i : I, f i) := by pi_instance
instance add_monoid [∀ i, add_monoid $ f i] : add_monoid (Π i : I, f i) := by pi_instance
instance add_comm_monoid [∀ i, add_comm_monoid $ f i] : add_comm_monoid (Π i : I, f i) := by pi_instance
instance add_group [∀ i, add_group $ f i] : add_group (Π i : I, f i) := by pi_instance
instance add_comm_group [∀ i, add_comm_group $ f i] : add_comm_group (Π i : I, f i) := by pi_instance
instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by pi_instance
instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by pi_instance
instance mul_action (α) {m : monoid α} [∀ i, mul_action α $ f i] : mul_action α (Π i : I, f i) :=
{ smul := λ c f i, c • f i,
mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,
one_smul := λ f, funext $ λ i, one_smul α _ }
instance distrib_mul_action (α) {m : monoid α} [∀ i, add_monoid $ f i] [∀ i, distrib_mul_action α $ f i] : distrib_mul_action α (Π i : I, f i) :=
{ smul_zero := λ c, funext $ λ i, smul_zero _,
smul_add := λ c f g, funext $ λ i, smul_add _ _ _,
..pi.mul_action _ }
variables (I f)
instance semimodule (α) {r : semiring α} [∀ i, add_comm_monoid $ f i] [∀ i, semimodule α $ f i] : semimodule α (Π i : I, f i) :=
{ add_smul := λ c f g, funext $ λ i, add_smul _ _ _,
zero_smul := λ f, funext $ λ i, zero_smul α _,
..pi.distrib_mul_action _ }
variables {I f}
instance module (α) {r : ring α} [∀ i, add_comm_group $ f i] [∀ i, module α $ f i] : module α (Π i : I, f i) := {..pi.semimodule I f α}
instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance add_left_cancel_semigroup [∀ i, add_left_cancel_semigroup $ f i] : add_left_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance add_right_cancel_semigroup [∀ i, add_right_cancel_semigroup $ f i] : add_right_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) :=
by pi_instance
instance ordered_comm_group [∀ i, ordered_comm_group $ f i] : ordered_comm_group (Π i : I, f i) :=
{ add_lt_add_left := λ a b hab c, ⟨λ i, add_le_add_left (hab.1 i) (c i),
λ h, hab.2 $ λ i, le_of_add_le_add_left (h i)⟩,
add_le_add_left := λ x y hxy c i, add_le_add_left (hxy i) _,
..pi.add_comm_group,
..pi.partial_order }
attribute [to_additive add_semigroup] pi.semigroup
attribute [to_additive add_comm_semigroup] pi.comm_semigroup
attribute [to_additive add_monoid] pi.monoid
attribute [to_additive add_comm_monoid] pi.comm_monoid
attribute [to_additive add_group] pi.group
attribute [to_additive add_comm_group] pi.comm_group
attribute [to_additive add_left_cancel_semigroup] pi.left_cancel_semigroup
attribute [to_additive add_right_cancel_semigroup] pi.right_cancel_semigroup
@[to_additive]
lemma list_prod_apply {α : Type*} {β : α → Type*} [∀a, monoid (β a)] (a : α) :
∀ (l : list (Πa, β a)), l.prod a = (l.map (λf:Πa, β a, f a)).prod
| [] := rfl
| (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l]
@[to_additive]
lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α)
(s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod :=
quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end
@[to_additive]
lemma finset_prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α)
(s : finset γ) (g : γ → Πa, β a) : s.prod g a = s.prod (λc, g c a) :=
show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod,
by rw [multiset_prod_apply, multiset.map_map]
instance is_ring_hom_pi
{α : Type u} {β : α → Type v} [R : Π a : α, ring (β a)]
{γ : Type w} [ring γ]
(f : Π a : α, γ → β a) [Rh : Π a : α, is_ring_hom (f a)] :
is_ring_hom (λ x b, f b x) :=
begin
split,
-- It's a pity that these can't be done using `simp` lemmas.
{ ext, rw [is_ring_hom.map_one (f x)], refl, },
{ intros x y, ext1 z, rw [is_ring_hom.map_mul (f z)], refl, },
{ intros x y, ext1 z, rw [is_ring_hom.map_add (f z)], refl, }
end
end pi
namespace prod
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β}
instance [has_add α] [has_add β] : has_add (α × β) :=
⟨λp q, (p.1 + q.1, p.2 + q.2)⟩
@[to_additive]
instance [has_mul α] [has_mul β] : has_mul (α × β) :=
⟨λp q, (p.1 * q.1, p.2 * q.2)⟩
@[simp, to_additive]
lemma fst_mul [has_mul α] [has_mul β] : (p * q).1 = p.1 * q.1 := rfl
@[simp, to_additive]
lemma snd_mul [has_mul α] [has_mul β] : (p * q).2 = p.2 * q.2 := rfl
@[simp, to_additive]
lemma mk_mul_mk [has_mul α] [has_mul β] (a₁ a₂ : α) (b₁ b₂ : β) :
(a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl
instance [has_zero α] [has_zero β] : has_zero (α × β) := ⟨(0, 0)⟩
@[to_additive]
instance [has_one α] [has_one β] : has_one (α × β) := ⟨(1, 1)⟩
@[simp, to_additive]
lemma fst_one [has_one α] [has_one β] : (1 : α × β).1 = 1 := rfl
@[simp, to_additive]
lemma snd_one [has_one α] [has_one β] : (1 : α × β).2 = 1 := rfl
@[to_additive]
lemma one_eq_mk [has_one α] [has_one β] : (1 : α × β) = (1, 1) := rfl
instance [has_neg α] [has_neg β] : has_neg (α × β) := ⟨λp, (- p.1, - p.2)⟩
@[to_additive]
instance [has_inv α] [has_inv β] : has_inv (α × β) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩
@[simp, to_additive]
lemma fst_inv [has_inv α] [has_inv β] : (p⁻¹).1 = (p.1)⁻¹ := rfl
@[simp, to_additive]
lemma snd_inv [has_inv α] [has_inv β] : (p⁻¹).2 = (p.2)⁻¹ := rfl
@[to_additive]
lemma inv_mk [has_inv α] [has_inv β] (a : α) (b : β) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl
instance [add_semigroup α] [add_semigroup β] : add_semigroup (α × β) :=
{ add_assoc := assume a b c, mk.inj_iff.mpr ⟨add_assoc _ _ _, add_assoc _ _ _⟩,
.. prod.has_add }
@[to_additive add_semigroup]
instance [semigroup α] [semigroup β] : semigroup (α × β) :=
{ mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩,
.. prod.has_mul }
instance [add_monoid α] [add_monoid β] : add_monoid (α × β) :=
{ zero_add := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_add _, zero_add _⟩,
add_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨add_zero _, add_zero _⟩,
.. prod.add_semigroup, .. prod.has_zero }
@[to_additive add_monoid]
instance [monoid α] [monoid β] : monoid (α × β) :=
{ one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩,
mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩,
.. prod.semigroup, .. prod.has_one }
instance [add_group α] [add_group β] : add_group (α × β) :=
{ add_left_neg := assume a, mk.inj_iff.mpr ⟨add_left_neg _, add_left_neg _⟩,
.. prod.add_monoid, .. prod.has_neg }
@[to_additive add_group]
instance [group α] [group β] : group (α × β) :=
{ mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩,
.. prod.monoid, .. prod.has_inv }
instance [add_comm_semigroup α] [add_comm_semigroup β] : add_comm_semigroup (α × β) :=
{ add_comm := assume a b, mk.inj_iff.mpr ⟨add_comm _ _, add_comm _ _⟩,
.. prod.add_semigroup }
@[to_additive add_comm_semigroup]
instance [comm_semigroup α] [comm_semigroup β] : comm_semigroup (α × β) :=
{ mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩,
.. prod.semigroup }
instance [add_comm_monoid α] [add_comm_monoid β] : add_comm_monoid (α × β) :=
{ .. prod.add_comm_semigroup, .. prod.add_monoid }
@[to_additive add_comm_monoid]
instance [comm_monoid α] [comm_monoid β] : comm_monoid (α × β) :=
{ .. prod.comm_semigroup, .. prod.monoid }
instance [add_comm_group α] [add_comm_group β] : add_comm_group (α × β) :=
{ .. prod.add_comm_semigroup, .. prod.add_group }
@[to_additive add_comm_group]
instance [comm_group α] [comm_group β] : comm_group (α × β) :=
{ .. prod.comm_semigroup, .. prod.group }
@[to_additive is_add_monoid_hom]
lemma fst.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.fst : α × β → α) :=
{ map_mul := λ _ _, rfl, map_one := rfl }
@[to_additive is_add_monoid_hom]
lemma snd.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.snd : α × β → β) :=
{ map_mul := λ _ _, rfl, map_one := rfl }
/-- Given monoids `α, β`, the natural projection homomorphism from `α × β` to `α`. -/
@[to_additive prod.add_monoid_hom.fst "Given add_monoids `α, β`, the natural projection homomorphism from `α × β` to `α`."]
def monoid_hom.fst [monoid α] [monoid β] : α × β →* α :=
⟨λ x, x.1, rfl, λ _ _, prod.fst_mul⟩
/-- Given monoids `α, β`, the natural projection homomorphism from `α × β` to `β`.-/
@[to_additive prod.add_monoid_hom.snd "Given add_monoids `α, β`, the natural projection homomorphism from `α × β` to `β`."]
def monoid_hom.snd [monoid α] [monoid β] : α × β →* β :=
⟨λ x, x.2, rfl, λ _ _, prod.snd_mul⟩
@[to_additive is_add_group_hom]
lemma fst.is_group_hom [group α] [group β] : is_group_hom (prod.fst : α × β → α) :=
{ map_mul := λ _ _, rfl }
@[to_additive is_add_group_hom]
lemma snd.is_group_hom [group α] [group β] : is_group_hom (prod.snd : α × β → β) :=
{ map_mul := λ _ _, rfl }
attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom
fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom
@[to_additive]
lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} :
(t.prod f).1 = t.prod (λc, (f c).1) :=
(finset.prod_hom prod.fst).symm
@[to_additive]
lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} :
(t.prod f).2 = t.prod (λc, (f c).2) :=
(finset.prod_hom prod.snd).symm
instance [semiring α] [semiring β] : semiring (α × β) :=
{ zero_mul := λ a, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩,
mul_zero := λ a, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩,
left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩,
right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩,
..prod.add_comm_monoid, ..prod.monoid }
instance [ring α] [ring β] : ring (α × β) :=
{ ..prod.add_comm_group, ..prod.semiring }
instance [comm_ring α] [comm_ring β] : comm_ring (α × β) :=
{ ..prod.ring, ..prod.comm_monoid }
instance [nonzero_comm_ring α] [comm_ring β] : nonzero_comm_ring (α × β) :=
{ zero_ne_one := mt (congr_arg prod.fst) zero_ne_one,
..prod.comm_ring }
instance fst.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.fst : α × β → α) :=
by refine_struct {..}; simp
instance snd.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.snd : α × β → β) :=
by refine_struct {..}; simp
instance fst.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.fst : α × β → α) :=
by refine_struct {..}; simp
instance snd.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.snd : α × β → β) :=
by refine_struct {..}; simp
/-- Left injection function for the inner product
From a vector space (and also group and module) perspective the product is the same as the sum of
two vector spaces. `inl` and `inr` provide the corresponding injection functions.
-/
def inl [has_zero β] (a : α) : α × β := (a, 0)
/-- Right injection function for the inner product -/
def inr [has_zero α] (b : β) : α × β := (0, b)
lemma injective_inl [has_zero β] : function.injective (inl : α → α × β) :=
assume x y h, (prod.mk.inj_iff.mp h).1
lemma injective_inr [has_zero α] : function.injective (inr : β → α × β) :=
assume x y h, (prod.mk.inj_iff.mp h).2
@[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ :=
iff.intro (assume h, injective_inl h) (assume h, h ▸ rfl)
@[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ :=
iff.intro (assume h, injective_inr h) (assume h, h ▸ rfl)
@[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} :
inl a = inr b ↔ a = 0 ∧ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} :
inr b = inl a ↔ a = 0 ∧ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl
@[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl
@[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl
@[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl
instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩
@[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ]
(a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl
@[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ]
(a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl
@[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ]
(a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl
instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ]
[semimodule α β] [semimodule α γ] : semimodule α (β × γ) :=
{ smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩,
add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩,
mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩,
one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩,
zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩,
smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩,
.. prod.has_scalar }
instance {r : ring α} [add_comm_group β] [add_comm_group γ]
[module α β] [module α γ] : module α (β × γ) := {}
section substructures
variables (s : set α) (t : set β)
@[to_additive is_add_submonoid]
instance [monoid α] [monoid β] [is_submonoid s] [is_submonoid t] :
is_submonoid (s.prod t) :=
{ one_mem := by rw set.mem_prod; split; apply is_submonoid.one_mem,
mul_mem := by intros; rw set.mem_prod at *; split; apply is_submonoid.mul_mem; tauto }
@[to_additive prod.is_add_subgroup.prod]
instance is_subgroup.prod [group α] [group β] [is_subgroup s] [is_subgroup t] :
is_subgroup (s.prod t) :=
{ inv_mem := by intros; rw set.mem_prod at *; split; apply is_subgroup.inv_mem; tauto,
.. prod.is_submonoid s t }
instance is_subring.prod [ring α] [ring β] [is_subring s] [is_subring t] :
is_subring (s.prod t) :=
{ .. prod.is_submonoid s t, .. prod.is_add_subgroup.prod s t }
end substructures
end prod
namespace submonoid
/-- Given submonoids `s, t` of monoids `α, β` respectively, `s × t` as a submonoid of `α × β`. -/
@[to_additive prod "Given `add_submonoids` `s, t` of `add_monoids` `α, β` respectively, `s × t` as an `add_submonoid` of `α × β`."]
def prod {α : Type*} {β : Type*} [monoid α] [monoid β] (s : submonoid α) (t : submonoid β) :
submonoid (α × β) :=
{ carrier := (s : set α).prod t,
one_mem' := ⟨s.one_mem, t.one_mem⟩,
mul_mem' := λ _ _ h1 h2, ⟨s.mul_mem h1.1 h2.1, t.mul_mem h1.2 h2.2⟩ }
end submonoid
namespace finset
@[to_additive prod_mk_sum]
lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ)
(f : γ → α) (g : γ → β) : (s.prod f, s.prod g) = s.prod (λ x, (f x, g x)) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt})
end finset
|
819b653a7266dcd547be1df790755561c5b50886 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/module/submodule.lean | bfcb1e41b74b37bdf36688079ba87829bb2ef43f | [] | 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 | 13,519 | lean | /-
Copyright (c) 2015 Nathaniel Thomas. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.module.linear_map
import Mathlib.group_theory.group_action.sub_mul_action
import Mathlib.PostPort
universes u v l w
namespace Mathlib
/-!
# Submodules of a module
In this file we define
* `submodule R M` : a subset of a `module` `M` that contains zero and is closed with respect to addition and
scalar multiplication.
* `subspace k M` : an abbreviation for `submodule` assuming that `k` is a `field`.
## Tags
submodule, subspace, linear map
-/
/-- A submodule of a module is one which is closed under vector operations.
This is a sufficient condition for the subset of vectors in the submodule
to themselves form a module. -/
structure submodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [semimodule R M]
extends add_submonoid M, sub_mul_action R M
where
/-- Reinterpret a `submodule` as an `add_submonoid`. -/
/-- Reinterpret a `submodule` as an `sub_mul_action`. -/
namespace submodule
protected instance set.has_coe_t {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] : has_coe_t (submodule R M) (set M) :=
has_coe_t.mk fun (s : submodule R M) => carrier s
protected instance has_mem {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] : has_mem M (submodule R M) :=
has_mem.mk fun (x : M) (p : submodule R M) => x ∈ ↑p
protected instance has_coe_to_sort {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] : has_coe_to_sort (submodule R M) :=
has_coe_to_sort.mk (Type (max 0 v)) fun (p : submodule R M) => Subtype fun (x : M) => x ∈ p
@[simp] theorem coe_sort_coe {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] (p : submodule R M) : ↥↑p = ↥p :=
rfl
protected theorem exists {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] {p : submodule R M} {q : ↥p → Prop} : (∃ (x : ↥p), q x) ↔ ∃ (x : M), ∃ (H : x ∈ p), q { val := x, property := H } :=
set_coe.exists
protected theorem forall {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] {p : submodule R M} {q : ↥p → Prop} : (∀ (x : ↥p), q x) ↔ ∀ (x : M) (H : x ∈ p), q { val := x, property := H } :=
set_coe.forall
theorem coe_injective {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] : function.injective coe := sorry
@[simp] theorem coe_set_eq {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] {p : submodule R M} {q : submodule R M} : ↑p = ↑q ↔ p = q :=
function.injective.eq_iff coe_injective
@[simp] theorem mk_coe {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] (S : set M) (h₁ : 0 ∈ S) (h₂ : ∀ {a b : M}, a ∈ S → b ∈ S → a + b ∈ S) (h₃ : ∀ (c : R) {x : M}, x ∈ S → c • x ∈ S) : ↑(mk S h₁ h₂ h₃) = S :=
rfl
theorem ext'_iff {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] {p : submodule R M} {q : submodule R M} : p = q ↔ ↑p = ↑q :=
iff.symm coe_set_eq
theorem ext {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] {p : submodule R M} {q : submodule R M} (h : ∀ (x : M), x ∈ p ↔ x ∈ q) : p = q :=
coe_injective (set.ext h)
theorem to_add_submonoid_injective {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] : function.injective to_add_submonoid :=
fun (p q : submodule R M) (h : to_add_submonoid p = to_add_submonoid q) =>
iff.mpr ext'_iff (iff.mp add_submonoid.ext'_iff h)
@[simp] theorem to_add_submonoid_eq {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] {p : submodule R M} {q : submodule R M} : to_add_submonoid p = to_add_submonoid q ↔ p = q :=
function.injective.eq_iff to_add_submonoid_injective
theorem to_sub_mul_action_injective {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] : function.injective to_sub_mul_action :=
fun (p q : submodule R M) (h : to_sub_mul_action p = to_sub_mul_action q) =>
iff.mpr ext'_iff (iff.mp sub_mul_action.ext'_iff h)
@[simp] theorem to_sub_mul_action_eq {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] [semimodule R M] {p : submodule R M} {q : submodule R M} : to_sub_mul_action p = to_sub_mul_action q ↔ p = q :=
function.injective.eq_iff to_sub_mul_action_injective
end submodule
namespace submodule
-- We can infer the module structure implicitly from the bundled submodule,
-- rather than via typeclass resolution.
@[simp] theorem mem_carrier {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) {x : M} : x ∈ carrier p ↔ x ∈ ↑p :=
iff.rfl
@[simp] theorem mem_coe {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) {x : M} : x ∈ ↑p ↔ x ∈ p :=
iff.rfl
@[simp] theorem zero_mem {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) : 0 ∈ p :=
zero_mem' p
theorem add_mem {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) {x : M} {y : M} (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p :=
add_mem' p h₁ h₂
theorem smul_mem {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) {x : M} (r : R) (h : x ∈ p) : r • x ∈ p :=
smul_mem' p r h
theorem sum_mem {R : Type u} {M : Type v} {ι : Type w} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) {t : finset ι} {f : ι → M} : (∀ (c : ι), c ∈ t → f c ∈ p) → (finset.sum t fun (i : ι) => f i) ∈ p :=
add_submonoid.sum_mem (to_add_submonoid p)
theorem sum_smul_mem {R : Type u} {M : Type v} {ι : Type w} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) {t : finset ι} {f : ι → M} (r : ι → R) (hyp : ∀ (c : ι), c ∈ t → f c ∈ p) : (finset.sum t fun (i : ι) => r i • f i) ∈ p :=
sum_mem p fun (i : ι) (hi : i ∈ t) => smul_mem p (r i) (hyp i hi)
@[simp] theorem smul_mem_iff' {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) {x : M} (u : units R) : ↑u • x ∈ p ↔ x ∈ p :=
sub_mul_action.smul_mem_iff' (to_sub_mul_action p) u
protected instance has_add {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) : Add ↥p :=
{ add := fun (x y : ↥p) => { val := subtype.val x + subtype.val y, property := sorry } }
protected instance has_zero {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) : HasZero ↥p :=
{ zero := { val := 0, property := zero_mem p } }
protected instance inhabited {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) : Inhabited ↥p :=
{ default := 0 }
protected instance has_scalar {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) : has_scalar R ↥p :=
has_scalar.mk fun (c : R) (x : ↥p) => { val := c • subtype.val x, property := sorry }
protected theorem nonempty {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) : set.nonempty ↑p :=
Exists.intro 0 (zero_mem p)
@[simp] theorem mk_eq_zero {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) {x : M} (h : x ∈ p) : { val := x, property := h } = 0 ↔ x = 0 :=
subtype.ext_iff_val
@[simp] theorem coe_eq_coe {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} {p : submodule R M} {x : ↥p} {y : ↥p} : ↑x = ↑y ↔ x = y :=
iff.symm subtype.ext_iff_val
@[simp] theorem coe_eq_zero {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} {p : submodule R M} {x : ↥p} : ↑x = 0 ↔ x = 0 :=
coe_eq_coe
@[simp] theorem coe_add {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} {p : submodule R M} (x : ↥p) (y : ↥p) : ↑(x + y) = ↑x + ↑y :=
rfl
@[simp] theorem coe_zero {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} {p : submodule R M} : ↑0 = 0 :=
rfl
@[simp] theorem coe_smul {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} {p : submodule R M} (r : R) (x : ↥p) : ↑(r • x) = r • ↑x :=
rfl
@[simp] theorem coe_mk {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} {p : submodule R M} (x : M) (hx : x ∈ p) : ↑{ val := x, property := hx } = x :=
rfl
@[simp] theorem coe_mem {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} {p : submodule R M} (x : ↥p) : ↑x ∈ p :=
subtype.property x
@[simp] protected theorem eta {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} {p : submodule R M} (x : ↥p) (hx : ↑x ∈ p) : { val := ↑x, property := hx } = x :=
subtype.eta x hx
protected instance add_comm_monoid {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) : add_comm_monoid ↥p :=
add_comm_monoid.mk Add.add sorry 0 sorry sorry sorry
protected instance semimodule {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) : semimodule R ↥p :=
semimodule.mk sorry sorry
/-- Embedding of a submodule `p` to the ambient space `M`. -/
protected def subtype {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) : linear_map R (↥p) M :=
linear_map.mk coe sorry sorry
@[simp] theorem subtype_apply {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) (x : ↥p) : coe_fn (submodule.subtype p) x = ↑x :=
rfl
theorem subtype_eq_val {R : Type u} {M : Type v} [semiring R] [add_comm_monoid M] {semimodule_M : semimodule R M} (p : submodule R M) : ⇑(submodule.subtype p) = subtype.val :=
rfl
theorem neg_mem {R : Type u} {M : Type v} [ring R] [add_comm_group M] {semimodule_M : semimodule R M} (p : submodule R M) {x : M} (hx : x ∈ p) : -x ∈ p :=
sub_mul_action.neg_mem (to_sub_mul_action p) hx
/-- Reinterpret a submodule as an additive subgroup. -/
def to_add_subgroup {R : Type u} {M : Type v} [ring R] [add_comm_group M] {semimodule_M : semimodule R M} (p : submodule R M) : add_subgroup M :=
add_subgroup.mk (add_submonoid.carrier (to_add_submonoid p)) sorry sorry sorry
@[simp] theorem coe_to_add_subgroup {R : Type u} {M : Type v} [ring R] [add_comm_group M] {semimodule_M : semimodule R M} (p : submodule R M) : ↑(to_add_subgroup p) = ↑p :=
rfl
theorem sub_mem {R : Type u} {M : Type v} [ring R] [add_comm_group M] {semimodule_M : semimodule R M} (p : submodule R M) {x : M} {y : M} : x ∈ p → y ∈ p → x - y ∈ p :=
add_subgroup.sub_mem (to_add_subgroup p)
@[simp] theorem neg_mem_iff {R : Type u} {M : Type v} [ring R] [add_comm_group M] {semimodule_M : semimodule R M} (p : submodule R M) {x : M} : -x ∈ p ↔ x ∈ p :=
add_subgroup.neg_mem_iff (to_add_subgroup p)
theorem add_mem_iff_left {R : Type u} {M : Type v} [ring R] [add_comm_group M] {semimodule_M : semimodule R M} (p : submodule R M) {x : M} {y : M} : y ∈ p → (x + y ∈ p ↔ x ∈ p) :=
add_subgroup.add_mem_cancel_right (to_add_subgroup p)
theorem add_mem_iff_right {R : Type u} {M : Type v} [ring R] [add_comm_group M] {semimodule_M : semimodule R M} (p : submodule R M) {x : M} {y : M} : x ∈ p → (x + y ∈ p ↔ y ∈ p) :=
add_subgroup.add_mem_cancel_left (to_add_subgroup p)
protected instance has_neg {R : Type u} {M : Type v} [ring R] [add_comm_group M] {semimodule_M : semimodule R M} (p : submodule R M) : Neg ↥p :=
{ neg := fun (x : ↥p) => { val := -subtype.val x, property := sorry } }
@[simp] theorem coe_neg {R : Type u} {M : Type v} [ring R] [add_comm_group M] {semimodule_M : semimodule R M} (p : submodule R M) (x : ↥p) : ↑(-x) = -↑x :=
rfl
protected instance add_comm_group {R : Type u} {M : Type v} [ring R] [add_comm_group M] {semimodule_M : semimodule R M} (p : submodule R M) : add_comm_group ↥p :=
add_comm_group.mk Add.add sorry 0 sorry sorry Neg.neg add_comm_group.sub sorry sorry
@[simp] theorem coe_sub {R : Type u} {M : Type v} [ring R] [add_comm_group M] {semimodule_M : semimodule R M} (p : submodule R M) (x : ↥p) (y : ↥p) : ↑(x - y) = ↑x - ↑y :=
rfl
end submodule
namespace submodule
theorem smul_mem_iff {R : Type u} {M : Type v} [division_ring R] [add_comm_group M] [module R M] (p : submodule R M) {r : R} {x : M} (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p :=
sub_mul_action.smul_mem_iff (to_sub_mul_action p) r0
end submodule
/-- Subspace of a vector space. Defined to equal `submodule`. -/
def subspace (R : Type u) (M : Type v) [field R] [add_comm_group M] [vector_space R M] :=
submodule R M
|
e9db6192b4bdfcc78bbd0f198bb06cf686940a6c | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/category_theory/instances/CommRing/default.lean | cd858b60fb30cffc89d7271e179c54e8f6295c54 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 257 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.instances.CommRing.basic
import category_theory.instances.CommRing.adjunctions
|
6967d02d06070a837898304bcf9dc69ad7b25d69 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/ifThenElseIssue.lean | 92394fb82d66449cc0a00e7a7cb90514592463e5 | [
"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 | 782 | lean | -- set_option trace.Meta.isDefEq true
-- set_option trace.Elab true
def f1 (s : Nat × Bool) : Bool :=
if s.2 then false else true
def f2 (s : Nat × Bool) : Bool :=
if @Prod.snd _ _ s then false else true
def f3 (s : Nat × Bool) : Bool :=
if Prod.snd s then false else true
def f4 (s : Nat × String × Bool) : Bool :=
if s.2.2 then false else true
def sec (s : α × β) : β :=
s.2
def f5 (s : Nat × Bool) : Bool :=
if sec s then false else true
def f6 (s : Nat × (Bool → Bool)) : Bool :=
if sec s true then false else true
def f7 (s : List Bool) : Bool :=
if s.head! then false else true
def f8 (s : List Bool) : Bool :=
if (s.map not).head! then false else true
def f9 (s : List Bool) : Bool :=
if List.head! (s.map not) then false else true
|
aaf8e2e42d71c0ea4cf4afeecaf2b5193032a6af | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /tests/lean/run/backtrackable_estate.lean | 0516612957e184f3c06aefb5bf7e1c5af33600c1 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 687 | lean | import Init.System.IO
structure MyState :=
(bs : Nat := 0) -- backtrackable state
(ps : Nat := 0) -- non backtrackable state
instance : HasRepr MyState :=
⟨fun s => repr (s.bs, s.ps)⟩
instance : EStateM.Backtrackable Nat MyState :=
{ save := fun s => s.bs,
restore := fun s d => { s with bs := d } }
abbrev M := EStateM String MyState
def bInc : M Unit := -- increment backtrackble counter
modify $ fun s => { s with bs := s.bs + 1 }
def pInc : M Unit := -- increment nonbacktrackable counter
modify $ fun s => { s with ps := s.ps + 1 }
def tst : M MyState :=
do bInc;
pInc;
((bInc *> throw "failed") <|> pInc);
pInc;
get
#eval tst.run' {} -- (some (1, 3))
|
dcd60e318d8bac1127f17c6e95b5a027c82dc370 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/group_theory/quotient_group.lean | fb38d998879063acb2e5d616c05e6a5f1c408fa9 | [
"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 | 7,510 | lean | /-
Copyright (c) 2018 Kevin Buzzard and Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Patrick Massot.
This file is to a certain extent based on `quotient_module.lean` by Johannes Hölzl.
-/
import group_theory.coset
universes u v
namespace quotient_group
variables {G : Type u} [group G] (N : subgroup G) [nN : N.normal] {H : Type v} [group H]
include nN
@[to_additive quotient_add_group.add_group]
instance : group (quotient N) :=
{ one := (1 : G),
mul := quotient.map₂' (*)
(λ a₁ b₁ hab₁ a₂ b₂ hab₂,
((N.mul_mem_cancel_right (N.inv_mem hab₂)).1
(by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹),
mul_assoc _ b₂, ← mul_assoc b₂, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)];
exact nN.conj_mem _ hab₁ _))),
mul_assoc := λ a b c, quotient.induction_on₃' a b c
(λ a b c, congr_arg mk (mul_assoc a b c)),
one_mul := λ a, quotient.induction_on' a
(λ a, congr_arg mk (one_mul a)),
mul_one := λ a, quotient.induction_on' a
(λ a, congr_arg mk (mul_one a)),
inv := λ a, quotient.lift_on' a (λ a, ((a⁻¹ : G) : quotient N))
(λ a b hab, quotient.sound' begin
show a⁻¹⁻¹ * b⁻¹ ∈ N,
rw ← mul_inv_rev,
exact N.inv_mem (nN.mem_comm hab)
end),
mul_left_inv := λ a, quotient.induction_on' a
(λ a, congr_arg mk (mul_left_inv a)) }
/-- The group homomorphism from `G` to `G/N`. -/
@[to_additive quotient_add_group.mk' "The additive group homomorphism from `G` to `G/N`."]
def mk' : G →* quotient N := monoid_hom.mk' (quotient_group.mk) (λ _ _, rfl)
@[simp, to_additive quotient_add_group.ker_mk]
lemma ker_mk :
monoid_hom.ker (quotient_group.mk' N : G →* quotient_group.quotient N) = N :=
begin
ext g,
rw [monoid_hom.mem_ker, eq_comm],
show (((1 : G) : quotient_group.quotient N)) = g ↔ _,
rw [quotient_group.eq, one_inv, one_mul],
end
-- for commutative groups we don't need normality assumption
omit nN
@[to_additive quotient_add_group.add_comm_group]
instance {G : Type*} [comm_group G] (N : subgroup G) : comm_group (quotient N) :=
{ mul_comm := λ a b, quotient.induction_on₂' a b
(λ a b, congr_arg mk (mul_comm a b)),
..@quotient_group.group _ _ N N.normal_of_comm }
include nN
local notation ` Q ` := quotient N
@[simp, to_additive quotient_add_group.coe_zero]
lemma coe_one : ((1 : G) : Q) = 1 := rfl
@[simp, to_additive quotient_add_group.coe_add]
lemma coe_mul (a b : G) : ((a * b : G) : Q) = a * b := rfl
@[simp, to_additive quotient_add_group.coe_neg]
lemma coe_inv (a : G) : ((a⁻¹ : G) : Q) = a⁻¹ := rfl
@[simp] lemma coe_pow (a : G) (n : ℕ) : ((a ^ n : G) : Q) = a ^ n :=
(mk' N).map_pow a n
@[simp] lemma coe_gpow (a : G) (n : ℤ) : ((a ^ n : G) : Q) = a ^ n :=
(mk' N).map_gpow a n
/-- A group homomorphism `φ : G →* H` with `N ⊆ ker(φ)` descends (i.e. `lift`s) to a
group homomorphism `G/N →* H`. -/
@[to_additive quotient_add_group.lift "An `add_group` homomorphism `φ : G →+ H` with `N ⊆ ker(φ)`
descends (i.e. `lift`s) to a group homomorphism `G/N →* H`."]
def lift (φ : G →* H) (HN : ∀x∈N, φ x = 1) : Q →* H :=
monoid_hom.mk'
(λ q : Q, q.lift_on' φ $ assume a b (hab : a⁻¹ * b ∈ N),
(calc φ a = φ a * 1 : (mul_one _).symm
... = φ a * φ (a⁻¹ * b) : HN (a⁻¹ * b) hab ▸ rfl
... = φ (a * (a⁻¹ * b)) : (is_mul_hom.map_mul φ a (a⁻¹ * b)).symm
... = φ b : by rw mul_inv_cancel_left))
(λ q r, quotient.induction_on₂' q r $ is_mul_hom.map_mul φ)
@[simp, to_additive quotient_add_group.lift_mk]
lemma lift_mk {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) :
lift N φ HN (g : Q) = φ g := rfl
@[simp, to_additive quotient_add_group.lift_mk']
lemma lift_mk' {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) :
lift N φ HN (mk g : Q) = φ g := rfl
@[simp, to_additive quotient_add_group.lift_quot_mk]
lemma lift_quot_mk {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) :
lift N φ HN (quot.mk _ g : Q) = φ g := rfl
/-- A group homomorphism `f : G →* H` induces a map `G/N →* H/M` if `N ⊆ f⁻¹(M)`. -/
@[to_additive quotient_add_group.map "An `add_group` homomorphism `f : G →+ H` induces a map
`G/N →+ H/M` if `N ⊆ f⁻¹(M)`."]
def map (M : subgroup H) [M.normal] (f : G →* H) (h : N ≤ M.comap f) :
quotient N →* quotient M :=
begin
refine quotient_group.lift N ((mk' M).comp f) _,
assume x hx,
refine quotient_group.eq.2 _,
rw [mul_one, subgroup.inv_mem_iff],
exact h hx,
end
omit nN
variables (φ : G →* H)
open function monoid_hom
/-- The induced map from the quotient by the kernel to the codomain. -/
@[to_additive quotient_add_group.ker_lift "The induced map from the quotient by the kernel to the
codomain."]
def ker_lift : quotient (ker φ) →* H :=
lift _ φ $ λ g, φ.mem_ker.mp
@[simp, to_additive quotient_add_group.ker_lift_mk]
lemma ker_lift_mk (g : G) : (ker_lift φ) g = φ g :=
lift_mk _ _ _
@[simp, to_additive quotient_add_group.ker_lift_mk']
lemma ker_lift_mk' (g : G) : (ker_lift φ) (mk g) = φ g :=
lift_mk' _ _ _
@[to_additive quotient_add_group.injective_ker_lift]
lemma ker_lift_injective : injective (ker_lift φ) :=
assume a b, quotient.induction_on₂' a b $
assume a b (h : φ a = φ b), quotient.sound' $
show a⁻¹ * b ∈ ker φ, by rw [mem_ker,
is_mul_hom.map_mul φ, ← h, is_group_hom.map_inv φ, inv_mul_self]
-- Note that ker φ isn't definitionally ker (to_range φ)
-- so there is a bit of annoying code duplication here
/-- The induced map from the quotient by the kernel to the range. -/
@[to_additive quotient_add_group.range_ker_lift "The induced map from the quotient by the kernel to
the range."]
def range_ker_lift : quotient (ker φ) →* φ.range :=
lift _ (to_range φ) $ λ g hg, (mem_ker _).mp $ by rwa to_range_ker
@[to_additive quotient_add_group.range_ker_lift_injective]
lemma range_ker_lift_injective : injective (range_ker_lift φ) :=
assume a b, quotient.induction_on₂' a b $
assume a b (h : to_range φ a = to_range φ b), quotient.sound' $
show a⁻¹ * b ∈ ker φ, by rw [←to_range_ker, mem_ker,
is_mul_hom.map_mul (to_range φ), ← h, is_group_hom.map_inv (to_range φ), inv_mul_self]
@[to_additive quotient_add_group.range_ker_lift_surjective]
lemma range_ker_lift_surjective : surjective (range_ker_lift φ) :=
begin
rintro ⟨_, g, rfl⟩,
use mk g,
refl,
end
/-- The first isomorphism theorem (a definition): the canonical isomorphism between
`G/(ker φ)` to `range φ`. -/
@[to_additive quotient_add_group.quotient_ker_equiv_range "The first isomorphism theorem
(a definition): the canonical isomorphism between `G/(ker φ)` to `range φ`."]
noncomputable def quotient_ker_equiv_range : (quotient (ker φ)) ≃* range φ :=
mul_equiv.of_bijective (range_ker_lift φ) ⟨range_ker_lift_injective φ, range_ker_lift_surjective φ⟩
/-- The canonical isomorphism `G/(ker φ) ≃* H` induced by a surjection `φ : G →* H`. -/
@[to_additive quotient_add_group.quotient_ker_equiv_of_surjective "The canonical isomorphism
`G/(ker φ) ≃+ H` induced by a surjection `φ : G →+ H`."]
noncomputable def quotient_ker_equiv_of_surjective (hφ : function.surjective φ) :
(quotient (ker φ)) ≃* H :=
mul_equiv.of_bijective (ker_lift φ) ⟨ker_lift_injective φ, λ h, begin
rcases hφ h with ⟨g, rfl⟩,
use mk g,
refl
end⟩
end quotient_group
|
d4a8ea7eea1c0cab110f1fbc78887af5a696335c | 88892181780ff536a81e794003fe058062f06758 | /src/knopp/common.lean | a52f733d3e9a5d4aa2b63194a642683863d99192 | [] | 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 | 1,018 | lean | import knopp.natural
import data.rat
import data.fin
universes u
namespace knopp
@[reducible]
def rational := ℚ
@[reducible]
def natural := ℕ+
inductive none_of : list Prop → Prop
| nil : none_of list.nil
| cons {h : Prop} {hs : list Prop} : ¬h → none_of hs → none_of (list.cons h hs)
inductive one_and_only_one : list Prop → Prop
| nil : false → one_and_only_one list.nil
| cons {h : Prop} {hs : list Prop} : (h → none_of hs) → (¬h → one_and_only_one hs) → one_and_only_one (list.cons h hs)
def nat.fix {α : Sort u} (f : Π n, (fin n → α) → α) (n : ℕ) : α :=
begin
apply f n, intros s,
induction n with n ih,
{ exfalso, cases s with _ h, cases h },
{ cases s with x hₓ,
replace hₓ := eq_or_lt_of_le (nat.le_of_lt_succ hₓ),
by_cases h₂ : x = n,
{ subst n, exact f x ih },
{ apply ih, use x, finish } }
end
end knopp
-- def fib : Π n, (fin n → ℕ) → ℕ
-- | 0 _ := 1
-- | 1 _ := 1
-- | (m + 2) f := f ⟨m + 1, _⟩ + f ⟨m, _⟩
|
2bdb72c4985dc0cb81854aae5b403e3734e193ae | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/polynomial/div.lean | f221f4fe4bf94b44aa0dc052027490a89d805ca3 | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 21,575 | 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.inductions
import data.polynomial.monic
import ring_theory.multiplicity
/-!
# Division of univariate polynomials
The main defs are `div_by_monic` and `mod_by_monic`.
The compatibility between these is given by `mod_by_monic_add_div`.
We also define `root_multiplicity`.
-/
noncomputable theory
open_locale classical big_operators polynomial
open finset
namespace polynomial
universes u v w z
variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ}
section comm_semiring
variables [comm_semiring R]
theorem X_dvd_iff {α : Type u} [comm_semiring α] {f : α[X]} : X ∣ f ↔ f.coeff 0 = 0 :=
⟨λ ⟨g, hfg⟩, by rw [hfg, mul_comm, coeff_mul_X_zero],
λ hf, ⟨f.div_X, by rw [mul_comm, ← add_zero (f.div_X * X), ← C_0, ← hf, div_X_mul_X_add]⟩⟩
end comm_semiring
section comm_semiring
variables [comm_semiring R] {p q : R[X]}
lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p)
(hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q :=
have zn0 : (0 : R) ≠ 1, by haveI := nontrivial.of_polynomial_ne hq; exact zero_ne_one,
⟨nat_degree q, λ ⟨r, hr⟩,
have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction,
have hr0 : r ≠ 0, from λ hr0, by simp * at *,
have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1,
by simp [show _ = _, from hmp],
have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0,
from hpn1.symm ▸ zn0.symm,
have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0,
by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1,
one_pow, one_mul, ne.def, hr0]; simp,
have hnp : 0 < nat_degree p,
by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0];
exact hp,
begin
have := congr_arg nat_degree hr,
rw [nat_degree_mul' hpnr0, nat_degree_pow' hpn0', add_mul, add_assoc] at this,
exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_one_le_right (nat.zero_le _) hnp)
(add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this
end⟩
end comm_semiring
section ring
variables [ring R] {p q : R[X]}
lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) :
degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p :=
have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2,
have hq0 : q ≠ 0 := hq.ne_zero_of_polynomial_ne h.2,
have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1
(by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0];
exact h.1),
degree_sub_lt
(by rw [hq.degree_mul, degree_C_mul_X_pow _ hp, degree_eq_nat_degree h.2,
degree_eq_nat_degree hq0, ← with_bot.coe_add, tsub_add_cancel_of_le hlt])
h.2
(by rw [leading_coeff_mul_monic hq, leading_coeff_mul_X_pow, leading_coeff_C])
/-- See `div_by_monic`. -/
noncomputable def div_mod_by_monic_aux : Π (p : R[X]) {q : R[X]},
monic q → R[X] × R[X]
| p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then
let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in
have wf : _ := div_wf_lemma h hq,
let dm := div_mod_by_monic_aux (p - z * q) hq in
⟨z + dm.1, dm.2⟩
else ⟨0, p⟩
using_well_founded {dec_tac := tactic.assumption}
/-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/
def div_by_monic (p q : R[X]) : R[X] :=
if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0
/-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/
def mod_by_monic (p q : R[X]) : R[X] :=
if hq : monic q then (div_mod_by_monic_aux p hq).2 else p
infixl ` /ₘ ` : 70 := div_by_monic
infixl ` %ₘ ` : 70 := mod_by_monic
lemma degree_mod_by_monic_lt [nontrivial R] : ∀ (p : R[X]) {q : R[X]}
(hq : monic q), degree (p %ₘ q) < degree q
| p := λ q hq,
if h : degree q ≤ degree p ∧ p ≠ 0 then
have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq,
have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q :=
degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q)
hq,
begin
unfold mod_by_monic at this ⊢,
unfold div_mod_by_monic_aux,
rw dif_pos hq at this ⊢,
rw if_pos h,
exact this
end
else
or.cases_on (not_and_distrib.1 h) begin
unfold mod_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h],
exact lt_of_not_ge,
end
begin
assume hp,
unfold mod_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h, not_not.1 hp],
exact lt_of_le_of_ne bot_le
(ne.symm (mt degree_eq_bot.1 hq.ne_zero)),
end
using_well_founded {dec_tac := tactic.assumption}
@[simp] lemma zero_mod_by_monic (p : R[X]) : 0 %ₘ p = 0 :=
begin
unfold mod_by_monic div_mod_by_monic_aux,
by_cases hp : monic p,
{ rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] },
{ rw [dif_neg hp] }
end
@[simp] lemma zero_div_by_monic (p : R[X]) : 0 /ₘ p = 0 :=
begin
unfold div_by_monic div_mod_by_monic_aux,
by_cases hp : monic p,
{ rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] },
{ rw [dif_neg hp] }
end
@[simp] lemma mod_by_monic_zero (p : R[X]) : p %ₘ 0 = p :=
if h : monic (0 : R[X]) then by { haveI := monic_zero_iff_subsingleton.mp h, simp }
else by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h
@[simp] lemma div_by_monic_zero (p : R[X]) : p /ₘ 0 = 0 :=
if h : monic (0 : R[X]) then by { haveI := monic_zero_iff_subsingleton.mp h, simp }
else by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h
lemma div_by_monic_eq_of_not_monic (p : R[X]) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq
lemma mod_by_monic_eq_of_not_monic (p : R[X]) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq
lemma mod_by_monic_eq_self_iff [nontrivial R] (hq : monic q) : p %ₘ q = p ↔ degree p < degree q :=
⟨λ h, h ▸ degree_mod_by_monic_lt _ hq,
λ h, have ¬ degree q ≤ degree p := not_le_of_gt h,
by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩
theorem degree_mod_by_monic_le (p : R[X]) {q : R[X]}
(hq : monic q) : degree (p %ₘ q) ≤ degree q :=
by { nontriviality R, exact (degree_mod_by_monic_lt _ hq).le }
end ring
section comm_ring
variables [comm_ring R] {p q : R[X]}
lemma mod_by_monic_eq_sub_mul_div : ∀ (p : R[X]) {q : R[X]} (hq : monic q),
p %ₘ q = p - q * (p /ₘ q)
| p := λ q hq,
if h : degree q ≤ degree p ∧ p ≠ 0 then
have wf : _ := div_wf_lemma h hq,
have ih : _ := mod_by_monic_eq_sub_mul_div
(p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq,
begin
unfold mod_by_monic div_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_pos h],
rw [mod_by_monic, dif_pos hq] at ih,
refine ih.trans _,
unfold div_by_monic,
rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm]
end
else
begin
unfold mod_by_monic div_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero]
end
using_well_founded {dec_tac := tactic.assumption}
lemma mod_by_monic_add_div (p : R[X]) {q : R[X]} (hq : monic q) :
p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq)
lemma div_by_monic_eq_zero_iff [nontrivial R] (hq : monic q) : p /ₘ q = 0 ↔ degree p < degree q :=
⟨λ h, by have := mod_by_monic_add_div p hq;
rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq] at this,
λ h, have ¬ degree q ≤ degree p := not_le_of_gt h,
by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩
lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) :
degree q + degree (p /ₘ q) = degree p :=
begin
nontriviality R,
have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq, not_lt],
have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 :=
by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero],
have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) :=
calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq
... ≤ _ : by rw [degree_mul' hlc, degree_eq_nat_degree hq.ne_zero,
degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe];
exact nat.le_add_right _ _,
calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul' hlc)
... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_right_of_degree_lt hmod).symm
... = _ : congr_arg _ (mod_by_monic_add_div _ hq)
end
lemma degree_div_by_monic_le (p q : R[X]) : degree (p /ₘ q) ≤ degree p :=
if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl]
else if hq : monic q then
if h : degree q ≤ degree p
then by haveI := nontrivial.of_polynomial_ne hp0;
rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq.ne_zero,
degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq).1 (not_lt.2 h))];
exact with_bot.coe_le_coe.2 (nat.le_add_left _ _)
else
by unfold div_by_monic div_mod_by_monic_aux;
simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le]
else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le
lemma degree_div_by_monic_lt (p : R[X]) {q : R[X]} (hq : monic q)
(hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p :=
if hpq : degree p < degree q
then begin
haveI := nontrivial.of_polynomial_ne hp0,
rw [(div_by_monic_eq_zero_iff hq).2 hpq, degree_eq_nat_degree hp0],
exact with_bot.bot_lt_coe _
end
else begin
haveI := nontrivial.of_polynomial_ne hp0,
rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq.ne_zero,
degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq).1 hpq)],
exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left
(with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq.ne_zero) ▸ h0q))
end
theorem nat_degree_div_by_monic {R : Type u} [comm_ring R] (f : R[X]) {g : R[X]}
(hg : g.monic) : nat_degree (f /ₘ g) = nat_degree f - nat_degree g :=
begin
nontriviality R,
by_cases hfg : f /ₘ g = 0,
{ rw [hfg, nat_degree_zero], rw div_by_monic_eq_zero_iff hg at hfg,
rw tsub_eq_zero_iff_le.mpr (nat_degree_le_nat_degree $ le_of_lt hfg) },
have hgf := hfg, rw div_by_monic_eq_zero_iff hg at hgf, push_neg at hgf,
have := degree_add_div_by_monic hg hgf,
have hf : f ≠ 0, { intro hf, apply hfg, rw [hf, zero_div_by_monic] },
rw [degree_eq_nat_degree hf, degree_eq_nat_degree hg.ne_zero, degree_eq_nat_degree hfg,
← with_bot.coe_add, with_bot.coe_eq_coe] at this,
rw [← this, add_tsub_cancel_left]
end
lemma div_mod_by_monic_unique {f g} (q r : R[X]) (hg : monic g)
(h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r :=
begin
nontriviality R,
have h₁ : r - f %ₘ g = -g * (q - f /ₘ g),
from eq_of_sub_eq_zero
(by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)];
simp [mul_add, mul_comm, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]),
have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)),
by simp [h₁],
have h₄ : degree (r - f %ₘ g) < degree g,
from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (f %ₘ g)) :
degree_sub_le _ _
... < degree g : max_lt_iff.2 ⟨h.2, degree_mod_by_monic_lt _ hg⟩,
have h₅ : q - (f /ₘ g) = 0,
from by_contradiction
(λ hqf, not_le_of_gt h₄ $
calc degree g ≤ degree g + degree (q - f /ₘ g) :
by erw [degree_eq_nat_degree hg.ne_zero, degree_eq_nat_degree hqf,
with_bot.coe_le_coe];
exact nat.le_add_right _ _
... = degree (r - f %ₘ g) :
by rw [h₂, degree_mul']; simpa [monic.def.1 hg]),
exact ⟨eq.symm $ eq_of_sub_eq_zero h₅,
eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩
end
lemma map_mod_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) :
(p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f :=
begin
nontriviality S,
haveI : nontrivial R := f.domain_nontrivial,
have : map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q),
{ exact (div_mod_by_monic_unique ((p /ₘ q).map f) _ (hq.map f)
⟨eq.symm $ by rw [← polynomial.map_mul, ← polynomial.map_add, mod_by_monic_add_div _ hq],
calc _ ≤ degree (p %ₘ q) : degree_map_le _ _
... < degree q : degree_mod_by_monic_lt _ hq
... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _
(by rw [monic.def.1 hq, f.map_one]; exact one_ne_zero)⟩) },
exact ⟨this.1.symm, this.2.symm⟩
end
lemma map_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) :
(p /ₘ q).map f = p.map f /ₘ q.map f :=
(map_mod_div_by_monic f hq).1
lemma map_mod_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) :
(p %ₘ q).map f = p.map f %ₘ q.map f :=
(map_mod_div_by_monic f hq).2
lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p :=
⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add];
exact dvd_mul_right _ _,
λ h, begin
nontriviality R,
obtain ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h,
by_contradiction hpq0,
have hmod : p %ₘ q = q * (r - p /ₘ q),
{ rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr] },
have : degree (q * (r - p /ₘ q)) < degree q :=
hmod ▸ degree_mod_by_monic_lt _ hq,
have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 :=
λ h, hpq0 $ leading_coeff_eq_zero.1
(by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]),
have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 :=
by rwa [monic.def.1 hq, one_mul],
rw [degree_mul' hlc, degree_eq_nat_degree hq.ne_zero,
degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this,
exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this)
end⟩
theorem map_dvd_map [comm_ring S] (f : R →+* S) (hf : function.injective f) {x y : R[X]}
(hx : x.monic) : x.map f ∣ y.map f ↔ x ∣ y :=
begin
rw [← dvd_iff_mod_by_monic_eq_zero hx, ← dvd_iff_mod_by_monic_eq_zero (hx.map f),
← map_mod_by_monic f hx],
exact ⟨λ H, map_injective f hf $ by rw [H, polynomial.map_zero],
λ H, by rw [H, polynomial.map_zero]⟩
end
@[simp] lemma mod_by_monic_one (p : R[X]) : p %ₘ 1 = 0 :=
(dvd_iff_mod_by_monic_eq_zero (by convert monic_one)).2 (one_dvd _)
@[simp] lemma div_by_monic_one (p : R[X]) : p /ₘ 1 = p :=
by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp
@[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : R[X]) (a : R) :
p %ₘ (X - C a) = C (p.eval a) :=
begin
nontriviality R,
have h : (p %ₘ (X - C a)).eval a = p.eval a,
{ rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul,
eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero] },
have : degree (p %ₘ (X - C a)) < 1 :=
degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a),
have : degree (p %ₘ (X - C a)) ≤ 0,
{ cases (degree (p %ₘ (X - C a))),
{ exact bot_le },
{ exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } },
rw [eq_C_of_degree_le_zero this, eval_C] at h,
rw [eq_C_of_degree_le_zero this, h]
end
lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a :=
⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul],
λ h : p.eval a = 0,
by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)};
rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩
lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a :=
⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _),
mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h,
λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩
lemma mod_by_monic_X (p : R[X]) : p %ₘ X = C (p.eval 0) :=
by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero]
lemma eval₂_mod_by_monic_eq_self_of_root [comm_ring S] {f : R →+* S}
{p q : R[X]} (hq : q.monic) {x : S} (hx : q.eval₂ f x = 0) :
(p %ₘ q).eval₂ f x = p.eval₂ f x :=
by rw [mod_by_monic_eq_sub_mul_div p hq, eval₂_sub, eval₂_mul, hx, zero_mul, sub_zero]
lemma sum_mod_by_monic_coeff (hq : q.monic) {n : ℕ} (hn : q.degree ≤ n) :
∑ (i : fin n), monomial i ((p %ₘ q).coeff i) = p %ₘ q :=
begin
nontriviality R,
exact (sum_fin (λ i c, monomial i c) (by simp)
((degree_mod_by_monic_lt _ hq).trans_le hn)).trans
(sum_monomial_eq _)
end
lemma sub_dvd_eval_sub (a b : R) (p : R[X]) : a - b ∣ p.eval a - p.eval b :=
begin
suffices : X - C b ∣ p - C (p.eval b),
{ simpa only [coe_eval_ring_hom, eval_sub, eval_X, eval_C] using (eval_ring_hom a).map_dvd this },
simp [dvd_iff_is_root]
end
lemma mul_div_mod_by_monic_cancel_left (p : R[X]) {q : R[X]} (hmo : q.monic) : q * p /ₘ q = p :=
begin
nontriviality R,
refine (div_mod_by_monic_unique _ 0 hmo ⟨by rw [zero_add], _⟩).1,
rw [degree_zero],
exact ne.bot_lt (λ h, hmo.ne_zero (degree_eq_bot.1 h))
end
variable (R)
lemma not_is_field : ¬ is_field R[X] :=
begin
nontriviality R,
rw ring.not_is_field_iff_exists_ideal_bot_lt_and_lt_top,
use ideal.span {polynomial.X},
split,
{ rw [bot_lt_iff_ne_bot, ne.def, ideal.span_singleton_eq_bot],
exact polynomial.X_ne_zero, },
{ rw [lt_top_iff_ne_top, ne.def, ideal.eq_top_iff_one, ideal.mem_span_singleton,
polynomial.X_dvd_iff, polynomial.coeff_one_zero],
exact one_ne_zero, }
end
variable {R}
section multiplicity
/-- An algorithm for deciding polynomial divisibility.
The algorithm is "compute `p %ₘ q` and compare to `0`".
See `polynomial.mod_by_monic` for the algorithm that computes `%ₘ`.
-/
def decidable_dvd_monic (p : R[X]) (hq : monic q) : decidable (q ∣ p) :=
decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq)
open_locale classical
lemma multiplicity_X_sub_C_finite (a : R) (h0 : p ≠ 0) :
multiplicity.finite (X - C a) p :=
begin
haveI := nontrivial.of_polynomial_ne h0,
refine multiplicity_finite_of_degree_pos_of_monic _ (monic_X_sub_C _) h0,
rw degree_X_sub_C,
dec_trivial,
end
/-- The largest power of `X - C a` which divides `p`.
This is computable via the divisibility algorithm `polynomial.decidable_dvd_monic`. -/
def root_multiplicity (a : R) (p : R[X]) : ℕ :=
if h0 : p = 0 then 0
else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) :=
λ n, @not.decidable _ (decidable_dvd_monic p ((monic_X_sub_C a).pow (n + 1))) in
by exactI nat.find (multiplicity_X_sub_C_finite a h0)
lemma root_multiplicity_eq_multiplicity (p : R[X]) (a : R) :
root_multiplicity a p = if h0 : p = 0 then 0 else
(multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) :=
by simp [multiplicity, root_multiplicity, part.dom];
congr; funext; congr
@[simp] lemma root_multiplicity_zero {x : R} : root_multiplicity x 0 = 0 := dif_pos rfl
@[simp] lemma root_multiplicity_eq_zero_iff {p : R[X]} {x : R} :
root_multiplicity x p = 0 ↔ (is_root p x → p = 0) :=
by simp only [root_multiplicity_eq_multiplicity, dite_eq_left_iff, part_enat.get_eq_iff_eq_coe,
nat.cast_zero, multiplicity.multiplicity_eq_zero, dvd_iff_is_root, not_imp_not]
lemma root_multiplicity_eq_zero {p : R[X]} {x : R} (h : ¬ is_root p x) :
root_multiplicity x p = 0 :=
root_multiplicity_eq_zero_iff.2 (λ h', (h h').elim)
@[simp] lemma root_multiplicity_pos' {p : R[X]} {x : R} :
0 < root_multiplicity x p ↔ p ≠ 0 ∧ is_root p x :=
by rw [pos_iff_ne_zero, ne.def, root_multiplicity_eq_zero_iff, not_imp, and.comm]
lemma root_multiplicity_pos {p : R[X]} (hp : p ≠ 0) {x : R} :
0 < root_multiplicity x p ↔ is_root p x :=
root_multiplicity_pos'.trans (and_iff_right hp)
@[simp] lemma root_multiplicity_C (r a : R) : root_multiplicity a (C r) = 0 :=
by simp only [root_multiplicity_eq_zero_iff, is_root, eval_C, C_eq_zero, imp_self]
lemma pow_root_multiplicity_dvd (p : R[X]) (a : R) :
(X - C a) ^ root_multiplicity a p ∣ p :=
if h : p = 0 then by simp [h]
else by rw [root_multiplicity_eq_multiplicity, dif_neg h];
exact multiplicity.pow_multiplicity_dvd _
lemma div_by_monic_mul_pow_root_multiplicity_eq
(p : R[X]) (a : R) :
p /ₘ ((X - C a) ^ root_multiplicity a p) *
(X - C a) ^ root_multiplicity a p = p :=
have monic ((X - C a) ^ root_multiplicity a p),
from (monic_X_sub_C _).pow _,
by conv_rhs { rw [← mod_by_monic_add_div p this,
(dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] };
simp [mul_comm]
lemma eval_div_by_monic_pow_root_multiplicity_ne_zero
{p : R[X]} (a : R) (hp : p ≠ 0) :
eval a (p /ₘ ((X - C a) ^ root_multiplicity a p)) ≠ 0 :=
begin
haveI : nontrivial R := nontrivial.of_polynomial_ne hp,
rw [ne.def, ← is_root.def, ← dvd_iff_is_root],
rintros ⟨q, hq⟩,
have := div_by_monic_mul_pow_root_multiplicity_eq p a,
rw [mul_comm, hq, ← mul_assoc, ← pow_succ',
root_multiplicity_eq_multiplicity, dif_neg hp] at this,
exact multiplicity.is_greatest'
(multiplicity_finite_of_degree_pos_of_monic
(show (0 : with_bot ℕ) < degree (X - C a),
by rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) hp)
(nat.lt_succ_self _) (dvd_of_mul_right_eq _ this)
end
end multiplicity
end comm_ring
end polynomial
|
1a9bf26a5acbbe9dad7242e7d0c8bfe8b29c282a | 5a5e1bb8063d7934afac91f30aa17c715821040b | /lean4SOS/SOS/ExternTest.lean | 3b27d92020e5988478093952426065021ba45d6d | [] | no_license | ramonfmir/leanSOS | 1883392d73710db5c6e291a2abd03a6c5b44a42b | 14b50713dc887f6d408b7b2bce1f8af5bb619958 | refs/heads/main | 1,683,348,826,105 | 1,622,056,982,000 | 1,622,056,982,000 | 341,232,766 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 152 | lean | import Init.Data.Float
-- leanpkg build bin LINK_OPTS=-rdynamic
--@[extern "my_abs"]
--constant my_abs (x : Float) : IO Float
--#eval my_abs (-44.4)
|
19db926576b781dc4653ffd9f074e15759f8a0f6 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Lean/Meta/Tactic/Split.lean | 06debdb4f016ed928eb42ef5fca9b165f8571ed6 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 15,380 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Match.MatchEqs
import Lean.Meta.Tactic.Generalize
namespace Lean.Meta
namespace Split
def getSimpMatchContext : MetaM Simp.Context :=
return {
simpTheorems := {}
congrTheorems := (← getSimpCongrTheorems)
config := { Simp.neutralConfig with dsimp := false }
}
def simpMatch (e : Expr) : MetaM Simp.Result := do
(·.1) <$> Simp.main e (← getSimpMatchContext) (methods := { pre })
where
pre (e : Expr) : SimpM Simp.Step := do
let some app ← matchMatcherApp? e | return Simp.Step.visit { expr := e }
-- First try to reduce matcher
match (← reduceRecMatcher? e) with
| some e' => return Simp.Step.done { expr := e' }
| none =>
match (← Simp.simpMatchCore? app e SplitIf.discharge?) with
| some r => return r
| none => return Simp.Step.visit { expr := e }
def simpMatchTarget (mvarId : MVarId) : MetaM MVarId := mvarId.withContext do
let target ← instantiateMVars (← mvarId.getType)
let r ← simpMatch target
applySimpResultToTarget mvarId target r
private def simpMatchCore (matchDeclName : Name) (matchEqDeclName : Name) (e : Expr) : MetaM Simp.Result := do
(·.1) <$> Simp.main e (← getSimpMatchContext) (methods := { pre })
where
pre (e : Expr) : SimpM Simp.Step := do
if e.isAppOf matchDeclName then
-- First try to reduce matcher
match (← reduceRecMatcher? e) with
| some e' => return Simp.Step.done { expr := e' }
| none =>
-- Try lemma
let simpTheorem := {
origin := .decl matchEqDeclName
proof := mkConst matchEqDeclName
rfl := (← isRflTheorem matchEqDeclName)
}
match (← withReducible <| Simp.tryTheorem? e simpTheorem SplitIf.discharge?) with
| none => return Simp.Step.visit { expr := e }
| some r => return Simp.Step.done r
else
return Simp.Step.visit { expr := e }
private def simpMatchTargetCore (mvarId : MVarId) (matchDeclName : Name) (matchEqDeclName : Name) : MetaM MVarId := do
mvarId.withContext do
let target ← instantiateMVars (← mvarId.getType)
let r ← simpMatchCore matchDeclName matchEqDeclName target
match r.proof? with
| some proof => mvarId.replaceTargetEq r.expr proof
| none => mvarId.replaceTargetDefEq r.expr
private partial def withEqs (lhs rhs : Array Expr) (k : Array Expr → Array Expr → MetaM α) : MetaM α := do
go 0 #[] #[]
where
go (i : Nat) (hs : Array Expr) (rfls : Array Expr) : MetaM α := do
if i < lhs.size then
withLocalDeclD (← mkFreshUserName `heq) (← mkEqHEq lhs[i]! rhs[i]!) fun h => do
let rfl ← if (← inferType h).isEq then mkEqRefl lhs[i]! else mkHEqRefl lhs[i]!
go (i+1) (hs.push h) (rfls.push rfl)
else
k hs rfls
/--
This method makes sure each discriminant is a free variable.
Return the tuple `(discrsNew, discrEqs, mvarId)`. `discrsNew` in an array representing the new discriminants, `discrEqs` is an array of auxiliary equality hypotheses
that connect the new discriminants to the original terms they represent.
Remark: `discrEqs.size ≤ discrsNew.size`
Remark:
We should only generalize `discrs` occurrences as `match`-expression discriminants.
For example, given the following goal.
```
x : Nat
⊢ (match g x with
| 0 => 1
| Nat.succ y => g x) =
2 * x + 1
```
we should not generalize the `g x` in the rhs of the second alternative, and the two resulting goals
for the `split` tactic should be
```
case h_1
x x✝ : Nat
h✝ : g x = 0
⊢ 1 = 2 * x + 1
case h_2
x x✝ y✝ : Nat
h✝ : g x = Nat.succ y✝
⊢ g x = 2 * x + 1
```
-/
private partial def generalizeMatchDiscrs (mvarId : MVarId) (matcherDeclName : Name) (motiveType : Expr) (discrs : Array Expr) : MetaM (Array FVarId × Array FVarId × MVarId) := mvarId.withContext do
if discrs.all (·.isFVar) then
return (discrs.map (·.fvarId!), #[], mvarId)
let some matcherInfo ← getMatcherInfo? matcherDeclName | unreachable!
let numDiscrEqs := matcherInfo.getNumDiscrEqs -- Number of `h : discr = pattern` equations
let (targetNew, rfls) ←
forallTelescope motiveType fun discrVars _ =>
withEqs discrs discrVars fun eqs rfls => do
let foundRef ← IO.mkRef false
let rec mkNewTarget (e : Expr) : MetaM Expr := do
let pre (e : Expr) : MetaM TransformStep := do
if !e.isAppOf matcherDeclName || e.getAppNumArgs != matcherInfo.arity then
return .continue
let some matcherApp ← matchMatcherApp? e | return .continue
for matcherDiscr in matcherApp.discrs, discr in discrs do
unless matcherDiscr == discr do
trace[Meta.Tactic.split] "discr mismatch {matcherDiscr} != {discr}"
return .continue
let matcherApp := { matcherApp with discrs := discrVars }
foundRef.set true
let mut altsNew := #[]
for i in [:matcherApp.alts.size] do
let alt := matcherApp.alts[i]!
let altNumParams := matcherApp.altNumParams[i]!
let altNew ← lambdaTelescope alt fun xs body => do
if xs.size < altNumParams || xs.size < numDiscrEqs then
throwError "'applyMatchSplitter' failed, unexpected `match` alternative"
let body ← mkLambdaFVars xs[altNumParams:] (← mkNewTarget body)
let ys := xs[:altNumParams - numDiscrEqs]
if numDiscrEqs == 0 then
mkLambdaFVars ys body
else
let altEqs := xs[altNumParams - numDiscrEqs : altNumParams]
withNewAltEqs matcherInfo eqs altEqs fun altEqsNew subst => do
let body := body.replaceFVars altEqs subst
mkLambdaFVars (ys++altEqsNew) body
altsNew := altsNew.push altNew
return .done { matcherApp with alts := altsNew }.toExpr
transform (← instantiateMVars e) pre
let targetNew ← mkNewTarget (← mvarId.getType)
unless (← foundRef.get) do
throwError "'applyMatchSplitter' failed, did not find discriminants"
let targetNew ← mkForallFVars (discrVars ++ eqs) targetNew
unless (← isTypeCorrect targetNew) do
throwError "'applyMatchSplitter' failed, failed to generalize target"
return (targetNew, rfls)
let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew (← mvarId.getTag)
trace[Meta.Tactic.split] "targetNew:\n{mvarNew.mvarId!}"
mvarId.assign (mkAppN (mkAppN mvarNew discrs) rfls)
let (discrs', mvarId') ← mvarNew.mvarId!.introNP discrs.size
let (discrEqs, mvarId') ← mvarId'.introNP discrs.size
return (discrs', discrEqs, mvarId')
where
/--
- `eqs` are free variables `h_eq : discr = discrVar`. `eqs.size == discrs.size`
- `altEqs` are free variables of the form `h_altEq : discr = pattern`. `altEqs.size = numDiscrEqs ≤ discrs.size`
This method executes `k altEqsNew subst` where
- `altEqsNew` are fresh free variables of the form `h_altEqNew : discrVar = pattern`
- `subst` are terms of the form `h_eq.trans h_altEqNew : discr = pattern`. We use `subst` later to replace occurences of `h_altEq` with `h_eq.trans h_altEqNew`.
-/
withNewAltEqs (matcherInfo : MatcherInfo) (eqs : Array Expr) (altEqs : Array Expr) (k : Array Expr → Array Expr → MetaM Expr) : MetaM Expr := do
let eqs' := (eqs.zip matcherInfo.discrInfos).filterMap fun (eq, info) => if info.hName?.isNone then none else some eq
-- `eqs'.size == altEqs.size ≤ eqs.size`
let rec go (i : Nat) (altEqsNew : Array Expr) (subst : Array Expr) : MetaM Expr := do
if i < altEqs.size then
let altEqDecl ← getFVarLocalDecl altEqs[i]!
let eq := eqs'[i]!
let eqType ← inferType eq
let altEqType := altEqDecl.type
match eqType.eq?, altEqType.eq? with
| some (_, _, discrVar), some (_, _ /- discr -/, pattern) =>
withLocalDeclD altEqDecl.userName (← mkEq discrVar pattern) fun altEqNew => do
go (i+1) (altEqsNew.push altEqNew) (subst.push (← mkEqTrans eq altEqNew))
| _, _ =>
match eqType.heq?, altEqType.heq? with
| some (_, _, _, discrVar), some (_, _ /- discr -/, _, pattern) =>
withLocalDeclD altEqDecl.userName (← mkHEq discrVar pattern) fun altEqNew => do
go (i+1) (altEqsNew.push altEqNew) (subst.push (← mkHEqTrans eq altEqNew))
| _, _ =>
throwError "'applyMatchSplitter' failed, unexpected discriminant equalities"
else
k altEqsNew subst
go 0 #[] #[]
private def substDiscrEqs (mvarId : MVarId) (fvarSubst : FVarSubst) (discrEqs : Array FVarId) : MetaM MVarId := mvarId.withContext do
let mut mvarId := mvarId
let mut fvarSubst := fvarSubst
for fvarId in discrEqs do
if let .fvar fvarId := fvarSubst.apply (mkFVar fvarId) then
let (fvarId, mvarId') ← heqToEq mvarId fvarId
match (← substCore? mvarId' fvarId (symm := false) fvarSubst) with
| some (fvarSubst', mvarId') => mvarId := mvarId'; fvarSubst := fvarSubst'
| none =>
match (← substCore? mvarId' fvarId (symm := true) fvarSubst) with
| some (fvarSubst', mvarId') => mvarId := mvarId'; fvarSubst := fvarSubst'
| none => mvarId := mvarId'
return mvarId
def applyMatchSplitter (mvarId : MVarId) (matcherDeclName : Name) (us : Array Level) (params : Array Expr) (discrs : Array Expr) : MetaM (List MVarId) := do
let some info ← getMatcherInfo? matcherDeclName | throwError "'applyMatchSplitter' failed, '{matcherDeclName}' is not a 'match' auxiliary declaration."
let matchEqns ← Match.getEquationsFor matcherDeclName
-- splitterPre does not have the correct universe elimination level, but this is fine, we only use it to compute the `motiveType`,
-- and we only care about the `motiveType` arguments, and not the resulting `Sort u`.
let splitterPre := mkAppN (mkConst matchEqns.splitterName us.toList) params
let motiveType := (← whnfForall (← inferType splitterPre)).bindingDomain!
trace[Meta.Tactic.split] "applyMatchSplitter\n{mvarId}"
let (discrFVarIds, discrEqs, mvarId) ← generalizeMatchDiscrs mvarId matcherDeclName motiveType discrs
trace[Meta.Tactic.split] "after generalizeMatchDiscrs\n{mvarId}"
let mvarId ← generalizeTargetsEq mvarId motiveType (discrFVarIds.map mkFVar)
mvarId.withContext do trace[Meta.Tactic.split] "discrEqs after generalizeTargetsEq: {discrEqs.map mkFVar}"
trace[Meta.Tactic.split] "after generalize\n{mvarId}"
let numEqs := discrs.size
let (discrFVarIdsNew, mvarId) ← mvarId.introN discrs.size
trace[Meta.Tactic.split] "after introN\n{mvarId}"
let discrsNew := discrFVarIdsNew.map mkFVar
let mvarType ← mvarId.getType
let elimUniv ← mvarId.withContext <| getLevel mvarType
let us ← if let some uElimPos := info.uElimPos? then
pure <| us.set! uElimPos elimUniv
else
unless elimUniv.isZero do
throwError "match-splitter can only eliminate into `Prop`"
pure us
let splitter := mkAppN (mkConst matchEqns.splitterName us.toList) params
mvarId.withContext do
let motive ← mkLambdaFVars discrsNew mvarType
let splitter := mkAppN (mkApp splitter motive) discrsNew
check splitter
trace[Meta.Tactic.split] "after check splitter"
let mvarIds ← mvarId.apply splitter
unless mvarIds.length == matchEqns.size do
throwError "'applyMatchSplitter' failed, unexpected number of goals created after applying splitter for '{matcherDeclName}'."
let (_, mvarIds) ← mvarIds.foldlM (init := (0, [])) fun (i, mvarIds) mvarId => do
let numParams := matchEqns.splitterAltNumParams[i]!
let (_, mvarId) ← mvarId.introN numParams
trace[Meta.Tactic.split] "before unifyEqs\n{mvarId}"
match (← Cases.unifyEqs? (numEqs + info.getNumDiscrEqs) mvarId {}) with
| none => return (i+1, mvarIds) -- case was solved
| some (mvarId, fvarSubst) =>
trace[Meta.Tactic.split] "after unifyEqs\n{mvarId}"
let mvarId ← substDiscrEqs mvarId fvarSubst discrEqs
return (i+1, mvarId::mvarIds)
return mvarIds.reverse
def splitMatch (mvarId : MVarId) (e : Expr) : MetaM (List MVarId) := do
try
let some app ← matchMatcherApp? e | throwError "match application expected"
let matchEqns ← Match.getEquationsFor app.matcherName
let mvarIds ← applyMatchSplitter mvarId app.matcherName app.matcherLevels app.params app.discrs
let (_, mvarIds) ← mvarIds.foldlM (init := (0, [])) fun (i, mvarIds) mvarId => do
let mvarId ← simpMatchTargetCore mvarId app.matcherName matchEqns.eqnNames[i]!
return (i+1, mvarId::mvarIds)
return mvarIds.reverse
catch ex =>
throwNestedTacticEx `splitMatch ex
/-- Return an `if-then-else` or `match-expr` to split. -/
partial def findSplit? (env : Environment) (e : Expr) (splitIte := true) (exceptionSet : ExprSet := {}) : Option Expr :=
go e
where
go (e : Expr) : Option Expr :=
if let some target := e.find? isCandidate then
if e.isIte || e.isDIte then
let cond := target.getArg! 1 5
-- Try to find a nested `if` in `cond`
go cond |>.getD target
else
some target
else
none
isCandidate (e : Expr) : Bool := Id.run do
if exceptionSet.contains e then
false
else if splitIte && (e.isIte || e.isDIte) then
!(e.getArg! 1 5).hasLooseBVars
else if let some info := isMatcherAppCore? env e then
let args := e.getAppArgs
for i in [info.getFirstDiscrPos : info.getFirstDiscrPos + info.numDiscrs] do
if args[i]!.hasLooseBVars then
return false
return true
else
false
end Split
open Split
partial def splitTarget? (mvarId : MVarId) (splitIte := true) : MetaM (Option (List MVarId)) := commitWhenSome? do
let target ← instantiateMVars (← mvarId.getType)
let rec go (badCases : ExprSet) : MetaM (Option (List MVarId)) := do
if let some e := findSplit? (← getEnv) target splitIte badCases then
if e.isIte || e.isDIte then
return (← splitIfTarget? mvarId).map fun (s₁, s₂) => [s₁.mvarId, s₂.mvarId]
else
try
splitMatch mvarId e
catch _ =>
go (badCases.insert e)
else
trace[Meta.Tactic.split] "did not find term to split\n{MessageData.ofGoal mvarId}"
return none
go {}
def splitLocalDecl? (mvarId : MVarId) (fvarId : FVarId) : MetaM (Option (List MVarId)) := commitWhenSome? do
mvarId.withContext do
if let some e := findSplit? (← getEnv) (← instantiateMVars (← inferType (mkFVar fvarId))) then
if e.isIte || e.isDIte then
return (← splitIfLocalDecl? mvarId fvarId).map fun (mvarId₁, mvarId₂) => [mvarId₁, mvarId₂]
else
let (fvarIds, mvarId) ← mvarId.revert #[fvarId]
let num := fvarIds.size
let mvarIds ← splitMatch mvarId e
let mvarIds ← mvarIds.mapM fun mvarId => return (← mvarId.introNP num).2
return some mvarIds
else
return none
builtin_initialize registerTraceClass `Meta.Tactic.split
end Lean.Meta
|
fe3c35dee62ba36f6bc964e4d11242db2de2580a | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/constructions.lean | 9ae73f8a80ad0e1fc7191af686d00a014907bf40 | [] | 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 | 33,962 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.maps
import Mathlib.PostPort
universes u v w x u_1 u_2 u_3 u_4
namespace Mathlib
/-!
# 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
-/
protected instance subtype.topological_space {α : Type u} {p : α → Prop} [t : topological_space α] : topological_space (Subtype p) :=
topological_space.induced coe t
protected instance quot.topological_space {α : Type u} {r : α → α → Prop} [t : topological_space α] : topological_space (Quot r) :=
topological_space.coinduced (Quot.mk r) t
protected instance quotient.topological_space {α : Type u} {s : setoid α} [t : topological_space α] : topological_space (quotient s) :=
topological_space.coinduced quotient.mk t
protected instance prod.topological_space {α : Type u} {β : Type v} [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) :=
topological_space.induced prod.fst t₁ ⊓ topological_space.induced prod.snd t₂
protected instance sum.topological_space {α : Type u} {β : Type v} [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) :=
topological_space.coinduced sum.inl t₁ ⊔ topological_space.coinduced sum.inr t₂
protected instance sigma.topological_space {α : Type u} {β : α → Type v} [t₂ : (a : α) → topological_space (β a)] : topological_space (sigma β) :=
supr fun (a : α) => topological_space.coinduced (sigma.mk a) (t₂ a)
protected instance Pi.topological_space {α : Type u} {β : α → Type v} [t₂ : (a : α) → topological_space (β a)] : topological_space ((a : α) → β a) :=
infi fun (a : α) => topological_space.induced (fun (f : (a : α) → β a) => f a) (t₂ a)
protected instance ulift.topological_space {α : Type u} [t : topological_space α] : topological_space (ulift α) :=
topological_space.induced ulift.down t
/-- The image of a dense set under `quotient.mk` is a dense set. -/
theorem dense.quotient {α : Type u} [setoid α] [topological_space α] {s : set α} (H : dense s) : dense (quotient.mk '' s) :=
dense_range.dense_image (function.surjective.dense_range (surjective_quotient_mk α)) continuous_coinduced_rng H
/-- The composition of `quotient.mk` and a function with dense range has dense range. -/
theorem dense_range.quotient {α : Type u} {β : Type v} [setoid α] [topological_space α] {f : β → α} (hf : dense_range f) : dense_range (quotient.mk ∘ f) :=
dense_range.comp (function.surjective.dense_range (surjective_quotient_mk α)) hf continuous_coinduced_rng
protected instance subtype.discrete_topology {α : Type u} {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (Subtype p) :=
discrete_topology.mk
(bot_unique
fun (s : set (Subtype p)) (hs : topological_space.is_open ⊥ s) =>
Exists.intro (coe '' s)
{ left := is_open_discrete (coe '' s), right := set.preimage_image_eq s subtype.coe_injective })
protected instance sum.discrete_topology {α : Type u} {β : Type v} [topological_space α] [topological_space β] [hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) := sorry
protected instance sigma.discrete_topology {α : Type u} {β : α → Type v} [(a : α) → topological_space (β a)] [h : ∀ (a : α), discrete_topology (β a)] : discrete_topology (sigma β) := sorry
/-
The 𝓝 filter and the subspace topology.
-/
theorem mem_nhds_subtype {α : Type u} [topological_space α] (s : set α) (a : Subtype fun (x : α) => x ∈ s) (t : set (Subtype fun (x : α) => x ∈ s)) : t ∈ nhds a ↔ ∃ (u : set α), ∃ (H : u ∈ nhds ↑a), coe ⁻¹' u ⊆ t :=
mem_nhds_induced coe a t
theorem nhds_subtype {α : Type u} [topological_space α] (s : set α) (a : Subtype fun (x : α) => x ∈ s) : nhds a = filter.comap coe (nhds ↑a) :=
nhds_induced coe a
theorem continuous_fst {α : Type u} {β : Type v} [topological_space α] [topological_space β] : continuous prod.fst :=
continuous_inf_dom_left continuous_induced_dom
theorem continuous_at_fst {α : Type u} {β : Type v} [topological_space α] [topological_space β] {p : α × β} : continuous_at prod.fst p :=
continuous.continuous_at continuous_fst
theorem continuous_snd {α : Type u} {β : Type v} [topological_space α] [topological_space β] : continuous prod.snd :=
continuous_inf_dom_right continuous_induced_dom
theorem continuous_at_snd {α : Type u} {β : Type v} [topological_space α] [topological_space β] {p : α × β} : continuous_at prod.snd p :=
continuous.continuous_at continuous_snd
theorem continuous.prod_mk {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [topological_space β] [topological_space γ] {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous fun (x : γ) => (f x, g x) :=
continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg)
theorem continuous.prod_map {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] {f : γ → α} {g : δ → β} (hf : continuous f) (hg : continuous g) : continuous fun (x : γ × δ) => (f (prod.fst x), g (prod.snd x)) :=
continuous.prod_mk (continuous.comp hf continuous_fst) (continuous.comp hg continuous_snd)
theorem filter.eventually.prod_inl_nhds {α : Type u} {β : Type v} [topological_space α] [topological_space β] {p : α → Prop} {a : α} (h : filter.eventually (fun (x : α) => p x) (nhds a)) (b : β) : filter.eventually (fun (x : α × β) => p (prod.fst x)) (nhds (a, b)) :=
continuous_at_fst h
theorem filter.eventually.prod_inr_nhds {α : Type u} {β : Type v} [topological_space α] [topological_space β] {p : β → Prop} {b : β} (h : filter.eventually (fun (x : β) => p x) (nhds b)) (a : α) : filter.eventually (fun (x : α × β) => p (prod.snd x)) (nhds (a, b)) :=
continuous_at_snd h
theorem filter.eventually.prod_mk_nhds {α : Type u} {β : Type v} [topological_space α] [topological_space β] {pa : α → Prop} {a : α} (ha : filter.eventually (fun (x : α) => pa x) (nhds a)) {pb : β → Prop} {b : β} (hb : filter.eventually (fun (y : β) => pb y) (nhds b)) : filter.eventually (fun (p : α × β) => pa (prod.fst p) ∧ pb (prod.snd p)) (nhds (a, b)) :=
filter.eventually.and (filter.eventually.prod_inl_nhds ha b) (filter.eventually.prod_inr_nhds hb a)
theorem continuous_swap {α : Type u} {β : Type v} [topological_space α] [topological_space β] : continuous prod.swap :=
continuous.prod_mk continuous_snd continuous_fst
theorem continuous_uncurry_left {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} (a : α) (h : continuous (function.uncurry f)) : continuous (f a) :=
(fun (this : continuous (function.uncurry f ∘ fun (b : β) => (a, b))) => this)
(continuous.comp h (continuous.prod_mk continuous_const continuous_id'))
theorem continuous_uncurry_right {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} (b : β) (h : continuous (function.uncurry f)) : continuous fun (a : α) => f a b :=
(fun (this : continuous (function.uncurry f ∘ fun (a : α) => (a, b))) => this)
(continuous.comp h (continuous.prod_mk continuous_id' continuous_const))
theorem continuous_curry {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [topological_space β] [topological_space γ] {g : α × β → γ} (a : α) (h : continuous g) : continuous (function.curry g a) :=
(fun (this : continuous (g ∘ fun (b : β) => (a, b))) => this)
(continuous.comp h (continuous.prod_mk continuous_const continuous_id'))
theorem is_open.prod {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) :=
is_open_inter (is_open.preimage continuous_fst hs) (is_open.preimage continuous_snd ht)
theorem nhds_prod_eq {α : Type u} {β : Type v} [topological_space α] [topological_space β] {a : α} {b : β} : nhds (a, b) = filter.prod (nhds a) (nhds b) := sorry
theorem mem_nhds_prod_iff {α : Type u} {β : Type v} [topological_space α] [topological_space β] {a : α} {b : β} {s : set (α × β)} : s ∈ nhds (a, b) ↔ ∃ (u : set α), ∃ (H : u ∈ nhds a), ∃ (v : set β), ∃ (H : v ∈ nhds b), set.prod u v ⊆ s := sorry
theorem filter.has_basis.prod_nhds {α : Type u} {β : Type v} [topological_space α] [topological_space β] {ιa : Type u_1} {ιb : Type u_2} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {a : α} {b : β} (ha : filter.has_basis (nhds a) pa sa) (hb : filter.has_basis (nhds b) pb sb) : filter.has_basis (nhds (a, b)) (fun (i : ιa × ιb) => pa (prod.fst i) ∧ pb (prod.snd i))
fun (i : ιa × ιb) => set.prod (sa (prod.fst i)) (sb (prod.snd i)) := sorry
protected instance prod.discrete_topology {α : Type u} {β : Type v} [topological_space α] [topological_space β] [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) :=
discrete_topology.mk (eq_of_nhds_eq_nhds fun (_x : α × β) => sorry)
theorem prod_mem_nhds_sets {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ nhds a) (hb : t ∈ nhds b) : set.prod s t ∈ nhds (a, b) :=
eq.mpr (id (Eq._oldrec (Eq.refl (set.prod s t ∈ nhds (a, b))) nhds_prod_eq)) (filter.prod_mem_prod ha hb)
theorem nhds_swap {α : Type u} {β : Type v} [topological_space α] [topological_space β] (a : α) (b : β) : nhds (a, b) = filter.map prod.swap (nhds (b, a)) := sorry
theorem filter.tendsto.prod_mk_nhds {α : Type u} {β : Type v} [topological_space α] [topological_space β] {γ : Type u_1} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : filter.tendsto ma f (nhds a)) (hb : filter.tendsto mb f (nhds b)) : filter.tendsto (fun (c : γ) => (ma c, mb c)) f (nhds (a, b)) :=
eq.mpr (id (Eq._oldrec (Eq.refl (filter.tendsto (fun (c : γ) => (ma c, mb c)) f (nhds (a, b)))) nhds_prod_eq))
(filter.tendsto.prod_mk ha hb)
theorem filter.eventually.curry_nhds {α : Type u} {β : Type v} [topological_space α] [topological_space β] {p : α × β → Prop} {x : α} {y : β} (h : filter.eventually (fun (x : α × β) => p x) (nhds (x, y))) : filter.eventually (fun (x' : α) => filter.eventually (fun (y' : β) => p (x', y')) (nhds y)) (nhds x) :=
filter.eventually.curry
(eq.mp (Eq._oldrec (Eq.refl (filter.eventually (fun (x : α × β) => p x) (nhds (x, y)))) nhds_prod_eq) h)
theorem continuous_at.prod {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [topological_space β] [topological_space γ] {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (fun (x : α) => (f x, g x)) x :=
filter.tendsto.prod_mk_nhds hf hg
theorem continuous_at.prod_map {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] {f : α → γ} {g : β → δ} {p : α × β} (hf : continuous_at f (prod.fst p)) (hg : continuous_at g (prod.snd p)) : continuous_at (fun (p : α × β) => (f (prod.fst p), g (prod.snd p))) p :=
continuous_at.prod (continuous_at.comp hf (continuous.continuous_at continuous_fst))
(continuous_at.comp hg (continuous.continuous_at continuous_snd))
theorem continuous_at.prod_map' {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] {f : α → γ} {g : β → δ} {x : α} {y : β} (hf : continuous_at f x) (hg : continuous_at g y) : continuous_at (fun (p : α × β) => (f (prod.fst p), g (prod.snd p))) (x, y) :=
(fun (hf : continuous_at f (prod.fst (x, y))) =>
(fun (hg : continuous_at g (prod.snd (x, y))) => continuous_at.prod_map hf hg) hg)
hf
theorem prod_generate_from_generate_from_eq {α : Type u_1} {β : Type u_2} {s : set (set α)} {t : set (set β)} (hs : ⋃₀s = set.univ) (ht : ⋃₀t = set.univ) : prod.topological_space =
topological_space.generate_from
(set_of fun (g : set (α × β)) => ∃ (u : set α), ∃ (H : u ∈ s), ∃ (v : set β), ∃ (H : v ∈ t), g = set.prod u v) := sorry
theorem prod_eq_generate_from {α : Type u} {β : Type v} [topological_space α] [topological_space β] : prod.topological_space =
topological_space.generate_from
(set_of fun (g : set (α × β)) => ∃ (s : set α), ∃ (t : set β), is_open s ∧ is_open t ∧ g = set.prod s t) := sorry
theorem is_open_prod_iff {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set (α × β)} : is_open s ↔
∀ (a : α) (b : β), (a, b) ∈ s → ∃ (u : set α), ∃ (v : set β), is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s := sorry
theorem continuous_uncurry_of_discrete_topology_left {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [topological_space β] [topological_space γ] [discrete_topology α] {f : α → β → γ} (h : ∀ (a : α), continuous (f a)) : continuous (function.uncurry f) := sorry
/-- Given a neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood
that is a subset of `s`. -/
theorem exists_nhds_square {α : Type u} [topological_space α] {s : set (α × α)} {x : α} (hx : s ∈ nhds (x, x)) : ∃ (U : set α), is_open U ∧ x ∈ U ∧ set.prod U U ⊆ s := sorry
/-- The first projection in a product of topological spaces sends open sets to open sets. -/
theorem is_open_map_fst {α : Type u} {β : Type v} [topological_space α] [topological_space β] : is_open_map prod.fst := sorry
/-- The second projection in a product of topological spaces sends open sets to open sets. -/
theorem is_open_map_snd {α : Type u} {β : Type v} [topological_space α] [topological_space β] : is_open_map prod.snd := sorry
/-- A product set is open in a product space if and only if each factor is open, or one of them is
empty -/
theorem is_open_prod_iff' {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} {t : set β} : is_open (set.prod s t) ↔ is_open s ∧ is_open t ∨ s = ∅ ∨ t = ∅ := sorry
theorem closure_prod_eq {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := sorry
theorem map_mem_closure2 {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [topological_space β] [topological_space γ] {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous fun (p : α × β) => f (prod.fst p) (prod.snd p)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀ (a : α) (b : β), a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := sorry
theorem is_closed.prod {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := sorry
/-- The product of two dense sets is a dense set. -/
theorem dense.prod {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} {t : set β} (hs : dense s) (ht : dense t) : dense (set.prod s t) :=
fun (x : α × β) =>
eq.mpr (id (Eq._oldrec (Eq.refl (x ∈ closure (set.prod s t))) closure_prod_eq))
{ left := hs (prod.fst x), right := ht (prod.snd x) }
/-- If `f` and `g` are maps with dense range, then `prod.map f g` has dense range. -/
theorem dense_range.prod_map {β : Type v} {γ : Type w} [topological_space β] [topological_space γ] {ι : Type u_1} {κ : Type u_2} {f : ι → β} {g : κ → γ} (hf : dense_range f) (hg : dense_range g) : dense_range (prod.map f g) := sorry
theorem inducing.prod_mk {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) : inducing fun (x : α × γ) => (f (prod.fst x), g (prod.snd x)) := sorry
theorem embedding.prod_mk {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding fun (x : α × γ) => (f (prod.fst x), g (prod.snd x)) := sorry
protected theorem is_open_map.prod {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map fun (p : α × γ) => (f (prod.fst p), g (prod.snd p)) := sorry
protected theorem open_embedding.prod {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding fun (x : α × γ) => (f (prod.fst x), g (prod.snd x)) :=
open_embedding_of_embedding_open (embedding.prod_mk (open_embedding.to_embedding hf) (open_embedding.to_embedding hg))
(is_open_map.prod (open_embedding.is_open_map hf) (open_embedding.is_open_map hg))
theorem embedding_graph {α : Type u} {β : Type v} [topological_space α] [topological_space β] {f : α → β} (hf : continuous f) : embedding fun (x : α) => (x, f x) :=
embedding_of_embedding_compose (continuous.prod_mk continuous_id hf) continuous_fst embedding_id
theorem continuous_inl {α : Type u} {β : Type v} [topological_space α] [topological_space β] : continuous sum.inl :=
continuous_sup_rng_left continuous_coinduced_rng
theorem continuous_inr {α : Type u} {β : Type v} [topological_space α] [topological_space β] : continuous sum.inr :=
continuous_sup_rng_right continuous_coinduced_rng
theorem continuous_sum_rec {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [topological_space β] [topological_space γ] {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : continuous (sum.rec f g) := sorry
theorem is_open_sum_iff {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set (α ⊕ β)} : is_open s ↔ is_open (sum.inl ⁻¹' s) ∧ is_open (sum.inr ⁻¹' s) :=
iff.rfl
theorem is_open_map_sum {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [topological_space β] [topological_space γ] {f : α ⊕ β → γ} (h₁ : is_open_map fun (a : α) => f (sum.inl a)) (h₂ : is_open_map fun (b : β) => f (sum.inr b)) : is_open_map f := sorry
theorem embedding_inl {α : Type u} {β : Type v} [topological_space α] [topological_space β] : embedding sum.inl := sorry
theorem embedding_inr {α : Type u} {β : Type v} [topological_space α] [topological_space β] : embedding sum.inr := sorry
theorem is_open_range_inl {α : Type u} {β : Type v} [topological_space α] [topological_space β] : is_open (set.range sum.inl) := sorry
theorem is_open_range_inr {α : Type u} {β : Type v} [topological_space α] [topological_space β] : is_open (set.range sum.inr) := sorry
theorem open_embedding_inl {α : Type u} {β : Type v} [topological_space α] [topological_space β] : open_embedding sum.inl :=
open_embedding.mk (embedding.mk (embedding.to_inducing embedding_inl) (embedding.inj embedding_inl)) is_open_range_inl
theorem open_embedding_inr {α : Type u} {β : Type v} [topological_space α] [topological_space β] : open_embedding sum.inr :=
open_embedding.mk (embedding.mk (embedding.to_inducing embedding_inr) (embedding.inj embedding_inr)) is_open_range_inr
theorem embedding_subtype_coe {α : Type u} [topological_space α] {p : α → Prop} : embedding coe :=
embedding.mk (inducing.mk rfl) subtype.coe_injective
theorem continuous_subtype_val {α : Type u} [topological_space α] {p : α → Prop} : continuous subtype.val :=
continuous_induced_dom
theorem continuous_subtype_coe {α : Type u} [topological_space α] {p : α → Prop} : continuous coe :=
continuous_subtype_val
theorem is_open.open_embedding_subtype_coe {α : Type u} [topological_space α] {s : set α} (hs : is_open s) : open_embedding coe :=
open_embedding.mk (embedding.mk (inducing.mk rfl) subtype.coe_injective) (Eq.symm subtype.range_coe ▸ hs)
theorem is_open.is_open_map_subtype_coe {α : Type u} [topological_space α] {s : set α} (hs : is_open s) : is_open_map coe :=
open_embedding.is_open_map (is_open.open_embedding_subtype_coe hs)
theorem is_open_map.restrict {α : Type u} {β : Type v} [topological_space α] [topological_space β] {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) : is_open_map (set.restrict f s) :=
is_open_map.comp hf (is_open.is_open_map_subtype_coe hs)
theorem is_closed.closed_embedding_subtype_coe {α : Type u} [topological_space α] {s : set α} (hs : is_closed s) : closed_embedding coe :=
closed_embedding.mk (embedding.mk (inducing.mk rfl) subtype.coe_injective) (Eq.symm subtype.range_coe ▸ hs)
theorem continuous_subtype_mk {α : Type u} {β : Type v} [topological_space α] [topological_space β] {p : α → Prop} {f : β → α} (hp : ∀ (x : β), p (f x)) (h : continuous f) : continuous fun (x : β) => { val := f x, property := hp x } :=
continuous_induced_rng h
theorem continuous_inclusion {α : Type u} [topological_space α] {s : set α} {t : set α} (h : s ⊆ t) : continuous (set.inclusion h) :=
continuous_subtype_mk (fun (x : ↥s) => set.inclusion._proof_1 h x) continuous_subtype_coe
theorem continuous_at_subtype_coe {α : Type u} [topological_space α] {p : α → Prop} {a : Subtype p} : continuous_at coe a :=
iff.mp continuous_iff_continuous_at continuous_subtype_coe a
theorem map_nhds_subtype_coe_eq {α : Type u} [topological_space α] {p : α → Prop} {a : α} (ha : p a) (h : (set_of fun (a : α) => p a) ∈ nhds a) : filter.map coe (nhds { val := a, property := ha }) = nhds a := sorry
theorem nhds_subtype_eq_comap {α : Type u} [topological_space α] {p : α → Prop} {a : α} {h : p a} : nhds { val := a, property := h } = filter.comap coe (nhds a) :=
nhds_induced coe { val := a, property := h }
theorem tendsto_subtype_rng {α : Type u} [topological_space α] {β : Type u_1} {p : α → Prop} {b : filter β} {f : β → Subtype p} {a : Subtype p} : filter.tendsto f b (nhds a) ↔ filter.tendsto (fun (x : β) => ↑(f x)) b (nhds ↑a) := sorry
theorem continuous_subtype_nhds_cover {α : Type u} {β : Type v} [topological_space α] [topological_space β] {ι : Sort u_1} {f : α → β} {c : ι → α → Prop} (c_cover : ∀ (x : α), ∃ (i : ι), (set_of fun (x : α) => c i x) ∈ nhds x) (f_cont : ∀ (i : ι), continuous fun (x : Subtype (c i)) => f ↑x) : continuous f := sorry
theorem continuous_subtype_is_closed_cover {α : Type u} {β : Type v} [topological_space α] [topological_space β] {ι : Type u_1} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite fun (i : ι) => set_of fun (x : α) => c i x) (h_is_closed : ∀ (i : ι), is_closed (set_of fun (x : α) => c i x)) (h_cover : ∀ (x : α), ∃ (i : ι), c i x) (f_cont : ∀ (i : ι), continuous fun (x : Subtype (c i)) => f ↑x) : continuous f := sorry
theorem closure_subtype {α : Type u} [topological_space α] {p : α → Prop} {x : Subtype fun (a : α) => p a} {s : set (Subtype fun (a : α) => p a)} : x ∈ closure s ↔ ↑x ∈ closure (coe '' s) :=
closure_induced fun (x y : Subtype fun (a : α) => p a) => subtype.eq
theorem quotient_map_quot_mk {α : Type u} [topological_space α] {r : α → α → Prop} : quotient_map (Quot.mk r) :=
{ left := quot.exists_rep, right := rfl }
theorem continuous_quot_mk {α : Type u} [topological_space α] {r : α → α → Prop} : continuous (Quot.mk r) :=
continuous_coinduced_rng
theorem continuous_quot_lift {α : Type u} {β : Type v} [topological_space α] [topological_space β] {r : α → α → Prop} {f : α → β} (hr : ∀ (a b : α), r a b → f a = f b) (h : continuous f) : continuous (Quot.lift f hr) :=
continuous_coinduced_dom h
theorem quotient_map_quotient_mk {α : Type u} [topological_space α] {s : setoid α} : quotient_map quotient.mk :=
quotient_map_quot_mk
theorem continuous_quotient_mk {α : Type u} [topological_space α] {s : setoid α} : continuous quotient.mk :=
continuous_coinduced_rng
theorem continuous_quotient_lift {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : setoid α} {f : α → β} (hs : ∀ (a b : α), a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs) :=
continuous_coinduced_dom h
theorem continuous_pi {α : Type u} {ι : Type u_1} {π : ι → Type u_2} [topological_space α] [(i : ι) → topological_space (π i)] {f : α → (i : ι) → π i} (h : ∀ (i : ι), continuous fun (a : α) => f a i) : continuous f :=
continuous_infi_rng fun (i : ι) => continuous_induced_rng (h i)
theorem continuous_apply {ι : Type u_1} {π : ι → Type u_2} [(i : ι) → topological_space (π i)] (i : ι) : continuous fun (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. -/
theorem continuous_update {ι : Type u_1} {π : ι → Type u_2} [DecidableEq ι] [(i : ι) → topological_space (π i)] {i : ι} {f : (i : ι) → π i} : continuous fun (x : π i) => function.update f i x := sorry
theorem nhds_pi {ι : Type u_1} {π : ι → Type u_2} [t : (i : ι) → topological_space (π i)] {a : (i : ι) → π i} : nhds a = infi fun (i : ι) => filter.comap (fun (x : (i : ι) → π i) => x i) (nhds (a i)) := sorry
theorem tendsto_pi {α : Type u} {ι : Type u_1} {π : ι → Type u_2} [t : (i : ι) → topological_space (π i)] {f : α → (i : ι) → π i} {g : (i : ι) → π i} {u : filter α} : filter.tendsto f u (nhds g) ↔ ∀ (x : ι), filter.tendsto (fun (i : α) => f i x) u (nhds (g x)) := sorry
theorem is_open_set_pi {ι : Type u_1} {π : ι → Type u_2} [(a : ι) → topological_space (π a)] {i : set ι} {s : (a : ι) → set (π a)} (hi : set.finite i) (hs : ∀ (a : ι), a ∈ i → is_open (s a)) : is_open (set.pi i s) :=
eq.mpr (id (Eq._oldrec (Eq.refl (is_open (set.pi i s))) (set.pi_def i s)))
(is_open_bInter hi fun (a : ι) (ha : a ∈ i) => is_open.preimage (continuous_apply a) (hs a ha))
theorem set_pi_mem_nhds {ι : Type u_1} {π : ι → Type u_2} [(a : ι) → topological_space (π a)] {i : set ι} {s : (a : ι) → set (π a)} {x : (a : ι) → π a} (hi : set.finite i) (hs : ∀ (a : ι), a ∈ i → s a ∈ nhds (x a)) : set.pi i s ∈ nhds x := sorry
theorem pi_eq_generate_from {ι : Type u_1} {π : ι → Type u_2} [(a : ι) → topological_space (π a)] : Pi.topological_space =
topological_space.generate_from
(set_of
fun (g : set ((a : ι) → π a)) =>
∃ (s : (a : ι) → set (π a)), ∃ (i : finset ι), (∀ (a : ι), a ∈ i → is_open (s a)) ∧ g = set.pi (↑i) s) := sorry
theorem pi_generate_from_eq {ι : Type u_1} {π : ι → Type u_2} {g : (a : ι) → set (set (π a))} : Pi.topological_space =
topological_space.generate_from
(set_of
fun (t : set ((a : ι) → π a)) =>
∃ (s : (a : ι) → set (π a)), ∃ (i : finset ι), (∀ (a : ι), a ∈ i → s a ∈ g a) ∧ t = set.pi (↑i) s) := sorry
theorem pi_generate_from_eq_fintype {ι : Type u_1} {π : ι → Type u_2} {g : (a : ι) → set (set (π a))} [fintype ι] (hg : ∀ (a : ι), ⋃₀g a = set.univ) : Pi.topological_space =
topological_space.generate_from
(set_of
fun (t : set ((a : ι) → π a)) => ∃ (s : (a : ι) → set (π a)), (∀ (a : ι), s a ∈ g a) ∧ t = set.pi set.univ s) := sorry
theorem continuous_sigma_mk {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] {i : ι} : continuous (sigma.mk i) :=
continuous_supr_rng continuous_coinduced_rng
theorem is_open_sigma_iff {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] {s : set (sigma σ)} : is_open s ↔ ∀ (i : ι), is_open (sigma.mk i ⁻¹' s) := sorry
theorem is_closed_sigma_iff {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] {s : set (sigma σ)} : is_closed s ↔ ∀ (i : ι), is_closed (sigma.mk i ⁻¹' s) :=
is_open_sigma_iff
theorem is_open_map_sigma_mk {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] {i : ι} : is_open_map (sigma.mk i) := sorry
theorem is_open_range_sigma_mk {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] {i : ι} : is_open (set.range (sigma.mk i)) :=
eq.mpr (id (Eq._oldrec (Eq.refl (is_open (set.range (sigma.mk i)))) (Eq.symm set.image_univ)))
(is_open_map_sigma_mk set.univ is_open_univ)
theorem is_closed_map_sigma_mk {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] {i : ι} : is_closed_map (sigma.mk i) := sorry
theorem is_closed_sigma_mk {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] {i : ι} : is_closed (set.range (sigma.mk i)) :=
eq.mpr (id (Eq._oldrec (Eq.refl (is_closed (set.range (sigma.mk i)))) (Eq.symm set.image_univ)))
(is_closed_map_sigma_mk set.univ is_closed_univ)
theorem open_embedding_sigma_mk {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] {i : ι} : open_embedding (sigma.mk i) :=
open_embedding_of_continuous_injective_open continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk
theorem closed_embedding_sigma_mk {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] {i : ι} : closed_embedding (sigma.mk i) :=
closed_embedding_of_continuous_injective_closed continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk
theorem embedding_sigma_mk {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] {i : ι} : embedding (sigma.mk i) :=
closed_embedding.to_embedding closed_embedding_sigma_mk
/-- A map out of a sum type is continuous if its restriction to each summand is. -/
theorem continuous_sigma {β : Type v} {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] [topological_space β] {f : sigma σ → β} (h : ∀ (i : ι), continuous fun (a : σ i) => f (sigma.mk i a)) : continuous f :=
continuous_supr_dom fun (i : ι) => continuous_coinduced_dom (h i)
theorem continuous_sigma_map {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] {κ : Type u_3} {τ : κ → Type u_4} [(k : κ) → topological_space (τ k)] {f₁ : ι → κ} {f₂ : (i : ι) → σ i → τ (f₁ i)} (hf : ∀ (i : ι), continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := sorry
theorem is_open_map_sigma {β : Type v} {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] [topological_space β] {f : sigma σ → β} (h : ∀ (i : ι), is_open_map fun (a : σ i) => f (sigma.mk i a)) : is_open_map f := sorry
/-- The sum of embeddings is an embedding. -/
theorem embedding_sigma_map {ι : Type u_1} {σ : ι → Type u_2} [(i : ι) → topological_space (σ i)] {τ : ι → Type u_3} [(i : ι) → topological_space (τ i)] {f : (i : ι) → σ i → τ i} (hf : ∀ (i : ι), embedding (f i)) : embedding (sigma.map id f) := sorry
theorem continuous_ulift_down {α : Type u} [topological_space α] : continuous ulift.down :=
continuous_induced_dom
theorem continuous_ulift_up {α : Type u} [topological_space α] : continuous ulift.up :=
continuous_induced_rng continuous_id
theorem mem_closure_of_continuous {α : Type u} {β : Type v} [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : set.maps_to f s (closure t)) : f a ∈ closure t :=
set.mem_of_mem_of_subset (set.mem_of_mem_of_subset (set.mem_image_of_mem f ha) (image_closure_subset_closure_image hf))
(closure_minimal (set.maps_to.image_subset h) is_closed_closure)
theorem mem_closure_of_continuous2 {α : Type u} {β : Type v} {γ : Type w} [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous fun (p : α × β) => f (prod.fst p) (prod.snd p)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀ (a : α), a ∈ s → ∀ (b : β), b ∈ t → f a b ∈ closure u) : f a b ∈ closure u := sorry
|
03a8f3f523dbdd7e323e9c48bd166bf12d2ec340 | df561f413cfe0a88b1056655515399c546ff32a5 | /3-multiplication-world/l1.lean | 0a95540acbd3bbf136cf926ea912a2f7bdd4623f | [] | no_license | nicholaspun/natural-number-game-solutions | 31d5158415c6f582694680044c5c6469032c2a06 | 1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0 | refs/heads/main | 1,675,123,625,012 | 1,607,633,548,000 | 1,607,633,548,000 | 318,933,860 | 3 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 126 | lean | lemma zero_mul (m : mynat) : 0 * m = 0 :=
begin
induction m with k Pk,
apply mul_zero,
rw mul_succ,
rw add_zero,
exact Pk,
end |
7fca00f694fc328cb206cf79678c948059555df5 | dc253be9829b840f15d96d986e0c13520b085033 | /homotopy/spherical_fibrations.hlean | 82b6380a9df82f3bcd48f5fab9b3ad7b2bbd4833 | [
"Apache-2.0"
] | permissive | cmu-phil/Spectral | 4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea | 3b078f5f1de251637decf04bd3fc8aa01930a6b3 | refs/heads/master | 1,685,119,195,535 | 1,684,169,772,000 | 1,684,169,772,000 | 46,450,197 | 42 | 13 | null | 1,505,516,767,000 | 1,447,883,921,000 | Lean | UTF-8 | Lean | false | false | 5,206 | hlean | import homotopy.join homotopy.smash types.nat.hott
open eq equiv trunc function bool join sphere sphere.ops prod
open pointed sigma smash is_trunc nat
namespace spherical_fibrations
/- classifying type of spherical fibrations -/
definition BG (n : ℕ) [is_succ n] : Type₁ :=
Σ(X : Type₀), ∥ X ≃ S (pred n) ∥
definition pointed_BG [instance] [constructor] (n : ℕ) [is_succ n] : pointed (BG n) :=
pointed.mk ⟨ S (pred n) , tr erfl ⟩
definition pBG [constructor] (n : ℕ) [is_succ n] : Type* := pointed.mk' (BG n)
definition G (n : ℕ) [is_succ n] : Type₁ :=
pt = pt :> BG n
definition G_char (n : ℕ) [is_succ n] : G n ≃ (S (pred n) ≃ S (pred n)) :=
calc
G n ≃ Σ(p : pType.carrier (S (pred n)) = pType.carrier (S (pred n))), _ : sigma_eq_equiv
... ≃ (pType.carrier (S (pred n)) = pType.carrier (S (pred n))) : sigma_equiv_of_is_contr_right _ _
... ≃ (S (pred n) ≃ S (pred n)) : eq_equiv_equiv
definition mirror (n : ℕ) [is_succ n] : S (pred n) → G n :=
begin
intro v, apply to_inv (G_char n),
exact sorry
end
/-
Can we give a fibration P : S n → Type, P base = F n = Ω(BF n) = (S. n ≃* S. n)
and total space sigma P ≃ G (n+1) = Ω(BG (n+1)) = (S n.+1 ≃ S .n+1)
Yes, let eval : BG (n+1) → S n be the evaluation map
-/
definition is_succ_1 [instance] : is_succ 1 := is_succ.mk 0
definition S_of_BG (n : ℕ) : Ω(pBG (n+1)) → S n :=
λ f, f..1 ▸ pt
definition BG_succ (n : ℕ) [H : is_succ n] : BG n → BG (n+1) :=
begin
induction H with n,
intro X, cases X with X p,
refine sigma.mk (susp X) _, induction p with f, apply tr,
exact susp.equiv f
end
/- classifying type of pointed spherical fibrations -/
definition BF (n : ℕ) : Type₁ :=
Σ(X : Type*), ∥ X ≃* S n ∥
definition pointed_BF [instance] [constructor] (n : ℕ) : pointed (BF n) :=
pointed.mk ⟨ S n , tr pequiv.rfl ⟩
definition pBF [constructor] (n : ℕ) : Type* := pointed.mk' (BF n)
definition BF_succ (n : ℕ) : BF n → BF (n+1) :=
begin
intro X, cases X with X p,
apply sigma.mk (susp X), induction p with f, apply tr,
apply susp.susp_pequiv f
end
definition BF_of_BG {n : ℕ} [H : is_succ n] : BG n → BF n :=
begin
induction H with n,
intro X, cases X with X p,
apply sigma.mk (pointed.MK (susp X) susp.north),
induction p with f, apply tr,
apply pequiv_of_equiv (susp.equiv f),
reflexivity
end
definition BG_of_BF {n : ℕ} : BF n → BG (n + 1) :=
begin
intro X, cases X with X hX,
apply sigma.mk (carrier X), induction hX with fX,
apply tr, exact fX
end
definition BG_mul {n m : ℕ} [Hn : is_succ n] [Hm : is_succ m] (X : BG n) (Y : BG m) :
BG (n + m) :=
begin
induction Hn with n, induction Hm with m,
cases X with X pX, cases Y with Y pY,
apply sigma.mk (join X Y),
induction pX with fX, induction pY with fY,
apply tr, rewrite [succ_add],
exact join_equiv_join fX fY ⬝e join_sphere n m
end
definition BF_mul {n m : ℕ} (X : BF n) (Y : BF m) : BF (n + m) :=
begin
cases X with X hX, cases Y with Y hY,
apply sigma.mk (smash X Y),
induction hX with fX, induction hY with fY, apply tr,
exact sorry -- needs smash.spheres : psmash (S. n) (S. m) ≃ S. (n + m)
end
definition BF_of_BG_mul (n m : ℕ) [is_succ n] [is_succ m] (X : BG n) (Y : BG m)
: BF_of_BG (BG_mul X Y) = BF_mul (BF_of_BG X) (BF_of_BG Y) :=
sorry
-- Thom spaces
namespace thom
variables {X : Type} {n : ℕ} (α : X → BF n)
-- the canonical section of an F-object
protected definition sec (x : X) : carrier (sigma.pr1 (α x)) :=
Point _
open pushout sigma
definition thom_space : Type :=
pushout (λx : X, ⟨x , thom.sec α x⟩) (const X unit.star)
end thom
/-
Things to do:
- Orientability and orientations
* Thom class u ∈ ~Hⁿ(Tξ)
* eventually prove Thom-Isomorphism (Rudyak IV.5.7)
- define BG∞ and BF∞ as colimits of BG n and BF n
- Ω(BF n) = ΩⁿSⁿ₁ + ΩⁿSⁿ₋₁ (self-maps of degree ±1)
- succ_BF n is (n - 2) connected (from Freudenthal)
- pfiber (BG_of_BF n) ≃* S. n
- π₁(BF n)=π₁(BG n)=ℤ/2ℤ
- double covers BSG and BSF
- O : BF n → BG 1 = Σ(A : Type), ∥ A = bool ∥
- BSG n = sigma O
- π₁(BSG n)=π₁(BSF n)=O
- BSO(n),
- find BF' n : Type₀ with BF' n ≃ BF n etc.
- canonical bundle γₙ : ℝP(n) → ℝP∞=BO(1) → Type₀
prove T(γₙ) = ℝP(n+1)
- BG∞ = BF∞ (in fact = BGL₁(S), the group of units of the sphere spectrum)
- clutching construction:
any f : S n → SG(n) gives S n.+1 → BSG(n) (mut.mut. for O(n),SO(n),etc.)
- all bundles on S 3 are trivial, incl. tangent bundle
- Adams' result on vector fields on spheres:
there are maximally ρ(n)-1 indep.sections of the tangent bundle of S (n-1)
where ρ(n) is the n'th Radon-Hurwitz number.→
-/
-- tangent bundle on S 2:
namespace two_sphere
definition tau : S 2 → BG 2 :=
begin
intro v, induction v with x, do 2 exact pt,
exact sorry
end
end two_sphere
end spherical_fibrations
|
245eaae49fd6e17d3cfeca8fd434086820c51ee0 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /stage0/src/Lean/Elab/Level.lean | 86906a3384aa6cbc9d78f5ca58440f44e76dbcf3 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,507 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.LevelDefEq
import Lean.Elab.Exception
import Lean.Elab.Log
namespace Lean
namespace Elab
namespace Level
structure Context :=
(ref : Syntax)
(levelNames : List Name)
structure State :=
(ngen : NameGenerator)
(mctx : MetavarContext)
abbrev LevelElabM := ReaderT Context (EStateM Exception State)
instance : MonadError LevelElabM :=
{ getRef := do ctx ← read; pure ctx.ref,
withRef := fun α ref x => adaptReader (fun (ctx : Context) => { ctx with ref := ref }) x,
addContext := fun ref msg => pure (ref, msg) }
instance : MonadNameGenerator LevelElabM :=
{ getNGen := do s ← get; pure s.ngen,
setNGen := fun ngen => modify fun s => { s with ngen := ngen } }
def mkFreshLevelMVar : LevelElabM Level := do
mvarId ← mkFreshId;
modify $ fun s => { s with mctx := s.mctx.addLevelMVarDecl mvarId };
pure $ mkLevelMVar mvarId
partial def elabLevel : Syntax → LevelElabM Level
| stx => withRef stx do
let kind := stx.getKind;
if kind == `Lean.Parser.Level.paren then
elabLevel (stx.getArg 1)
else if kind == `Lean.Parser.Level.max then do
let args := (stx.getArg 1).getArgs;
lvl ← elabLevel args.back;
args.foldrRangeM 0 (args.size - 1)
(fun stx lvl => do
arg ← elabLevel stx;
pure (mkLevelMax lvl arg))
lvl
else if kind == `Lean.Parser.Level.imax then do
let args := (stx.getArg 1).getArgs;
lvl ← elabLevel args.back;
args.foldrRangeM 0 (args.size - 1)
(fun stx lvl => do
arg ← elabLevel stx;
pure (mkLevelIMax lvl arg))
lvl
else if kind == `Lean.Parser.Level.hole then do
mkFreshLevelMVar
else if kind == numLitKind then do
match stx.isNatLit? with
| some val => pure (Level.ofNat val)
| none => throwIllFormedSyntax
else if kind == identKind then do
let paramName := stx.getId;
ctx ← read;
unless (ctx.levelNames.contains paramName) $ throwError ("unknown universe level " ++ paramName);
pure $ mkLevelParam paramName
else if kind == `Lean.Parser.Level.addLit then do
lvl ← elabLevel (stx.getArg 0);
match (stx.getArg 2).isNatLit? with
| some val => pure (lvl.addOffset val)
| none => throwIllFormedSyntax
else
throwError "unexpected universe level syntax kind"
end Level
export Level (LevelElabM)
end Elab
end Lean
|
db745bd96fe24cec68778cb8b2c388f2c414ae7b | 94e33a31faa76775069b071adea97e86e218a8ee | /src/analysis/calculus/tangent_cone.lean | 600f7a9a7b723701245a1465219568a4b9c480c7 | [
"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 | 19,939 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.convex.topology
import analysis.normed_space.basic
import analysis.specific_limits.basic
/-!
# Tangent cone
In this file, we define two predicates `unique_diff_within_at 𝕜 s x` and `unique_diff_on 𝕜 s`
ensuring that, if a function has two derivatives, then they have to coincide. As a direct
definition of this fact (quantifying on all target types and all functions) would depend on
universes, we use a more intrinsic definition: if all the possible tangent directions to the set
`s` at the point `x` span a dense subset of the whole subset, it is easy to check that the
derivative has to be unique.
Therefore, we introduce the set of all tangent directions, named `tangent_cone_at`,
and express `unique_diff_within_at` and `unique_diff_on` in terms of it.
One should however think of this definition as an implementation detail: the only reason to
introduce the predicates `unique_diff_within_at` and `unique_diff_on` is to ensure the uniqueness
of the derivative. This is why their names reflect their uses, and not how they are defined.
## Implementation details
Note that this file is imported by `fderiv.lean`. Hence, derivatives are not defined yet. The
property of uniqueness of the derivative is therefore proved in `fderiv.lean`, but based on the
properties of the tangent cone we prove here.
-/
variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
open filter set
open_locale topological_space
section tangent_cone
variables {E : Type*} [add_comm_monoid E] [module 𝕜 E] [topological_space E]
/-- The set of all tangent directions to the set `s` at the point `x`. -/
def tangent_cone_at (s : set E) (x : E) : set E :=
{y : E | ∃(c : ℕ → 𝕜) (d : ℕ → E), (∀ᶠ n in at_top, x + d n ∈ s) ∧
(tendsto (λn, ∥c n∥) at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))}
/-- A property ensuring that the tangent cone to `s` at `x` spans a dense subset of the whole space.
The main role of this property is to ensure that the differential within `s` at `x` is unique,
hence this name. The uniqueness it asserts is proved in `unique_diff_within_at.eq` in `fderiv.lean`.
To avoid pathologies in dimension 0, we also require that `x` belongs to the closure of `s` (which
is automatic when `E` is not `0`-dimensional).
-/
@[mk_iff] structure unique_diff_within_at (s : set E) (x : E) : Prop :=
(dense_tangent_cone : dense ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E))
(mem_closure : x ∈ closure s)
/-- A property ensuring that the tangent cone to `s` at any of its points spans a dense subset of
the whole space. The main role of this property is to ensure that the differential along `s` is
unique, hence this name. The uniqueness it asserts is proved in `unique_diff_on.eq` in
`fderiv.lean`. -/
def unique_diff_on (s : set E) : Prop :=
∀x ∈ s, unique_diff_within_at 𝕜 s x
end tangent_cone
variables {E : Type*} [normed_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F]
variables {G : Type*} [normed_group G] [normed_space ℝ G]
variables {𝕜} {x y : E} {s t : set E}
section tangent_cone
/- This section is devoted to the properties of the tangent cone. -/
open normed_field
lemma tangent_cone_univ : tangent_cone_at 𝕜 univ x = univ :=
begin
refine univ_subset_iff.1 (λy hy, _),
rcases exists_one_lt_norm 𝕜 with ⟨w, hw⟩,
refine ⟨λn, w^n, λn, (w^n)⁻¹ • y, univ_mem' (λn, mem_univ _), _, _⟩,
{ simp only [norm_pow],
exact tendsto_pow_at_top_at_top_of_one_lt hw },
{ convert tendsto_const_nhds,
ext n,
have : w ^ n * (w ^ n)⁻¹ = 1,
{ apply mul_inv_cancel,
apply pow_ne_zero,
simpa [norm_eq_zero] using (ne_of_lt (lt_trans zero_lt_one hw)).symm },
rw [smul_smul, this, one_smul] }
end
lemma tangent_cone_mono (h : s ⊆ t) :
tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x :=
begin
rintros y ⟨c, d, ds, ctop, clim⟩,
exact ⟨c, d, mem_of_superset ds (λn hn, h hn), ctop, clim⟩
end
/-- Auxiliary lemma ensuring that, under the assumptions defining the tangent cone,
the sequence `d` tends to 0 at infinity. -/
lemma tangent_cone_at.lim_zero {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E}
(hc : tendsto (λn, ∥c n∥) l at_top) (hd : tendsto (λn, c n • d n) l (𝓝 y)) :
tendsto d l (𝓝 0) :=
begin
have A : tendsto (λn, ∥c n∥⁻¹) l (𝓝 0) := tendsto_inv_at_top_zero.comp hc,
have B : tendsto (λn, ∥c n • d n∥) l (𝓝 ∥y∥) :=
(continuous_norm.tendsto _).comp hd,
have C : tendsto (λn, ∥c n∥⁻¹ * ∥c n • d n∥) l (𝓝 (0 * ∥y∥)) := A.mul B,
rw zero_mul at C,
have : ∀ᶠ n in l, ∥c n∥⁻¹ * ∥c n • d n∥ = ∥d n∥,
{ apply (eventually_ne_of_tendsto_norm_at_top hc 0).mono (λn hn, _),
rw [norm_smul, ← mul_assoc, inv_mul_cancel, one_mul],
rwa [ne.def, norm_eq_zero] },
have D : tendsto (λ n, ∥d n∥) l (𝓝 0) :=
tendsto.congr' this C,
rw tendsto_zero_iff_norm_tendsto_zero,
exact D
end
lemma tangent_cone_mono_nhds (h : 𝓝[s] x ≤ 𝓝[t] x) :
tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x :=
begin
rintros y ⟨c, d, ds, ctop, clim⟩,
refine ⟨c, d, _, ctop, clim⟩,
suffices : tendsto (λ n, x + d n) at_top (𝓝[t] x),
from tendsto_principal.1 (tendsto_inf.1 this).2,
refine (tendsto_inf.2 ⟨_, tendsto_principal.2 ds⟩).mono_right h,
simpa only [add_zero] using tendsto_const_nhds.add (tangent_cone_at.lim_zero at_top ctop clim)
end
/-- Tangent cone of `s` at `x` depends only on `𝓝[s] x`. -/
lemma tangent_cone_congr (h : 𝓝[s] x = 𝓝[t] x) :
tangent_cone_at 𝕜 s x = tangent_cone_at 𝕜 t x :=
subset.antisymm
(tangent_cone_mono_nhds $ le_of_eq h)
(tangent_cone_mono_nhds $ le_of_eq h.symm)
/-- Intersecting with a neighborhood of the point does not change the tangent cone. -/
lemma tangent_cone_inter_nhds (ht : t ∈ 𝓝 x) :
tangent_cone_at 𝕜 (s ∩ t) x = tangent_cone_at 𝕜 s x :=
tangent_cone_congr (nhds_within_restrict' _ ht).symm
/-- The tangent cone of a product contains the tangent cone of its left factor. -/
lemma subset_tangent_cone_prod_left {t : set F} {y : F} (ht : y ∈ closure t) :
linear_map.inl 𝕜 E F '' (tangent_cone_at 𝕜 s x) ⊆ tangent_cone_at 𝕜 (s ×ˢ t) (x, y) :=
begin
rintros _ ⟨v, ⟨c, d, hd, hc, hy⟩, rfl⟩,
have : ∀n, ∃d', y + d' ∈ t ∧ ∥c n • d'∥ < ((1:ℝ)/2)^n,
{ assume n,
rcases mem_closure_iff_nhds.1 ht _ (eventually_nhds_norm_smul_sub_lt (c n) y
(pow_pos one_half_pos n)) with ⟨z, hz, hzt⟩,
exact ⟨z - y, by simpa using hzt, by simpa using hz⟩ },
choose d' hd' using this,
refine ⟨c, λn, (d n, d' n), _, hc, _⟩,
show ∀ᶠ n in at_top, (x, y) + (d n, d' n) ∈ s ×ˢ t,
{ filter_upwards [hd] with n hn,
simp [hn, (hd' n).1] },
{ apply tendsto.prod_mk_nhds hy _,
refine squeeze_zero_norm (λn, (hd' n).2.le) _,
exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one }
end
/-- The tangent cone of a product contains the tangent cone of its right factor. -/
lemma subset_tangent_cone_prod_right {t : set F} {y : F}
(hs : x ∈ closure s) :
linear_map.inr 𝕜 E F '' (tangent_cone_at 𝕜 t y) ⊆ tangent_cone_at 𝕜 (s ×ˢ t) (x, y) :=
begin
rintros _ ⟨w, ⟨c, d, hd, hc, hy⟩, rfl⟩,
have : ∀n, ∃d', x + d' ∈ s ∧ ∥c n • d'∥ < ((1:ℝ)/2)^n,
{ assume n,
rcases mem_closure_iff_nhds.1 hs _ (eventually_nhds_norm_smul_sub_lt (c n) x
(pow_pos one_half_pos n)) with ⟨z, hz, hzs⟩,
exact ⟨z - x, by simpa using hzs, by simpa using hz⟩ },
choose d' hd' using this,
refine ⟨c, λn, (d' n, d n), _, hc, _⟩,
show ∀ᶠ n in at_top, (x, y) + (d' n, d n) ∈ s ×ˢ t,
{ filter_upwards [hd] with n hn,
simp [hn, (hd' n).1] },
{ apply tendsto.prod_mk_nhds _ hy,
refine squeeze_zero_norm (λn, (hd' n).2.le) _,
exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one }
end
/-- The tangent cone of a product contains the tangent cone of each factor. -/
lemma maps_to_tangent_cone_pi {ι : Type*} [decidable_eq ι] {E : ι → Type*}
[Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)]
{s : Π i, set (E i)} {x : Π i, E i} {i : ι} (hi : ∀ j ≠ i, x j ∈ closure (s j)) :
maps_to (linear_map.single i : E i →ₗ[𝕜] Π j, E j) (tangent_cone_at 𝕜 (s i) (x i))
(tangent_cone_at 𝕜 (set.pi univ s) x) :=
begin
rintros w ⟨c, d, hd, hc, hy⟩,
have : ∀ n (j ≠ i), ∃ d', x j + d' ∈ s j ∧ ∥c n • d'∥ < (1 / 2 : ℝ) ^ n,
{ assume n j hj,
rcases mem_closure_iff_nhds.1 (hi j hj) _ (eventually_nhds_norm_smul_sub_lt (c n) (x j)
(pow_pos one_half_pos n)) with ⟨z, hz, hzs⟩,
exact ⟨z - x j, by simpa using hzs, by simpa using hz⟩ },
choose! d' hd's hcd',
refine ⟨c, λ n, function.update (d' n) i (d n), hd.mono (λ n hn j hj', _), hc,
tendsto_pi_nhds.2 $ λ j, _⟩,
{ rcases em (j = i) with rfl|hj; simp * },
{ rcases em (j = i) with rfl|hj,
{ simp [hy] },
{ suffices : tendsto (λ n, c n • d' n j) at_top (𝓝 0), by simpa [hj],
refine squeeze_zero_norm (λ n, (hcd' n j hj).le) _,
exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } }
end
/-- If a subset of a real vector space contains an open segment, then the direction of this
segment belongs to the tangent cone at its endpoints. -/
lemma mem_tangent_cone_of_open_segment_subset {s : set G} {x y : G} (h : open_segment ℝ x y ⊆ s) :
y - x ∈ tangent_cone_at ℝ s x :=
begin
let c := λn:ℕ, (2:ℝ)^(n+1),
let d := λn:ℕ, (c n)⁻¹ • (y-x),
refine ⟨c, d, filter.univ_mem' (λn, h _), _, _⟩,
show x + d n ∈ open_segment ℝ x y,
{ rw open_segment_eq_image,
refine ⟨(c n)⁻¹, ⟨_, _⟩, _⟩,
{ rw inv_pos, apply pow_pos, norm_num },
{ apply inv_lt_one, apply one_lt_pow _ (nat.succ_ne_zero _), norm_num },
{ simp only [d, sub_smul, smul_sub, one_smul], abel } },
show filter.tendsto (λ (n : ℕ), ∥c n∥) filter.at_top filter.at_top,
{ have : (λ (n : ℕ), ∥c n∥) = c,
by { ext n, exact abs_of_nonneg (pow_nonneg (by norm_num) _) },
rw this,
exact (tendsto_pow_at_top_at_top_of_one_lt (by norm_num)).comp (tendsto_add_at_top_nat 1) },
show filter.tendsto (λ (n : ℕ), c n • d n) filter.at_top (𝓝 (y - x)),
{ have : (λ (n : ℕ), c n • d n) = (λn, y - x),
{ ext n,
simp only [d, smul_smul],
rw [mul_inv_cancel, one_smul],
exact pow_ne_zero _ (by norm_num) },
rw this,
apply tendsto_const_nhds }
end
/-- If a subset of a real vector space contains a segment, then the direction of this
segment belongs to the tangent cone at its endpoints. -/
lemma mem_tangent_cone_of_segment_subset {s : set G} {x y : G} (h : segment ℝ x y ⊆ s) :
y - x ∈ tangent_cone_at ℝ s x :=
mem_tangent_cone_of_open_segment_subset ((open_segment_subset_segment ℝ x y).trans h)
end tangent_cone
section unique_diff
/-!
### Properties of `unique_diff_within_at` and `unique_diff_on`
This section is devoted to properties of the predicates
`unique_diff_within_at` and `unique_diff_on`. -/
lemma unique_diff_on.unique_diff_within_at {s : set E} {x} (hs : unique_diff_on 𝕜 s) (h : x ∈ s) :
unique_diff_within_at 𝕜 s x :=
hs x h
lemma unique_diff_within_at_univ : unique_diff_within_at 𝕜 univ x :=
by { rw [unique_diff_within_at_iff, tangent_cone_univ], simp }
lemma unique_diff_on_univ : unique_diff_on 𝕜 (univ : set E) :=
λx hx, unique_diff_within_at_univ
lemma unique_diff_on_empty : unique_diff_on 𝕜 (∅ : set E) :=
λ x hx, hx.elim
lemma unique_diff_within_at.mono_nhds (h : unique_diff_within_at 𝕜 s x)
(st : 𝓝[s] x ≤ 𝓝[t] x) :
unique_diff_within_at 𝕜 t x :=
begin
simp only [unique_diff_within_at_iff] at *,
rw [mem_closure_iff_nhds_within_ne_bot] at h ⊢,
exact ⟨h.1.mono $ submodule.span_mono $ tangent_cone_mono_nhds st,
h.2.mono st⟩
end
lemma unique_diff_within_at.mono (h : unique_diff_within_at 𝕜 s x) (st : s ⊆ t) :
unique_diff_within_at 𝕜 t x :=
h.mono_nhds $ nhds_within_mono _ st
lemma unique_diff_within_at_congr (st : 𝓝[s] x = 𝓝[t] x) :
unique_diff_within_at 𝕜 s x ↔ unique_diff_within_at 𝕜 t x :=
⟨λ h, h.mono_nhds $ le_of_eq st, λ h, h.mono_nhds $ le_of_eq st.symm⟩
lemma unique_diff_within_at_inter (ht : t ∈ 𝓝 x) :
unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x :=
unique_diff_within_at_congr $ (nhds_within_restrict' _ ht).symm
lemma unique_diff_within_at.inter (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝 x) :
unique_diff_within_at 𝕜 (s ∩ t) x :=
(unique_diff_within_at_inter ht).2 hs
lemma unique_diff_within_at_inter' (ht : t ∈ 𝓝[s] x) :
unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x :=
unique_diff_within_at_congr $ (nhds_within_restrict'' _ ht).symm
lemma unique_diff_within_at.inter' (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝[s] x) :
unique_diff_within_at 𝕜 (s ∩ t) x :=
(unique_diff_within_at_inter' ht).2 hs
lemma unique_diff_within_at_of_mem_nhds (h : s ∈ 𝓝 x) : unique_diff_within_at 𝕜 s x :=
by simpa only [univ_inter] using unique_diff_within_at_univ.inter h
lemma is_open.unique_diff_within_at (hs : is_open s) (xs : x ∈ s) : unique_diff_within_at 𝕜 s x :=
unique_diff_within_at_of_mem_nhds (is_open.mem_nhds hs xs)
lemma unique_diff_on.inter (hs : unique_diff_on 𝕜 s) (ht : is_open t) : unique_diff_on 𝕜 (s ∩ t) :=
λx hx, (hs x hx.1).inter (is_open.mem_nhds ht hx.2)
lemma is_open.unique_diff_on (hs : is_open s) : unique_diff_on 𝕜 s :=
λx hx, is_open.unique_diff_within_at hs hx
/-- The product of two sets of unique differentiability at points `x` and `y` has unique
differentiability at `(x, y)`. -/
lemma unique_diff_within_at.prod {t : set F} {y : F}
(hs : unique_diff_within_at 𝕜 s x) (ht : unique_diff_within_at 𝕜 t y) :
unique_diff_within_at 𝕜 (s ×ˢ t) (x, y) :=
begin
rw [unique_diff_within_at_iff] at ⊢ hs ht,
rw [closure_prod_eq],
refine ⟨_, hs.2, ht.2⟩,
have : _ ≤ submodule.span 𝕜 (tangent_cone_at 𝕜 (s ×ˢ t) (x, y)) :=
submodule.span_mono (union_subset (subset_tangent_cone_prod_left ht.2)
(subset_tangent_cone_prod_right hs.2)),
rw [linear_map.span_inl_union_inr, set_like.le_def] at this,
exact (hs.1.prod ht.1).mono this
end
lemma unique_diff_within_at.univ_pi (ι : Type*) [fintype ι] (E : ι → Type*)
[Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)]
(s : Π i, set (E i)) (x : Π i, E i) (h : ∀ i, unique_diff_within_at 𝕜 (s i) (x i)) :
unique_diff_within_at 𝕜 (set.pi univ s) x :=
begin
classical,
simp only [unique_diff_within_at_iff, closure_pi_set] at h ⊢,
refine ⟨(dense_pi univ (λ i _, (h i).1)).mono _, λ i _, (h i).2⟩,
norm_cast,
simp only [← submodule.supr_map_single, supr_le_iff, linear_map.map_span, submodule.span_le,
← maps_to'],
exact λ i, (maps_to_tangent_cone_pi $ λ j hj, (h j).2).mono subset.rfl submodule.subset_span
end
lemma unique_diff_within_at.pi (ι : Type*) [fintype ι] (E : ι → Type*)
[Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)]
(s : Π i, set (E i)) (x : Π i, E i) (I : set ι)
(h : ∀ i ∈ I, unique_diff_within_at 𝕜 (s i) (x i)) :
unique_diff_within_at 𝕜 (set.pi I s) x :=
begin
classical,
rw [← set.univ_pi_piecewise],
refine unique_diff_within_at.univ_pi _ _ _ _ (λ i, _),
by_cases hi : i ∈ I; simp [*, unique_diff_within_at_univ],
end
/-- The product of two sets of unique differentiability is a set of unique differentiability. -/
lemma unique_diff_on.prod {t : set F} (hs : unique_diff_on 𝕜 s) (ht : unique_diff_on 𝕜 t) :
unique_diff_on 𝕜 (s ×ˢ t) :=
λ ⟨x, y⟩ h, unique_diff_within_at.prod (hs x h.1) (ht y h.2)
/-- The finite product of a family of sets of unique differentiability is a set of unique
differentiability. -/
lemma unique_diff_on.pi (ι : Type*) [fintype ι] (E : ι → Type*)
[Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)]
(s : Π i, set (E i)) (I : set ι) (h : ∀ i ∈ I, unique_diff_on 𝕜 (s i)) :
unique_diff_on 𝕜 (set.pi I s) :=
λ x hx, unique_diff_within_at.pi _ _ _ _ _ $ λ i hi, h i hi (x i) (hx i hi)
/-- The finite product of a family of sets of unique differentiability is a set of unique
differentiability. -/
lemma unique_diff_on.univ_pi (ι : Type*) [fintype ι] (E : ι → Type*)
[Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)]
(s : Π i, set (E i)) (h : ∀ i, unique_diff_on 𝕜 (s i)) :
unique_diff_on 𝕜 (set.pi univ s) :=
unique_diff_on.pi _ _ _ _ $ λ i _, h i
/-- In a real vector space, a convex set with nonempty interior is a set of unique
differentiability at every point of its closure. -/
theorem unique_diff_within_at_convex {s : set G} (conv : convex ℝ s) (hs : (interior s).nonempty)
{x : G} (hx : x ∈ closure s) : unique_diff_within_at ℝ s x :=
begin
rcases hs with ⟨y, hy⟩,
suffices : y - x ∈ interior (tangent_cone_at ℝ s x),
{ refine ⟨dense.of_closure _, hx⟩,
simp [(submodule.span ℝ (tangent_cone_at ℝ s x)).eq_top_of_nonempty_interior'
⟨y - x, interior_mono submodule.subset_span this⟩] },
rw [mem_interior_iff_mem_nhds],
replace hy : interior s ∈ 𝓝 y := is_open.mem_nhds is_open_interior hy,
apply mem_of_superset ((is_open_map_sub_right x).image_mem_nhds hy),
rintros _ ⟨z, zs, rfl⟩,
refine mem_tangent_cone_of_open_segment_subset (subset.trans _ interior_subset),
exact conv.open_segment_closure_interior_subset_interior hx zs,
end
/-- In a real vector space, a convex set with nonempty interior is a set of unique
differentiability. -/
theorem unique_diff_on_convex {s : set G} (conv : convex ℝ s) (hs : (interior s).nonempty) :
unique_diff_on ℝ s :=
λ x xs, unique_diff_within_at_convex conv hs (subset_closure xs)
lemma unique_diff_on_Ici (a : ℝ) : unique_diff_on ℝ (Ici a) :=
unique_diff_on_convex (convex_Ici a) $ by simp only [interior_Ici, nonempty_Ioi]
lemma unique_diff_on_Iic (a : ℝ) : unique_diff_on ℝ (Iic a) :=
unique_diff_on_convex (convex_Iic a) $ by simp only [interior_Iic, nonempty_Iio]
lemma unique_diff_on_Ioi (a : ℝ) : unique_diff_on ℝ (Ioi a) :=
is_open_Ioi.unique_diff_on
lemma unique_diff_on_Iio (a : ℝ) : unique_diff_on ℝ (Iio a) :=
is_open_Iio.unique_diff_on
lemma unique_diff_on_Icc {a b : ℝ} (hab : a < b) : unique_diff_on ℝ (Icc a b) :=
unique_diff_on_convex (convex_Icc a b) $ by simp only [interior_Icc, nonempty_Ioo, hab]
lemma unique_diff_on_Ico (a b : ℝ) : unique_diff_on ℝ (Ico a b) :=
if hab : a < b
then unique_diff_on_convex (convex_Ico a b) $ by simp only [interior_Ico, nonempty_Ioo, hab]
else by simp only [Ico_eq_empty hab, unique_diff_on_empty]
lemma unique_diff_on_Ioc (a b : ℝ) : unique_diff_on ℝ (Ioc a b) :=
if hab : a < b
then unique_diff_on_convex (convex_Ioc a b) $ by simp only [interior_Ioc, nonempty_Ioo, hab]
else by simp only [Ioc_eq_empty hab, unique_diff_on_empty]
lemma unique_diff_on_Ioo (a b : ℝ) : unique_diff_on ℝ (Ioo a b) :=
is_open_Ioo.unique_diff_on
/-- The real interval `[0, 1]` is a set of unique differentiability. -/
lemma unique_diff_on_Icc_zero_one : unique_diff_on ℝ (Icc (0:ℝ) 1) :=
unique_diff_on_Icc zero_lt_one
lemma unique_diff_within_at_Ioi (a : ℝ) : unique_diff_within_at ℝ (Ioi a) a :=
unique_diff_within_at_convex (convex_Ioi a) (by simp) (by simp)
lemma unique_diff_within_at_Iio (a : ℝ) : unique_diff_within_at ℝ (Iio a) a :=
unique_diff_within_at_convex (convex_Iio a) (by simp) (by simp)
end unique_diff
|
e23dafb6ae3e58d5a0fad1a2545862c6ac106a66 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/category_theory/linear/yoneda.lean | 9119efb0424e960bac94a3c1afae5a4c18bd244b | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 1,480 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.category.Module.basic
import category_theory.linear
import category_theory.preadditive.additive_functor
import category_theory.preadditive.opposite
/-!
# The Yoneda embedding for `R`-linear categories
The Yoneda embedding for `R`-linear categories `C`,
sends an object `X : C` to the `Module R`-valued presheaf on `C`,
with value on `Y : Cᵒᵖ` given by `Module.of R (unop Y ⟶ X)`.
TODO: `linear_yoneda R C` is `R`-linear.
TODO: In fact, `linear_yoneda` itself is additive and `R`-linear.
-/
namespace category_theory
open opposite
variables (R : Type*) [ring R] (C : Type*) [category C] [preadditive C] [linear R C]
/-- The Yoneda embedding for `R`-linear categories `C`,
sending an object `X : C` to the `Module R`-valued presheaf on `C`,
with value on `Y : Cᵒᵖ` given by `Module.of R (unop Y ⟶ X)`. -/
@[simps]
def linear_yoneda : C ⥤ Cᵒᵖ ⥤ Module R :=
{ obj := λ X,
{ obj := λ Y, Module.of R (unop Y ⟶ X),
map := λ Y Y' f, linear.left_comp R _ f.unop,
map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end,
map_id' := λ Y, begin ext, dsimp, erw [category.id_comp] end },
map := λ X X' f, { app := λ Y, linear.right_comp R _ f } }.
instance linear_yoneda_obj_additive (X : C) : ((linear_yoneda R C).obj X).additive := {}
end category_theory
|
0e6da67d253f01535ff7c2e47a043b1187732646 | 3f48345ac9bbaa421714efc9872a0409379bb4ae | /src/set_category/limits/Equalizer.lean | 96186ef90ab22eb0d69767ec7714c58362506707 | [] | no_license | QaisHamarneh/Coalgebra-in-Lean | b4318ee6d83780e5c734eb78fed98b1fe8016f7e | bd0452df98bc64b608e5dfd7babc42c301bb6a46 | refs/heads/master | 1,663,371,200,241 | 1,661,004,695,000 | 1,661,004,695,000 | 209,798,828 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,314 | lean | import tactic.tidy
import category_theory.category
import set_category.diagram_lemmas
import help_functions
namespace Equalizer
open set
diagram_lemmas
classical
function
help_functions
category_theory
universes v u
local notation f ` ⊚ `:80 g:80 := category_struct.comp g f
def is_equalizer {X : Type v} [category X]
{A B E : X} (f g : A ⟶ B)
(e : E ⟶ A) : Prop :=
f ⊚ e = g ⊚ e ∧
Π {Q : X} (q : Q ⟶ A),
f ⊚ q = g ⊚ q →
∃! h : Q ⟶ E, q = e ⊚ h
lemma equalizer_is_mono {X : Type v} [category X]
{A B E : X} (f₁ f₂ : A ⟶ B)
(e : E ⟶ A) (equaliz : is_equalizer f₁ f₂ e):
mono e :=
⟨
begin
intros Q g₁ g₂ m,
have s1 : f₁ ⊚ (e ⊚ g₁) = f₂ ⊚ (e ⊚ g₁) := by tidy,
have compit : _ := equaliz.2 (e ⊚ g₁) s1,
cases compit with h spec_h,
have g₁_h : g₁ = h := spec_h.2 g₁ rfl,
have g₂_h : g₂ = h := spec_h.2 g₂ m,
simp [g₁_h , g₂_h]
end
⟩
variables {A B : Type u}
variables (f g : A ⟶ B)
def equalizer_set : set A := λ a, f a = g a
lemma eqaulizer_set_is_equalizer :
is_equalizer f g ((equalizer_set f g) ↪ A) :=
let E := equalizer_set f g in
let e := E ↪ A in
⟨
have elements : ∀ a, (f ∘ e) a = (g ∘ e) a :=
λ a, a.property,
funext elements
,
begin
intros Q q fq_gq,
have s0 : ∀ b : Q , (f ⊚ q) b = (g ⊚ q) b :=
assume b, by rw fq_gq,
have s1 : ∀ b : Q , q b ∈ E :=
assume b, s0 b,
let h : Q → E := λ b, ⟨q b, s1 b⟩,
have q_eh : q = e ∘ h := by tidy,
use h,
split,
exact q_eh,
intros h₁ spec_h₁,
tidy,
have inj : injective e := inj_inclusion A E,
have ey_eh: e ∘ h₁ = e ∘ h := by rw [← spec_h₁ , q_eh],
have elements : ∀ b, (e ∘ h₁) b = (e ∘ h) b :=
assume a, by rw ey_eh,
dsimp at *,
solve_by_elim
end
⟩
end Equalizer |
4e6a17f1a78e70a6ec074ef7cd1ec60b3ae6b23f | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/ring_theory/derivation.lean | 275e5565368ad88048a5005b49f2e5a2dc96e3fe | [
"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 | 8,364 | lean | /-
Copyright © 2020 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nicolò Cavalleri
-/
import algebra.lie.of_associative
import ring_theory.algebra_tower
/-!
# Derivations
This file defines derivation. A derivation `D` from the `R`-algebra `A` to the `A`-module `M` is an
`R`-linear map that satisfy the Leibniz rule `D (a * b) = a * D b + D a * b`.
## Notation
The notation `⁅D1, D2⁆` is used for the commutator of two derivations.
TODO: this file is just a stub to go on with some PRs in the geometry section. It only
implements the definition of derivations in commutative algebra. This will soon change: as soon
as bimodules will be there in mathlib I will change this file to take into account the
non-commutative case. Any development on the theory of derivations is discouraged until the
definitive definition of derivation will be implemented.
-/
open algebra ring_hom
/-- `D : derivation R A M` is an `R`-linear map from `A` to `M` that satisfies the `leibniz`
equality.
TODO: update this when bimodules are defined. -/
@[protect_proj]
structure derivation (R : Type*) (A : Type*) [comm_semiring R] [comm_semiring A]
[algebra R A] (M : Type*) [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M]
[is_scalar_tower R A M]
extends A →ₗ[R] M :=
(leibniz' (a b : A) : to_fun (a * b) = a • to_fun b + b • to_fun a)
namespace derivation
section
variables {R : Type*} [comm_semiring R]
variables {A : Type*} [comm_semiring A] [algebra R A]
variables {M : Type*} [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M]
variables [is_scalar_tower R A M]
variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A)
instance : has_coe_to_fun (derivation R A M) := ⟨_, λ D, D.to_linear_map.to_fun⟩
instance has_coe_to_linear_map : has_coe (derivation R A M) (A →ₗ[R] M) :=
⟨λ D, D.to_linear_map⟩
@[simp] lemma to_fun_eq_coe : D.to_fun = ⇑D := rfl
@[simp, norm_cast]
lemma coe_fn_coe (f : derivation R A M) :
⇑(f : A →ₗ[R] M) = f := rfl
lemma coe_injective (H : ⇑D1 = D2) : D1 = D2 :=
by { cases D1, cases D2, congr', exact linear_map.coe_injective H }
@[ext] theorem ext (H : ∀ a, D1 a = D2 a) : D1 = D2 :=
coe_injective $ funext H
@[simp] lemma map_add : D (a + b) = D a + D b := is_add_hom.map_add D a b
@[simp] lemma map_zero : D 0 = 0 := is_add_monoid_hom.map_zero D
@[simp] lemma map_smul : D (r • a) = r • D a := linear_map.map_smul D r a
@[simp] lemma leibniz : D (a * b) = a • D b + b • D a := D.leibniz' _ _
@[simp] lemma map_one_eq_zero : D 1 = 0 :=
begin
have h : D 1 = D (1 * 1) := by rw mul_one,
rwa [leibniz D 1 1, one_smul, self_eq_add_right] at h
end
@[simp] lemma map_algebra_map : D (algebra_map R A r) = 0 :=
by rw [←mul_one r, ring_hom.map_mul, map_one, ←smul_def, map_smul, map_one_eq_zero, smul_zero]
instance : has_zero (derivation R A M) :=
⟨⟨(0 : A →ₗ[R] M), λ a b, by simp only [add_zero, linear_map.zero_apply,
linear_map.to_fun_eq_coe, smul_zero]⟩⟩
instance : inhabited (derivation R A M) := ⟨0⟩
instance : add_comm_monoid (derivation R A M) :=
{ add := λ D1 D2, ⟨D1 + D2, λ a b, by { simp only [leibniz, linear_map.add_apply,
linear_map.to_fun_eq_coe, coe_fn_coe, smul_add], cc }⟩,
add_assoc := λ D E F, ext $ λ a, add_assoc _ _ _,
zero_add := λ D, ext $ λ a, zero_add _,
add_zero := λ D, ext $ λ a, add_zero _,
add_comm := λ D E, ext $ λ a, add_comm _ _,
..derivation.has_zero }
@[simp] lemma add_apply : (D1 + D2) a = D1 a + D2 a := rfl
@[priority 100]
instance derivation.Rsemimodule : semimodule R (derivation R A M) :=
{ smul := λ r D, ⟨r • D, λ a b, by simp only [linear_map.smul_apply, leibniz,
linear_map.to_fun_eq_coe, smul_algebra_smul_comm, coe_fn_coe, smul_add, add_comm],⟩,
mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _,
one_smul := λ D, ext $ λ b, one_smul _ _,
smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _,
smul_zero := λ a, ext $ λ b, smul_zero _,
add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _,
zero_smul := λ D, ext $ λ b, zero_smul _ _ }
@[simp] lemma smul_to_linear_map_coe : ↑(r • D) = (r • D : A →ₗ[R] M) := rfl
@[simp] lemma Rsmul_apply : (r • D) a = r • D a := rfl
instance : semimodule A (derivation R A M) :=
{ smul := λ a D, ⟨a • D, λ b c, by { dsimp, simp only [smul_add, leibniz, smul_comm a, add_comm] }⟩,
mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _,
one_smul := λ D, ext $ λ b, one_smul A _,
smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _,
smul_zero := λ a, ext $ λ b, smul_zero _,
add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _,
zero_smul := λ D, ext $ λ b, zero_smul A _ }
@[simp] lemma smul_apply : (a • D) b = a • D b := rfl
instance : is_scalar_tower R A (derivation R A M) :=
⟨λ x y z, ext (λ a, smul_assoc _ _ _)⟩
end
section
variables {R : Type*} [comm_ring R]
variables {A : Type*} [comm_ring A] [algebra R A]
section
variables {M : Type*} [add_comm_group M] [module A M] [module R M] [is_scalar_tower R A M]
variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A)
@[simp] lemma map_neg : D (-a) = -D a := linear_map.map_neg D a
@[simp] lemma map_sub : D (a - b) = D a - D b := linear_map.map_sub D a b
instance : add_comm_group (derivation R A M) :=
{ neg := λ D, ⟨-D, λ a b, by simp only [linear_map.neg_apply, smul_neg, neg_add_rev, leibniz,
linear_map.to_fun_eq_coe, coe_fn_coe, add_comm]⟩,
sub := λ D1 D2, ⟨D1 - D2, λ a b, by { simp only [linear_map.to_fun_eq_coe, linear_map.sub_apply,
leibniz, coe_fn_coe, smul_sub], abel }⟩,
sub_eq_add_neg := λ D1 D2, ext (λ i, sub_eq_add_neg _ _),
add_left_neg := λ D, ext $ λ a, add_left_neg _,
..derivation.add_comm_monoid }
@[simp] lemma sub_apply : (D1 - D2) a = D1 a - D2 a := rfl
end
section lie_structures
/-! # Lie structures -/
variables (D : derivation R A A) {D1 D2 : derivation R A A} (r : R) (a b : A)
/-- The commutator of derivations is again a derivation. -/
def commutator (D1 D2 : derivation R A A) : derivation R A A :=
{ leibniz' := λ a b, by
{ simp only [ring.lie_def, map_add, id.smul_eq_mul, linear_map.mul_apply, leibniz,
linear_map.to_fun_eq_coe, coe_fn_coe, linear_map.sub_apply], ring, },
..⁅(D1 : module.End R A), (D2 : module.End R A)⁆, }
instance : has_bracket (derivation R A A) (derivation R A A) := ⟨derivation.commutator⟩
@[simp] lemma commutator_coe_linear_map :
↑⁅D1, D2⁆ = ⁅(D1 : module.End R A), (D2 : module.End R A)⁆ := rfl
lemma commutator_apply : ⁅D1, D2⁆ a = D1 (D2 a) - D2 (D1 a) := rfl
instance : lie_ring (derivation R A A) :=
{ add_lie := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, },
lie_add := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, },
lie_self := λ d, by { ext a, simp only [commutator_apply, add_apply, map_add], ring_nf, },
leibniz_lie := λ d e f,
by { ext a, simp only [commutator_apply, add_apply, sub_apply, map_sub], ring, } }
instance : lie_algebra R (derivation R A A) :=
{ lie_smul := λ r d e, by { ext a, simp only [commutator_apply, map_smul, smul_sub, Rsmul_apply]},
..derivation.Rsemimodule }
end lie_structures
end
end derivation
section comp_der
namespace linear_map
variables {R : Type*} [comm_semiring R]
variables {A : Type*} [comm_semiring A] [algebra R A]
variables {M : Type*} [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M]
variables {N : Type*} [add_cancel_comm_monoid N] [semimodule A N] [semimodule R N]
variables [is_scalar_tower R A M] [is_scalar_tower R A N]
/-- The composition of a linear map and a derivation is a derivation. -/
def comp_der (f : M →ₗ[A] N) (D : derivation R A M) : derivation R A N :=
{ to_fun := λ a, f (D a),
map_add' := λ a1 a2, by rw [D.map_add, f.map_add],
map_smul' := λ r a, by rw [derivation.map_smul, map_smul_of_tower],
leibniz' := λ a b, by simp only [derivation.leibniz, linear_map.map_smul, linear_map.map_add,
add_comm] }
@[simp] lemma comp_der_apply (f : M →ₗ[A] N) (D : derivation R A M) (a : A) :
f.comp_der D a = f (D a) := rfl
end linear_map
end comp_der
|
dddbfdb20e832df6bed6038a2fe9af63ec26fac9 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/field_theory/finite/polynomial.lean | 699e2be51408ac68369ceb53d77c834cd9df3781 | [
"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 | 7,966 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import linear_algebra.finite_dimensional
import linear_algebra.basic
import ring_theory.mv_polynomial.basic
import data.mv_polynomial.expand
import field_theory.finite.basic
/-!
## Polynomials over finite fields
-/
namespace mv_polynomial
variables {σ : Type*}
/-- A polynomial over the integers is divisible by `n : ℕ`
if and only if it is zero over `zmod n`. -/
lemma C_dvd_iff_zmod (n : ℕ) (φ : mv_polynomial σ ℤ) :
C (n:ℤ) ∣ φ ↔ map (int.cast_ring_hom (zmod n)) φ = 0 :=
C_dvd_iff_map_hom_eq_zero _ _ (char_p.int_cast_eq_zero_iff (zmod n) n) _
section frobenius
variables {p : ℕ} [fact p.prime]
lemma frobenius_zmod (f : mv_polynomial σ (zmod p)) : frobenius _ p f = expand p f :=
begin
apply induction_on f,
{ intro a, rw [expand_C, frobenius_def, ← C_pow, zmod.pow_card], },
{ simp only [alg_hom.map_add, ring_hom.map_add], intros _ _ hf hg, rw [hf, hg] },
{ simp only [expand_X, ring_hom.map_mul, alg_hom.map_mul],
intros _ _ hf, rw [hf, frobenius_def], },
end
lemma expand_zmod (f : mv_polynomial σ (zmod p)) : expand p f = f ^ p :=
(frobenius_zmod _).symm
end frobenius
end mv_polynomial
namespace mv_polynomial
noncomputable theory
open_locale big_operators classical
open set linear_map submodule
variables {K : Type*} {σ : Type*}
section indicator
variables [fintype K] [fintype σ]
/-- Over a field, this is the indicator function as an `mv_polynomial`. -/
def indicator [comm_ring K] (a : σ → K) : mv_polynomial σ K :=
∏ n, (1 - (X n - C (a n)) ^ (fintype.card K - 1))
section comm_ring
variables [comm_ring K]
lemma eval_indicator_apply_eq_one (a : σ → K) :
eval a (indicator a) = 1 :=
begin
nontriviality,
have : 0 < fintype.card K - 1 := tsub_pos_of_lt fintype.one_lt_card,
simp only [indicator, map_prod, map_sub, map_one, map_pow, eval_X, eval_C,
sub_self, zero_pow this, sub_zero, finset.prod_const_one]
end
lemma degrees_indicator (c : σ → K) :
degrees (indicator c) ≤ ∑ s : σ, (fintype.card K - 1) • {s} :=
begin
rw [indicator],
refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _),
refine le_trans (degrees_sub _ _) _,
rw [degrees_one, ← bot_eq_zero, bot_sup_eq],
refine le_trans (degrees_pow _ _) (nsmul_le_nsmul_of_le_right _ _),
refine le_trans (degrees_sub _ _) _,
rw [degrees_C, ← bot_eq_zero, sup_bot_eq],
exact degrees_X' _
end
lemma indicator_mem_restrict_degree (c : σ → K) :
indicator c ∈ restrict_degree σ K (fintype.card K - 1) :=
begin
rw [mem_restrict_degree_iff_sup, indicator],
assume n,
refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _),
simp_rw [ ← multiset.coe_count_add_monoid_hom, (multiset.count_add_monoid_hom n).map_sum,
add_monoid_hom.map_nsmul, multiset.coe_count_add_monoid_hom, nsmul_eq_mul, nat.cast_id],
transitivity,
refine finset.sum_eq_single n _ _,
{ assume b hb ne, rw [multiset.count_singleton, if_neg ne.symm, mul_zero] },
{ assume h, exact (h $ finset.mem_univ _).elim },
{ rw [multiset.count_singleton_self, mul_one] }
end
end comm_ring
variables [field K]
lemma eval_indicator_apply_eq_zero (a b : σ → K) (h : a ≠ b) :
eval a (indicator b) = 0 :=
begin
obtain ⟨i, hi⟩ : ∃ i, a i ≠ b i := by rwa [(≠), function.funext_iff, not_forall] at h,
simp only [indicator, map_prod, map_sub, map_one, map_pow, eval_X, eval_C,
sub_self, finset.prod_eq_zero_iff],
refine ⟨i, finset.mem_univ _, _⟩,
rw [finite_field.pow_card_sub_one_eq_one, sub_self],
rwa [(≠), sub_eq_zero],
end
end indicator
section
variables (K σ)
/-- `mv_polynomial.eval` as a `K`-linear map. -/
@[simps] def evalₗ [comm_semiring K] : mv_polynomial σ K →ₗ[K] (σ → K) → K :=
{ to_fun := λ p e, eval e p,
map_add' := λ p q, by { ext x, rw ring_hom.map_add, refl, },
map_smul' := λ a p, by { ext e, rw [smul_eq_C_mul, ring_hom.map_mul, eval_C], refl } }
end
variables [field K] [fintype K] [fintype σ]
lemma map_restrict_dom_evalₗ : (restrict_degree σ K (fintype.card K - 1)).map (evalₗ K σ) = ⊤ :=
begin
refine top_unique (set_like.le_def.2 $ assume e _, mem_map.2 _),
refine ⟨∑ n : σ → K, e n • indicator n, _, _⟩,
{ exact sum_mem (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) },
{ ext n,
simp only [linear_map.map_sum, @finset.sum_apply (σ → K) (λ_, K) _ _ _ _ _,
pi.smul_apply, linear_map.map_smul],
simp only [evalₗ_apply],
transitivity,
refine finset.sum_eq_single n (λ b _ h, _) _,
{ rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] },
{ exact λ h, (h $ finset.mem_univ n).elim },
{ rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } }
end
end mv_polynomial
namespace mv_polynomial
open_locale classical cardinal
open linear_map submodule
universe u
variables (σ : Type u) (K : Type u) [fintype K]
/-- The submodule of multivariate polynomials whose degree of each variable is strictly less
than the cardinality of K. -/
@[derive [add_comm_group, module K, inhabited]]
def R [comm_ring K] : Type u := restrict_degree σ K (fintype.card K - 1)
/-- Evaluation in the `mv_polynomial.R` subtype. -/
def evalᵢ [comm_ring K] : R σ K →ₗ[K] (σ → K) → K :=
((evalₗ K σ).comp (restrict_degree σ K (fintype.card K - 1)).subtype)
section comm_ring
variables [comm_ring K]
noncomputable instance decidable_restrict_degree (m : ℕ) :
decidable_pred (∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) :=
by simp only [set.mem_set_of_eq]; apply_instance
end comm_ring
variables [field K]
lemma dim_R [fintype σ] : module.rank K (R σ K) = fintype.card (σ → K) :=
calc module.rank K (R σ K) =
module.rank K (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} →₀ K) :
linear_equiv.dim_eq
(finsupp.supported_equiv_finsupp {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card K - 1 })
... = #{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} :
by rw [finsupp.dim_eq, dim_self, mul_one]
... = #{s : σ → ℕ | ∀ (n : σ), s n < fintype.card K } :
begin
refine quotient.sound ⟨equiv.subtype_equiv finsupp.equiv_fun_on_fintype $ assume f, _⟩,
refine forall_congr (assume n, le_tsub_iff_right _),
exact fintype.card_pos_iff.2 ⟨0⟩
end
... = #(σ → {n // n < fintype.card K}) :
(@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card K)).cardinal_eq
... = #(σ → fin (fintype.card K)) :
(equiv.arrow_congr (equiv.refl σ) (equiv.refl _)).cardinal_eq
... = #(σ → K) :
(equiv.arrow_congr (equiv.refl σ) (fintype.equiv_fin K).symm).cardinal_eq
... = fintype.card (σ → K) : cardinal.mk_fintype _
instance [fintype σ] : finite_dimensional K (R σ K) :=
is_noetherian.iff_fg.1 $ is_noetherian.iff_dim_lt_aleph_0.mpr
(by simpa only [dim_R] using cardinal.nat_lt_aleph_0 (fintype.card (σ → K)))
lemma finrank_R [fintype σ] : finite_dimensional.finrank K (R σ K) = fintype.card (σ → K) :=
finite_dimensional.finrank_eq_of_dim_eq (dim_R σ K)
lemma range_evalᵢ [fintype σ] : (evalᵢ σ K).range = ⊤ :=
begin
rw [evalᵢ, linear_map.range_comp, range_subtype],
exact map_restrict_dom_evalₗ
end
lemma ker_evalₗ [fintype σ] : (evalᵢ σ K).ker = ⊥ :=
begin
refine (ker_eq_bot_iff_range_eq_top_of_finrank_eq_finrank _).mpr (range_evalᵢ _ _),
rw [finite_dimensional.finrank_fintype_fun_eq_card, finrank_R]
end
lemma eq_zero_of_eval_eq_zero [fintype σ] (p : mv_polynomial σ K)
(h : ∀v:σ → K, eval v p = 0) (hp : p ∈ restrict_degree σ K (fintype.card K - 1)) :
p = 0 :=
let p' : R σ K := ⟨p, hp⟩ in
have p' ∈ (evalᵢ σ K).ker := funext h,
show p'.1 = (0 : R σ K).1, from congr_arg _ $ by rwa [ker_evalₗ, mem_bot] at this
end mv_polynomial
|
c0641016a9fe07a4e8401a92698383c04b54e4ac | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/fintype/card_auto.lean | 9aef04cdc0e5b4dfef4fd41cfdeb02a65a8f628d | [] | 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 | 16,962 | 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.algebra.big_operators.ring
import Mathlib.PostPort
universes u_1 u_4 u_2 u_3 u_5 u_6
namespace Mathlib
/-!
Results about "big operations" over a `fintype`, and consequent
results about cardinalities of certain types.
## Implementation note
This content had previously been in `data.fintype`, but was moved here to avoid
requiring `algebra.big_operators` (and hence many other imports) as a
dependency of `fintype`.
-/
namespace fintype
theorem prod_bool {α : Type u_1} [comm_monoid α] (f : Bool → α) :
(finset.prod finset.univ fun (b : Bool) => f b) = f tt * f false :=
sorry
theorem card_eq_sum_ones {α : Type u_1} [fintype α] :
card α = finset.sum finset.univ fun (a : α) => 1 :=
finset.card_eq_sum_ones finset.univ
theorem prod_extend_by_one {α : Type u_1} {ι : Type u_4} [DecidableEq ι] [fintype ι] [comm_monoid α]
(s : finset ι) (f : ι → α) :
(finset.prod finset.univ fun (i : ι) => ite (i ∈ s) (f i) 1) =
finset.prod s fun (i : ι) => f i :=
sorry
theorem sum_eq_zero {α : Type u_1} {M : Type u_4} [fintype α] [add_comm_monoid M] (f : α → M)
(h : ∀ (a : α), f a = 0) : (finset.sum finset.univ fun (a : α) => f a) = 0 :=
finset.sum_eq_zero fun (a : α) (ha : a ∈ finset.univ) => h a
theorem sum_congr {α : Type u_1} {M : Type u_4} [fintype α] [add_comm_monoid M] (f : α → M)
(g : α → M) (h : ∀ (a : α), f a = g a) :
(finset.sum finset.univ fun (a : α) => f a) = finset.sum finset.univ fun (a : α) => g a :=
finset.sum_congr rfl fun (a : α) (ha : a ∈ finset.univ) => h a
theorem sum_eq_single {α : Type u_1} {M : Type u_4} [fintype α] [add_comm_monoid M] {f : α → M}
(a : α) (h : ∀ (x : α), x ≠ a → f x = 0) : (finset.sum finset.univ fun (x : α) => f x) = f a :=
finset.sum_eq_single a (fun (x : α) (_x : x ∈ finset.univ) (hx : x ≠ a) => h x hx)
fun (ha : ¬a ∈ finset.univ) => false.elim (ha (finset.mem_univ a))
theorem sum_unique {β : Type u_2} {M : Type u_4} [add_comm_monoid M] [unique β] (f : β → M) :
(finset.sum finset.univ fun (x : β) => f x) = f Inhabited.default :=
sorry
/-- If a product of a `finset` of a subsingleton type has a given
value, so do the terms in that product. -/
theorem eq_of_subsingleton_of_sum_eq {M : Type u_4} [add_comm_monoid M] {ι : Type u_1}
[subsingleton ι] {s : finset ι} {f : ι → M} {b : M} (h : (finset.sum s fun (i : ι) => f i) = b)
(i : ι) (H : i ∈ s) : f i = b :=
finset.eq_of_card_le_one_of_sum_eq (finset.card_le_one_of_subsingleton s) h
end fintype
theorem is_compl.prod_mul_prod {α : Type u_1} {M : Type u_4} [fintype α] [DecidableEq α]
[comm_monoid M] {s : finset α} {t : finset α} (h : is_compl s t) (f : α → M) :
((finset.prod s fun (i : α) => f i) * finset.prod t fun (i : α) => f i) =
finset.prod finset.univ fun (i : α) => f i :=
sorry
theorem finset.prod_mul_prod_compl {α : Type u_1} {M : Type u_4} [fintype α] [DecidableEq α]
[comm_monoid M] (s : finset α) (f : α → M) :
((finset.prod s fun (i : α) => f i) * finset.prod (sᶜ) fun (i : α) => f i) =
finset.prod finset.univ fun (i : α) => f i :=
is_compl.prod_mul_prod is_compl_compl f
theorem finset.sum_compl_add_sum {α : Type u_1} {M : Type u_4} [fintype α] [DecidableEq α]
[add_comm_monoid M] (s : finset α) (f : α → M) :
((finset.sum (sᶜ) fun (i : α) => f i) + finset.sum s fun (i : α) => f i) =
finset.sum finset.univ fun (i : α) => f i :=
is_compl.sum_add_sum (is_compl.symm is_compl_compl) f
theorem fin.prod_univ_def {β : Type u_2} [comm_monoid β] {n : ℕ} (f : fin n → β) :
(finset.prod finset.univ fun (i : fin n) => f i) = list.prod (list.map f (list.fin_range n)) :=
sorry
theorem fin.sum_of_fn {β : Type u_2} [add_comm_monoid β] {n : ℕ} (f : fin n → β) :
list.sum (list.of_fn f) = finset.sum finset.univ fun (i : fin n) => f i :=
sorry
/-- A product of a function `f : fin 0 → β` is `1` because `fin 0` is empty -/
@[simp] theorem fin.prod_univ_zero {β : Type u_2} [comm_monoid β] (f : fin 0 → β) :
(finset.prod finset.univ fun (i : fin 0) => f i) = 1 :=
rfl
/-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the product of `f x`, for some `x : fin (n + 1)` times the remaining product -/
theorem fin.prod_univ_succ_above {β : Type u_2} [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β)
(x : fin (n + 1)) :
(finset.prod finset.univ fun (i : fin (n + 1)) => f i) =
f x * finset.prod finset.univ fun (i : fin n) => f (coe_fn (fin.succ_above x) i) :=
sorry
/-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the sum of `f x`, for some `x : fin (n + 1)` plus the remaining product -/
theorem fin.sum_univ_succ_above {β : Type u_2} [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β)
(x : fin (n + 1)) :
(finset.sum finset.univ fun (i : fin (n + 1)) => f i) =
f x + finset.sum finset.univ fun (i : fin n) => f (coe_fn (fin.succ_above x) i) :=
fin.prod_univ_succ_above (fun (i : fin (n + 1)) => f i) x
/-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the product of `f 0` plus the remaining product -/
theorem fin.prod_univ_succ {β : Type u_2} [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) :
(finset.prod finset.univ fun (i : fin (n + 1)) => f i) =
f 0 * finset.prod finset.univ fun (i : fin n) => f (fin.succ i) :=
fin.prod_univ_succ_above f 0
/-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the sum of `f 0` plus the remaining product -/
theorem fin.sum_univ_succ {β : Type u_2} [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) :
(finset.sum finset.univ fun (i : fin (n + 1)) => f i) =
f 0 + finset.sum finset.univ fun (i : fin n) => f (fin.succ i) :=
fin.sum_univ_succ_above f 0
/-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the product of `f (fin.last n)` plus the remaining product -/
theorem fin.prod_univ_cast_succ {β : Type u_2} [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) :
(finset.prod finset.univ fun (i : fin (n + 1)) => f i) =
(finset.prod finset.univ fun (i : fin n) => f (coe_fn fin.cast_succ i)) * f (fin.last n) :=
sorry
/-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the sum of `f (fin.last n)` plus the remaining sum -/
theorem fin.sum_univ_cast_succ {β : Type u_2} [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) :
(finset.sum finset.univ fun (i : fin (n + 1)) => f i) =
(finset.sum finset.univ fun (i : fin n) => f (coe_fn fin.cast_succ i)) + f (fin.last n) :=
fin.prod_univ_cast_succ fun (i : fin (n + 1)) => f i
@[simp] theorem fintype.card_sigma {α : Type u_1} (β : α → Type u_2) [fintype α]
[(a : α) → fintype (β a)] :
fintype.card (sigma β) = finset.sum finset.univ fun (a : α) => fintype.card (β a) :=
finset.card_sigma finset.univ fun (a : α) => (fun (_x : α) => finset.univ) a
-- FIXME ouch, this should be in the main file.
@[simp] theorem fintype.card_sum (α : Type u_1) (β : Type u_2) [fintype α] [fintype β] :
fintype.card (α ⊕ β) = fintype.card α + fintype.card β :=
sorry
@[simp] theorem finset.card_pi {α : Type u_1} [DecidableEq α] {δ : α → Type u_2} (s : finset α)
(t : (a : α) → finset (δ a)) :
finset.card (finset.pi s t) = finset.prod s fun (a : α) => finset.card (t a) :=
multiset.card_pi (finset.val s) fun (a : α) => (fun (a : α) => finset.val (t a)) a
@[simp] theorem fintype.card_pi_finset {α : Type u_1} [DecidableEq α] [fintype α] {δ : α → Type u_2}
(t : (a : α) → finset (δ a)) :
finset.card (fintype.pi_finset t) = finset.prod finset.univ fun (a : α) => finset.card (t a) :=
sorry
@[simp] theorem fintype.card_pi {α : Type u_1} {β : α → Type u_2} [DecidableEq α] [fintype α]
[f : (a : α) → fintype (β a)] :
fintype.card ((a : α) → β a) = finset.prod finset.univ fun (a : α) => fintype.card (β a) :=
fintype.card_pi_finset fun (_x : α) => finset.univ
-- FIXME ouch, this should be in the main file.
@[simp] theorem fintype.card_fun {α : Type u_1} {β : Type u_2} [DecidableEq α] [fintype α]
[fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α :=
sorry
@[simp] theorem card_vector {α : Type u_1} [fintype α] (n : ℕ) :
fintype.card (vector α n) = fintype.card α ^ n :=
sorry
@[simp] theorem finset.prod_attach_univ {α : Type u_1} {β : Type u_2} [fintype α] [comm_monoid β]
(f : (Subtype fun (a : α) => a ∈ finset.univ) → β) :
(finset.prod (finset.attach finset.univ)
fun (x : Subtype fun (a : α) => a ∈ finset.univ) => f x) =
finset.prod finset.univ fun (x : α) => f { val := x, property := finset.mem_univ x } :=
sorry
/-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`.
`univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ
in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and
`fintype.pi_finset t` is a `finset (Π a, t a)`. -/
theorem finset.prod_univ_pi {α : Type u_1} {β : Type u_2} [DecidableEq α] [fintype α]
[comm_monoid β] {δ : α → Type u_3} {t : (a : α) → finset (δ a)}
(f : ((a : α) → a ∈ finset.univ → δ a) → β) :
(finset.prod (finset.pi finset.univ t) fun (x : (a : α) → a ∈ finset.univ → δ a) => f x) =
finset.prod (fintype.pi_finset t)
fun (x : (a : α) → δ a) => f fun (a : α) (_x : a ∈ finset.univ) => x a :=
sorry
/-- The product over `univ` of a sum can be written as a sum over the product of sets,
`fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not
over `univ` -/
theorem finset.prod_univ_sum {α : Type u_1} {β : Type u_2} [DecidableEq α] [fintype α]
[comm_semiring β] {δ : α → Type u_1} [(a : α) → DecidableEq (δ a)] {t : (a : α) → finset (δ a)}
{f : (a : α) → δ a → β} :
(finset.prod finset.univ fun (a : α) => finset.sum (t a) fun (b : δ a) => f a b) =
finset.sum (fintype.pi_finset t)
fun (p : (a : α) → δ a) => finset.prod finset.univ fun (x : α) => f x (p x) :=
sorry
/-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n`
gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that
`x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead
a proof reducing to the usual binomial theorem to have a result over semirings. -/
theorem fintype.sum_pow_mul_eq_add_pow (α : Type u_1) [fintype α] {R : Type u_2} [comm_semiring R]
(a : R) (b : R) :
(finset.sum finset.univ
fun (s : finset α) => a ^ finset.card s * b ^ (fintype.card α - finset.card s)) =
(a + b) ^ fintype.card α :=
finset.sum_pow_mul_eq_add_pow a b finset.univ
theorem fin.sum_pow_mul_eq_add_pow {n : ℕ} {R : Type u_1} [comm_semiring R] (a : R) (b : R) :
(finset.sum finset.univ
fun (s : finset (fin n)) => a ^ finset.card s * b ^ (n - finset.card s)) =
(a + b) ^ n :=
sorry
theorem function.bijective.sum_comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} [fintype α]
[fintype β] [add_comm_monoid γ] {f : α → β} (hf : function.bijective f) (g : β → γ) :
(finset.sum finset.univ fun (i : α) => g (f i)) = finset.sum finset.univ fun (i : β) => g i :=
sorry
theorem equiv.sum_comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} [fintype α] [fintype β]
[add_comm_monoid γ] (e : α ≃ β) (f : β → γ) :
(finset.sum finset.univ fun (i : α) => f (coe_fn e i)) =
finset.sum finset.univ fun (i : β) => f i :=
function.bijective.sum_comp (equiv.bijective e) f
/-- It is equivalent to sum a function over `fin n` or `finset.range n`. -/
theorem fin.sum_univ_eq_sum_range {α : Type u_1} [add_comm_monoid α] (f : ℕ → α) (n : ℕ) :
(finset.sum finset.univ fun (i : fin n) => f ↑i) =
finset.sum (finset.range n) fun (i : ℕ) => f i :=
sorry
theorem finset.prod_fin_eq_prod_range {β : Type u_2} [comm_monoid β] {n : ℕ} (c : fin n → β) :
(finset.prod finset.univ fun (i : fin n) => c i) =
finset.prod (finset.range n)
fun (i : ℕ) =>
dite (i < n) (fun (h : i < n) => c { val := i, property := h }) fun (h : ¬i < n) => 1 :=
sorry
theorem finset.prod_subtype {α : Type u_1} {M : Type u_2} [comm_monoid M] {p : α → Prop}
{F : fintype (Subtype p)} (s : finset α) (h : ∀ (x : α), x ∈ s ↔ p x) (f : α → M) :
(finset.prod s fun (a : α) => f a) = finset.prod finset.univ fun (a : Subtype p) => f ↑a :=
sorry
theorem finset.sum_to_finset_eq_subtype {α : Type u_1} {M : Type u_2} [add_comm_monoid M]
[fintype α] (p : α → Prop) [decidable_pred p] (f : α → M) :
(finset.sum (set.to_finset (set_of fun (x : α) => p x)) fun (a : α) => f a) =
finset.sum finset.univ fun (a : Subtype p) => f ↑a :=
sorry
theorem finset.prod_fiberwise {α : Type u_1} {β : Type u_2} {γ : Type u_3} [DecidableEq β]
[fintype β] [comm_monoid γ] (s : finset α) (f : α → β) (g : α → γ) :
(finset.prod finset.univ
fun (b : β) =>
finset.prod (finset.filter (fun (a : α) => f a = b) s) fun (a : α) => g a) =
finset.prod s fun (a : α) => g a :=
finset.prod_fiberwise_of_maps_to (fun (x : α) (_x : x ∈ s) => finset.mem_univ (f x))
fun (a : α) => g a
theorem fintype.prod_fiberwise {α : Type u_1} {β : Type u_2} {γ : Type u_3} [fintype α]
[DecidableEq β] [fintype β] [comm_monoid γ] (f : α → β) (g : α → γ) :
(finset.prod finset.univ
fun (b : β) => finset.prod finset.univ fun (a : Subtype fun (a : α) => f a = b) => g ↑a) =
finset.prod finset.univ fun (a : α) => g a :=
sorry
theorem fintype.prod_dite {α : Type u_1} {β : Type u_2} [fintype α] {p : α → Prop}
[decidable_pred p] [comm_monoid β] (f : (a : α) → p a → β) (g : (a : α) → ¬p a → β) :
(finset.prod finset.univ fun (a : α) => dite (p a) (f a) (g a)) =
(finset.prod finset.univ
fun (a : Subtype fun (a : α) => p a) => f (↑a) (subtype.property a)) *
finset.prod finset.univ
fun (a : Subtype fun (a : α) => ¬p a) => g (↑a) (subtype.property a) :=
sorry
theorem fintype.sum_sum_elim {α₁ : Type u_4} {α₂ : Type u_5} {M : Type u_6} [fintype α₁]
[fintype α₂] [add_comm_monoid M] (f : α₁ → M) (g : α₂ → M) :
(finset.sum finset.univ fun (x : α₁ ⊕ α₂) => sum.elim f g x) =
(finset.sum finset.univ fun (a₁ : α₁) => f a₁) +
finset.sum finset.univ fun (a₂ : α₂) => g a₂ :=
sorry
theorem fintype.prod_sum_type {α₁ : Type u_4} {α₂ : Type u_5} {M : Type u_6} [fintype α₁]
[fintype α₂] [comm_monoid M] (f : α₁ ⊕ α₂ → M) :
(finset.prod finset.univ fun (x : α₁ ⊕ α₂) => f x) =
(finset.prod finset.univ fun (a₁ : α₁) => f (sum.inl a₁)) *
finset.prod finset.univ fun (a₂ : α₂) => f (sum.inr a₂) :=
sorry
namespace list
theorem prod_take_of_fn {α : Type u_1} [comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) :
prod (take i (of_fn f)) =
finset.prod (finset.filter (fun (j : fin n) => subtype.val j < i) finset.univ)
fun (j : fin n) => f j :=
sorry
-- `to_additive` does not work on `prod_take_of_fn` because of `0 : ℕ` in the proof.
-- Use `multiplicative` instead.
theorem sum_take_of_fn {α : Type u_1} [add_comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) :
sum (take i (of_fn f)) =
finset.sum (finset.filter (fun (j : fin n) => subtype.val j < i) finset.univ)
fun (j : fin n) => f j :=
prod_take_of_fn f i
theorem prod_of_fn {α : Type u_1} [comm_monoid α] {n : ℕ} {f : fin n → α} :
prod (of_fn f) = finset.prod finset.univ fun (i : fin n) => f i :=
sorry
theorem alternating_sum_eq_finset_sum {G : Type u_1} [add_comm_group G] (L : List G) :
alternating_sum L =
finset.sum finset.univ
fun (i : fin (length L)) => (-1) ^ ↑i •ℤ nth_le L (↑i) (fin.is_lt i) :=
sorry
theorem alternating_prod_eq_finset_prod {G : Type u_1} [comm_group G] (L : List G) :
alternating_prod L =
finset.prod finset.univ
fun (i : fin (length L)) => nth_le L (↑i) (subtype.property i) ^ (-1) ^ ↑i :=
sorry
end Mathlib |
850d075869dc7ce542acdb91051109d6d970e9fc | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /test/equiv_rw.lean | ae548862f15091e9e16141548b98d6e546f97289 | [
"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 | 10,258 | 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 tactic.equiv_rw
-- Uncomment this line to observe the steps of constructing appropriate equivalences.
-- set_option trace.equiv_rw_type true
-- This fails if we use `occurs` rather than `kdepends_on` in `equiv_rw_type`.
instance : equiv_functor set :=
{ map := λ α β e s, by { equiv_rw e.symm, assumption, } }
-- Rewriting a hypothesis along an equivalence.
example {α β : Type} (e : α ≃ β)
(f : α → ℕ) (h : ∀ b : β, f (e.symm b) = 0) (i : α) : f i = 0 :=
begin
equiv_rw e at i,
apply h,
end
-- Check that dependent hypotheses are reverted and reintroduced.
example {α β : Type} (e : α ≃ β) (Z : α → Type) (f : Π a, Z a → ℕ)
(h : ∀ (b : β) (x : Z (e.symm b)), f (e.symm b) x = 0)
(i : α) (x : Z i) : f i x = 0 :=
begin
equiv_rw e at i,
guard_hyp i : β,
guard_target f (e.symm i) x = 0,
guard_hyp x : Z ((e.symm) i),
exact h i x,
end
-- Rewriting the goal along an equivalence.
example {α β : Type} (e : α ≃ β) (b : β) : α :=
begin
equiv_rw e,
exact b,
end
-- Fail if the equivalence can't be used.
example {α β γ : Type} (e : β ≃ γ) (a : α) : α :=
begin
success_if_fail { equiv_rw e at a },
success_if_fail { equiv_rw e },
exact a,
end
-- Verify that `equiv_rw` will rewrite under `equiv_functor` instances.
example {α β : Type} (u : unique α) (e : α ≃ β) : β :=
begin
equiv_rw e at u,
apply inhabited.default,
end
example {α β : Type} (p : equiv.perm α) (e : α ≃ β) : equiv.perm β :=
begin
equiv_rw e at p,
exact p,
end
-- We can rewrite the goal under functors.
example {α β : Type} (e : α ≃ β) (b : β) : option α :=
begin
equiv_rw e,
exact some b,
end
-- We can rewrite hypotheses under functors.
example {α β : Type} (e : α ≃ β) (b : option α) : option β :=
begin
equiv_rw e at b,
exact b,
end
-- We can rewrite hypotheses under compositions of functors.
example {α β : Type} (e : α ≃ β) (b : list (list α)) : list β :=
begin
equiv_rw e at b,
exact b.join,
end
-- Check that we can rewrite in the target position of function types.
example {α β γ : Type} (e : α ≃ β) (f : γ → β) : γ → α :=
begin
equiv_rw e,
exact f,
end
-- Check that we can rewrite in the source position of function types.
example {α β γ : Type} (e : α ≃ β) (f : β → γ) : α → γ :=
begin
equiv_rw e,
exact f,
end
-- Rewriting under multiple functors.
example {α β : Type} (e : α ≃ β) (b : β) : list (option α) :=
begin
equiv_rw e,
exact [none, some b],
end
-- Rewriting under multiple functors, including functions.
example {α β γ : Type} (e : α ≃ β) (b : β) : γ → list (option α) :=
begin
equiv_rw e,
exact (λ g, [none, some b]),
end
-- Rewriting in multiple positions.
example {α β : Type*} [has_add β] (e : α ≃ β) : α → α :=
begin
have : (α → α) ≃ _, {
apply equiv.arrow_congr,
apply e,
apply e, },
equiv_rw e,
exact (@id β),
end
-- Rewriting in multiple positions.
example {α β : Type} [has_add β] (e : α ≃ β) : β → α → α :=
begin
equiv_rw e,
exact (+),
end
-- Rewriting in multiple positions.
example {α β : Type} [has_add β] (e : α ≃ β) : α → α → α :=
begin
equiv_rw e,
exact (+),
end
example {α β γ : Type} (e : α ≃ β) (s : β ⊕ γ) : α ⊕ γ :=
begin
equiv_rw e,
exact s,
end
example {α β γ : Type} (e : α ≃ β) (s : β ⊕ γ) : (α ⊕ γ) × (γ ⊕ α) :=
begin
equiv_rw e,
exact (s, s.swap),
end
example {α β γ : Type} (e : α ≃ β) (s : α ⊕ γ) : (β ⊕ γ) × (γ ⊕ β) :=
begin
equiv_rw e at s,
exact (s, s.swap),
end
example {α β γ : Type} (e : α ≃ β) (s : (α ⊕ γ) × β) : (β ⊕ γ) :=
begin
success_if_fail { equiv_rw e at s {max_depth := 4} },
equiv_rw e at s,
exact s.1,
end
-- Test generating the actual equivalence using `equiv_rw_type`.
example {α β : Type} (e : α ≃ β) (b : β) : α × (ℕ ⊕ ℕ) :=
begin
have e' : α × (ℕ ⊕ ℕ) ≃ _ := by equiv_rw_type e,
apply e'.inv_fun,
exact (b, sum.inl 0)
end
example {α β : Type} (e : α ≃ β) (P : α → Prop) (h : { a // P a }) : β :=
begin
equiv_rw e at h,
exact h.val,
end
example {α β : Type} (e : α ≃ β) (P : α → Prop) (h : ∀ a, P a) (b : β) : { a // P a } :=
begin
equiv_rw e,
use b,
apply h,
end
example {α β : Type} (e : α ≃ β) (P : α → Prop) (h : ∀ a : α, P a) (b : β) : P (e.symm b) :=
begin
equiv_rw e.symm at b,
exact h b,
end
example {α β : Type} (e : α ≃ β) (P : α → Sort*) (h : Π a : α, P a) (b : β) : P (e.symm b) :=
begin
-- this is a bit perverse, as `equiv_rw e.symm at b` is more natural,
-- but this tests rewriting in the argument of a dependent function
equiv_rw e at h,
exact h _,
end
-- a poor example, rewriting in the base of a dependent pair
example {α β : Type} (P : α → Type) (h : Σ a, P a) (e : α ≃ β) : β :=
begin
equiv_rw e at h,
exact h.1
end
-- rewriting in the argument of a dependent function can't be done in one step
example {α β γ : Type} (e : α ≃ β) (P : α → Type*) (h : Π a : α, (P a) × (option α)) (b : β) :
option β :=
begin
equiv_rw e at h,
have t := h b,
equiv_rw e at t,
exact t.2,
end
-- Demonstrate using `equiv_rw` to build new instances of `equiv_functor`
-- Observe that the next three declarations could easily be implemented by a tactic.
-- This has been automated in the `transport` branch,
-- so we won't attempt to write a deriver handler until we join with that.
def semigroup.map {α β : Type} (e : α ≃ β) : semigroup α → semigroup β :=
begin
intro S,
refine_struct { .. },
-- transport data fields using `equiv_rw`
{ have mul := S.mul,
equiv_rw e at mul,
-- This `equiv_rw` performs the following steps:
-- have e' := (equiv.arrow_congr' e (equiv.arrow_congr' e e)),
-- have h := (e'.symm_apply_apply mul).symm,
-- revert h,
-- generalize : (e' mul) = mul',
-- intro h,
-- clear_dependent mul,
-- rename mul' mul,
exact mul, },
-- transport axioms by simplifying, and applying the original axiom
{ intros, dsimp, simp, apply S.mul_assoc, }
end
example {α β : Type} (e : α ≃ β) (S : semigroup α) :
(semigroup.map e S).mul =
(equiv.arrow_congr' e (equiv.arrow_congr' e e)) has_mul.mul :=
rfl
example {α β : Type} (e : α ≃ β) (S : semigroup α) (x y : β) :
begin
haveI := semigroup.map e S,
exact x * y = e (e.symm x * e.symm y)
end :=
rfl
lemma semigroup.id_map (α : Type) : semigroup.map (equiv.refl α) = id :=
by { ext, refl, }
lemma semigroup.map_map {α β γ : Type} (e : α ≃ β) (f : β ≃ γ) :
semigroup.map (e.trans f) = (semigroup.map f) ∘ (semigroup.map e) :=
by { ext, dsimp [semigroup.map], simp, }
-- TODO (after joining the `transport` branch) create a derive handler for this
instance : equiv_functor semigroup :=
{ map := λ α β e, semigroup.map e,
map_refl' := semigroup.id_map,
map_trans' := λ α β γ e f, semigroup.map_map e f, }
-- Verify that we can now use `equiv_rw` under `semigroup`:
example {α : Type} [I : semigroup α] {β : Type} (e : α ≃ β) : semigroup β :=
begin
equiv_rw e at I,
exact I,
end
-- Now we do `monoid`, to try out a structure with constants.
-- The constructions and proofs here are written as uniformly as possible.
-- This example is the blueprint for the `transport` tactic.
mk_simp_attribute transport_simps' "simps useful inside `transport`"
attribute [transport_simps']
eq_rec_constant
cast_eq
equiv.to_fun_as_coe
equiv.arrow_congr'_apply
equiv.symm_apply_apply
equiv.apply_eq_iff_eq_symm_apply
def monoid.map {α β : Type} (e : α ≃ β) (S : monoid α) : monoid β :=
begin
refine_struct { .. },
{ have mul := S.mul, equiv_rw e at mul, exact mul, },
{ try { unfold_projs },
simp only with transport_simps',
have mul_assoc := S.mul_assoc,
equiv_rw e at mul_assoc,
solve_by_elim, },
{ have one := S.one, equiv_rw e at one, exact one, },
{ try { unfold_projs },
simp only with transport_simps,
have one_mul := S.one_mul,
equiv_rw e at one_mul,
solve_by_elim, },
{ try { unfold_projs },
simp only with transport_simps,
have mul_one := S.mul_one,
equiv_rw e at mul_one,
solve_by_elim, },
{ have npow := S.npow, equiv_rw e at npow, exact npow, },
{ try { unfold_projs },
simp only with transport_simps,
have npow_zero' := S.npow_zero',
equiv_rw e at npow_zero',
solve_by_elim, },
{ try { unfold_projs },
simp only with transport_simps,
have npow_succ' := S.npow_succ',
equiv_rw e at npow_succ',
solve_by_elim, },
end
example {α β : Type} (e : α ≃ β) (S : monoid α) :
(monoid.map e S).mul =
(equiv.arrow_congr' e (equiv.arrow_congr' e e)) has_mul.mul :=
rfl
example {α β : Type} (e : α ≃ β) (S : monoid α) (x y : β) :
begin
haveI := monoid.map e S,
exact x * y = e (e.symm x * e.symm y)
end :=
rfl
example {α β : Type} (e : α ≃ β) (S : monoid α) :
begin
haveI := monoid.map e S,
exact (1 : β) = e (1 : α)
end :=
rfl
example
{α : Type} {β : Type}
(m : α → α → α)
(e : α ≃ β) :
β → β → β :=
begin
equiv_rw e at m,
exact m,
end
-- This used to fail because metavariables were getting stuck!
example
{α : Type} {β : Type 2}
(m : α → α → α)
(e : α ≃ β) :
β → β → β :=
begin
equiv_rw e at m,
exact m,
end
-- Rewriting multiple equivalences on target
example
{α β χ δ : Type}
(m : β → β → δ → δ)
(e₁ : α ≃ β)
(e₂ : χ ≃ δ) :
α → α → χ → χ :=
begin
equiv_rw [e₁, e₂],
exact m,
end
-- Rewriting multiple equivalences on a hypothesis
example
{α β χ δ : Type}
(m : α → α → χ → χ)
(e₁ : α ≃ β)
(e₂ : χ ≃ δ) :
β → β → δ → δ :=
begin
equiv_rw [e₁, e₂] at m,
exact m,
end
example
{α β χ δ : Type}
(m : β → β → β)
(e : α ≃ β) :
α → α → α :=
begin
equiv_rw e at *,
exact m,
end
|
52dc6471c8e77d195fbad8bdde67a2e1b3a94dd2 | 618003631150032a5676f229d13a079ac875ff77 | /src/topology/metric_space/hausdorff_distance.lean | c843b8b8f6f2ad266f621998f080e3142ed5c2b5 | [
"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 | 32,383 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sébastien Gouëzel
-/
import topology.metric_space.isometry
import topology.instances.ennreal
/-!
# Hausdorff distance
The Hausdorff distance on subsets of a metric (or emetric) space.
Given two subsets `s` and `t` of a metric space, their Hausdorff distance is the smallest `d`
such that any point `s` is within `d` of a point in `t`, and conversely. This quantity
is often infinite (think of `s` bounded and `t` unbounded), and therefore better
expressed in the setting of emetric spaces.
## Main definitions
This files introduces:
* `inf_edist x s`, the infimum edistance of a point `x` to a set `s` in an emetric space
* `Hausdorff_edist s t`, the Hausdorff edistance of two sets in an emetric space
* Versions of these notions on metric spaces, called respectively `inf_dist` and
`Hausdorff_dist`.
-/
noncomputable theory
open_locale classical
universes u v w
open classical set function topological_space filter
namespace emetric
section inf_edist
open_locale ennreal
variables {α : Type u} {β : Type v} [emetric_space α] [emetric_space β] {x y : α} {s t : set α} {Φ : α → β}
/-- The minimal edistance of a point to a set -/
def inf_edist (x : α) (s : set α) : ennreal := Inf ((edist x) '' s)
@[simp] lemma inf_edist_empty : inf_edist x ∅ = ∞ :=
by unfold inf_edist; simp
/-- The edist to a union is the minimum of the edists -/
@[simp] lemma inf_edist_union : inf_edist x (s ∪ t) = inf_edist x s ⊓ inf_edist x t :=
by simp [inf_edist, image_union, Inf_union]
/-- The edist to a singleton is the edistance to the single point of this singleton -/
@[simp] lemma inf_edist_singleton : inf_edist x {y} = edist x y :=
by simp [inf_edist]
/-- The edist to a set is bounded above by the edist to any of its points -/
lemma inf_edist_le_edist_of_mem (h : y ∈ s) : inf_edist x s ≤ edist x y :=
Inf_le ((mem_image _ _ _).2 ⟨y, h, by refl⟩)
/-- If a point `x` belongs to `s`, then its edist to `s` vanishes -/
lemma inf_edist_zero_of_mem (h : x ∈ s) : inf_edist x s = 0 :=
le_zero_iff_eq.1 $ @edist_self _ _ x ▸ inf_edist_le_edist_of_mem h
/-- The edist is monotonous with respect to inclusion -/
lemma inf_edist_le_inf_edist_of_subset (h : s ⊆ t) : inf_edist x t ≤ inf_edist x s :=
Inf_le_Inf (image_subset _ h)
/-- If the edist to a set is `< r`, there exists a point in the set at edistance `< r` -/
lemma exists_edist_lt_of_inf_edist_lt {r : ennreal} (h : inf_edist x s < r) :
∃y∈s, edist x y < r :=
let ⟨t, ⟨ht, tr⟩⟩ := Inf_lt_iff.1 h in
let ⟨y, ⟨ys, hy⟩⟩ := (mem_image _ _ _).1 ht in
⟨y, ys, by rwa ← hy at tr⟩
/-- The edist of `x` to `s` is bounded by the sum of the edist of `y` to `s` and
the edist from `x` to `y` -/
lemma inf_edist_le_inf_edist_add_edist : inf_edist x s ≤ inf_edist y s + edist x y :=
begin
have : ∀z ∈ s, Inf (edist x '' s) ≤ edist y z + edist x y := λz hz, calc
Inf (edist x '' s) ≤ edist x z :
Inf_le ((mem_image _ _ _).2 ⟨z, hz, by refl⟩)
... ≤ edist x y + edist y z : edist_triangle _ _ _
... = edist y z + edist x y : add_comm _ _,
have : (λz, z + edist x y) (Inf (edist y '' s)) = Inf ((λz, z + edist x y) '' (edist y '' s)),
{ refine Inf_of_continuous _ _ (by simp),
{ exact continuous_id.add continuous_const },
{ assume a b h, simp, apply add_le_add_right' h }},
simp only [inf_edist] at this,
rw [inf_edist, inf_edist, this, ← image_comp],
simpa only [and_imp, function.comp_app, le_Inf_iff, exists_imp_distrib, ball_image_iff]
end
/-- The edist to a set depends continuously on the point -/
lemma continuous_inf_edist : continuous (λx, inf_edist x s) :=
continuous_of_le_add_edist 1 (by simp) $
by simp only [one_mul, inf_edist_le_inf_edist_add_edist, forall_2_true_iff]
/-- The edist to a set and to its closure coincide -/
lemma inf_edist_closure : inf_edist x (closure s) = inf_edist x s :=
begin
refine le_antisymm (inf_edist_le_inf_edist_of_subset subset_closure) _,
refine ennreal.le_of_forall_epsilon_le (λε εpos h, _),
have εpos' : (0 : ennreal) < ε := by simpa,
have : inf_edist x (closure s) < inf_edist x (closure s) + ε/2 :=
ennreal.lt_add_right h (ennreal.half_pos εpos'),
rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ycs, hy⟩,
-- y : α, ycs : y ∈ closure s, hy : edist x y < inf_edist x (closure s) + ↑ε / 2
rcases emetric.mem_closure_iff.1 ycs (ε/2) (ennreal.half_pos εpos') with ⟨z, zs, dyz⟩,
-- z : α, zs : z ∈ s, dyz : edist y z < ↑ε / 2
calc inf_edist x s ≤ edist x z : inf_edist_le_edist_of_mem zs
... ≤ edist x y + edist y z : edist_triangle _ _ _
... ≤ (inf_edist x (closure s) + ε / 2) + (ε/2) : add_le_add' (le_of_lt hy) (le_of_lt dyz)
... = inf_edist x (closure s) + ↑ε : by rw [add_assoc, ennreal.add_halves]
end
/-- A point belongs to the closure of `s` iff its infimum edistance to this set vanishes -/
lemma mem_closure_iff_inf_edist_zero : x ∈ closure s ↔ inf_edist x s = 0 :=
⟨λh, by rw ← inf_edist_closure; exact inf_edist_zero_of_mem h,
λh, emetric.mem_closure_iff.2 $ λε εpos, exists_edist_lt_of_inf_edist_lt (by rwa h)⟩
/-- Given a closed set `s`, a point belongs to `s` iff its infimum edistance to this set vanishes -/
lemma mem_iff_ind_edist_zero_of_closed (h : is_closed s) : x ∈ s ↔ inf_edist x s = 0 :=
begin
convert ← mem_closure_iff_inf_edist_zero,
exact closure_eq_iff_is_closed.2 h
end
/-- The infimum edistance is invariant under isometries -/
lemma inf_edist_image (hΦ : isometry Φ) :
inf_edist (Φ x) (Φ '' t) = inf_edist x t :=
begin
simp only [inf_edist],
apply congr_arg,
ext b, split,
{ assume hb,
rcases (mem_image _ _ _).1 hb with ⟨y, ⟨hy, hy'⟩⟩,
rcases (mem_image _ _ _).1 hy with ⟨z, ⟨hz, hz'⟩⟩,
rw [← hy', ← hz', hΦ x z],
exact mem_image_of_mem _ hz },
{ assume hb,
rcases (mem_image _ _ _).1 hb with ⟨y, ⟨hy, hy'⟩⟩,
rw [← hy', ← hΦ x y],
exact mem_image_of_mem _ (mem_image_of_mem _ hy) }
end
end inf_edist --section
/-- The Hausdorff edistance between two sets is the smallest `r` such that each set
is contained in the `r`-neighborhood of the other one -/
def Hausdorff_edist {α : Type u} [emetric_space α] (s t : set α) : ennreal :=
Sup ((λx, inf_edist x t) '' s) ⊔ Sup ((λx, inf_edist x s) '' t)
lemma Hausdorff_edist_def {α : Type u} [emetric_space α] (s t : set α) :
Hausdorff_edist s t = Sup ((λx, inf_edist x t) '' s) ⊔ Sup ((λx, inf_edist x s) '' t) := rfl
attribute [irreducible] Hausdorff_edist
section Hausdorff_edist
open_locale ennreal
variables {α : Type u} {β : Type v} [emetric_space α] [emetric_space β]
{x y : α} {s t u : set α} {Φ : α → β}
/-- The Hausdorff edistance of a set to itself vanishes -/
@[simp] lemma Hausdorff_edist_self : Hausdorff_edist s s = 0 :=
begin
erw [Hausdorff_edist_def, sup_idem, ← le_bot_iff],
apply Sup_le _,
simp [le_bot_iff, inf_edist_zero_of_mem, le_refl] {contextual := tt},
end
/-- The Haudorff edistances of `s` to `t` and of `t` to `s` coincide -/
lemma Hausdorff_edist_comm : Hausdorff_edist s t = Hausdorff_edist t s :=
by unfold Hausdorff_edist; apply sup_comm
/-- Bounding the Hausdorff edistance by bounding the edistance of any point
in each set to the other set -/
lemma Hausdorff_edist_le_of_inf_edist {r : ennreal}
(H1 : ∀x ∈ s, inf_edist x t ≤ r) (H2 : ∀x ∈ t, inf_edist x s ≤ r) :
Hausdorff_edist s t ≤ r :=
begin
simp only [Hausdorff_edist, -mem_image, set.ball_image_iff, Sup_le_iff, sup_le_iff],
exact ⟨H1, H2⟩
end
/-- Bounding the Hausdorff edistance by exhibiting, for any point in each set,
another point in the other set at controlled distance -/
lemma Hausdorff_edist_le_of_mem_edist {r : ennreal}
(H1 : ∀x ∈ s, ∃y ∈ t, edist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, edist x y ≤ r) :
Hausdorff_edist s t ≤ r :=
begin
refine Hausdorff_edist_le_of_inf_edist _ _,
{ assume x xs,
rcases H1 x xs with ⟨y, yt, hy⟩,
exact le_trans (inf_edist_le_edist_of_mem yt) hy },
{ assume x xt,
rcases H2 x xt with ⟨y, ys, hy⟩,
exact le_trans (inf_edist_le_edist_of_mem ys) hy }
end
/-- The distance to a set is controlled by the Hausdorff distance -/
lemma inf_edist_le_Hausdorff_edist_of_mem (h : x ∈ s) : inf_edist x t ≤ Hausdorff_edist s t :=
begin
rw Hausdorff_edist_def,
refine le_trans (le_Sup _) le_sup_left,
exact mem_image_of_mem _ h
end
/-- If the Hausdorff distance is `<r`, then any point in one of the sets has
a corresponding point at distance `<r` in the other set -/
lemma exists_edist_lt_of_Hausdorff_edist_lt {r : ennreal} (h : x ∈ s) (H : Hausdorff_edist s t < r) :
∃y∈t, edist x y < r :=
exists_edist_lt_of_inf_edist_lt $ calc
inf_edist x t ≤ Sup ((λx, inf_edist x t) '' s) : le_Sup (mem_image_of_mem _ h)
... ≤ Sup ((λx, inf_edist x t) '' s) ⊔ Sup ((λx, inf_edist x s) '' t) : le_sup_left
... < r : by rwa Hausdorff_edist_def at H
/-- The distance from `x` to `s`or `t` is controlled in terms of the Hausdorff distance
between `s` and `t` -/
lemma inf_edist_le_inf_edist_add_Hausdorff_edist :
inf_edist x t ≤ inf_edist x s + Hausdorff_edist s t :=
ennreal.le_of_forall_epsilon_le $ λε εpos h, begin
have εpos' : (0 : ennreal) < ε := by simpa,
have : inf_edist x s < inf_edist x s + ε/2 :=
ennreal.lt_add_right (ennreal.add_lt_top.1 h).1 (ennreal.half_pos εpos'),
rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, dxy⟩,
-- y : α, ys : y ∈ s, dxy : edist x y < inf_edist x s + ↑ε / 2
have : Hausdorff_edist s t < Hausdorff_edist s t + ε/2 :=
ennreal.lt_add_right (ennreal.add_lt_top.1 h).2 (ennreal.half_pos εpos'),
rcases exists_edist_lt_of_Hausdorff_edist_lt ys this with ⟨z, zt, dyz⟩,
-- z : α, zt : z ∈ t, dyz : edist y z < Hausdorff_edist s t + ↑ε / 2
calc inf_edist x t ≤ edist x z : inf_edist_le_edist_of_mem zt
... ≤ edist x y + edist y z : edist_triangle _ _ _
... ≤ (inf_edist x s + ε/2) + (Hausdorff_edist s t + ε/2) : add_le_add' (le_of_lt dxy) (le_of_lt dyz)
... = inf_edist x s + Hausdorff_edist s t + ε : by simp [ennreal.add_halves, add_comm, add_left_comm]
end
/-- The Hausdorff edistance is invariant under eisometries -/
lemma Hausdorff_edist_image (h : isometry Φ) :
Hausdorff_edist (Φ '' s) (Φ '' t) = Hausdorff_edist s t :=
begin
unfold Hausdorff_edist,
congr,
{ ext b,
split,
{ assume hb,
rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩,
rcases (mem_image _ _ _ ).1 hy with ⟨z, ⟨hz, hz'⟩⟩,
rw [← hy', ← hz', inf_edist_image h],
exact mem_image_of_mem _ hz },
{ assume hb,
rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩,
rw [← hy', ← inf_edist_image h],
exact mem_image_of_mem _ (mem_image_of_mem _ hy) }},
{ ext b,
split,
{ assume hb,
rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩,
rcases (mem_image _ _ _ ).1 hy with ⟨z, ⟨hz, hz'⟩⟩,
rw [← hy', ← hz', inf_edist_image h],
exact mem_image_of_mem _ hz },
{ assume hb,
rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩,
rw [← hy', ← inf_edist_image h],
exact mem_image_of_mem _ (mem_image_of_mem _ hy) }}
end
/-- The Hausdorff distance is controlled by the diameter of the union -/
lemma Hausdorff_edist_le_ediam (hs : s.nonempty) (ht : t.nonempty) : Hausdorff_edist s t ≤ diam (s ∪ t) :=
begin
rcases hs with ⟨x, xs⟩,
rcases ht with ⟨y, yt⟩,
refine Hausdorff_edist_le_of_mem_edist _ _,
{ exact λz hz, ⟨y, yt, edist_le_diam_of_mem (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ },
{ exact λz hz, ⟨x, xs, edist_le_diam_of_mem (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ }
end
/-- The Hausdorff distance satisfies the triangular inequality -/
lemma Hausdorff_edist_triangle : Hausdorff_edist s u ≤ Hausdorff_edist s t + Hausdorff_edist t u :=
begin
rw Hausdorff_edist_def,
simp only [and_imp, set.mem_image, Sup_le_iff, exists_imp_distrib,
sup_le_iff, -mem_image, set.ball_image_iff],
split,
show ∀x ∈ s, inf_edist x u ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xs, calc
inf_edist x u ≤ inf_edist x t + Hausdorff_edist t u : inf_edist_le_inf_edist_add_Hausdorff_edist
... ≤ Hausdorff_edist s t + Hausdorff_edist t u :
add_le_add_right' (inf_edist_le_Hausdorff_edist_of_mem xs),
show ∀x ∈ u, inf_edist x s ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xu, calc
inf_edist x s ≤ inf_edist x t + Hausdorff_edist t s : inf_edist_le_inf_edist_add_Hausdorff_edist
... ≤ Hausdorff_edist u t + Hausdorff_edist t s :
add_le_add_right' (inf_edist_le_Hausdorff_edist_of_mem xu)
... = Hausdorff_edist s t + Hausdorff_edist t u : by simp [Hausdorff_edist_comm, add_comm]
end
/-- The Hausdorff edistance between a set and its closure vanishes -/
@[simp, priority 1100]
lemma Hausdorff_edist_self_closure : Hausdorff_edist s (closure s) = 0 :=
begin
erw ← le_bot_iff,
simp only [Hausdorff_edist, inf_edist_closure, -le_zero_iff_eq, and_imp,
set.mem_image, Sup_le_iff, exists_imp_distrib, sup_le_iff,
set.ball_image_iff, ennreal.bot_eq_zero, -mem_image],
simp only [inf_edist_zero_of_mem, mem_closure_iff_inf_edist_zero, le_refl, and_self,
forall_true_iff] {contextual := tt}
end
/-- Replacing a set by its closure does not change the Hausdorff edistance. -/
@[simp] lemma Hausdorff_edist_closure₁ : Hausdorff_edist (closure s) t = Hausdorff_edist s t :=
begin
refine le_antisymm _ _,
{ calc _ ≤ Hausdorff_edist (closure s) s + Hausdorff_edist s t : Hausdorff_edist_triangle
... = Hausdorff_edist s t : by simp [Hausdorff_edist_comm] },
{ calc _ ≤ Hausdorff_edist s (closure s) + Hausdorff_edist (closure s) t : Hausdorff_edist_triangle
... = Hausdorff_edist (closure s) t : by simp }
end
/-- Replacing a set by its closure does not change the Hausdorff edistance. -/
@[simp] lemma Hausdorff_edist_closure₂ : Hausdorff_edist s (closure t) = Hausdorff_edist s t :=
by simp [@Hausdorff_edist_comm _ _ s _]
/-- The Hausdorff edistance between sets or their closures is the same -/
@[simp] lemma Hausdorff_edist_closure : Hausdorff_edist (closure s) (closure t) = Hausdorff_edist s t :=
by simp
/-- Two sets are at zero Hausdorff edistance if and only if they have the same closure -/
lemma Hausdorff_edist_zero_iff_closure_eq_closure : Hausdorff_edist s t = 0 ↔ closure s = closure t :=
⟨begin
assume h,
refine subset.antisymm _ _,
{ have : s ⊆ closure t := λx xs, mem_closure_iff_inf_edist_zero.2 $ begin
erw ← le_bot_iff,
have := @inf_edist_le_Hausdorff_edist_of_mem _ _ _ _ t xs,
rwa h at this,
end,
by rw ← @closure_closure _ _ t; exact closure_mono this },
{ have : t ⊆ closure s := λx xt, mem_closure_iff_inf_edist_zero.2 $ begin
erw ← le_bot_iff,
have := @inf_edist_le_Hausdorff_edist_of_mem _ _ _ _ s xt,
rw Hausdorff_edist_comm at h,
rwa h at this,
end,
by rw ← @closure_closure _ _ s; exact closure_mono this }
end,
λh, by rw [← Hausdorff_edist_closure, h, Hausdorff_edist_self]⟩
/-- Two closed sets are at zero Hausdorff edistance if and only if they coincide -/
lemma Hausdorff_edist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) :
Hausdorff_edist s t = 0 ↔ s = t :=
by rw [Hausdorff_edist_zero_iff_closure_eq_closure, closure_eq_iff_is_closed.2 hs,
closure_eq_iff_is_closed.2 ht]
/-- The Haudorff edistance to the empty set is infinite -/
lemma Hausdorff_edist_empty (ne : s.nonempty) : Hausdorff_edist s ∅ = ∞ :=
begin
rcases ne with ⟨x, xs⟩,
have : inf_edist x ∅ ≤ Hausdorff_edist s ∅ := inf_edist_le_Hausdorff_edist_of_mem xs,
simpa using this,
end
/-- If a set is at finite Hausdorff edistance of a nonempty set, it is nonempty -/
lemma nonempty_of_Hausdorff_edist_ne_top (hs : s.nonempty) (fin : Hausdorff_edist s t ≠ ⊤) :
t.nonempty :=
t.eq_empty_or_nonempty.elim (λ ht, (fin $ ht.symm ▸ Hausdorff_edist_empty hs).elim) id
lemma empty_or_nonempty_of_Hausdorff_edist_ne_top (fin : Hausdorff_edist s t ≠ ⊤) :
s = ∅ ∧ t = ∅ ∨ s.nonempty ∧ t.nonempty :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ cases t.eq_empty_or_nonempty with ht ht,
{ exact or.inl ⟨hs, ht⟩ },
{ rw Hausdorff_edist_comm at fin,
exact or.inr ⟨nonempty_of_Hausdorff_edist_ne_top ht fin, ht⟩ } },
{ exact or.inr ⟨hs, nonempty_of_Hausdorff_edist_ne_top hs fin⟩ }
end
end Hausdorff_edist -- section
end emetric --namespace
/-Now, we turn to the same notions in metric spaces. To avoid the difficulties related to
Inf and Sup on ℝ (which is only conditionnally complete), we use the notions in ennreal formulated
in terms of the edistance, and coerce them to ℝ. Then their properties follow readily from the
corresponding properties in ennreal, modulo some tedious rewriting of inequalities from one to the
other -/
namespace metric
section
variables {α : Type u} {β : Type v} [metric_space α] [metric_space β] {s t u : set α} {x y : α} {Φ : α → β}
open emetric
/-- The minimal distance of a point to a set -/
def inf_dist (x : α) (s : set α) : ℝ := ennreal.to_real (inf_edist x s)
/-- the minimal distance is always nonnegative -/
lemma inf_dist_nonneg : 0 ≤ inf_dist x s := by simp [inf_dist]
/-- the minimal distance to the empty set is 0 (if you want to have the more reasonable
value ∞ instead, use `inf_edist`, which takes values in ennreal) -/
@[simp] lemma inf_dist_empty : inf_dist x ∅ = 0 :=
by simp [inf_dist]
/-- In a metric space, the minimal edistance to a nonempty set is finite -/
lemma inf_edist_ne_top (h : s.nonempty) : inf_edist x s ≠ ⊤ :=
begin
rcases h with ⟨y, hy⟩,
apply lt_top_iff_ne_top.1,
calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem hy
... < ⊤ : lt_top_iff_ne_top.2 (edist_ne_top _ _)
end
/-- The minimal distance of a point to a set containing it vanishes -/
lemma inf_dist_zero_of_mem (h : x ∈ s) : inf_dist x s = 0 :=
by simp [inf_edist_zero_of_mem h, inf_dist]
/-- The minimal distance to a singleton is the distance to the unique point in this singleton -/
@[simp] lemma inf_dist_singleton : inf_dist x {y} = dist x y :=
by simp [inf_dist, inf_edist, dist_edist]
/-- The minimal distance to a set is bounded by the distance to any point in this set -/
lemma inf_dist_le_dist_of_mem (h : y ∈ s) : inf_dist x s ≤ dist x y :=
begin
rw [dist_edist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ⟨_, h⟩) (edist_ne_top _ _)],
exact inf_edist_le_edist_of_mem h
end
/-- The minimal distance is monotonous with respect to inclusion -/
lemma inf_dist_le_inf_dist_of_subset (h : s ⊆ t) (hs : s.nonempty) :
inf_dist x t ≤ inf_dist x s :=
begin
have ht : t.nonempty := hs.mono h,
rw [inf_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) (inf_edist_ne_top hs)],
exact inf_edist_le_inf_edist_of_subset h
end
/-- If the minimal distance to a set is `<r`, there exists a point in this set at distance `<r` -/
lemma exists_dist_lt_of_inf_dist_lt {r : real} (h : inf_dist x s < r) (hs : s.nonempty) :
∃y∈s, dist x y < r :=
begin
have rpos : 0 < r := lt_of_le_of_lt inf_dist_nonneg h,
have : inf_edist x s < ennreal.of_real r,
{ rwa [inf_dist, ← ennreal.to_real_of_real (le_of_lt rpos), ennreal.to_real_lt_to_real (inf_edist_ne_top hs)] at h,
simp },
rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, hy⟩,
rw [edist_dist, ennreal.of_real_lt_of_real_iff rpos] at hy,
exact ⟨y, ys, hy⟩,
end
/-- The minimal distance from `x` to `s` is bounded by the distance from `y` to `s`, modulo
the distance between `x` and `y` -/
lemma inf_dist_le_inf_dist_add_dist : inf_dist x s ≤ inf_dist y s + dist x y :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ by simp [hs, dist_nonneg] },
{ rw [inf_dist, inf_dist, dist_edist, ← ennreal.to_real_add (inf_edist_ne_top hs) (edist_ne_top _ _),
ennreal.to_real_le_to_real (inf_edist_ne_top hs)],
{ apply inf_edist_le_inf_edist_add_edist },
{ simp [ennreal.add_eq_top, inf_edist_ne_top hs, edist_ne_top] }}
end
variable (s)
/-- The minimal distance to a set is Lipschitz in point with constant 1 -/
lemma lipschitz_inf_dist_pt : lipschitz_with 1 (λx, inf_dist x s) :=
lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist
/-- The minimal distance to a set is uniformly continuous in point -/
lemma uniform_continuous_inf_dist_pt :
uniform_continuous (λx, inf_dist x s) :=
(lipschitz_inf_dist_pt s).uniform_continuous
/-- The minimal distance to a set is continuous in point -/
lemma continuous_inf_dist_pt : continuous (λx, inf_dist x s) :=
(uniform_continuous_inf_dist_pt s).continuous
variable {s}
/-- The minimal distance to a set and its closure coincide -/
lemma inf_dist_eq_closure : inf_dist x (closure s) = inf_dist x s :=
by simp [inf_dist, inf_edist_closure]
/-- A point belongs to the closure of `s` iff its infimum distance to this set vanishes -/
lemma mem_closure_iff_inf_dist_zero (h : s.nonempty) : x ∈ closure s ↔ inf_dist x s = 0 :=
by simp [mem_closure_iff_inf_edist_zero, inf_dist, ennreal.to_real_eq_zero_iff, inf_edist_ne_top h]
/-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/
lemma mem_iff_inf_dist_zero_of_closed (h : is_closed s) (hs : s.nonempty) :
x ∈ s ↔ inf_dist x s = 0 :=
begin
have := @mem_closure_iff_inf_dist_zero _ _ s x hs,
rwa closure_eq_iff_is_closed.2 h at this
end
/-- The infimum distance is invariant under isometries -/
lemma inf_dist_image (hΦ : isometry Φ) :
inf_dist (Φ x) (Φ '' t) = inf_dist x t :=
by simp [inf_dist, inf_edist_image hΦ]
/-- The Hausdorff distance between two sets is the smallest nonnegative `r` such that each set is
included in the `r`-neighborhood of the other. If there is no such `r`, it is defined to
be `0`, arbitrarily -/
def Hausdorff_dist (s t : set α) : ℝ := ennreal.to_real (Hausdorff_edist s t)
/-- The Hausdorff distance is nonnegative -/
lemma Hausdorff_dist_nonneg : 0 ≤ Hausdorff_dist s t :=
by simp [Hausdorff_dist]
/-- If two sets are nonempty and bounded in a metric space, they are at finite Hausdorff edistance -/
lemma Hausdorff_edist_ne_top_of_nonempty_of_bounded (hs : s.nonempty) (ht : t.nonempty)
(bs : bounded s) (bt : bounded t) : Hausdorff_edist s t ≠ ⊤ :=
begin
rcases hs with ⟨cs, hcs⟩,
rcases ht with ⟨ct, hct⟩,
rcases (bounded_iff_subset_ball ct).1 bs with ⟨rs, hrs⟩,
rcases (bounded_iff_subset_ball cs).1 bt with ⟨rt, hrt⟩,
have : Hausdorff_edist s t ≤ ennreal.of_real (max rs rt),
{ apply Hausdorff_edist_le_of_mem_edist,
{ assume x xs,
existsi [ct, hct],
have : dist x ct ≤ max rs rt := le_trans (hrs xs) (le_max_left _ _),
rwa [edist_dist, ennreal.of_real_le_of_real_iff],
exact le_trans dist_nonneg this },
{ assume x xt,
existsi [cs, hcs],
have : dist x cs ≤ max rs rt := le_trans (hrt xt) (le_max_right _ _),
rwa [edist_dist, ennreal.of_real_le_of_real_iff],
exact le_trans dist_nonneg this }},
exact ennreal.lt_top_iff_ne_top.1 (lt_of_le_of_lt this (by simp [lt_top_iff_ne_top]))
end
/-- The Hausdorff distance between a set and itself is zero -/
@[simp] lemma Hausdorff_dist_self_zero : Hausdorff_dist s s = 0 :=
by simp [Hausdorff_dist]
/-- The Hausdorff distance from `s` to `t` and from `t` to `s` coincide -/
lemma Hausdorff_dist_comm : Hausdorff_dist s t = Hausdorff_dist t s :=
by simp [Hausdorff_dist, Hausdorff_edist_comm]
/-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable
value ∞ instead, use `Hausdorff_edist`, which takes values in ennreal) -/
@[simp] lemma Hausdorff_dist_empty : Hausdorff_dist s ∅ = 0 :=
begin
cases s.eq_empty_or_nonempty with h h,
{ simp [h] },
{ simp [Hausdorff_dist, Hausdorff_edist_empty h] }
end
/-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable
value ∞ instead, use `Hausdorff_edist`, which takes values in ennreal) -/
@[simp] lemma Hausdorff_dist_empty' : Hausdorff_dist ∅ s = 0 :=
by simp [Hausdorff_dist_comm]
/-- Bounding the Hausdorff distance by bounding the distance of any point
in each set to the other set -/
lemma Hausdorff_dist_le_of_inf_dist {r : ℝ} (hr : r ≥ 0)
(H1 : ∀x ∈ s, inf_dist x t ≤ r) (H2 : ∀x ∈ t, inf_dist x s ≤ r) :
Hausdorff_dist s t ≤ r :=
begin
by_cases h1 : Hausdorff_edist s t = ⊤,
by rwa [Hausdorff_dist, h1, ennreal.top_to_real],
cases s.eq_empty_or_nonempty with hs hs,
by rwa [hs, Hausdorff_dist_empty'],
cases t.eq_empty_or_nonempty with ht ht,
by rwa [ht, Hausdorff_dist_empty],
have : Hausdorff_edist s t ≤ ennreal.of_real r,
{ apply Hausdorff_edist_le_of_inf_edist _ _,
{ assume x hx,
have I := H1 x hx,
rwa [inf_dist, ← ennreal.to_real_of_real hr,
ennreal.to_real_le_to_real (inf_edist_ne_top ht) ennreal.of_real_ne_top] at I },
{ assume x hx,
have I := H2 x hx,
rwa [inf_dist, ← ennreal.to_real_of_real hr,
ennreal.to_real_le_to_real (inf_edist_ne_top hs) ennreal.of_real_ne_top] at I }},
rwa [Hausdorff_dist, ← ennreal.to_real_of_real hr,
ennreal.to_real_le_to_real h1 ennreal.of_real_ne_top]
end
/-- Bounding the Hausdorff distance by exhibiting, for any point in each set,
another point in the other set at controlled distance -/
lemma Hausdorff_dist_le_of_mem_dist {r : ℝ} (hr : 0 ≤ r)
(H1 : ∀x ∈ s, ∃y ∈ t, dist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, dist x y ≤ r) :
Hausdorff_dist s t ≤ r :=
begin
apply Hausdorff_dist_le_of_inf_dist hr,
{ assume x xs,
rcases H1 x xs with ⟨y, yt, hy⟩,
exact le_trans (inf_dist_le_dist_of_mem yt) hy },
{ assume x xt,
rcases H2 x xt with ⟨y, ys, hy⟩,
exact le_trans (inf_dist_le_dist_of_mem ys) hy }
end
/-- The Hausdorff distance is controlled by the diameter of the union -/
lemma Hausdorff_dist_le_diam (hs : s.nonempty) (bs : bounded s) (ht : t.nonempty) (bt : bounded t) :
Hausdorff_dist s t ≤ diam (s ∪ t) :=
begin
rcases hs with ⟨x, xs⟩,
rcases ht with ⟨y, yt⟩,
refine Hausdorff_dist_le_of_mem_dist diam_nonneg _ _,
{ exact λz hz, ⟨y, yt, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩)
(subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ },
{ exact λz hz, ⟨x, xs, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩)
(subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ }
end
/-- The distance to a set is controlled by the Hausdorff distance -/
lemma inf_dist_le_Hausdorff_dist_of_mem (hx : x ∈ s) (fin : Hausdorff_edist s t ≠ ⊤) :
inf_dist x t ≤ Hausdorff_dist s t :=
begin
have ht : t.nonempty := nonempty_of_Hausdorff_edist_ne_top ⟨x, hx⟩ fin,
rw [Hausdorff_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) fin],
exact inf_edist_le_Hausdorff_edist_of_mem hx
end
/-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance
`<r` of a point in the other set -/
lemma exists_dist_lt_of_Hausdorff_dist_lt {r : ℝ} (h : x ∈ s) (H : Hausdorff_dist s t < r)
(fin : Hausdorff_edist s t ≠ ⊤) : ∃y∈t, dist x y < r :=
begin
have r0 : 0 < r := lt_of_le_of_lt (Hausdorff_dist_nonneg) H,
have : Hausdorff_edist s t < ennreal.of_real r,
by rwa [Hausdorff_dist, ← ennreal.to_real_of_real (le_of_lt r0),
ennreal.to_real_lt_to_real fin (ennreal.of_real_ne_top)] at H,
rcases exists_edist_lt_of_Hausdorff_edist_lt h this with ⟨y, hy, yr⟩,
rw [edist_dist, ennreal.of_real_lt_of_real_iff r0] at yr,
exact ⟨y, hy, yr⟩
end
/-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance
`<r` of a point in the other set -/
lemma exists_dist_lt_of_Hausdorff_dist_lt' {r : ℝ} (h : y ∈ t) (H : Hausdorff_dist s t < r)
(fin : Hausdorff_edist s t ≠ ⊤) : ∃x∈s, dist x y < r :=
begin
rw Hausdorff_dist_comm at H,
rw Hausdorff_edist_comm at fin,
simpa [dist_comm] using exists_dist_lt_of_Hausdorff_dist_lt h H fin
end
/-- The infimum distance to `s` and `t` are the same, up to the Hausdorff distance
between `s` and `t` -/
lemma inf_dist_le_inf_dist_add_Hausdorff_dist (fin : Hausdorff_edist s t ≠ ⊤) :
inf_dist x t ≤ inf_dist x s + Hausdorff_dist s t :=
begin
rcases empty_or_nonempty_of_Hausdorff_edist_ne_top fin with ⟨hs,ht⟩|⟨hs,ht⟩,
{ simp only [hs, ht, Hausdorff_dist_empty, inf_dist_empty, zero_add] },
rw [inf_dist, inf_dist, Hausdorff_dist, ← ennreal.to_real_add (inf_edist_ne_top hs) fin,
ennreal.to_real_le_to_real (inf_edist_ne_top ht)],
{ exact inf_edist_le_inf_edist_add_Hausdorff_edist },
{ exact ennreal.add_ne_top.2 ⟨inf_edist_ne_top hs, fin⟩ }
end
/-- The Hausdorff distance is invariant under isometries -/
lemma Hausdorff_dist_image (h : isometry Φ) :
Hausdorff_dist (Φ '' s) (Φ '' t) = Hausdorff_dist s t :=
by simp [Hausdorff_dist, Hausdorff_edist_image h]
/-- The Hausdorff distance satisfies the triangular inequality -/
lemma Hausdorff_dist_triangle (fin : Hausdorff_edist s t ≠ ⊤) :
Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u :=
begin
by_cases Hausdorff_edist s u = ⊤,
{ calc Hausdorff_dist s u = 0 + 0 : by simp [Hausdorff_dist, h]
... ≤ Hausdorff_dist s t + Hausdorff_dist t u :
add_le_add (Hausdorff_dist_nonneg) (Hausdorff_dist_nonneg) },
{ have Dtu : Hausdorff_edist t u < ⊤ := calc
Hausdorff_edist t u ≤ Hausdorff_edist t s + Hausdorff_edist s u : Hausdorff_edist_triangle
... = Hausdorff_edist s t + Hausdorff_edist s u : by simp [Hausdorff_edist_comm]
... < ⊤ : by simp [ennreal.add_lt_top]; simp [ennreal.lt_top_iff_ne_top, h, fin],
rw [Hausdorff_dist, Hausdorff_dist, Hausdorff_dist,
← ennreal.to_real_add fin (lt_top_iff_ne_top.1 Dtu), ennreal.to_real_le_to_real h],
{ exact Hausdorff_edist_triangle },
{ simp [ennreal.add_eq_top, lt_top_iff_ne_top.1 Dtu, fin] }}
end
/-- The Hausdorff distance satisfies the triangular inequality -/
lemma Hausdorff_dist_triangle' (fin : Hausdorff_edist t u ≠ ⊤) :
Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u :=
begin
rw Hausdorff_edist_comm at fin,
have I : Hausdorff_dist u s ≤ Hausdorff_dist u t + Hausdorff_dist t s := Hausdorff_dist_triangle fin,
simpa [add_comm, Hausdorff_dist_comm] using I
end
/-- The Hausdorff distance between a set and its closure vanish -/
@[simp, priority 1100]
lemma Hausdorff_dist_self_closure : Hausdorff_dist s (closure s) = 0 :=
by simp [Hausdorff_dist]
/-- Replacing a set by its closure does not change the Hausdorff distance. -/
@[simp] lemma Hausdorff_dist_closure₁ : Hausdorff_dist (closure s) t = Hausdorff_dist s t :=
by simp [Hausdorff_dist]
/-- Replacing a set by its closure does not change the Hausdorff distance. -/
@[simp] lemma Hausdorff_dist_closure₂ : Hausdorff_dist s (closure t) = Hausdorff_dist s t :=
by simp [Hausdorff_dist]
/-- The Hausdorff distance between two sets and their closures coincide -/
@[simp] lemma Hausdorff_dist_closure : Hausdorff_dist (closure s) (closure t) = Hausdorff_dist s t :=
by simp [Hausdorff_dist]
/-- Two sets are at zero Hausdorff distance if and only if they have the same closures -/
lemma Hausdorff_dist_zero_iff_closure_eq_closure (fin : Hausdorff_edist s t ≠ ⊤) :
Hausdorff_dist s t = 0 ↔ closure s = closure t :=
by simp [Hausdorff_edist_zero_iff_closure_eq_closure.symm, Hausdorff_dist,
ennreal.to_real_eq_zero_iff, fin]
/-- Two closed sets are at zero Hausdorff distance if and only if they coincide -/
lemma Hausdorff_dist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t)
(fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ s = t :=
by simp [(Hausdorff_edist_zero_iff_eq_of_closed hs ht).symm, Hausdorff_dist,
ennreal.to_real_eq_zero_iff, fin]
end --section
end metric --namespace
|
aabce27997458b52bbc571b41cffa82c00ce7e79 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/data/finset/default.lean | bc8a05f442171edba566fcb51dbfacdfda7157f3 | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 215 | lean | import data.finset.basic
import data.finset.fold
import data.finset.intervals
import data.finset.lattice
import data.finset.nat_antidiagonal
import data.finset.pi
import data.finset.powerset
import data.finset.sort
|
909193a4b923aacfbbeae22aee996d97bfb98d9f | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/bench/parser.lean | 9d6807bddd418df6ecac74f5fac69135fbeac888 | [
"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 | 401 | lean | import Lean.Parser.Module
/-!
Test parsing only on a .lean file, which necessarily has to be one that does
not depend on non-built-in syntax, e.g. `Init.Prelude`. -/
def main : List String → IO Unit
| [fname, n] => do
let env ← Lean.mkEmptyEnvironment
for _ in [0:n.toNat!] do
discard $ Lean.Parser.testParseFile env fname
| _ => throw $ IO.userError "give file and iteration count"
|
04b77e7d770297e8fe086a59f168964d53ac6cf2 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/continued_fractions/default.lean | 74b9c92c2de58c52fd2f55a8ad1abaa5f7cf5524 | [
"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 | 507 | lean | /-
Copyright (c) 2019 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import algebra.continued_fractions.basic
import algebra.continued_fractions.translations
import algebra.continued_fractions.continuants_recurrence
import algebra.continued_fractions.terminated_stable
import algebra.continued_fractions.convergents_equiv
import algebra.continued_fractions.computation
/-!
# Default Exports for Continued Fractions
-/
|
755ac0b592f8bff9316d258d846622d841904579 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Core.lean | 850a7601147912373818f741b240096940a88da4 | [
"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 | 64,138 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
notation, basic datatypes and type classes
-/
prelude
notation `Prop` := Sort 0
notation f ` $ `:1 a:0 := f a
/- Logical operations and relations -/
reserve prefix `¬`:40
reserve infixr ` ∧ `:35
reserve infixr ` /\ `:35
reserve infixr ` \/ `:30
reserve infixr ` ∨ `:30
reserve infix ` <-> `:20
reserve infix ` ↔ `:20
reserve infix ` = `:50
reserve infix ` == `:50
reserve infix ` != `:50
reserve infix ` ~= `:50
reserve infix ` ≅ `:50
reserve infix ` ≠ `:50
reserve infix ` ≈ `:50
reserve infixr ` ▸ `:75
/- types and Type constructors -/
reserve infixr ` × `:35
/- arithmetic operations -/
reserve infixl ` + `:65
reserve infixl ` - `:65
reserve infixl ` * `:70
reserve infixl ` / `:70
reserve infixl ` % `:70
reserve infixl ` %ₙ `:70
reserve prefix `-`:100
reserve infixr ` ^ `:80
reserve infixr ` ∘ `:90
reserve infix ` <= `:50
reserve infix ` ≤ `:50
reserve infix ` < `:50
reserve infix ` >= `:50
reserve infix ` ≥ `:50
reserve infix ` > `:50
/- boolean operations -/
reserve prefix `!`:40
reserve infixl ` && `:35
reserve infixl ` || `:30
/- other symbols -/
reserve infixl ` ++ `:65
reserve infixr ` :: `:67
/- Control -/
reserve infixr ` <|> `:2
reserve infixr ` >>= `:55
reserve infixr ` >=> `:55
reserve infixl ` <*> `:60
reserve infixl ` <* ` :60
reserve infixr ` *> ` :60
reserve infixr ` >> ` :60
reserve infixr ` <$> `:100
reserve infixr ` <$ ` :100
reserve infixr ` $> ` :100
reserve infixl ` <&> `:100
universes u v w
/-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/
unsafe axiom lcProof {α : Prop} : α
/-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/
unsafe axiom lcUnreachable {α : Sort u} : α
@[inline] def id {α : Sort u} (a : α) : α := a
def inline {α : Sort u} (a : α) : α := a
@[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ :=
fun b a => f a b
/-
The kernel definitional equality test (t =?= s) has special support for idDelta applications.
It implements the following rules
1) (idDelta t) =?= t
2) t =?= (idDelta t)
3) (idDelta t) =?= s IF (unfoldOf t) =?= s
4) t =?= idDelta s IF t =?= (unfoldOf s)
This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel.
We use idDelta applications to address performance problems when Type checking
theorems generated by the equation Compiler.
-/
@[inline] def idDelta {α : Sort u} (a : α) : α :=
a
/-- Gadget for optional parameter support. -/
@[reducible] def optParam (α : Sort u) (default : α) : Sort u :=
α
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def outParam (α : Sort u) : Sort u := α
/-- Auxiliary Declaration used to implement the notation (a : α) -/
@[reducible] def typedExpr (α : Sort u) (a : α) : α := a
/- `idRhs` is an auxiliary Declaration used in the equation Compiler to address performance
issues when proving equational theorems. The equation Compiler uses it as a marker. -/
@[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a
inductive PUnit : Sort u
| unit : PUnit
/-- An abbreviation for `PUnit.{0}`, its most common instantiation.
This Type should be preferred over `PUnit` where possible to avoid
unnecessary universe parameters. -/
abbrev Unit : Type := PUnit
@[matchPattern] abbrev Unit.unit : Unit := PUnit.unit
/- Remark: thunks have an efficient implementation in the runtime. -/
structure Thunk (α : Type u) : Type u :=
(fn : Unit → α)
attribute [extern "lean_mk_thunk"] Thunk.mk
@[noinline, extern "lean_thunk_pure"]
protected def Thunk.pure {α : Type u} (a : α) : Thunk α :=
⟨fun _ => a⟩
@[noinline, extern "lean_thunk_get_own"]
protected def Thunk.get {α : Type u} (x : @& Thunk α) : α :=
x.fn ()
@[noinline, extern "lean_thunk_map"]
protected def Thunk.map {α : Type u} {β : Type v} (f : α → β) (x : Thunk α) : Thunk β :=
⟨fun _ => f x.get⟩
@[noinline, extern "lean_thunk_bind"]
protected def Thunk.bind {α : Type u} {β : Type v} (x : Thunk α) (f : α → Thunk β) : Thunk β :=
⟨fun _ => (f x.get).get⟩
/- Remark: tasks have an efficient implementation in the runtime. -/
structure Task (α : Type u) : Type u :=
(fn : Unit → α)
attribute [extern "lean_mk_task"] Task.mk
@[noinline, extern "lean_task_pure"]
protected def Task.pure {α : Type u} (a : α) : Task α :=
⟨fun _ => a⟩
@[noinline, extern "lean_task_get"]
protected def Task.get {α : Type u} (x : @& Task α) : α :=
x.fn ()
@[noinline, extern "lean_task_map"]
protected def Task.map {α : Type u} {β : Type v} (f : α → β) (x : Task α) : Task β :=
⟨fun _ => f x.get⟩
@[noinline, extern "lean_task_bind"]
protected def Task.bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) : Task β :=
⟨fun _ => (f x.get).get⟩
inductive True : Prop
| intro : True
inductive False : Prop
inductive Empty : Type
def Not (a : Prop) : Prop := a → False
prefix `¬` := Not
inductive Eq {α : Sort u} (a : α) : α → Prop
| refl : Eq a
@[elabAsEliminator, inline, reducible]
def Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {C : α → Sort u1} (m : C a) {b : α} (h : Eq a b) : C b :=
@Eq.rec α a (fun α _ => C α) m b h
@[elabAsEliminator, inline, reducible]
def Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {C : α → Sort u1} {b : α} (h : Eq a b) (m : C a) : C b :=
@Eq.rec α a (fun α _ => C α) m b h
/-
Initialize the Quotient Module, which effectively adds the following definitions:
constant Quot {α : Sort u} (r : α → α → Prop) : Sort u
constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r
constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :
(∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β
constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} :
(∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q
-/
init_quot
inductive HEq {α : Sort u} (a : α) : ∀ {β : Sort u}, β → Prop
| refl : HEq a
structure Prod (α : Type u) (β : Type v) :=
(fst : α) (snd : β)
attribute [unbox] Prod
/-- Similar to `Prod`, but α and β can be propositions.
We use this Type internally to automatically generate the brecOn recursor. -/
structure PProd (α : Sort u) (β : Sort v) :=
(fst : α) (snd : β)
structure And (a b : Prop) : Prop :=
intro :: (left : a) (right : b)
structure Iff (a b : Prop) : Prop :=
intro :: (mp : a → b) (mpr : b → a)
/- Eq basic support -/
infix `=` := Eq
@[matchPattern] def rfl {α : Sort u} {a : α} : a = a := Eq.refl a
@[elabAsEliminator]
theorem Eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b :=
Eq.ndrec h₂ h₁
infixr `▸` := Eq.subst
theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c :=
h₂ ▸ h₁
theorem Eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a :=
h ▸ rfl
infix `~=` := HEq
infix `≅` := HEq
@[matchPattern] def HEq.rfl {α : Sort u} {a : α} : a ≅ a := HEq.refl a
theorem eqOfHEq {α : Sort u} {a a' : α} (h : a ≅ a') : a = a' :=
have ∀ (α' : Sort u) (a' : α') (h₁ : @HEq α a α' a') (h₂ : α = α'), (Eq.recOn h₂ a : α') = a' :=
fun (α' : Sort u) (a' : α') (h₁ : @HEq α a α' a') => HEq.recOn h₁ (fun (h₂ : α = α) => rfl);
show (Eq.ndrecOn (Eq.refl α) a : α) = a' from
this α a' h (Eq.refl α)
inductive Sum (α : Type u) (β : Type v)
| inl {} (val : α) : Sum
| inr {} (val : β) : Sum
inductive PSum (α : Sort u) (β : Sort v)
| inl {} (val : α) : PSum
| inr {} (val : β) : PSum
inductive Or (a b : Prop) : Prop
| inl {} (h : a) : Or
| inr {} (h : b) : Or
def Or.introLeft {a : Prop} (b : Prop) (ha : a) : Or a b :=
Or.inl ha
def Or.introRight (a : Prop) {b : Prop} (hb : b) : Or a b :=
Or.inr hb
structure Sigma {α : Type u} (β : α → Type v) :=
mk :: (fst : α) (snd : β fst)
attribute [unbox] Sigma
structure PSigma {α : Sort u} (β : α → Sort v) :=
mk :: (fst : α) (snd : β fst)
inductive Bool : Type
| false : Bool
| true : Bool
/- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/
structure Subtype {α : Sort u} (p : α → Prop) :=
(val : α) (property : p val)
inductive Exists {α : Sort u} (p : α → Prop) : Prop
| intro (w : α) (h : p w) : Exists
class inductive Decidable (p : Prop)
| isFalse (h : ¬p) : Decidable
| isTrue (h : p) : Decidable
abbrev DecidablePred {α : Sort u} (r : α → Prop) :=
∀ (a : α), Decidable (r a)
abbrev DecidableRel {α : Sort u} (r : α → α → Prop) :=
∀ (a b : α), Decidable (r a b)
abbrev DecidableEq (α : Sort u) :=
∀ (a b : α), Decidable (a = b)
def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (a = b) :=
s a b
inductive Option (α : Type u)
| none {} : Option
| some (val : α) : Option
attribute [unbox] Option
export Option (none some)
export Bool (false true)
inductive List (T : Type u)
| nil {} : List
| cons (hd : T) (tl : List) : List
infixr `::` := List.cons
inductive Nat
| zero : Nat
| succ (n : Nat) : Nat
/- Auxiliary axiom used to implement `sorry`.
TODO: add this theorem on-demand. That is,
we should only add it if after the first error. -/
axiom sorryAx (α : Sort u) (synthetic := true) : α
/- Declare builtin and reserved notation -/
class HasZero (α : Type u) := (zero : α)
class HasOne (α : Type u) := (one : α)
class HasAdd (α : Type u) := (add : α → α → α)
class HasMul (α : Type u) := (mul : α → α → α)
class HasNeg (α : Type u) := (neg : α → α)
class HasSub (α : Type u) := (sub : α → α → α)
class HasDiv (α : Type u) := (div : α → α → α)
class HasMod (α : Type u) := (mod : α → α → α)
class HasModN (α : Type u) := (modn : α → Nat → α)
class HasLessEq (α : Type u) := (LessEq : α → α → Prop)
class HasLess (α : Type u) := (Less : α → α → Prop)
class HasBeq (α : Type u) := (beq : α → α → Bool)
class HasAppend (α : Type u) := (append : α → α → α)
class HasOrelse (α : Type u) := (orelse : α → α → α)
class HasAndthen (α : Type u) := (andthen : α → α → α)
class HasEquiv (α : Sort u) := (Equiv : α → α → Prop)
class HasEmptyc (α : Type u) := (emptyc : α)
class HasPow (α : Type u) (β : Type v) :=
(pow : α → β → α)
infix `+` := HasAdd.add
infix `*` := HasMul.mul
infix `-` := HasSub.sub
infix `/` := HasDiv.div
infix `%` := HasMod.mod
infix `%ₙ` := HasModN.modn
prefix `-` := HasNeg.neg
infix `<=` := HasLessEq.LessEq
infix `≤` := HasLessEq.LessEq
infix `<` := HasLess.Less
infix `==` := HasBeq.beq
infix `++` := HasAppend.append
notation `∅` := HasEmptyc.emptyc _
infix `≈` := HasEquiv.Equiv
infixr `^` := HasPow.pow
infixr `/\` := And
infixr `∧` := And
infixr `\/` := Or
infixr `∨` := Or
infix `<->` := Iff
infix `↔` := Iff
-- notation `exists` binders `, ` r:(scoped P, Exists P) := r
-- notation `∃` binders `, ` r:(scoped P, Exists P) := r
infixr `<|>` := HasOrelse.orelse
infixr `>>` := HasAndthen.andthen
@[reducible] def GreaterEq {α : Type u} [HasLessEq α] (a b : α) : Prop := HasLessEq.LessEq b a
@[reducible] def Greater {α : Type u} [HasLess α] (a b : α) : Prop := HasLess.Less b a
infix `>=` := GreaterEq
infix `≥` := GreaterEq
infix `>` := Greater
@[inline] def bit0 {α : Type u} [s : HasAdd α] (a : α) : α := a + a
@[inline] def bit1 {α : Type u} [s₁ : HasOne α] [s₂ : HasAdd α] (a : α) : α := (bit0 a) + 1
attribute [matchPattern] HasZero.zero HasOne.one bit0 bit1 HasAdd.add HasNeg.neg
/- Nat basic instances -/
@[extern "lean_nat_add"]
protected def Nat.add : (@& Nat) → (@& Nat) → Nat
| a, Nat.zero => a
| a, Nat.succ b => Nat.succ (Nat.add a b)
/- We mark the following definitions as pattern to make sure they can be used in recursive equations,
and reduced by the equation Compiler. -/
attribute [matchPattern] Nat.add Nat.add._main
instance : HasZero Nat := ⟨Nat.zero⟩
instance : HasOne Nat := ⟨Nat.succ (Nat.zero)⟩
instance : HasAdd Nat := ⟨Nat.add⟩
/- Auxiliary constant used by equation compiler. -/
constant hugeFuel : Nat := 10000
def std.priority.default : Nat := 1000
def std.priority.max : Nat := 0xFFFFFFFF
protected def Nat.prio := std.priority.default + 100
/-
Global declarations of right binding strength
If a Module reassigns these, it will be incompatible with other modules that adhere to these
conventions.
When hovering over a symbol, use "C-c C-k" to see how to input it.
-/
def std.prec.max : Nat := 1024 -- the strength of application, identifiers, (, [, etc.
def std.prec.arrow : Nat := 25
/-
The next def is "max + 10". It can be used e.g. for postfix operations that should
be stronger than application.
-/
def std.prec.maxPlus : Nat := std.prec.max + 10
infixr `×` := Prod
-- notation for n-ary tuples
/- Some type that is not a scalar value in our runtime. -/
structure NonScalar :=
(val : Nat)
/- Some type that is not a scalar value in our runtime and is universe polymorphic. -/
inductive PNonScalar : Type u
| mk (v : Nat) : PNonScalar
/- For numeric literals notation -/
class HasOfNat (α : Type u) :=
(ofNat : Nat → α)
export HasOfNat (ofNat)
instance : HasOfNat Nat :=
⟨id⟩
/- sizeof -/
class HasSizeof (α : Sort u) :=
(sizeof : α → Nat)
export HasSizeof (sizeof)
/-
Declare sizeof instances and theorems for types declared before HasSizeof.
From now on, the inductive Compiler will automatically generate sizeof instances and theorems.
-/
/- Every Type `α` has a default HasSizeof instance that just returns 0 for every element of `α` -/
protected def default.sizeof (α : Sort u) : α → Nat
| a => 0
instance defaultHasSizeof (α : Sort u) : HasSizeof α :=
⟨default.sizeof α⟩
protected def Nat.sizeof : Nat → Nat
| n => n
instance : HasSizeof Nat :=
⟨Nat.sizeof⟩
protected def Prod.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (Prod α β) → Nat
| ⟨a, b⟩ => 1 + sizeof a + sizeof b
instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (Prod α β) :=
⟨Prod.sizeof⟩
protected def Sum.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (Sum α β) → Nat
| Sum.inl a => 1 + sizeof a
| Sum.inr b => 1 + sizeof b
instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (Sum α β) :=
⟨Sum.sizeof⟩
protected def PSum.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (PSum α β) → Nat
| PSum.inl a => 1 + sizeof a
| PSum.inr b => 1 + sizeof b
instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (PSum α β) :=
⟨PSum.sizeof⟩
protected def Sigma.sizeof {α : Type u} {β : α → Type v} [HasSizeof α] [∀ a, HasSizeof (β a)] : Sigma β → Nat
| ⟨a, b⟩ => 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [HasSizeof α] [∀ a, HasSizeof (β a)] : HasSizeof (Sigma β) :=
⟨Sigma.sizeof⟩
protected def PSigma.sizeof {α : Type u} {β : α → Type v} [HasSizeof α] [∀ a, HasSizeof (β a)] : PSigma β → Nat
| ⟨a, b⟩ => 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [HasSizeof α] [∀ a, HasSizeof (β a)] : HasSizeof (PSigma β) :=
⟨PSigma.sizeof⟩
protected def PUnit.sizeof : PUnit → Nat
| u => 1
instance : HasSizeof PUnit := ⟨PUnit.sizeof⟩
protected def Bool.sizeof : Bool → Nat
| b => 1
instance : HasSizeof Bool := ⟨Bool.sizeof⟩
protected def Option.sizeof {α : Type u} [HasSizeof α] : Option α → Nat
| none => 1
| some a => 1 + sizeof a
instance (α : Type u) [HasSizeof α] : HasSizeof (Option α) :=
⟨Option.sizeof⟩
protected def List.sizeof {α : Type u} [HasSizeof α] : List α → Nat
| List.nil => 1
| List.cons a l => 1 + sizeof a + List.sizeof l
instance (α : Type u) [HasSizeof α] : HasSizeof (List α) :=
⟨List.sizeof⟩
protected def Subtype.sizeof {α : Type u} [HasSizeof α] {p : α → Prop} : Subtype p → Nat
| ⟨a, _⟩ => sizeof a
instance {α : Type u} [HasSizeof α] (p : α → Prop) : HasSizeof (Subtype p) :=
⟨Subtype.sizeof⟩
theorem natAddZero (n : Nat) : n + 0 = n := rfl
theorem optParamEq (α : Sort u) (default : α) : optParam α default = α := rfl
/-- Like `by applyInstance`, but not dependent on the tactic framework. -/
@[reducible] def inferInstance {α : Type u} [i : α] : α := i
@[reducible, elabSimple] def inferInstanceAs (α : Type u) [i : α] : α := i
/- Boolean operators -/
@[macroInline] def cond {a : Type u} : Bool → a → a → a
| true, x, y => x
| false, x, y => y
@[inline] def condEq {β : Sort u} (b : Bool) (h₁ : b = true → β) (h₂ : b = false → β) : β :=
@Bool.casesOn (λ x => b = x → β) b h₂ h₁ rfl
@[macroInline] def or : Bool → Bool → Bool
| true, _ => true
| false, b => b
@[macroInline] def and : Bool → Bool → Bool
| false, _ => false
| true, b => b
@[macroInline] def not : Bool → Bool
| true => false
| false => true
@[macroInline] def xor : Bool → Bool → Bool
| true, b => not b
| false, b => b
prefix `!` := not
infix `||` := or
infix `&&` := and
@[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂
@[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂
@[inline] def bne {α : Type u} [HasBeq α] (a b : α) : Bool :=
!(a == b)
infix `!=` := bne
/- Logical connectives an equality -/
def implies (a b : Prop) := a → b
theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r :=
fun hp => h₂ (h₁ hp)
def trivial : True := ⟨⟩
@[macroInline] def False.elim {C : Sort u} (h : False) : C :=
False.rec (fun _ => C) h
@[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b :=
False.elim (h₂ h₁)
theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a :=
fun ha => h₂ (h₁ ha)
theorem notFalse : ¬False := id
-- proof irrelevance is built in
theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl
theorem id.def {α : Sort u} (a : α) : id a = a := rfl
@[macroInline] def Eq.mp {α β : Sort u} (h₁ : α = β) (h₂ : α) : β :=
Eq.recOn h₁ h₂
@[macroInline] def Eq.mpr {α β : Sort u} : (α = β) → β → α :=
fun h₁ h₂ => Eq.recOn (Eq.symm h₁) h₂
@[elabAsEliminator]
theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b :=
Eq.subst (Eq.symm h₁) h₂
theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ :=
Eq.subst h₁ (Eq.subst h₂ rfl)
theorem congrFun {α : Sort u} {β : α → Sort v} {f g : ∀ x, β x} (h : f = g) (a : α) : f a = g a :=
Eq.subst h (Eq.refl (f a))
theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : a₁ = a₂) : f a₁ = f a₂ :=
congr rfl h
theorem transRelLeft {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c :=
h₂ ▸ h₁
theorem transRelRight {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c :=
h₁.symm ▸ h₂
theorem ofEqTrue {p : Prop} (h : p = True) : p :=
h.symm ▸ trivial
theorem notOfEqFalse {p : Prop} (h : p = False) : ¬p :=
fun hp => h ▸ hp
@[macroInline] def cast {α β : Sort u} (h : α = β) (a : α) : β :=
Eq.rec a h
theorem castProofIrrel {α β : Sort u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl
theorem castEq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl
@[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b)
infix `≠` := Ne
theorem Ne.def {α : Sort u} (a b : α) : a ≠ b = ¬ (a = b) := rfl
section Ne
variable {α : Sort u}
variables {a b : α} {p : Prop}
theorem Ne.intro (h : a = b → False) : a ≠ b := h
theorem Ne.elim (h : a ≠ b) : a = b → False := h
theorem Ne.irrefl (h : a ≠ a) : False := h rfl
theorem Ne.symm (h : a ≠ b) : b ≠ a :=
fun h₁ => h (h₁.symm)
theorem falseOfNe : a ≠ a → False := Ne.irrefl
theorem neFalseOfSelf : p → p ≠ False :=
fun (hp : p) (h : p = False) => h ▸ hp
theorem neTrueOfNot : ¬p → p ≠ True :=
fun (hnp : ¬p) (h : p = True) => (h ▸ hnp) trivial
theorem trueNeFalse : ¬True = False :=
neFalseOfSelf trivial
end Ne
theorem eqFalseOfNeTrue : ∀ {b : Bool}, b ≠ true → b = false
| true, h => False.elim (h rfl)
| false, h => rfl
theorem eqTrueOfNeFalse : ∀ {b : Bool}, b ≠ false → b = true
| true, h => rfl
| false, h => False.elim (h rfl)
theorem neFalseOfEqTrue : ∀ {b : Bool}, b = true → b ≠ false
| true, _ => fun h => Bool.noConfusion h
| false, h => Bool.noConfusion h
theorem neTrueOfEqFalse : ∀ {b : Bool}, b = false → b ≠ true
| true, h => Bool.noConfusion h
| false, _ => fun h => Bool.noConfusion h
section
variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ}
@[elabAsEliminator]
theorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {C : ∀ {β : Sort u2}, β → Sort u1} (m : C a) {β : Sort u2} {b : β} (h : a ≅ b) : C b :=
@HEq.rec α a (fun β b _ => C b) m β b h
@[elabAsEliminator]
theorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {C : ∀ {β : Sort u2}, β → Sort u1} {β : Sort u2} {b : β} (h : a ≅ b) (m : C a) : C b :=
@HEq.rec α a (fun β b _ => C b) m β b h
theorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a ≅ b) (h₂ : p a) : p b :=
Eq.recOn (eqOfHEq h₁) h₂
theorem HEq.subst {p : ∀ (T : Sort u), T → Prop} (h₁ : a ≅ b) (h₂ : p α a) : p β b :=
HEq.ndrecOn h₁ h₂
theorem HEq.symm (h : a ≅ b) : b ≅ a :=
HEq.ndrecOn h (HEq.refl a)
theorem heqOfEq (h : a = a') : a ≅ a' :=
Eq.subst h (HEq.refl a)
theorem HEq.trans (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c :=
HEq.subst h₂ h₁
theorem heqOfHEqOfEq (h₁ : a ≅ b) (h₂ : b = b') : a ≅ b' :=
HEq.trans h₁ (heqOfEq h₂)
theorem heqOfEqOfHEq (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b :=
HEq.trans (heqOfEq h₁) h₂
def typeEqOfHEq (h : a ≅ b) : α = β :=
HEq.ndrecOn h (Eq.refl α)
end
theorem eqRecHEq {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} (h : a = a') (p : φ a), (Eq.recOn h p : φ a') ≅ p
| a, _, rfl, p => HEq.refl p
theorem ofHEqTrue {a : Prop} (h : a ≅ True) : a :=
ofEqTrue (eqOfHEq h)
theorem castHEq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a ≅ a
| α, _, rfl, a => HEq.refl a
variables {a b c d : Prop}
theorem And.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c :=
And.rec h₂ h₁
theorem And.swap : a ∧ b → b ∧ a :=
fun ⟨ha, hb⟩ => ⟨hb, ha⟩
def And.symm := @And.swap
theorem Or.elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c :=
Or.rec h₂ h₃ h₁
theorem Or.swap (h : a ∨ b) : b ∨ a :=
Or.elim h Or.inr Or.inl
def Or.symm := @Or.swap
/- xor -/
def Xor (a b : Prop) : Prop := (a ∧ ¬ b) ∨ (b ∧ ¬ a)
theorem Iff.elim (h₁ : (a → b) → (b → a) → c) (h₂ : a ↔ b) : c :=
Iff.rec h₁ h₂
theorem Iff.left : (a ↔ b) → a → b := Iff.mp
theorem Iff.right : (a ↔ b) → b → a := Iff.mpr
theorem iffIffImpliesAndImplies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) :=
Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right)
theorem Iff.refl (a : Prop) : a ↔ a :=
Iff.intro (fun h => h) (fun h => h)
theorem Iff.rfl {a : Prop} : a ↔ a :=
Iff.refl a
theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c :=
Iff.intro
(fun ha => Iff.mp h₂ (Iff.mp h₁ ha))
(fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc))
theorem Iff.symm (h : a ↔ b) : b ↔ a :=
Iff.intro (Iff.right h) (Iff.left h)
theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) :=
Iff.intro Iff.symm Iff.symm
theorem Eq.toIff {a b : Prop} (h : a = b) : a ↔ b :=
Eq.recOn h Iff.rfl
theorem neqOfNotIff {a b : Prop} : ¬(a ↔ b) → a ≠ b :=
fun h₁ h₂ =>
have a ↔ b from Eq.subst h₂ (Iff.refl a);
absurd this h₁
theorem notIffNotOfIff (h₁ : a ↔ b) : ¬a ↔ ¬b :=
Iff.intro
(fun (hna : ¬ a) (hb : b) => hna (Iff.right h₁ hb))
(fun (hnb : ¬ b) (ha : a) => hnb (Iff.left h₁ ha))
theorem ofIffTrue (h : a ↔ True) : a :=
Iff.mp (Iff.symm h) trivial
theorem notOfIffFalse : (a ↔ False) → ¬a := Iff.mp
theorem iffTrueIntro (h : a) : a ↔ True :=
Iff.intro
(fun hl => trivial)
(fun hr => h)
theorem iffFalseIntro (h : ¬a) : a ↔ False :=
Iff.intro h (False.rec (fun _ => a))
theorem notNotIntro (ha : a) : ¬¬a :=
fun hna => hna ha
theorem notTrue : (¬ True) ↔ False :=
iffFalseIntro (notNotIntro trivial)
/- or resolution rulses -/
theorem resolveLeft {a b : Prop} (h : a ∨ b) (na : ¬ a) : b :=
Or.elim h (fun ha => absurd ha na) id
theorem negResolveLeft {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b :=
Or.elim h (fun na => absurd ha na) id
theorem resolveRight {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a :=
Or.elim h id (fun hb => absurd hb nb)
theorem negResolveRight {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a :=
Or.elim h id (fun nb => absurd hb nb)
/- Exists -/
theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop}
(h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b :=
Exists.rec h₂ h₁
/- Decidable -/
@[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool :=
Decidable.casesOn h (fun h₁ => false) (fun h₂ => true)
export Decidable (isTrue isFalse decide)
instance beqOfEq {α : Type u} [DecidableEq α] : HasBeq α :=
⟨fun a b => decide (a = b)⟩
theorem decideTrueEqTrue (h : Decidable True) : @decide True h = true :=
match h with
| isTrue h => rfl
| isFalse h => False.elim (Iff.mp notTrue h)
theorem decideFalseEqFalse (h : Decidable False) : @decide False h = false :=
match h with
| isFalse h => rfl
| isTrue h => False.elim h
theorem decideEqTrue : ∀ {p : Prop} [s : Decidable p], p → decide p = true
| _, isTrue _, _ => rfl
| _, isFalse h₁, h₂ => absurd h₂ h₁
theorem decideEqFalse : ∀ {p : Prop} [s : Decidable p], ¬p → decide p = false
| _, isTrue h₁, h₂ => absurd h₁ h₂
| _, isFalse h, _ => rfl
theorem ofDecideEqTrue {p : Prop} [s : Decidable p] : decide p = true → p :=
fun h => match s with
| isTrue h₁ => h₁
| isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁))
theorem ofDecideEqFalse {p : Prop} [s : Decidable p] : decide p = false → ¬p :=
fun h => match s with
| isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁))
| isFalse h₁ => h₁
/-- Similar to `decide`, but uses an explicit instance -/
@[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool :=
@decide p d
theorem toBoolUsingEqTrue {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true :=
@decideEqTrue _ d h
theorem ofBoolUsingEqTrue {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p :=
@ofDecideEqTrue _ d h
theorem ofBoolUsingEqFalse {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p :=
@ofDecideEqFalse _ d h
instance : Decidable True :=
isTrue trivial
instance : Decidable False :=
isFalse notFalse
-- We use "dependent" if-then-else to be able to communicate the if-then-else condition
-- to the branches
@[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] : (c → α) → (¬ c → α) → α :=
fun t e => Decidable.casesOn h e t
/- if-then-else -/
@[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α :=
Decidable.casesOn h (fun hnc => e) (fun hc => t)
namespace Decidable
variables {p q : Prop}
def recOnTrue [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃)
: (Decidable.recOn h h₂ h₁ : Sort u) :=
Decidable.casesOn h (fun h => False.rec _ (h h₃)) (fun h => h₄)
def recOnFalse [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃)
: (Decidable.recOn h h₂ h₁ : Sort u) :=
Decidable.casesOn h (fun h => h₄) (fun h => False.rec _ (h₃ h))
@[macroInline] def byCases {q : Sort u} [s : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q :=
match s with
| isTrue h => h1 h
| isFalse h => h2 h
theorem em (p : Prop) [Decidable p] : p ∨ ¬p :=
byCases Or.inl Or.inr
theorem byContradiction [Decidable p] (h : ¬p → False) : p :=
byCases id (fun np => False.elim (h np))
theorem ofNotNot [Decidable p] : ¬ ¬ p → p :=
fun hnn => byContradiction (fun hn => absurd hn hnn)
theorem notNotIff (p) [Decidable p] : (¬ ¬ p) ↔ p :=
Iff.intro ofNotNot notNotIntro
theorem notAndIffOrNot (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q :=
Iff.intro
(fun h => match d₁, d₂ with
| isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h
| _, isFalse h₂ => Or.inr h₂
| isFalse h₁, _ => Or.inl h₁)
(fun (h) ⟨hp, hq⟩ => Or.elim h (fun h => h hp) (fun h => h hq))
end Decidable
section
variables {p q : Prop}
@[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q :=
if hp : p then isTrue (Iff.mp h hp)
else isFalse (Iff.mp (notIffNotOfIff h) hp)
@[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q :=
decidableOfDecidableOfIff hp h.toIff
end
section
variables {p q : Prop}
@[macroInline] instance [Decidable p] [Decidable q] : Decidable (p ∧ q) :=
if hp : p then
if hq : q then isTrue ⟨hp, hq⟩
else isFalse (fun h => hq (And.right h))
else isFalse (fun h => hp (And.left h))
@[macroInline] instance [Decidable p] [Decidable q] : Decidable (p ∨ q) :=
if hp : p then isTrue (Or.inl hp) else
if hq : q then isTrue (Or.inr hq) else
isFalse (fun h => Or.elim h hp hq)
instance [Decidable p] : Decidable (¬p) :=
if hp : p then isFalse (absurd hp) else isTrue hp
@[macroInline] instance implies.Decidable [Decidable p] [Decidable q] : Decidable (p → q) :=
if hp : p then
if hq : q then isTrue (fun h => hq)
else isFalse (fun h => absurd (h hp) hq)
else isTrue (fun h => absurd h hp)
instance [Decidable p] [Decidable q] : Decidable (p ↔ q) :=
if hp : p then
if hq : q then isTrue ⟨fun _ => hq, fun _ => hp⟩
else isFalse $ fun h => hq (h.1 hp)
else
if hq : q then isFalse $ fun h => hp (h.2 hq)
else isTrue $ ⟨fun h => absurd h hp, fun h => absurd h hq⟩
instance [Decidable p] [Decidable q] : Decidable (Xor p q) :=
if hp : p then
if hq : q then isFalse (fun h => Or.elim h (fun ⟨_, h⟩ => h hq : ¬(p ∧ ¬ q)) (fun ⟨_, h⟩ => h hp : ¬(q ∧ ¬ p)))
else isTrue $ Or.inl ⟨hp, hq⟩
else
if hq : q then isTrue $ Or.inr ⟨hq, hp⟩
else isFalse (fun h => Or.elim h (fun ⟨h, _⟩ => hp h : ¬(p ∧ ¬ q)) (fun ⟨h, _⟩ => hq h : ¬(q ∧ ¬ p)))
end
@[inline] instance {α : Sort u} [DecidableEq α] (a b : α) : Decidable (a ≠ b) :=
match decEq a b with
| isTrue h => isFalse $ fun h' => absurd h h'
| isFalse h => isTrue h
theorem Bool.falseNeTrue (h : false = true) : False :=
Bool.noConfusion h
@[inline] instance : DecidableEq Bool :=
fun a b => match a, b with
| false, false => isTrue rfl
| false, true => isFalse Bool.falseNeTrue
| true, false => isFalse (Ne.symm Bool.falseNeTrue)
| true, true => isTrue rfl
/- if-then-else expression theorems -/
theorem ifPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t :=
match h with
| (isTrue hc) => rfl
| (isFalse hnc) => absurd hc hnc
theorem ifNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e :=
match h with
| (isTrue hc) => absurd hc hnc
| (isFalse hnc) => rfl
theorem difPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc :=
match h with
| (isTrue hc) => rfl
| (isFalse hnc) => absurd hc hnc
theorem difNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc :=
match h with
| (isTrue hc) => absurd hc hnc
| (isFalse hnc) => rfl
-- Remark: dite and ite are "defally equal" when we ignore the proofs.
theorem difEqIf (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (fun h => t) (fun h => e) = ite c t e :=
match h with
| (isTrue hc) => rfl
| (isFalse hnc) => rfl
instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) :=
match dC with
| (isTrue hc) => dT
| (isFalse hc) => dE
instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) :=
match dC with
| (isTrue hc) => dT hc
| (isFalse hc) => dE hc
/-- Universe lifting operation -/
structure ULift.{r, s} (α : Type s) : Type (max s r) :=
up :: (down : α)
namespace ULift
/- Bijection between α and ULift.{v} α -/
theorem upDown {α : Type u} : ∀ (b : ULift.{v} α), up (down b) = b
| up a => rfl
theorem downUp {α : Type u} (a : α) : down (up.{v} a) = a := rfl
end ULift
/-- Universe lifting operation from Sort to Type -/
structure PLift (α : Sort u) : Type u :=
up :: (down : α)
namespace PLift
/- Bijection between α and PLift α -/
theorem upDown {α : Sort u} : ∀ (b : PLift α), up (down b) = b
| up a => rfl
theorem downUp {α : Sort u} (a : α) : down (up a) = a := rfl
end PLift
/- pointed types -/
structure PointedType :=
(type : Type u) (val : type)
/- Inhabited -/
class Inhabited (α : Sort u) :=
(default : α)
constant arbitrary (α : Sort u) [Inhabited α] : α :=
Inhabited.default α
instance Prop.Inhabited : Inhabited Prop :=
⟨True⟩
instance Fun.Inhabited (α : Sort u) {β : Sort v} [h : Inhabited β] : Inhabited (α → β) :=
Inhabited.casesOn h (fun b => ⟨fun a => b⟩)
instance Forall.Inhabited (α : Sort u) {β : α → Sort v} [∀ x, Inhabited (β x)] : Inhabited (∀ x, β x) :=
⟨fun a => arbitrary (β a)⟩
instance : Inhabited Bool := ⟨false⟩
instance : Inhabited True := ⟨trivial⟩
instance : Inhabited Nat := ⟨0⟩
instance : Inhabited NonScalar := ⟨⟨arbitrary _⟩⟩
instance : Inhabited PNonScalar.{u} := ⟨⟨arbitrary _⟩⟩
instance : Inhabited PointedType := ⟨{type := PUnit, val := ⟨⟩}⟩
class inductive Nonempty (α : Sort u) : Prop
| intro (val : α) : Nonempty
protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p :=
Nonempty.rec h₂ h₁
instance nonemptyOfInhabited {α : Sort u} [Inhabited α] : Nonempty α :=
⟨arbitrary α⟩
theorem nonemptyOfExists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α
| ⟨w, h⟩ => ⟨w⟩
/- Subsingleton -/
class inductive Subsingleton (α : Sort u) : Prop
| intro (h : ∀ (a b : α), a = b) : Subsingleton
protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : ∀ (a b : α), a = b :=
Subsingleton.casesOn h (fun p => p)
protected def Subsingleton.helim {α β : Sort u} [h : Subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a ≅ b :=
Eq.recOn h (fun a b => heqOfEq (Subsingleton.elim a b))
instance subsingletonProp (p : Prop) : Subsingleton p :=
⟨fun a b => proofIrrel a b⟩
instance (p : Prop) : Subsingleton (Decidable p) :=
Subsingleton.intro $ fun d₁ =>
match d₁ with
| (isTrue t₁) => fun d₂ =>
match d₂ with
| (isTrue t₂) => Eq.recOn (proofIrrel t₁ t₂) rfl
| (isFalse f₂) => absurd t₁ f₂
| (isFalse f₁) => fun d₂ =>
match d₂ with
| (isTrue t₂) => absurd t₂ f₁
| (isFalse f₂) => Eq.recOn (proofIrrel f₁ f₂) rfl
protected theorem recSubsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u}
[h₃ : ∀ (h : p), Subsingleton (h₁ h)] [h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)]
: Subsingleton (Decidable.casesOn h h₂ h₁) :=
match h with
| (isTrue h) => h₃ h
| (isFalse h) => h₄ h
section relation
variables {α : Sort u} {β : Sort v} (r : β → β → Prop)
def Reflexive := ∀ x, r x x
def Symmetric := ∀ {x y}, r x y → r y x
def Transitive := ∀ {x y z}, r x y → r y z → r x z
def Equivalence := Reflexive r ∧ Symmetric r ∧ Transitive r
def Total := ∀ x y, r x y ∨ r y x
def mkEquivalence (rfl : Reflexive r) (symm : Symmetric r) (trans : Transitive r) : Equivalence r :=
⟨rfl, @symm, @trans⟩
def Irreflexive := ∀ x, ¬ r x x
def AntiSymmetric := ∀ {x y}, r x y → r y x → x = y
def emptyRelation (a₁ a₂ : α) : Prop := False
def Subrelation (q r : β → β → Prop) := ∀ {x y}, q x y → r x y
def InvImage (f : α → β) : α → α → Prop :=
fun a₁ a₂ => r (f a₁) (f a₂)
theorem InvImage.Transitive (f : α → β) (h : Transitive r) : Transitive (InvImage r f) :=
fun (a₁ a₂ a₃ : α) (h₁ : InvImage r f a₁ a₂) (h₂ : InvImage r f a₂ a₃) => h h₁ h₂
theorem InvImage.Irreflexive (f : α → β) (h : Irreflexive r) : Irreflexive (InvImage r f) :=
fun (a : α) (h₁ : InvImage r f a a) => h (f a) h₁
inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop
| base : ∀ a b, r a b → TC a b
| trans : ∀ a b c, TC a b → TC b c → TC a c
@[elabAsEliminator]
theorem TC.ndrec.{u1, u2} {α : Sort u} {r : α → α → Prop} {C : α → α → Prop}
(m₁ : ∀ (a b : α), r a b → C a b)
(m₂ : ∀ (a b c : α), TC r a b → TC r b c → C a b → C b c → C a c)
{a b : α} (h : TC r a b) : C a b :=
@TC.rec α r (fun a b _ => C a b) m₁ m₂ a b h
@[elabAsEliminator]
theorem TC.ndrecOn.{u1, u2} {α : Sort u} {r : α → α → Prop} {C : α → α → Prop}
{a b : α} (h : TC r a b)
(m₁ : ∀ (a b : α), r a b → C a b)
(m₂ : ∀ (a b c : α), TC r a b → TC r b c → C a b → C b c → C a c)
: C a b :=
@TC.rec α r (fun a b _ => C a b) m₁ m₂ a b h
end relation
section Binary
variables {α : Type u} {β : Type v}
variable (f : α → α → α)
def Commutative := ∀ a b, f a b = f b a
def Associative := ∀ a b c, f (f a b) c = f a (f b c)
def RightCommutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁
def LeftCommutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b)
theorem leftComm : Commutative f → Associative f → LeftCommutative f :=
fun hcomm hassoc a b c =>
((Eq.symm (hassoc a b c)).trans (hcomm a b ▸ rfl : f (f a b) c = f (f b a) c)).trans (hassoc b a c)
theorem rightComm : Commutative f → Associative f → RightCommutative f :=
fun hcomm hassoc a b c =>
((hassoc a b c).trans (hcomm b c ▸ rfl : f a (f b c) = f a (f c b))).trans (Eq.symm (hassoc a c b))
end Binary
/- Subtype -/
namespace Subtype
def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x)
| ⟨a, h⟩ => ⟨a, h⟩
variables {α : Type u} {p : α → Prop}
theorem tagIrrelevant {a : α} (h1 h2 : p a) : mk a h1 = mk a h2 :=
rfl
protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2
| ⟨x, h1⟩, ⟨.(x), h2⟩, rfl => rfl
theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a :=
Subtype.eq rfl
instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} :=
⟨⟨a, h⟩⟩
instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} :=
fun ⟨a, h₁⟩ ⟨b, h₂⟩ =>
if h : a = b then isTrue (Subtype.eq h)
else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h))
end Subtype
/- Sum -/
section
variables {α : Type u} {β : Type v}
instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (Sum α β) :=
⟨Sum.inl (arbitrary α)⟩
instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (Sum α β) :=
⟨Sum.inr (arbitrary β)⟩
instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) :=
fun a b =>
match a, b with
| (Sum.inl a), (Sum.inl b) =>
if h : a = b then isTrue (h ▸ rfl)
else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h))
| (Sum.inr a), (Sum.inr b) =>
if h : a = b then isTrue (h ▸ rfl)
else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h))
| (Sum.inr a), (Sum.inl b) => isFalse (fun h => Sum.noConfusion h)
| (Sum.inl a), (Sum.inr b) => isFalse (fun h => Sum.noConfusion h)
end
/- Product -/
section
variables {α : Type u} {β : Type v}
instance [Inhabited α] [Inhabited β] : Inhabited (Prod α β) :=
⟨(arbitrary α, arbitrary β)⟩
instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) :=
fun ⟨a, b⟩ ⟨a', b'⟩ =>
match (decEq a a') with
| (isTrue e₁) =>
match (decEq b b') with
| (isTrue e₂) => isTrue (Eq.recOn e₁ (Eq.recOn e₂ rfl))
| (isFalse n₂) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₂' n₂))
| (isFalse n₁) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₁' n₁))
instance [HasBeq α] [HasBeq β] : HasBeq (α × β) :=
⟨fun ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ => a₁ == a₂ && b₁ == b₂⟩
instance [HasLess α] [HasLess β] : HasLess (α × β) :=
⟨fun s t => s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)⟩
instance prodHasDecidableLt
[HasLess α] [HasLess β] [DecidableEq α] [DecidableEq β]
[∀ (a b : α), Decidable (a < b)] [∀ (a b : β), Decidable (a < b)]
: ∀ (s t : α × β), Decidable (s < t) :=
fun t s => Or.Decidable
theorem Prod.ltDef [HasLess α] [HasLess β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) :=
rfl
end
def Prod.map.{u₁, u₂, v₁, v₂} {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂}
(f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂
| (a, b) => (f a, g b)
/- Dependent products -/
-- notation `Σ` binders `, ` r:(scoped p, Sigma p) := r
-- notation `Σ'` binders `, ` r:(scoped p, PSigma p) := r
theorem exOfPsig {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x)
| ⟨x, hx⟩ => ⟨x, hx⟩
section
variables {α : Type u} {β : α → Type v}
protected theorem Sigma.eq : ∀ {p₁ p₂ : Sigma (fun a => β a)} (h₁ : p₁.1 = p₂.1), (Eq.recOn h₁ p₁.2 : β p₂.1) = p₂.2 → p₁ = p₂
| ⟨a, b⟩, ⟨.(a), .(b)⟩, rfl, rfl => rfl
end
section
variables {α : Sort u} {β : α → Sort v}
protected theorem PSigma.eq : ∀ {p₁ p₂ : PSigma β} (h₁ : p₁.1 = p₂.1), (Eq.recOn h₁ p₁.2 : β p₂.1) = p₂.2 → p₁ = p₂
| ⟨a, b⟩, ⟨.(a), .(b)⟩, rfl, rfl => rfl
end
/- Universe polymorphic unit -/
theorem punitEq (a b : PUnit) : a = b :=
PUnit.recOn a (PUnit.recOn b rfl)
theorem punitEqPUnit (a : PUnit) : a = () :=
punitEq a ()
instance : Subsingleton PUnit :=
Subsingleton.intro punitEq
instance : Inhabited PUnit :=
⟨⟨⟩⟩
instance : DecidableEq PUnit :=
fun a b => isTrue (punitEq a b)
/- Setoid -/
class Setoid (α : Sort u) :=
(r : α → α → Prop) (iseqv : Equivalence r)
instance setoidHasEquiv {α : Sort u} [Setoid α] : HasEquiv α :=
⟨Setoid.r⟩
namespace Setoid
variables {α : Sort u} [Setoid α]
theorem refl (a : α) : a ≈ a :=
match Setoid.iseqv α with
| ⟨hRefl, hSymm, hTrans⟩ => hRefl a
theorem symm {a b : α} (hab : a ≈ b) : b ≈ a :=
match Setoid.iseqv α with
| ⟨hRefl, hSymm, hTrans⟩ => hSymm hab
theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c :=
match Setoid.iseqv α with
| ⟨hRefl, hSymm, hTrans⟩ => hTrans hab hbc
end Setoid
/- Propositional extensionality -/
axiom propext {a b : Prop} : (a ↔ b) → a = b
theorem eqTrueIntro {a : Prop} (h : a) : a = True :=
propext (iffTrueIntro h)
theorem eqFalseIntro {a : Prop} (h : ¬a) : a = False :=
propext (iffFalseIntro h)
/- Quotients -/
-- Iff can now be used to do substitutions in a calculation
theorem iffSubst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b :=
Eq.subst (propext h₁) h₂
namespace Quot
axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b
attribute [elabAsEliminator] lift ind
protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : ∀ a b, r a b → f a = f b) (a : α) : lift f c (Quot.mk r a) = f a :=
rfl
protected theorem indBeta {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} (p : ∀ a, β (Quot.mk r a)) (a : α) : (ind p (Quot.mk r a) : β (Quot.mk r a)) = p a :=
rfl
@[reducible, elabAsEliminator, inline]
protected def liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : ∀ a b, r a b → f a = f b) : β :=
lift f c q
@[elabAsEliminator]
protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} (q : Quot r) (h : ∀ a, β (Quot.mk r a)) : β q :=
ind h q
theorem existsRep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) :=
Quot.inductionOn q (fun a => ⟨a, rfl⟩)
section
variable {α : Sort u}
variable {r : α → α → Prop}
variable {β : Quot r → Sort v}
@[reducible, macroInline]
protected def indep (f : ∀ a, β (Quot.mk r a)) (a : α) : PSigma β :=
⟨Quot.mk r a, f a⟩
protected theorem indepCoherent (f : ∀ a, β (Quot.mk r a))
(h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b)
: ∀ a b, r a b → Quot.indep f a = Quot.indep f b :=
fun a b e => PSigma.eq (sound e) (h a b e)
protected theorem liftIndepPr1
(f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b)
(q : Quot r) : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q :=
Quot.ind (fun (a : α) => Eq.refl (Quot.indep f a).1) q
@[reducible, elabAsEliminator, inline]
protected def rec
(f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b)
(q : Quot r) : β q :=
Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2)
@[reducible, elabAsEliminator, inline]
protected def recOn
(q : Quot r) (f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b) : β q :=
Quot.rec f h q
@[reducible, elabAsEliminator, inline]
protected def recOnSubsingleton
[h : ∀ a, Subsingleton (β (Quot.mk r a))] (q : Quot r) (f : ∀ a, β (Quot.mk r a)) : β q :=
Quot.rec f (fun a b h => Subsingleton.elim _ (f b)) q
@[reducible, elabAsEliminator, inline]
protected def hrecOn
(q : Quot r) (f : ∀ a, β (Quot.mk r a)) (c : ∀ (a b : α) (p : r a b), f a ≅ f b) : β q :=
Quot.recOn q f $
fun a b p => eqOfHEq $
have p₁ : (Eq.rec (f a) (sound p) : β (Quot.mk r b)) ≅ f a := eqRecHEq (sound p) (f a);
HEq.trans p₁ (c a b p)
end
end Quot
def Quotient {α : Sort u} (s : Setoid α) :=
@Quot α Setoid.r
namespace Quotient
@[inline]
protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s :=
Quot.mk Setoid.r a
def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → Quotient.mk a = Quotient.mk b :=
Quot.sound
@[reducible, elabAsEliminator]
protected def lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : (∀ a b, a ≈ b → f a = f b) → Quotient s → β :=
Quot.lift f
@[elabAsEliminator]
protected theorem ind {α : Sort u} [s : Setoid α] {β : Quotient s → Prop} : (∀ a, β (Quotient.mk a)) → ∀ q, β q :=
Quot.ind
@[reducible, elabAsEliminator, inline]
protected def liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : ∀ a b, a ≈ b → f a = f b) : β :=
Quot.liftOn q f c
@[elabAsEliminator]
protected theorem inductionOn {α : Sort u} [s : Setoid α] {β : Quotient s → Prop} (q : Quotient s) (h : ∀ a, β (Quotient.mk a)) : β q :=
Quot.inductionOn q h
theorem existsRep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => Quotient.mk a = q) :=
Quot.existsRep q
section
variable {α : Sort u}
variable [s : Setoid α]
variable {β : Quotient s → Sort v}
@[inline]
protected def rec
(f : ∀ a, β (Quotient.mk a)) (h : ∀ (a b : α) (p : a ≈ b), (Eq.rec (f a) (Quotient.sound p) : β (Quotient.mk b)) = f b)
(q : Quotient s) : β q :=
Quot.rec f h q
@[reducible, elabAsEliminator, inline]
protected def recOn
(q : Quotient s) (f : ∀ a, β (Quotient.mk a)) (h : ∀ (a b : α) (p : a ≈ b), (Eq.rec (f a) (Quotient.sound p) : β (Quotient.mk b)) = f b) : β q :=
Quot.recOn q f h
@[reducible, elabAsEliminator, inline]
protected def recOnSubsingleton
[h : ∀ a, Subsingleton (β (Quotient.mk a))] (q : Quotient s) (f : ∀ a, β (Quotient.mk a)) : β q :=
@Quot.recOnSubsingleton _ _ _ h q f
@[reducible, elabAsEliminator, inline]
protected def hrecOn
(q : Quotient s) (f : ∀ a, β (Quotient.mk a)) (c : ∀ (a b : α) (p : a ≈ b), f a ≅ f b) : β q :=
Quot.hrecOn q f c
end
section
universes uA uB uC
variables {α : Sort uA} {β : Sort uB} {φ : Sort uC}
variables [s₁ : Setoid α] [s₂ : Setoid β]
@[reducible, elabAsEliminator, inline]
protected def lift₂
(f : α → β → φ)(c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂)
(q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ :=
Quotient.lift
(fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂)
(fun (a b : α) (h : a ≈ b) =>
@Quotient.ind β s₂
(fun (a1 : Quotient s₂) =>
(Quotient.lift (f a) (fun (a1 b : β) => c a a1 a b (Setoid.refl a)) a1)
=
(Quotient.lift (f b) (fun (a b1 : β) => c b a b b1 (Setoid.refl b)) a1))
(fun (a' : β) => c a a' b a' h (Setoid.refl a'))
q₂)
q₁
@[reducible, elabAsEliminator, inline]
protected def liftOn₂
(q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → φ) (c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) : φ :=
Quotient.lift₂ f c q₁ q₂
@[elabAsEliminator]
protected theorem ind₂ {φ : Quotient s₁ → Quotient s₂ → Prop} (h : ∀ a b, φ (Quotient.mk a) (Quotient.mk b)) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ q₁ q₂ :=
Quotient.ind (fun a₁ => Quotient.ind (fun a₂ => h a₁ a₂) q₂) q₁
@[elabAsEliminator]
protected theorem inductionOn₂
{φ : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : ∀ a b, φ (Quotient.mk a) (Quotient.mk b)) : φ q₁ q₂ :=
Quotient.ind (fun a₁ => Quotient.ind (fun a₂ => h a₁ a₂) q₂) q₁
@[elabAsEliminator]
protected theorem inductionOn₃
[s₃ : Setoid φ]
{δ : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : ∀ a b c, δ (Quotient.mk a) (Quotient.mk b) (Quotient.mk c))
: δ q₁ q₂ q₃ :=
Quotient.ind (fun a₁ => Quotient.ind (fun a₂ => Quotient.ind (fun a₃ => h a₁ a₂ a₃) q₃) q₂) q₁
end
section Exact
variable {α : Sort u}
private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop :=
Quotient.liftOn₂ q₁ q₂
(fun a₁ a₂ => a₁ ≈ a₂)
(fun a₁ a₂ b₁ b₂ a₁b₁ a₂b₂ =>
propext (Iff.intro
(fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂))
(fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂)))))
private theorem rel.refl [s : Setoid α] : ∀ (q : Quotient s), rel q q :=
fun q => Quot.inductionOn q (fun a => Setoid.refl a)
private theorem eqImpRel [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ :=
fun h => Eq.ndrecOn h (rel.refl q₁)
theorem exact [s : Setoid α] {a b : α} : Quotient.mk a = Quotient.mk b → a ≈ b :=
fun h => eqImpRel h
end Exact
section
universes uA uB uC
variables {α : Sort uA} {β : Sort uB}
variables [s₁ : Setoid α] [s₂ : Setoid β]
@[reducible, elabAsEliminator]
protected def recOnSubsingleton₂
{φ : Quotient s₁ → Quotient s₂ → Sort uC} [h : ∀ a b, Subsingleton (φ (Quotient.mk a) (Quotient.mk b))]
(q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : ∀ a b, φ (Quotient.mk a) (Quotient.mk b)) : φ q₁ q₂:=
@Quotient.recOnSubsingleton _ s₁ (fun q => φ q q₂) (fun a => Quotient.ind (fun b => h a b) q₂) q₁
(fun a => Quotient.recOnSubsingleton q₂ (fun b => f a b))
end
end Quotient
section
variable {α : Type u}
variable (r : α → α → Prop)
inductive EqvGen : α → α → Prop
| rel {} : ∀ x y, r x y → EqvGen x y
| refl {} : ∀ x, EqvGen x x
| symm {} : ∀ x y, EqvGen x y → EqvGen y x
| trans {} : ∀ x y z, EqvGen x y → EqvGen y z → EqvGen x z
theorem EqvGen.isEquivalence : Equivalence (@EqvGen α r) :=
mkEquivalence _ EqvGen.refl EqvGen.symm EqvGen.trans
def EqvGen.Setoid : Setoid α :=
Setoid.mk _ (EqvGen.isEquivalence r)
theorem Quot.exact {a b : α} (H : Quot.mk r a = Quot.mk r b) : EqvGen r a b :=
@Quotient.exact _ (EqvGen.Setoid r) a b (@congrArg _ _ _ _
(Quot.lift (@Quotient.mk _ (EqvGen.Setoid r)) (fun x y h => Quot.sound (EqvGen.rel x y h))) H)
theorem Quot.eqvGenSound {r : α → α → Prop} {a b : α} (H : EqvGen r a b) : Quot.mk r a = Quot.mk r b :=
EqvGen.recOn H
(fun x y h => Quot.sound h)
(fun x => rfl)
(fun x y _ IH => Eq.symm IH)
(fun x y z _ _ IH₁ IH₂ => Eq.trans IH₁ IH₂)
end
instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) :=
fun (q₁ q₂ : Quotient s) =>
Quotient.recOnSubsingleton₂ q₁ q₂
(fun a₁ a₂ =>
match (d a₁ a₂) with
| (isTrue h₁) => isTrue (Quotient.sound h₁)
| (isFalse h₂) => isFalse (fun h => absurd (Quotient.exact h) h₂))
/- Function extensionality -/
namespace Function
variables {α : Sort u} {β : α → Sort v}
def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x
protected theorem Equiv.refl (f : ∀ (x : α), β x) : Equiv f f :=
fun x => rfl
protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₁ :=
fun h x => Eq.symm (h x)
protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₃ → Equiv f₁ f₃ :=
fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x)
protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) :=
mkEquivalence (@Function.Equiv α β) (@Equiv.refl α β) (@Equiv.symm α β) (@Equiv.trans α β)
end Function
section
open Quotient
variables {α : Sort u} {β : α → Sort v}
@[instance]
private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) :=
Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β)
private def extfunApp (f : Quotient $ funSetoid α β) : ∀ (x : α), β x :=
fun x =>
Quot.liftOn f
(fun (f : ∀ (x : α), β x) => f x)
(fun f₁ f₂ h => h x)
theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ :=
show extfunApp (Quotient.mk f₁) = extfunApp (Quotient.mk f₂) from
congrArg extfunApp (sound h)
end
instance Forall.Subsingleton {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) :=
⟨fun f₁ f₂ => funext (fun a => Subsingleton.elim (f₁ a) (f₂ a))⟩
/- General operations on functions -/
namespace Function
universes u₁ u₂ u₃ u₄
variables {α : Sort u₁} {β : Sort u₂} {φ : Sort u₃} {δ : Sort u₄} {ζ : Sort u₁}
@[inline, reducible] def comp (f : β → φ) (g : α → β) : α → φ :=
fun x => f (g x)
infixr ` ∘ ` := Function.comp
@[inline, reducible] def onFun (f : β → β → φ) (g : α → β) : α → α → φ :=
fun x y => f (g x) (g y)
@[inline, reducible] def combine (f : α → β → φ) (op : φ → δ → ζ) (g : α → β → δ)
: α → β → ζ :=
fun x y => op (f x y) (g x y)
@[inline, reducible] def const (β : Sort u₂) (a : α) : β → α :=
fun x => a
@[inline, reducible] def swap {φ : α → β → Sort u₃} (f : ∀ x y, φ x y) : ∀ y x, φ x y :=
fun y x => f x y
end Function
/- Squash -/
def Squash (α : Type u) := Quot (fun (a b : α) => True)
def Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x
theorem Squash.ind {α : Type u} {β : Squash α → Prop} (h : ∀ (a : α), β (Squash.mk a)) : ∀ (q : Squash α), β q :=
Quot.ind h
@[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β :=
Quot.lift f (fun a b _ => Subsingleton.elim _ _) s
instance Squash.Subsingleton {α} : Subsingleton (Squash α) :=
⟨Squash.ind (fun (a : α) => Squash.ind (fun (b : α) => Quot.sound trivial))⟩
namespace Lean
/- Kernel reduction hints -/
/--
When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`.
The kernel will not use the interpreter if `c` is not a constant.
This feature is useful for performing proofs by reflection.
Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing
free variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with
`Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled.
Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base.
This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using
external type checkers (e.g., Trepplein) that do not implement this feature.
Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter.
So, you are mainly losing the capability of type checking your developement using external checkers. -/
def reduceBool (b : Bool) : Bool := b
/--
Similar to `Lean.reduceBool` for closed `Nat` terms.
Remark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`.
The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression.
We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/
def reduceNat (n : Nat) : Nat := n
def ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b := h
def ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b := h
end Lean
/- Classical reasoning support -/
namespace Classical
axiom choice {α : Sort u} : Nonempty α → α
noncomputable def indefiniteDescription {α : Sort u} (p : α → Prop)
(h : Exists (fun x => p x)) : {x // p x} :=
choice $ let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩
noncomputable def choose {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) : α :=
(indefiniteDescription p h).val
theorem chooseSpec {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) : p (choose h) :=
(indefiniteDescription p h).property
/- Diaconescu's theorem: excluded middle from choice, Function extensionality and propositional extensionality. -/
theorem em (p : Prop) : p ∨ ¬p :=
let U (x : Prop) : Prop := x = True ∨ p;
let V (x : Prop) : Prop := x = False ∨ p;
have exU : Exists (fun x => U x) from ⟨True, Or.inl rfl⟩;
have exV : Exists (fun x => V x) from ⟨False, Or.inl rfl⟩;
let u : Prop := choose exU;
let v : Prop := choose exV;
have uDef : U u from chooseSpec exU;
have vDef : V v from chooseSpec exV;
have notUvOrP : u ≠ v ∨ p from
Or.elim uDef
(fun hut =>
Or.elim vDef
(fun hvf =>
have hne : u ≠ v from hvf.symm ▸ hut.symm ▸ trueNeFalse;
Or.inl hne)
Or.inr)
Or.inr;
have pImpliesUv : p → u = v from
fun hp =>
have hpred : U = V from
funext $ fun x =>
have hl : (x = True ∨ p) → (x = False ∨ p) from
fun a => Or.inr hp;
have hr : (x = False ∨ p) → (x = True ∨ p) from
fun a => Or.inr hp;
show (x = True ∨ p) = (x = False ∨ p) from
propext (Iff.intro hl hr);
have h₀ : ∀ exU exV, @choose _ U exU = @choose _ V exV from
hpred ▸ fun exU exV => rfl;
show u = v from h₀ _ _;
Or.elim notUvOrP
(fun (hne : u ≠ v) => Or.inr (mt pImpliesUv hne))
Or.inl
theorem existsTrueOfNonempty {α : Sort u} : Nonempty α → Exists (fun (x : α) => True)
| ⟨x⟩ => ⟨x, trivial⟩
noncomputable def inhabitedOfNonempty {α : Sort u} (h : Nonempty α) : Inhabited α :=
⟨choice h⟩
noncomputable def inhabitedOfExists {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) :
Inhabited α :=
inhabitedOfNonempty (Exists.elim h (fun w hw => ⟨w⟩))
/- all propositions are Decidable -/
noncomputable def propDecidable (a : Prop) : Decidable a :=
choice $ Or.elim (em a)
(fun ha => ⟨isTrue ha⟩)
(fun hna => ⟨isFalse hna⟩)
noncomputable def decidableInhabited (a : Prop) : Inhabited (Decidable a) :=
⟨propDecidable a⟩
noncomputable def typeDecidableEq (α : Sort u) : DecidableEq α :=
fun x y => propDecidable (x = y)
noncomputable def typeDecidable (α : Sort u) : PSum α (α → False) :=
match (propDecidable (Nonempty α)) with
| (isTrue hp) => PSum.inl (@arbitrary _ (inhabitedOfNonempty hp))
| (isFalse hn) => PSum.inr (fun a => absurd (Nonempty.intro a) hn)
noncomputable def strongIndefiniteDescription {α : Sort u} (p : α → Prop)
(h : Nonempty α) : {x : α // Exists (fun (y : α) => p y) → p x} :=
@dite _ (Exists (fun (x : α) => p x)) (propDecidable _)
(fun (hp : Exists (fun (x : α) => p x)) =>
show {x : α // Exists (fun (y : α) => p y) → p x} from
let xp := indefiniteDescription _ hp;
⟨xp.val, fun h' => xp.property⟩)
(fun hp => ⟨choice h, fun h => absurd h hp⟩)
/- the Hilbert epsilon Function -/
noncomputable def epsilon {α : Sort u} [h : Nonempty α] (p : α → Prop) : α :=
(strongIndefiniteDescription p h).val
theorem epsilonSpecAux {α : Sort u} (h : Nonempty α) (p : α → Prop)
: Exists (fun y => p y) → p (@epsilon α h p) :=
(strongIndefiniteDescription p h).property
theorem epsilonSpec {α : Sort u} {p : α → Prop} (hex : Exists (fun y => p y)) :
p (@epsilon α (nonemptyOfExists hex) p) :=
epsilonSpecAux (nonemptyOfExists hex) p hex
theorem epsilonSingleton {α : Sort u} (x : α) : @epsilon α ⟨x⟩ (fun y => y = x) = x :=
@epsilonSpec α (fun y => y = x) ⟨x, rfl⟩
/- the axiom of choice -/
theorem axiomOfChoice {α : Sort u} {β : α → Sort v} {r : ∀ x, β x → Prop} (h : ∀ x, Exists (fun y => r x y)) :
Exists (fun (f : ∀ x, β x) => ∀ x, r x (f x)) :=
⟨_, fun x => chooseSpec (h x)⟩
theorem skolem {α : Sort u} {b : α → Sort v} {p : ∀ x, b x → Prop} :
(∀ x, Exists (fun y => p x y)) ↔ Exists (fun (f : ∀ x, b x) => ∀ x, p x (f x)) :=
⟨axiomOfChoice, fun ⟨f, hw⟩ (x) => ⟨f x, hw x⟩⟩
theorem propComplete (a : Prop) : a = True ∨ a = False :=
Or.elim (em a)
(fun t => Or.inl (eqTrueIntro t))
(fun f => Or.inr (eqFalseIntro f))
-- this supercedes byCases in Decidable
theorem byCases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q :=
@Decidable.byCases _ _ (propDecidable _) hpq hnpq
-- this supercedes byContradiction in Decidable
theorem byContradiction {p : Prop} (h : ¬p → False) : p :=
@Decidable.byContradiction _ (propDecidable _) h
end Classical
|
da2d586c33ad3b9d78bc1bd1c21162ea95cf7ea8 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/584a.lean | 94fc6ef997329d42fea747bb2d1b9c9e55180872 | [
"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 | 305 | lean | variables (A : Type) [H : inhabited A] (x : A)
include H
definition foo := x
check foo -- A and x are explicit
variables {A x}
definition foo' := x
check @foo' -- A is explicit, x is implicit
open nat
check foo nat 10
definition test : foo' = (10:nat) := rfl
set_option pp.implicit true
print test
|
efd2b494870430aa976ee4a5ce1a56ac1905a76b | 958488bc7f3c2044206e0358e56d7690b6ae696c | /lean/conjunction.lean | 4955b6f81f117c02be7c6d1e68ae7067148a1994 | [] | no_license | possientis/Prog | a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4 | d4b3debc37610a88e0dac3ac5914903604fd1d1f | refs/heads/master | 1,692,263,717,723 | 1,691,757,179,000 | 1,691,757,179,000 | 40,361,602 | 3 | 0 | null | 1,679,896,438,000 | 1,438,953,859,000 | Coq | UTF-8 | Lean | false | false | 1,076 | lean |
lemma L1 : ∀ (p q:Prop), p → q → p ∧ q :=
λ p q hp hq, and.intro hp hq
lemma L2 : ∀ (p q:Prop), p ∧ q → p :=
λ p q h, and.elim_left h
lemma L2' : ∀ (p q:Prop), p ∧ q → p :=
λ p q h, and.left h
lemma L3 : ∀ (p q:Prop), p ∧ q → q :=
λ p q h, and.elim_right h
lemma L3' : ∀ (p q:Prop), p ∧ q → q :=
λ p q h, and.right h
lemma L4 : ∀ (p q:Prop), p ∧ q → q ∧ p :=
λ p q h, and.intro (and.right h) (and.left h)
lemma L4' : ∀ (p q:Prop), p ∧ q → q ∧ p :=
λ p q h, ⟨(and.right h),(and.left h)⟩ -- \langle, \rangle, or \< \>
lemma L4'' : ∀ (p q:Prop), p ∧ q → q ∧ p :=
λ p q h, (|(and.right h),(and.left h)|)
--#check L1
--#check L2
--#check L2'
--#check L3
--#check L3'
--#check L4
--#check L4'
--#check L4''
variable l : list ℕ
--#check list.head l
--#check l.head
lemma L5 : ∀ (p q:Prop), p ∧ q → q ∧ p :=
λ p q h, ⟨h.right,h.left⟩
--#check L5
lemma L6 : ∀ (p q:Prop), p ∧ q → q ∧ p ∧ q :=
λ p q h, ⟨h.right,⟨h.left,h.right⟩⟩
--#check L6
|
c61a3964cf8a7b8c9c2a91ae113863a44f282a25 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /02_Dependent_Type_Theory.org.36.lean | ce2cbe1fed5852b91c4902056c553319d1e83790 | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 463 | lean | /- page 29 -/
import standard
namespace hide
constant list : Type → Type
namespace list
constant cons : Π A : Type, A → list A → list A
constant nil : Π A : Type, list A
constant append : Π A : Type, list A → list A → list A
end list
-- BEGIN
open hide.list
variable A : Type
variable a : A
variables l1 l2 : list A
check cons A a (nil A)
check append A (cons A a (nil A)) l1
check append A (append A (cons A a (nil A)) l1) l2
-- END
end hide
|
9b141be780e4ffc696313e433ad03135cd54f008 | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/run/tryPureCoe.lean | bd46d63ab37eece35b6f1899dcce0aa2b68f2e8e | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 506 | lean | new_frontend
def m1 : IO Bool :=
pure true
def p (x : Nat) : Bool :=
x > 0
def tst1 : IO Bool :=
true <&&> m1
def tst2 (x : Nat) : IO Bool :=
x = 0 <&&> m1
def tst3 (x : Nat) : IO Unit :=
whenM (m1 <&&> x > 0) $
throw $ IO.userError "test"
def tst4 (x : Nat) : IO Unit :=
whenM (x > 0 <&&> m1) $
throw $ IO.userError "test"
def tst5 (x : Nat) : IO Unit :=
whenM (p x <&&> m1) $
throw $ IO.userError "test"
def tst6 (x : Nat) : IO Unit :=
whenM (p x <&&> id m1) $
throw $ IO.userError "test"
|
1227775a91fa9b9fcae4d9a979ba1cfc35ae5274 | 1446f520c1db37e157b631385707cc28a17a595e | /stage0/src/Init/Lean/Parser/Parser.lean | 7fd57d4cbd262d7497a51dc4d4ea381febc30241 | [
"Apache-2.0"
] | permissive | bdbabiak/lean4 | cab06b8a2606d99a168dd279efdd404edb4e825a | 3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac | refs/heads/master | 1,615,045,275,530 | 1,583,793,696,000 | 1,583,793,696,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 78,555 | 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, Sebastian Ullrich
-/
prelude
import Init.Lean.Data.Trie
import Init.Lean.Data.Position
import Init.Lean.Syntax
import Init.Lean.ToExpr
import Init.Lean.Environment
import Init.Lean.Attributes
import Init.Lean.Message
import Init.Lean.Compiler.InitAttr
namespace Lean
namespace Parser
def isLitKind (k : SyntaxNodeKind) : Bool :=
k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind
abbrev mkAtom (info : SourceInfo) (val : String) : Syntax :=
Syntax.atom info val
abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax :=
Syntax.ident (some info) rawVal val []
/- Return character after position `pos` -/
def getNext (input : String) (pos : Nat) : Char :=
input.get (input.next pos)
/- Function application precedence.
In the standard lean language, only two tokens have precedence higher that `appPrec`.
- The token `.` has precedence `appPrec+1`. Thus, field accesses like `g (h x).f` are parsed as `g ((h x).f)`,
not `(g (h x)).f`
- The token `[` when not preceded with whitespace has precedence `appPrec+1`. If there is whitespace before
`[`, then its precedence is `appPrec`. Thus, `f a[i]` is parsed as `f (a[i])` where `a[i]` is an "find-like operation"
(e.g., array access, map access, etc.). `f a [i]` is parsed as `(f a) [i]` where `[i]` is a singleton collection
(e.g., a list). -/
def appPrec : Nat := 1024
structure TokenConfig :=
(val : String)
(lbp : Option Nat := none)
(lbpNoWs : Option Nat := none) -- optional left-binding power when there is not whitespace before the token.
namespace TokenConfig
def beq : TokenConfig → TokenConfig → Bool
| ⟨val₁, lbp₁, lbpnws₁⟩, ⟨val₂, lbp₂, lbpnws₂⟩ => val₁ == val₂ && lbp₁ == lbp₂ && lbpnws₁ == lbpnws₂
instance : HasBeq TokenConfig :=
⟨beq⟩
def toStr : TokenConfig → String
| ⟨val, some lbp, some lbpnws⟩ => val ++ ":" ++ toString lbp ++ ":" ++ toString lbpnws
| ⟨val, some lbp, none⟩ => val ++ ":" ++ toString lbp
| ⟨val, none, some lbpnws⟩ => val ++ ":none:" ++ toString lbpnws
| ⟨val, none, none⟩ => val
instance : HasToString TokenConfig := ⟨toStr⟩
end TokenConfig
structure TokenCacheEntry :=
(startPos stopPos : String.Pos := 0)
(token : Syntax := Syntax.missing)
structure ParserCache :=
(tokenCache : TokenCacheEntry := {})
def initCacheForInput (input : String) : ParserCache :=
{ tokenCache := { startPos := input.bsize + 1 /- make sure it is not a valid position -/} }
abbrev TokenTable := Trie TokenConfig
abbrev SyntaxNodeKindSet := PersistentHashMap SyntaxNodeKind Unit
def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet :=
s.insert k ()
/-
Input string and related data. Recall that the `FileMap` is a helper structure for mapping
`String.Pos` in the input string to line/column information. -/
structure InputContext :=
(input : String)
(fileName : String)
(fileMap : FileMap)
instance InputContext.inhabited : Inhabited InputContext :=
⟨{ input := "", fileName := "", fileMap := arbitrary _ }⟩
structure ParserContext extends InputContext :=
(rbp : Nat)
(env : Environment)
(tokens : TokenTable)
structure Error :=
(unexpected : String := "")
(expected : List String := [])
namespace Error
instance : Inhabited Error := ⟨{}⟩
private def expectedToString : List String → String
| [] => ""
| [e] => e
| [e1, e2] => e1 ++ " or " ++ e2
| e::es => e ++ ", " ++ expectedToString es
protected def toString (e : Error) : String :=
let unexpected := if e.unexpected == "" then [] else [e.unexpected];
let expected := if e.expected == [] then [] else ["expected " ++ expectedToString e.expected];
"; ".intercalate $ unexpected ++ expected
instance : HasToString Error := ⟨Error.toString⟩
protected def beq (e₁ e₂ : Error) : Bool :=
e₁.unexpected == e₂.unexpected && e₁.expected == e₂.expected
instance : HasBeq Error := ⟨Error.beq⟩
def merge (e₁ e₂ : Error) : Error :=
match e₂ with
| { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected }
end Error
structure ParserState :=
(stxStack : Array Syntax := #[])
(pos : String.Pos := 0)
(cache : ParserCache := {})
(errorMsg : Option Error := none)
namespace ParserState
@[inline] def hasError (s : ParserState) : Bool :=
s.errorMsg != none
@[inline] def stackSize (s : ParserState) : Nat :=
s.stxStack.size
def restore (s : ParserState) (iniStackSz : Nat) (iniPos : Nat) : ParserState :=
{ stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos, .. s}
def setPos (s : ParserState) (pos : Nat) : ParserState :=
{ pos := pos, .. s }
def setCache (s : ParserState) (cache : ParserCache) : ParserState :=
{ cache := cache, .. s }
def pushSyntax (s : ParserState) (n : Syntax) : ParserState :=
{ stxStack := s.stxStack.push n, .. s }
def popSyntax (s : ParserState) : ParserState :=
{ stxStack := s.stxStack.pop, .. s }
def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState :=
{ stxStack := s.stxStack.shrink iniStackSz, .. s }
def next (s : ParserState) (input : String) (pos : Nat) : ParserState :=
{ pos := input.next pos, .. s }
def toErrorMsg (ctx : ParserContext) (s : ParserState) : String :=
match s.errorMsg with
| none => ""
| some msg =>
let pos := ctx.fileMap.toPosition s.pos;
mkErrorStringWithPos ctx.fileName pos.line pos.column (toString msg)
def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ =>
if err != none && stack.size == iniStackSz then
-- If there is an error but there are no new nodes on the stack, we just return `s`
s
else
let newNode := Syntax.node k (stack.extract iniStackSz stack.size);
let stack := stack.shrink iniStackSz;
let stack := stack.push newNode;
⟨stack, pos, cache, err⟩
def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ =>
let newNode := Syntax.node k (stack.extract (iniStackSz - 1) stack.size);
let stack := stack.shrink iniStackSz;
let stack := stack.push newNode;
⟨stack, pos, cache, err⟩
def mkError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩
def mkUnexpectedError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩
def mkEOIError (s : ParserState) : ParserState :=
s.mkUnexpectedError "end of input"
def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩
def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := ex }⟩
def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩
end ParserState
def ParserFn := ParserContext → ParserState → ParserState
instance ParserFn.inhabited : Inhabited ParserFn := ⟨fun _ => id⟩
inductive FirstTokens
| epsilon : FirstTokens
| unknown : FirstTokens
| tokens : List TokenConfig → FirstTokens
| optTokens : List TokenConfig → FirstTokens
namespace FirstTokens
def seq : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => tks
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| tks, _ => tks
def toOptional : FirstTokens → FirstTokens
| tokens tks => optTokens tks
| tks => tks
def merge : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => toOptional tks
| tks, epsilon => toOptional tks
| tokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂)
| _, _ => unknown
def toStr : FirstTokens → String
| epsilon => "epsilon"
| unknown => "unknown"
| tokens tks => toString tks
| optTokens tks => "?" ++ toString tks
instance : HasToString FirstTokens := ⟨toStr⟩
end FirstTokens
structure ParserInfo :=
(collectTokens : List TokenConfig → List TokenConfig := id)
(collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id)
(firstTokens : FirstTokens := FirstTokens.unknown)
structure Parser :=
(info : ParserInfo := {})
(fn : ParserFn)
instance Parser.inhabited : Inhabited Parser :=
⟨{ fn := fun _ s => s }⟩
abbrev TrailingParser := Parser
@[noinline] def epsilonInfo : ParserInfo :=
{ firstTokens := FirstTokens.epsilon }
@[inline] def checkStackTopFn (p : Syntax → Bool) : ParserFn :=
fun c s =>
if p s.stxStack.back then s
else s.mkUnexpectedError "invalid leading token"
@[inline] def checkStackTop (p : Syntax → Bool) : Parser :=
{ info := epsilonInfo,
fn := checkStackTopFn p }
@[inline] def andthenFn (p q : ParserFn) : ParserFn :=
fun c s =>
let s := p c s;
if s.hasError then s else q c s
@[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.seq q.firstTokens }
@[inline] def andthen (p q : Parser) : Parser :=
{ info := andthenInfo p.info q.info,
fn := andthenFn p.fn q.fn }
instance hashAndthen : HasAndthen Parser :=
⟨andthen⟩
@[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let s := p c s;
s.mkNode n iniSz
@[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let s := p c s;
s.mkTrailingNode n iniSz
@[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens,
collectKinds := fun s => (p.collectKinds s).insert n,
firstTokens := p.firstTokens }
@[inline] def node (n : SyntaxNodeKind) (p : Parser) : Parser :=
{ info := nodeInfo n p.info,
fn := nodeFn n p.fn }
@[inline] def leadingNode (n : SyntaxNodeKind) (p : Parser) : Parser :=
node n p
@[inline] def trailingNode (n : SyntaxNodeKind) (p : Parser) : TrailingParser :=
{ info := nodeInfo n p.info,
fn := trailingNodeFn n p.fn }
@[inline] def group (p : Parser) : Parser :=
node nullKind p
def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, some error2⟩ =>
if pos == iniPos then ⟨stack, pos, cache, some (error1.merge error2)⟩
else s
| other => other
@[inline] def orelseFn (p q : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
match s.errorMsg with
| some errorMsg =>
if s.pos == iniPos then
mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos
else
s
| none => s
@[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.merge q.firstTokens }
@[inline] def orelse (p q : Parser) : Parser :=
{ info := orelseInfo p.info q.info,
fn := orelseFn p.fn q.fn }
instance hashOrelse : HasOrelse Parser :=
⟨orelse⟩
@[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo :=
{ collectTokens := info.collectTokens,
collectKinds := info.collectKinds }
@[inline] def tryFn (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
match p c s with
| ⟨stack, _, cache, some msg⟩ => ⟨stack.shrink iniSz, iniPos, cache, some msg⟩
| other => other
@[inline] def try (p : Parser) : Parser :=
{ info := p.info,
fn := tryFn p.fn }
@[inline] def optionalFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s;
s.mkNode nullKind iniSz
@[noinline] def optionaInfo (p : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens,
collectKinds := p.collectKinds,
firstTokens := p.firstTokens.toOptional }
@[inline] def optional (p : Parser) : Parser :=
{ info := optionaInfo p.info,
fn := optionalFn p.fn }
@[inline] def lookaheadFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
if s.hasError then s else s.restore iniSz iniPos
@[inline] def lookahead (p : Parser) : Parser :=
{ info := p.info,
fn := lookaheadFn p.fn }
@[specialize] partial def manyAux (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
if s.hasError then
if iniPos == s.pos then s.restore iniSz iniPos else s
else if iniPos == s.pos then s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything"
else manyAux c s
@[inline] def manyFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let s := manyAux p c s;
s.mkNode nullKind iniSz
@[inline] def many (p : Parser) : Parser :=
{ info := noFirstTokenInfo p.info,
fn := manyFn p.fn }
@[inline] def many1Fn (p : ParserFn) (unboxSingleton : Bool) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let s := andthenFn p (manyAux p) c s;
if s.stackSize - iniSz == 1 && unboxSingleton then
s
else
s.mkNode nullKind iniSz
@[inline] def many1 (p : Parser) (unboxSingleton := false) : Parser :=
{ info := p.info,
fn := many1Fn p.fn unboxSingleton }
@[specialize] private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool)
(iniSz : Nat) (unboxSingleton : Bool) : Bool → ParserFn
| pOpt, c, s =>
let sz := s.stackSize;
let pos := s.pos;
let s := p c s;
if s.hasError then
if s.pos > pos then s
else if pOpt then
let s := s.restore sz pos;
if s.stackSize - iniSz == 2 && unboxSingleton then
s.popSyntax
else
s.mkNode nullKind iniSz
else
-- append `Syntax.missing` to make clear that List is incomplete
let s := s.pushSyntax Syntax.missing;
s.mkNode nullKind iniSz
else
let sz := s.stackSize;
let pos := s.pos;
let s := sep c s;
if s.hasError then
let s := s.restore sz pos;
if s.stackSize - iniSz == 1 && unboxSingleton then
s
else
s.mkNode nullKind iniSz
else
sepByFnAux allowTrailingSep c s
@[specialize] def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
sepByFnAux p sep allowTrailingSep iniSz false true c s
@[specialize] def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) (unboxSingleton : Bool) : ParserFn
| c, s =>
let iniSz := s.stackSize;
sepByFnAux p sep allowTrailingSep iniSz unboxSingleton false c s
@[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds }
@[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds,
firstTokens := p.firstTokens }
@[inline] def sepBy (p sep : Parser) (allowTrailingSep : Bool := false) : Parser :=
{ info := sepByInfo p.info sep.info,
fn := sepByFn allowTrailingSep p.fn sep.fn }
@[inline] def sepBy1 (p sep : Parser) (allowTrailingSep : Bool := false) (unboxSingleton := false) : Parser :=
{ info := sepBy1Info p.info sep.info,
fn := sepBy1Fn allowTrailingSep p.fn sep.fn unboxSingleton }
@[specialize] partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn
| c, s =>
let i := s.pos;
if c.input.atEnd i then s.mkEOIError
else if p (c.input.get i) then s.next c.input i
else s.mkUnexpectedError errorMsg
@[specialize] partial def takeUntilFn (p : Char → Bool) : ParserFn
| c, s =>
let i := s.pos;
if c.input.atEnd i then s
else if p (c.input.get i) then s
else takeUntilFn c (s.next c.input i)
@[specialize] def takeWhileFn (p : Char → Bool) : ParserFn :=
takeUntilFn (fun c => !p c)
@[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn :=
andthenFn (satisfyFn p errorMsg) (takeWhileFn p)
partial def finishCommentBlock : Nat → ParserFn
| nesting, c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let i := input.next i;
if curr == '-' then
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if curr == '/' then -- "-/" end of comment
if nesting == 1 then s.next input i
else finishCommentBlock (nesting-1) c (s.next input i)
else
finishCommentBlock nesting c (s.next input i)
else if curr == '/' then
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i)
else finishCommentBlock nesting c (s.setPos i)
else finishCommentBlock nesting c (s.setPos i)
/- Consume whitespace and comments -/
partial def whitespace : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s
else
let curr := input.get i;
if curr.isWhitespace then whitespace c (s.next input i)
else if curr == '-' then
let i := input.next i;
let curr := input.get i;
if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i)
else s
else if curr == '/' then
let i := input.next i;
let curr := input.get i;
if curr == '-' then
let i := input.next i;
let curr := input.get i;
if curr == '-' then s -- "/--" doc comment is an actual token
else andthenFn (finishCommentBlock 1) whitespace c (s.next input i)
else s
else s
def mkEmptySubstringAt (s : String) (p : Nat) : Substring :=
{str := s, startPos := p, stopPos := p }
private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn
| c, s =>
let input := c.input;
let stopPos := s.pos;
let leading := mkEmptySubstringAt input startPos;
let val := input.extract startPos stopPos;
if trailingWs then
let s := whitespace c s;
let stopPos' := s.pos;
let trailing := { Substring . str := input, startPos := stopPos, stopPos := stopPos' };
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val;
s.pushSyntax atom
else
let trailing := mkEmptySubstringAt input stopPos;
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val;
s.pushSyntax atom
/-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/
@[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn
| c, s =>
let startPos := s.pos;
let s := p c s;
if s.hasError then s else rawAux startPos trailingWs c s
@[inline] def chFn (c : Char) (trailingWs := false) : ParserFn :=
rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs
def rawCh (c : Char) (trailingWs := false) : Parser :=
{ fn := chFn c trailingWs }
def hexDigitFn : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let i := input.next i;
if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i
else s.mkUnexpectedError "invalid hexadecimal numeral"
def quotedCharFn : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if curr == '\\' || curr == '\"' || curr == '\'' || curr == 'n' || curr == 't' then
s.next input i
else if curr == 'x' then
andthenFn hexDigitFn hexDigitFn c (s.next input i)
else if curr == 'u' then
andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i)
else
s.mkUnexpectedError "invalid escape sequence"
/-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/
def mkNodeToken (n : SyntaxNodeKind) (startPos : Nat) : ParserFn :=
fun c s =>
let input := c.input;
let stopPos := s.pos;
let leading := mkEmptySubstringAt input startPos;
let val := input.extract startPos stopPos;
let s := whitespace c s;
let wsStopPos := s.pos;
let trailing := { Substring . str := input, startPos := stopPos, stopPos := wsStopPos };
let info := { SourceInfo . leading := leading, pos := startPos, trailing := trailing };
s.pushSyntax (mkStxLit n val (some info))
def charLitFnAux (startPos : Nat) : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let s := s.setPos (input.next i);
let s := if curr == '\\' then quotedCharFn c s else s;
if s.hasError then s
else
let i := s.pos;
let curr := input.get i;
let s := s.setPos (input.next i);
if curr == '\'' then mkNodeToken charLitKind startPos c s
else s.mkUnexpectedError "missing end of character literal"
partial def strLitFnAux (startPos : Nat) : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let s := s.setPos (input.next i);
if curr == '\"' then
mkNodeToken strLitKind startPos c s
else if curr == '\\' then andthenFn quotedCharFn strLitFnAux c s
else strLitFnAux c s
def decimalNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhileFn (fun c => c.isDigit) c s;
let input := c.input;
let i := s.pos;
let curr := input.get i;
let s :=
/- TODO(Leo): should we use a different kind for numerals containing decimal points? -/
if curr == '.' then
let i := input.next i;
let curr := input.get i;
if curr.isDigit then
takeWhileFn (fun c => c.isDigit) c (s.setPos i)
else s
else s;
mkNodeToken numLitKind startPos c s
def binNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s;
mkNodeToken numLitKind startPos c s
def octalNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s;
mkNodeToken numLitKind startPos c s
def hexNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s;
mkNodeToken numLitKind startPos c s
def numberFnAux : ParserFn :=
fun c s =>
let input := c.input;
let startPos := s.pos;
if input.atEnd startPos then s.mkEOIError
else
let curr := input.get startPos;
if curr == '0' then
let i := input.next startPos;
let curr := input.get i;
if curr == 'b' || curr == 'B' then
binNumberFn startPos c (s.next input i)
else if curr == 'o' || curr == 'O' then
octalNumberFn startPos c (s.next input i)
else if curr == 'x' || curr == 'X' then
hexNumberFn startPos c (s.next input i)
else
decimalNumberFn startPos c (s.setPos i)
else if curr.isDigit then
decimalNumberFn startPos c (s.next input startPos)
else
s.mkError "numeral"
def isIdCont : String → ParserState → Bool
| input, s =>
let i := s.pos;
let curr := input.get i;
if curr == '.' then
let i := input.next i;
if input.atEnd i then
false
else
let curr := input.get i;
isIdFirst curr || isIdBeginEscape curr
else
false
private def isToken (idStartPos idStopPos : Nat) (tk : Option TokenConfig) : Bool :=
match tk with
| none => false
| some tk =>
-- if a token is both a symbol and a valid identifier (i.e. a keyword),
-- we want it to be recognized as a symbol
tk.val.bsize ≥ idStopPos - idStartPos
def mkTokenAndFixPos (startPos : Nat) (tk : Option TokenConfig) : ParserFn :=
fun c s =>
match tk with
| none => s.mkErrorAt "token" startPos
| some tk =>
let input := c.input;
let leading := mkEmptySubstringAt input startPos;
let val := tk.val;
let stopPos := startPos + val.bsize;
let s := s.setPos stopPos;
let s := whitespace c s;
let wsStopPos := s.pos;
let trailing := { Substring . str := input, startPos := stopPos, stopPos := wsStopPos };
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val;
s.pushSyntax atom
def mkIdResult (startPos : Nat) (tk : Option TokenConfig) (val : Name) : ParserFn :=
fun c s =>
let stopPos := s.pos;
if isToken startPos stopPos tk then
mkTokenAndFixPos startPos tk c s
else
let input := c.input;
let rawVal := { Substring . str := input, startPos := startPos, stopPos := stopPos };
let s := whitespace c s;
let trailingStopPos := s.pos;
let leading := mkEmptySubstringAt input startPos;
let trailing := { Substring . str := input, startPos := stopPos, stopPos := trailingStopPos };
let info := { SourceInfo . leading := leading, trailing := trailing, pos := startPos };
let atom := mkIdent info rawVal val;
s.pushSyntax atom
partial def identFnAux (startPos : Nat) (tk : Option TokenConfig) : Name → ParserFn
| r, c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if isIdBeginEscape curr then
let startPart := input.next i;
let s := takeUntilFn isIdEndEscape c (s.setPos startPart);
let stopPart := s.pos;
let s := satisfyFn isIdEndEscape "missing end of escaped identifier" c s;
if s.hasError then s
else
let r := mkNameStr r (input.extract startPart stopPart);
if isIdCont input s then
let s := s.next input s.pos;
identFnAux r c s
else
mkIdResult startPos tk r c s
else if isIdFirst curr then
let startPart := i;
let s := takeWhileFn isIdRest c (s.next input i);
let stopPart := s.pos;
let r := mkNameStr r (input.extract startPart stopPart);
if isIdCont input s then
let s := s.next input s.pos;
identFnAux r c s
else
mkIdResult startPos tk r c s
else
mkTokenAndFixPos startPos tk c s
private def isIdFirstOrBeginEscape (c : Char) : Bool :=
isIdFirst c || isIdBeginEscape c
private def nameLitAux (startPos : Nat) : ParserFn
| c, s =>
let input := c.input;
let s := identFnAux startPos none Name.anonymous c (s.next input startPos);
if s.hasError then
s.mkErrorAt "invalid Name literal" startPos
else
let stx := s.stxStack.back;
match stx with
| Syntax.ident _ rawStr _ _ =>
let s := s.popSyntax;
s.pushSyntax (Syntax.node nameLitKind #[mkAtomFrom stx rawStr.toString])
| _ => s.mkError "invalid Name literal"
private def tokenFnAux : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
let curr := input.get i;
if curr == '\"' then
strLitFnAux i c (s.next input i)
else if curr == '\'' then
charLitFnAux i c (s.next input i)
else if curr.isDigit then
numberFnAux c s
else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then
nameLitAux i c s
else
let (_, tk) := c.tokens.matchPrefix input i;
identFnAux i tk Name.anonymous c s
private def updateCache (startPos : Nat) (s : ParserState) : ParserState :=
match s with
| ⟨stack, pos, cache, none⟩ =>
if stack.size == 0 then s
else
let tk := stack.back;
⟨stack, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩
| other => other
def tokenFn : ParserFn :=
fun c s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let tkc := s.cache.tokenCache;
if tkc.startPos == i then
let s := s.pushSyntax tkc.token;
s.setPos tkc.stopPos
else
let s := tokenFnAux c s;
updateCache i s
def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Option Syntax :=
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError then (s.restore iniSz iniPos, none)
else
let stx := s.stxStack.back;
(s.restore iniSz iniPos, some stx)
@[inline] def peekToken (c : ParserContext) (s : ParserState) : ParserState × Option Syntax :=
let tkc := s.cache.tokenCache;
if tkc.startPos == s.pos then
(s, some tkc.token)
else
peekTokenAux c s
/- Treat keywords as identifiers. -/
def rawIdentFn : ParserFn :=
fun c s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else identFnAux i none Name.anonymous c s
@[inline] def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn :=
fun c s =>
let startPos := s.pos;
let s := tokenFn c s;
if s.hasError then
s.mkErrorsAt expected startPos
else
match s.stxStack.back with
| Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos
| _ => s.mkErrorsAt expected startPos
@[inline] def symbolFnAux (sym : String) (errorMsg : String) : ParserFn :=
satisfySymbolFn (fun s => s == sym) [errorMsg]
def symbolInfo (sym : String) (lbp : Option Nat) : ParserInfo :=
{ collectTokens := fun tks => { val := sym, lbp := lbp } :: tks,
firstTokens := FirstTokens.tokens [ { val := sym, lbp := lbp } ] }
@[inline] def symbolFn (sym : String) : ParserFn :=
symbolFnAux sym ("'" ++ sym ++ "'")
@[inline] def symbolAux (sym : String) (lbp : Option Nat := none) : Parser :=
let sym := sym.trim;
{ info := symbolInfo sym lbp,
fn := symbolFn sym }
@[inline] def symbol (sym : String) (lbp : Nat) : Parser :=
symbolAux sym lbp
/-- Check if the following token is the symbol _or_ identifier `sym`. Useful for
parsing local tokens that have not been added to the token table (but may have
been so by some unrelated code).
For example, the universe `max` Function is parsed using this combinator so that
it can still be used as an identifier outside of universes (but registering it
as a token in a Term Syntax would not break the universe Parser). -/
def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn :=
fun c s =>
let startPos := s.pos;
let s := tokenFn c s;
if s.hasError then s.mkErrorAt errorMsg startPos
else
match s.stxStack.back with
| Syntax.atom _ sym' =>
if sym == sym' then s else s.mkErrorAt errorMsg startPos
| Syntax.ident info rawVal _ _ =>
if sym == rawVal.toString then
let s := s.popSyntax;
s.pushSyntax (Syntax.atom info sym)
else
s.mkErrorAt errorMsg startPos
| _ => s.mkErrorAt errorMsg startPos
@[inline] def nonReservedSymbolFn (sym : String) : ParserFn :=
nonReservedSymbolFnAux sym ("'" ++ sym ++ "'")
def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo :=
{ firstTokens :=
if includeIdent then
FirstTokens.tokens [ { val := sym }, { val := "ident" } ]
else
FirstTokens.tokens [ { val := sym } ] }
@[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser :=
let sym := sym.trim;
{ info := nonReservedSymbolInfo sym includeIdent,
fn := nonReservedSymbolFn sym }
partial def strAux (sym : String) (errorMsg : String) : Nat → ParserFn
| j, c, s =>
if sym.atEnd j then s
else
let i := s.pos;
let input := c.input;
if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg
else strAux (sym.next j) c (s.next input i)
def checkTailWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| some info => info.trailing.stopPos > info.trailing.startPos
| none => false
def checkWsBeforeFn (errorMsg : String) : ParserFn :=
fun c s =>
let prev := s.stxStack.back;
if checkTailWs prev then s else s.mkError errorMsg
def checkWsBefore (errorMsg : String) : Parser :=
{ info := epsilonInfo,
fn := checkWsBeforeFn errorMsg }
def checkTailNoWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| some info => info.trailing.stopPos == info.trailing.startPos
| none => false
private def pickNonNone (stack : Array Syntax) : Syntax :=
match stack.findRev? $ fun stx => !stx.isNone with
| none => Syntax.missing
| some stx => stx
def checkNoWsBeforeFn (errorMsg : String) : ParserFn :=
fun c s =>
let prev := pickNonNone s.stxStack;
if checkTailNoWs prev then s else s.mkError errorMsg
def checkNoWsBefore (errorMsg : String) : Parser :=
{ info := epsilonInfo,
fn := checkNoWsBeforeFn errorMsg }
def symbolNoWsInfo (sym : String) (lbpNoWs : Option Nat) : ParserInfo :=
{ collectTokens := fun tks => { val := sym, lbpNoWs := lbpNoWs } :: tks,
firstTokens := FirstTokens.tokens [ { val := sym, lbpNoWs := lbpNoWs } ] }
@[inline] def symbolNoWsFnAux (sym : String) (errorMsg : String) : ParserFn :=
fun c s =>
let left := s.stxStack.back;
if checkTailNoWs left then
let startPos := s.pos;
let input := c.input;
let s := strAux sym errorMsg 0 c s;
if s.hasError then s
else
let leading := mkEmptySubstringAt input startPos;
let stopPos := startPos + sym.bsize;
let trailing := mkEmptySubstringAt input stopPos;
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } sym;
s.pushSyntax atom
else
s.mkError errorMsg
@[inline] def symbolNoWsFn (sym : String) : ParserFn :=
symbolNoWsFnAux sym ("'" ++ sym ++ "' without whitespaces around it")
/- Similar to `symbol`, but succeeds only if there is no space whitespace after leading term and after `sym`. -/
@[inline] def symbolNoWsAux (sym : String) (lbp : Option Nat) : Parser :=
let sym := sym.trim;
{ info := symbolNoWsInfo sym lbp,
fn := symbolNoWsFn sym }
@[inline] def symbolNoWs (sym : String) (lbp : Nat) : Parser :=
symbolNoWsAux sym lbp
def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn :=
satisfySymbolFn (fun s => s == sym || s == asciiSym) expected
def unicodeSymbolInfo (sym asciiSym : String) (lbp : Option Nat) : ParserInfo :=
{ collectTokens := fun tks => { val := sym, lbp := lbp } :: { val := asciiSym, lbp := lbp } :: tks,
firstTokens := FirstTokens.tokens [ { val := sym, lbp := lbp }, { val := asciiSym, lbp := lbp } ] }
@[inline] def unicodeSymbolFn (sym asciiSym : String) : ParserFn :=
unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"]
@[inline] def unicodeSymbol (sym asciiSym : String) (lbp : Option Nat := none) : Parser :=
let sym := sym.trim;
let asciiSym := asciiSym.trim;
{ info := unicodeSymbolInfo sym asciiSym lbp,
fn := unicodeSymbolFn sym asciiSym }
/- Succeeds if RBP > lower -/
def checkRBPGreaterFn (lower : Nat) (errorMsg : String) : ParserFn :=
fun c s =>
if c.rbp > lower then s.mkUnexpectedError errorMsg
else s
def checkRBPGreater (lower : Nat) (errorMsg : String) : Parser :=
{ info := epsilonInfo,
fn := checkRBPGreaterFn lower errorMsg }
def mkAtomicInfo (k : String) : ParserInfo :=
{ firstTokens := FirstTokens.tokens [ { val := k } ] }
def numLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos else s
@[inline] def numLitNoAntiquot : Parser :=
{ fn := numLitFn,
info := mkAtomicInfo "numLit" }
def strLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos else s
@[inline] def strLitNoAntiquot : Parser :=
{ fn := strLitFn,
info := mkAtomicInfo "strLit" }
def charLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos else s
@[inline] def charLitNoAntiquot : Parser :=
{ fn := charLitFn,
info := mkAtomicInfo "charLit" }
def nameLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos else s
@[inline] def nameLitNoAntiquot : Parser :=
{ fn := nameLitFn,
info := mkAtomicInfo "nameLit" }
def identFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos else s
@[inline] def identNoAntiquot : Parser :=
{ fn := identFn,
info := mkAtomicInfo "ident" }
@[inline] def rawIdentNoAntiquot : Parser :=
{ fn := rawIdentFn }
def identEqFn (id : Name) : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError then
s.mkErrorAt "identifier" iniPos
else match s.stxStack.back with
| Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos else s
| _ => s.mkErrorAt "identifier" iniPos
@[inline] def identEq (id : Name) : Parser :=
{ fn := identEqFn id,
info := mkAtomicInfo "ident" }
def quotedSymbolFn : ParserFn :=
nodeFn `quotedSymbol (andthenFn (andthenFn (chFn '`') (rawFn (takeUntilFn (fun c => c == '`')))) (chFn '`' true))
-- TODO: remove after old frontend is gone
def quotedSymbol : Parser :=
{ fn := quotedSymbolFn }
def unquotedSymbolFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || s.stxStack.back.isIdent || isLitKind s.stxStack.back.getKind then
s.mkErrorAt "symbol" iniPos
else
s
def unquotedSymbol : Parser :=
{ fn := unquotedSymbolFn }
instance stringToParserCoe : HasCoe String Parser :=
⟨symbolAux⟩
namespace ParserState
def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ => ⟨stack.shrink oldStackSize, pos, cache, err⟩
def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack.shrink oldStackSize, oldStopPos, cache, oldError⟩
def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState :=
match s with
| ⟨stack, pos, cache, some err⟩ =>
if oldError == err then s
else ⟨stack.shrink oldStackSize, pos, cache, some (oldError.merge err)⟩
| other => other
def mkLongestNodeAlt (s : ParserState) (startSize : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ =>
if stack.size == startSize then ⟨stack.push Syntax.missing, pos, cache, none⟩ -- parser did not create any node, then we just add `Syntax.missing`
else if stack.size == startSize + 1 then s
else
-- parser created more than one node, combine them into a single node
let node := Syntax.node nullKind (stack.extract startSize stack.size);
let stack := stack.shrink startSize;
⟨stack.push node, pos, cache, none⟩
def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ =>
let node := stack.back;
let stack := stack.shrink startStackSize;
let stack := stack.push node;
⟨stack, pos, cache, none⟩
def replaceLongest (s : ParserState) (startStackSize : Nat) (prevStackSize : Nat) : ParserState :=
let s := s.mkLongestNodeAlt prevStackSize;
s.keepLatest startStackSize
end ParserState
def longestMatchStep (startSize : Nat) (startPos : String.Pos) (p : ParserFn) : ParserFn :=
fun c s =>
let prevErrorMsg := s.errorMsg;
let prevStopPos := s.pos;
let prevSize := s.stackSize;
let s := s.restore prevSize startPos;
let s := p c s;
match prevErrorMsg, s.errorMsg with
| none, none => -- both succeeded
if s.pos > prevStopPos then s.replaceLongest startSize prevSize -- replace
else if s.pos < prevStopPos then s.restore prevSize prevStopPos -- keep prev
else s.mkLongestNodeAlt prevSize -- keep both
| none, some _ => -- prev succeeded, current failed
s.restore prevSize prevStopPos
| some oldError, some _ => -- both failed
if s.pos > prevStopPos then s.keepNewError prevSize
else if s.pos < prevStopPos then s.keepPrevError prevSize prevStopPos prevErrorMsg
else s.mergeErrors prevSize oldError
| some _, none => -- prev failed, current succeeded
let s := s.mkLongestNodeAlt prevSize; -- create successful alternative on the top of the stack
let successNode := s.stxStack.back;
let s := s.shrinkStack startSize; -- restore stack to initial size to make sure (failure) nodes are removed from the stack
s.pushSyntax successNode -- put successNode back on the stack
def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState :=
if !s.hasError && s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s
def longestMatchFnAux (startSize : Nat) (startPos : String.Pos) : List Parser → ParserFn
| [] => fun _ s => longestMatchMkResult startSize s
| p::ps => fun c s =>
let s := longestMatchStep startSize startPos p.fn c s;
longestMatchFnAux ps c s
def longestMatchFn₁ (p : ParserFn) : ParserFn :=
fun c s =>
let startSize := s.stackSize;
let s := p c s;
if s.hasError then s else s.mkLongestNodeAlt startSize
def longestMatchFn : List Parser → ParserFn
| [] => fun _ s => s.mkError "longestMatch: empty list"
| [p] => longestMatchFn₁ p.fn
| p::ps => fun c s =>
let startSize := s.stackSize;
let startPos := s.pos;
let s := p.fn c s;
if s.hasError then
let s := s.shrinkStack startSize;
longestMatchFnAux startSize startPos ps c s
else
let s := s.mkLongestNodeAlt startSize;
longestMatchFnAux startSize startPos ps c s
def anyOfFn : List Parser → ParserFn
| [], _, s => s.mkError "anyOf: empty list"
| [p], c, s => p.fn c s
| p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s
@[inline] def checkColGeFn (col : Nat) (errorMsg : String) : ParserFn :=
fun c s =>
let pos := c.fileMap.toPosition s.pos;
if pos.column ≥ col then s
else s.mkError errorMsg
@[inline] def checkColGe (col : Nat) (errorMsg : String) : Parser :=
{ fn := checkColGeFn col errorMsg }
@[inline] def withPosition (p : Position → Parser) : Parser :=
{ info := (p { line := 1, column := 0 }).info,
fn := fun c s =>
let pos := c.fileMap.toPosition s.pos;
(p pos).fn c s }
@[inline] def many1Indent (p : Parser) (errorMsg : String) : Parser :=
withPosition $ fun pos => many1 (checkColGe pos.column errorMsg >> p)
/-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/
def TokenMap (α : Type) := RBMap Name (List α) Name.quickLt
namespace TokenMap
def insert {α : Type} (map : TokenMap α) (k : Name) (v : α) : TokenMap α :=
match map.find? k with
| none => map.insert k [v]
| some vs => map.insert k (v::vs)
instance {α : Type} : Inhabited (TokenMap α) := ⟨RBMap.empty⟩
instance {α : Type} : HasEmptyc (TokenMap α) := ⟨RBMap.empty⟩
end TokenMap
structure PrattParsingTables :=
(leadingTable : TokenMap Parser := {})
(leadingParsers : List Parser := []) -- for supporting parsers we cannot obtain first token
(trailingTable : TokenMap TrailingParser := {})
(trailingParsers : List TrailingParser := []) -- for supporting parsers such as function application
instance PrattParsingTables.inhabited : Inhabited PrattParsingTables := ⟨{}⟩
/--
Each parser category is implemented using Pratt's parser.
The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`.
Users and plugins may define extra categories.
The field `leadingIdentAsSymbol` specifies how the parsing table
lookup function behaves for identifiers. The function `prattParser`
uses two tables `leadingTable` and `trailingTable`. They map tokens
to parsers. If `leadingIdentAsSymbol == false` and the leading token
is an identifier, then `prattParser` just executes the parsers
associated with the auxiliary token "ident". If
`leadingIdentAsSymbol == true` and the leading token is an
identifier `<foo>`, then `prattParser` combines the parsers
associated with the token `<foo>` with the parsers associated with
the auxiliary token "ident". We use this feature and the
`nonReservedSymbol` parser to implement the `tactic` parsers. We
use this approach to avoid creating a reserved symbol for each
builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users
may still use these symbols as identifiers (e.g., naming a
function). -/
structure ParserCategory :=
(tables : PrattParsingTables) (leadingIdentAsSymbol : Bool)
instance ParserCategory.inhabited : Inhabited ParserCategory := ⟨{ tables := {}, leadingIdentAsSymbol := false }⟩
abbrev ParserCategories := PersistentHashMap Name ParserCategory
def currLbp (left : Syntax) (c : ParserContext) (s : ParserState) : ParserState × Nat :=
let (s, stx?) := peekToken c s;
match stx? with
| some stx@(Syntax.atom _ sym) =>
if sym == "$" && checkTailNoWs stx then (s, appPrec) -- TODO: split `lbpNoWs` into "before" and "after", and set right lbp for '$' in antiquotations
else match c.tokens.matchPrefix sym 0 with
| (_, some tk) => match tk.lbp, tk.lbpNoWs with
| some lbp, none => (s, lbp)
| none, some lbpNoWs => (s, lbpNoWs)
| some lbp, some lbpNoWs => if checkTailNoWs left then (s, lbpNoWs) else (s, lbp)
| none, none => (s, 0)
| _ => (s, 0)
| some (Syntax.ident _ _ _ _) => (s, appPrec)
-- TODO(Leo): add support for associating lbp with syntax node kinds.
| some (Syntax.node k _) =>
if isLitKind k || k == fieldIdxKind then
(s, appPrec)
else
(s, 0)
| _ => (s, 0)
def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (leadingIdentAsSymbol : Bool) : ParserState × List α :=
let (s, stx) := peekToken c s;
let find (n : Name) : ParserState × List α :=
match map.find? n with
| some as => (s, as)
| _ => (s, []);
match stx with
| some (Syntax.atom _ sym) => find (mkNameSimple sym)
| some (Syntax.ident _ _ val _) =>
if leadingIdentAsSymbol then
match map.find? val with
| some as => match map.find? identKind with
| some as' => (s, as ++ as')
| _ => (s, as)
| none => find identKind
else
find identKind
| some (Syntax.node k _) => find k
| _ => (s, [])
abbrev CategoryParserFn := Name → ParserFn
def mkCategoryParserFnRef : IO (IO.Ref CategoryParserFn) :=
IO.mkRef $ fun _ => whitespace
@[init mkCategoryParserFnRef]
constant categoryParserFnRef : IO.Ref CategoryParserFn := arbitrary _
def mkCategoryParserFnExtension : IO (EnvExtension CategoryParserFn) :=
registerEnvExtension $ categoryParserFnRef.get
@[init mkCategoryParserFnExtension]
def categoryParserFnExtension : EnvExtension CategoryParserFn := arbitrary _
def categoryParserFn (catName : Name) : ParserFn :=
fun ctx s => categoryParserFnExtension.getState ctx.env catName ctx s
def categoryParser (catName : Name) (rbp : Nat) : Parser :=
{ fn := fun c s => categoryParserFn catName { rbp := rbp, .. c } s }
-- Define `termParser` here because we need it for antiquotations
@[inline] def termParser (rbp : Nat := 0) : Parser :=
categoryParser `term rbp
/- ============== -/
/- Antiquotations -/
/- ============== -/
def dollarSymbol : Parser := symbol "$" 1
/-- Fail if previous token is immediately followed by ':'. -/
private def noImmediateColon : Parser :=
{ fn := fun c s =>
let prev := s.stxStack.back;
if checkTailNoWs prev then
let input := c.input;
let i := s.pos;
if input.atEnd i then s
else
let curr := input.get i;
if curr == ':' then
s.mkUnexpectedError "unexpected ':'"
else s
else s
}
def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn :=
fun c s => match p c s with
| s'@{ errorMsg := some msg } => { s' with errorMsg := some { msg with expected := [] } }
| s' => s'
def setExpected (expected : List String) (p : Parser) : Parser :=
{ fn := setExpectedFn expected p.fn, info := p.info }
def pushNone : Parser :=
{ fn := fun c s => s.pushSyntax mkNullNode }
-- We support two kinds of antiquotations: `$id` and `$(t)`, where `id` is a term identifier and `t` is a term.
private def antiquotNestedExpr : Parser := node `antiquotNestedExpr ("(" >> termParser >> ")")
private def antiquotExpr : Parser := identNoAntiquot <|> antiquotNestedExpr
/--
Define parser for `$e` (if anonymous == true) and `$e:name`. Both
forms can also be used with an appended `*` to turn them into an
antiquotation "splice". If `kind` is given, it will additionally be checked
when evaluating `match_syntax`. Antiquotations can be escaped as in `$$e`, which
produces the syntax tree for `$e`. -/
def mkAntiquot (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parser :=
let kind := (kind.getD Name.anonymous) ++ `antiquot;
let nameP := checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbolAux ":" >> nonReservedSymbol name;
-- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different
-- antiquotation kind via `noImmediateColon`
let nameP := if anonymous then nameP <|> noImmediateColon >> pushNone >> pushNone else nameP;
-- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error
node kind $ try $
setExpected [] dollarSymbol >>
many (checkNoWsBefore "" >> dollarSymbol) >>
checkNoWsBefore "no space before spliced term" >> antiquotExpr >>
nameP >>
optional (checkNoWsBefore "" >> "*")
def tryAnti (c : ParserContext) (s : ParserState) : Bool :=
let (s, stx?) := peekToken c s;
match stx? with
| some stx@(Syntax.atom _ sym) => sym == "$"
| _ => false
@[inline] def withAntiquotFn (antiquotP p : ParserFn) : ParserFn :=
fun c s => if tryAnti c s then orelseFn antiquotP p c s else p c s
/-- Optimized version of `mkAntiquot ... <|> p`. -/
@[inline] def withAntiquot (antiquotP p : Parser) : Parser :=
{ fn := withAntiquotFn antiquotP.fn p.fn,
info := orelseInfo antiquotP.info p.info }
/- ===================== -/
/- End of Antiquotations -/
/- ===================== -/
def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) : Parser :=
withAntiquot (mkAntiquot name kind false) $ node kind p
def ident : Parser :=
withAntiquot (mkAntiquot "ident" identKind) identNoAntiquot
-- `ident` and `rawIdent` produce the same syntax tree, so we reuse the antiquotation kind name
def rawIdent : Parser :=
withAntiquot (mkAntiquot "ident" identKind) rawIdentNoAntiquot
def numLit : Parser :=
withAntiquot (mkAntiquot "numLit" numLitKind) numLitNoAntiquot
def strLit : Parser :=
withAntiquot (mkAntiquot "strLit" strLitKind) strLitNoAntiquot
def charLit : Parser :=
withAntiquot (mkAntiquot "charLit" charLitKind) charLitNoAntiquot
def nameLit : Parser :=
withAntiquot (mkAntiquot "nameLit" nameLitKind) nameLitNoAntiquot
def categoryParserOfStackFn (offset : Nat) : ParserFn :=
fun ctx s =>
let stack := s.stxStack;
if stack.size < offset + 1 then
s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small")
else
match stack.get! (stack.size - offset - 1) with
| Syntax.ident _ _ catName _ => categoryParserFn catName ctx s
| _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier")
def categoryParserOfStack (offset : Nat) (rbp : Nat := 0) : Parser :=
{ fn := fun c s => categoryParserOfStackFn offset { rbp := rbp, .. c } s }
private def mkResult (s : ParserState) (iniSz : Nat) : ParserState :=
if s.stackSize == iniSz + 1 then s
else s.mkNode nullKind iniSz -- throw error instead?
def leadingParserAux (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let (s, ps) := indexed tables.leadingTable c s leadingIdentAsSymbol;
let ps := tables.leadingParsers ++ ps;
if ps.isEmpty then
s.mkError (toString kind)
else
let s := longestMatchFn ps c s;
mkResult s iniSz
@[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) (antiquotParser : ParserFn) : ParserFn :=
withAntiquotFn antiquotParser (leadingParserAux kind tables leadingIdentAsSymbol)
def trailingLoopStep (tables : PrattParsingTables) (ps : List Parser) : ParserFn :=
fun c s =>
orelseFn (longestMatchFn ps) (anyOfFn tables.trailingParsers) c s
private def mkTrailingResult (s : ParserState) (iniSz : Nat) : ParserState :=
let s := mkResult s iniSz;
-- Stack contains `[..., left, result]`
-- We must remove `left`
let result := s.stxStack.back;
let s := s.popSyntax.popSyntax;
s.pushSyntax result
partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) : ParserState → ParserState
| s =>
let left := s.stxStack.back;
let (s, lbp) := currLbp left c s;
if c.rbp ≥ lbp then s
else
let iniSz := s.stackSize;
let identAsSymbol := false;
let (s, ps) := indexed tables.trailingTable c s identAsSymbol;
if ps.isEmpty && tables.trailingParsers.isEmpty then
s -- no available trailing parser
else
let s := trailingLoopStep tables ps c s;
if s.hasError then s
else
let s := mkTrailingResult s iniSz;
trailingLoop s
/--
Implements a recursive precedence parser according to Pratt's algorithm.
`antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers.
It should not be added to the regular leading parsers because it would heavily
overlap with antiquotation parsers nested inside them. -/
@[inline] def prattParser (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) (antiquotParser : ParserFn) : ParserFn :=
fun c s =>
let left := s.stxStack.back;
let (s, lbp) := currLbp left c s;
if c.rbp > lbp then s.mkUnexpectedError "unexpected token"
else
let s := leadingParser kind tables leadingIdentAsSymbol antiquotParser c s;
if s.hasError then s
else
trailingLoop tables c s
def mkBuiltinTokenTable : IO (IO.Ref TokenTable) := IO.mkRef {}
@[init mkBuiltinTokenTable] constant builtinTokenTable : IO.Ref TokenTable := arbitrary _
/- Global table with all SyntaxNodeKind's -/
def mkBuiltinSyntaxNodeKindSetRef : IO (IO.Ref SyntaxNodeKindSet) := IO.mkRef {}
@[init mkBuiltinSyntaxNodeKindSetRef] constant builtinSyntaxNodeKindSetRef : IO.Ref SyntaxNodeKindSet := arbitrary _
def mkBuiltinParserCategories : IO (IO.Ref ParserCategories) := IO.mkRef {}
@[init mkBuiltinParserCategories] constant builtinParserCategoriesRef : IO.Ref ParserCategories := arbitrary _
private def throwParserCategoryAlreadyDefined {α} (catName : Name) : ExceptT String Id α :=
throw ("parser category '" ++ toString catName ++ "' has already been defined")
private def addParserCategoryCore (categories : ParserCategories) (catName : Name) (initial : ParserCategory) : Except String ParserCategories :=
if categories.contains catName then
throwParserCategoryAlreadyDefined catName
else
pure $ categories.insert catName initial
/-- All builtin parser categories are Pratt's parsers -/
private def addBuiltinParserCategory (catName : Name) (leadingIdentAsSymbol : Bool) : IO Unit := do
categories ← builtinParserCategoriesRef.get;
categories ← IO.ofExcept $ addParserCategoryCore categories catName { tables := {}, leadingIdentAsSymbol := leadingIdentAsSymbol};
builtinParserCategoriesRef.set categories
inductive ParserExtensionOleanEntry
| token (val : TokenConfig) : ParserExtensionOleanEntry
| kind (val : SyntaxNodeKind) : ParserExtensionOleanEntry
| category (catName : Name) (leadingIdentAsSymbol : Bool)
| parser (catName : Name) (declName : Name) : ParserExtensionOleanEntry
inductive ParserExtensionEntry
| token (val : TokenConfig) : ParserExtensionEntry
| kind (val : SyntaxNodeKind) : ParserExtensionEntry
| category (catName : Name) (leadingIdentAsSymbol : Bool)
| parser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) : ParserExtensionEntry
structure ParserExtensionState :=
(tokens : TokenTable := {})
(kinds : SyntaxNodeKindSet := {})
(categories : ParserCategories := {})
(newEntries : List ParserExtensionOleanEntry := [])
instance ParserExtensionState.inhabited : Inhabited ParserExtensionState := ⟨{}⟩
abbrev ParserExtension := PersistentEnvExtension ParserExtensionOleanEntry ParserExtensionEntry ParserExtensionState
private def ParserExtension.mkInitial : IO ParserExtensionState := do
tokens ← builtinTokenTable.get;
kinds ← builtinSyntaxNodeKindSetRef.get;
categories ← builtinParserCategoriesRef.get;
pure { tokens := tokens, kinds := kinds, categories := categories }
private def mergePrecendences (msgPreamble : String) (sym : String) : Option Nat → Option Nat → Except String (Option Nat)
| none, b => pure b
| a, none => pure a
| some a, some b =>
if a == b then pure $ some a
else
throw $ msgPreamble ++ "precedence mismatch for '" ++ toString sym ++ "', previous: " ++ toString a ++ ", new: " ++ toString b
private def addTokenConfig (tokens : TokenTable) (tk : TokenConfig) : Except String TokenTable := do
if tk.val == "" then throw "invalid empty symbol"
else match tokens.find tk.val with
| none => pure $ tokens.insert tk.val tk
| some oldTk => do
lbp ← mergePrecendences "" tk.val oldTk.lbp tk.lbp;
lbpNoWs ← mergePrecendences "(no whitespace) " tk.val oldTk.lbpNoWs tk.lbpNoWs;
pure $ tokens.insert tk.val { lbp := lbp, lbpNoWs := lbpNoWs, .. tk }
def throwUnknownParserCategory {α} (catName : Name) : ExceptT String Id α :=
throw ("unknown parser category '" ++ toString catName ++ "'")
def addLeadingParser (categories : ParserCategories) (catName : Name) (parserName : Name) (p : Parser) : Except String ParserCategories :=
match categories.find? catName with
| none =>
throwUnknownParserCategory catName
| some cat =>
let addTokens (tks : List TokenConfig) : Except String ParserCategories :=
let tks := tks.map $ fun tk => mkNameSimple tk.val;
let tables := tks.eraseDups.foldl (fun (tables : PrattParsingTables) tk => { leadingTable := tables.leadingTable.insert tk p, .. tables }) cat.tables;
pure $ categories.insert catName { tables := tables, .. cat };
match p.info.firstTokens with
| FirstTokens.tokens tks => addTokens tks
| FirstTokens.optTokens tks => addTokens tks
| _ =>
let tables := { leadingParsers := p :: cat.tables.leadingParsers, .. cat.tables };
pure $ categories.insert catName { tables := tables, .. cat }
private def addTrailingParserAux (tables : PrattParsingTables) (p : TrailingParser) : PrattParsingTables :=
let addTokens (tks : List TokenConfig) : PrattParsingTables :=
let tks := tks.map $ fun tk => mkNameSimple tk.val;
tks.eraseDups.foldl (fun (tables : PrattParsingTables) tk => { trailingTable := tables.trailingTable.insert tk p, .. tables }) tables;
match p.info.firstTokens with
| FirstTokens.tokens tks => addTokens tks
| FirstTokens.optTokens tks => addTokens tks
| _ => { trailingParsers := p :: tables.trailingParsers, .. tables }
def addTrailingParser (categories : ParserCategories) (catName : Name) (p : TrailingParser) : Except String ParserCategories :=
match categories.find? catName with
| none => throwUnknownParserCategory catName
| some cat => pure $ categories.insert catName { tables := addTrailingParserAux cat.tables p, .. cat }
def addParser (categories : ParserCategories) (catName : Name) (declName : Name) (leading : Bool) (p : Parser) : Except String ParserCategories :=
match leading, p with
| true, p => addLeadingParser categories catName declName p
| false, p => addTrailingParser categories catName p
def addParserTokens (tokenTable : TokenTable) (info : ParserInfo) : Except String TokenTable :=
let newTokens := info.collectTokens [];
newTokens.foldlM addTokenConfig tokenTable
private def updateBuiltinTokens (info : ParserInfo) (declName : Name) : IO Unit := do
tokenTable ← builtinTokenTable.swap {};
match addParserTokens tokenTable info with
| Except.ok tokenTable => builtinTokenTable.set tokenTable
| Except.error msg => throw (IO.userError ("invalid builtin parser '" ++ toString declName ++ "', " ++ msg))
def addBuiltinParser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) : IO Unit := do
categories ← builtinParserCategoriesRef.get;
categories ← IO.ofExcept $ addParser categories catName declName leading p;
builtinParserCategoriesRef.set categories;
builtinSyntaxNodeKindSetRef.modify p.info.collectKinds;
updateBuiltinTokens p.info declName
def addBuiltinLeadingParser (catName : Name) (declName : Name) (p : Parser) : IO Unit :=
addBuiltinParser catName declName true p
def addBuiltinTrailingParser (catName : Name) (declName : Name) (p : TrailingParser) : IO Unit :=
addBuiltinParser catName declName false p
private def ParserExtension.addEntry (s : ParserExtensionState) (e : ParserExtensionEntry) : ParserExtensionState :=
match e with
| ParserExtensionEntry.token tk =>
match addTokenConfig s.tokens tk with
| Except.ok tokens => { tokens := tokens, newEntries := ParserExtensionOleanEntry.token tk :: s.newEntries, .. s }
| _ => unreachable!
| ParserExtensionEntry.kind k =>
{ kinds := s.kinds.insert k, newEntries := ParserExtensionOleanEntry.kind k :: s.newEntries, .. s }
| ParserExtensionEntry.category catName leadingIdentAsSymbol =>
if s.categories.contains catName then s
else { categories := s.categories.insert catName { tables := {}, leadingIdentAsSymbol := leadingIdentAsSymbol },
newEntries := ParserExtensionOleanEntry.category catName leadingIdentAsSymbol :: s.newEntries, .. s }
| ParserExtensionEntry.parser catName declName leading parser =>
match addParser s.categories catName declName leading parser with
| Except.ok categories => { categories := categories, newEntries := ParserExtensionOleanEntry.parser catName declName :: s.newEntries, .. s }
| _ => unreachable!
def compileParserDescr (categories : ParserCategories) : ParserDescr → Except String (Parser)
| ParserDescr.andthen d₁ d₂ => andthen <$> compileParserDescr d₁ <*> compileParserDescr d₂
| ParserDescr.orelse d₁ d₂ => orelse <$> compileParserDescr d₁ <*> compileParserDescr d₂
| ParserDescr.optional d => optional <$> compileParserDescr d
| ParserDescr.lookahead d => lookahead <$> compileParserDescr d
| ParserDescr.try d => try <$> compileParserDescr d
| ParserDescr.many d => many <$> compileParserDescr d
| ParserDescr.many1 d => many1 <$> compileParserDescr d
| ParserDescr.sepBy d₁ d₂ => sepBy <$> compileParserDescr d₁ <*> compileParserDescr d₂
| ParserDescr.sepBy1 d₁ d₂ => sepBy1 <$> compileParserDescr d₁ <*> compileParserDescr d₂
| ParserDescr.node k d => node k <$> compileParserDescr d
| ParserDescr.trailingNode k d => trailingNode k <$> compileParserDescr d
| ParserDescr.symbol tk lbp => pure $ symbolAux tk lbp
| ParserDescr.numLit => pure $ numLit
| ParserDescr.strLit => pure $ strLit
| ParserDescr.charLit => pure $ charLit
| ParserDescr.nameLit => pure $ nameLit
| ParserDescr.ident => pure $ ident
| ParserDescr.nonReservedSymbol tk includeIdent => pure $ nonReservedSymbol tk includeIdent
| ParserDescr.parser catName rbp =>
match categories.find? catName with
| some _ => pure $ categoryParser catName rbp
| none => throwUnknownParserCategory catName
unsafe def mkParserOfConstantUnsafe (env : Environment) (categories : ParserCategories) (constName : Name) : Except String (Bool × Parser) :=
match env.find? constName with
| none => throw ("unknow constant '" ++ toString constName ++ "'")
| some info =>
match info.type with
| Expr.const `Lean.Parser.TrailingParser _ _ => do
p ← env.evalConst Parser constName;
pure ⟨false, p⟩
| Expr.const `Lean.Parser.Parser _ _ => do
p ← env.evalConst Parser constName;
pure ⟨true, p⟩
| Expr.const `Lean.ParserDescr _ _ => do
d ← env.evalConst ParserDescr constName;
p ← compileParserDescr categories d;
pure ⟨true, p⟩
| Expr.const `Lean.TrailingParserDescr _ _ => do
d ← env.evalConst TrailingParserDescr constName;
p ← compileParserDescr categories d;
pure ⟨false, p⟩
| _ => throw ("unexpected parser type at '" ++ toString constName ++ "' (`ParserDescr`, `TrailingParserDescr`, `Parser` or `TrailingParser` expected")
@[implementedBy mkParserOfConstantUnsafe]
constant mkParserOfConstant (env : Environment) (categories : ParserCategories) (constName : Name) : Except String (Bool × Parser) :=
arbitrary _
private def ParserExtension.addImported (env : Environment) (es : Array (Array ParserExtensionOleanEntry)) : IO ParserExtensionState := do
s ← ParserExtension.mkInitial;
es.foldlM
(fun s entries =>
entries.foldlM
(fun s entry =>
match entry with
| ParserExtensionOleanEntry.token tk => do
tokens ← IO.ofExcept (addTokenConfig s.tokens tk);
pure { tokens := tokens, .. s }
| ParserExtensionOleanEntry.kind k =>
pure { kinds := s.kinds.insert k, .. s }
| ParserExtensionOleanEntry.category catName leadingIdentAsSymbol => do
categories ← IO.ofExcept (addParserCategoryCore s.categories catName { tables := {}, leadingIdentAsSymbol := leadingIdentAsSymbol});
pure { categories := categories, .. s }
| ParserExtensionOleanEntry.parser catName declName =>
match mkParserOfConstant env s.categories declName with
| Except.ok p =>
match addParser s.categories catName declName p.1 p.2 with
| Except.ok categories => pure { categories := categories, .. s }
| Except.error ex => throw (IO.userError ex)
| Except.error ex => throw (IO.userError ex))
s)
s
def mkParserExtension : IO ParserExtension :=
registerPersistentEnvExtension {
name := `parserExt,
mkInitial := ParserExtension.mkInitial,
addImportedFn := ParserExtension.addImported,
addEntryFn := ParserExtension.addEntry,
exportEntriesFn := fun s => s.newEntries.reverse.toArray,
statsFn := fun s => format "number of local entries: " ++ format s.newEntries.length
}
@[init mkParserExtension]
constant parserExtension : ParserExtension := arbitrary _
def isParserCategory (env : Environment) (catName : Name) : Bool :=
(parserExtension.getState env).categories.contains catName
def addParserCategory (env : Environment) (catName : Name) (leadingIdentAsSymbol : Bool) : Except String Environment := do
if isParserCategory env catName then
throwParserCategoryAlreadyDefined catName
else
pure $ parserExtension.addEntry env $ ParserExtensionEntry.category catName leadingIdentAsSymbol
/-
Return true if in the given category leading identifiers in parsers may be treated as atoms/symbols.
See comment at `ParserCategory`. -/
def leadingIdentAsSymbol (env : Environment) (catName : Name) : Bool :=
match (parserExtension.getState env).categories.find? catName with
| none => false
| some cat => cat.leadingIdentAsSymbol
private def catNameToString : Name → String
| Name.str Name.anonymous s _ => s
| n => n.toString
@[inline] def mkCategoryAntiquotParser (kind : Name) : ParserFn :=
-- allow "anonymous" antiquotations `$x` for the `term` category only
-- TODO: make customizable
-- one good example for a category that should not be anonymous is
-- `index` in `tests/lean/run/bigop.lean`.
let anonAntiquot := kind == `term;
(mkAntiquot (catNameToString kind) none anonAntiquot).fn
def categoryParserFnImpl (catName : Name) : ParserFn :=
fun ctx s =>
let categories := (parserExtension.getState ctx.env).categories;
match categories.find? catName with
| some cat =>
prattParser catName cat.tables cat.leadingIdentAsSymbol (mkCategoryAntiquotParser catName) ctx s
| none => s.mkUnexpectedError ("unknown parser category '" ++ toString catName ++ "'")
@[init] def setCategoryParserFnRef : IO Unit :=
categoryParserFnRef.set categoryParserFnImpl
def addToken (env : Environment) (tk : TokenConfig) : Except String Environment := do
-- Recall that `ParserExtension.addEntry` is pure, and assumes `addTokenConfig` does not fail.
-- So, we must run it here to handle exception.
addTokenConfig (parserExtension.getState env).tokens tk;
pure $ parserExtension.addEntry env $ ParserExtensionEntry.token tk
def addSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Environment :=
parserExtension.addEntry env $ ParserExtensionEntry.kind k
def isValidSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Bool :=
let kinds := (parserExtension.getState env).kinds;
kinds.contains k || k == choiceKind || k == identKind || isLitKind k
def getSyntaxNodeKinds (env : Environment) : List SyntaxNodeKind := do
let kinds := (parserExtension.getState env).kinds;
kinds.foldl (fun ks k _ => k::ks) []
def getTokenTable (env : Environment) : TokenTable :=
(parserExtension.getState env).tokens
def mkInputContext (input : String) (fileName : String) : InputContext :=
{ input := input,
fileName := fileName,
fileMap := input.toFileMap }
def mkParserContext (env : Environment) (ctx : InputContext) : ParserContext :=
{ rbp := 0,
toInputContext := ctx,
env := env,
tokens := getTokenTable env }
def mkParserState (input : String) : ParserState :=
{ cache := initCacheForInput input }
/- convenience function for testing -/
def runParserCategory (env : Environment) (catName : Name) (input : String) (fileName := "<input>") : Except String Syntax :=
let c := mkParserContext env (mkInputContext input fileName);
let s := mkParserState input;
let s := whitespace c s;
let s := categoryParserFnImpl catName c s;
if s.hasError then
Except.error (s.toErrorMsg c)
else
Except.ok s.stxStack.back
def declareBuiltinParser (env : Environment) (addFnName : Name) (catName : Name) (declName : Name) : IO Environment :=
let name := `_regBuiltinParser ++ declName;
let type := mkApp (mkConst `IO) (mkConst `Unit);
let val := mkAppN (mkConst addFnName) #[toExpr catName, toExpr declName, mkConst declName];
let decl := Declaration.defnDecl { name := name, lparams := [], type := type, value := val, hints := ReducibilityHints.opaque, isUnsafe := false };
match env.addAndCompile {} decl with
-- TODO: pretty print error
| Except.error _ => throw (IO.userError ("failed to emit registration code for builtin parser '" ++ toString declName ++ "'"))
| Except.ok env => IO.ofExcept (setInitAttr env name)
def declareLeadingBuiltinParser (env : Environment) (catName : Name) (declName : Name) : IO Environment :=
declareBuiltinParser env `Lean.Parser.addBuiltinLeadingParser catName declName
def declareTrailingBuiltinParser (env : Environment) (catName : Name) (declName : Name) : IO Environment :=
declareBuiltinParser env `Lean.Parser.addBuiltinTrailingParser catName declName
private def BuiltinParserAttribute.add (attrName : Name) (catName : Name)
(env : Environment) (declName : Name) (args : Syntax) (persistent : Bool) : IO Environment := do
when args.hasArgs $ throw (IO.userError ("invalid attribute '" ++ toString attrName ++ "', unexpected argument"));
unless persistent $ throw (IO.userError ("invalid attribute '" ++ toString attrName ++ "', must be persistent"));
match env.find? declName with
| none => throw $ IO.userError "unknown declaration"
| some decl =>
match decl.type with
| Expr.const `Lean.Parser.TrailingParser _ _ =>
declareTrailingBuiltinParser env catName declName
| Expr.const `Lean.Parser.Parser _ _ =>
declareLeadingBuiltinParser env catName declName
| _ =>
throw (IO.userError ("unexpected parser type at '" ++ toString declName ++ "' (`Parser` or `TrailingParser` expected"))
/-
The parsing tables for builtin parsers are "stored" in the extracted source code.
-/
def registerBuiltinParserAttribute (attrName : Name) (catName : Name) (leadingIdentAsSymbol := false) : IO Unit := do
addBuiltinParserCategory catName leadingIdentAsSymbol;
registerBuiltinAttribute {
name := attrName,
descr := "Builtin parser",
add := BuiltinParserAttribute.add attrName catName,
applicationTime := AttributeApplicationTime.afterCompilation
}
private def ParserAttribute.add (attrName : Name) (catName : Name) (env : Environment) (declName : Name) (args : Syntax) (persistent : Bool) : IO Environment := do
when args.hasArgs $ throw (IO.userError ("invalid attribute '" ++ toString attrName ++ "', unexpected argument"));
let categories := (parserExtension.getState env).categories;
match mkParserOfConstant env categories declName with
| Except.error ex => throw (IO.userError ex)
| Except.ok p => do
let leading := p.1;
let parser := p.2;
let tokens := parser.info.collectTokens [];
env ← tokens.foldlM
(fun env token =>
match addToken env token with
| Except.ok env => pure env
| Except.error msg => throw (IO.userError ("invalid parser '" ++ toString declName ++ "', " ++ msg)))
env;
let kinds := parser.info.collectKinds {};
let env := kinds.foldl (fun env kind _ => addSyntaxNodeKind env kind) env;
match addParser categories catName declName leading parser with
| Except.ok _ => pure $ parserExtension.addEntry env $ ParserExtensionEntry.parser catName declName leading parser
| Except.error ex => throw (IO.userError ex)
def mkParserAttributeImpl (attrName : Name) (catName : Name) : AttributeImpl :=
{ name := attrName,
descr := "parser",
add := ParserAttribute.add attrName catName,
applicationTime := AttributeApplicationTime.afterCompilation }
/- A builtin parser attribute that can be extended by users. -/
def registerBuiltinDynamicParserAttribute (attrName : Name) (catName : Name) : IO Unit := do
registerBuiltinAttribute (mkParserAttributeImpl attrName catName)
@[init] private def registerParserAttributeImplBuilder : IO Unit :=
registerAttributeImplBuilder `parserAttr $ fun args =>
match args with
| [DataValue.ofName attrName, DataValue.ofName catName] => pure $ mkParserAttributeImpl attrName catName
| _ => throw ("invalid parser attribute implementation builder arguments")
def registerParserCategory (env : Environment) (attrName : Name) (catName : Name) (leadingIdentAsSymbol := false) : IO Environment := do
env ← IO.ofExcept $ addParserCategory env catName leadingIdentAsSymbol;
registerAttributeOfBuilder env `parserAttr [DataValue.ofName attrName, DataValue.ofName catName]
-- declare `termParser` here since it is used everywhere via antiquotations
@[init] def regBuiltinTermParserAttr : IO Unit :=
registerBuiltinParserAttribute `builtinTermParser `term
@[init] def regTermParserAttribute : IO Unit :=
registerBuiltinDynamicParserAttribute `termParser `term
def fieldIdxFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let curr := c.input.get iniPos;
if curr.isDigit && curr != '0' then
let s := takeWhileFn (fun c => c.isDigit) c s;
mkNodeToken fieldIdxKind iniPos c s
else
s.mkErrorAt "field index" iniPos
@[inline] def fieldIdx : Parser :=
withAntiquot (mkAntiquot "fieldIdx" `fieldIdx)
{ fn := fieldIdxFn,
info := mkAtomicInfo "fieldIdx" }
end Parser
namespace Syntax
section
variables {β : Type} {m : Type → Type} [Monad m]
@[inline] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β :=
s.getArgs.foldlM (flip f) b
@[inline] def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run (s.foldArgsM f b)
@[inline] def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit :=
s.foldArgsM (fun s _ => f s) ()
@[inline] def foldSepArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β :=
s.getArgs.foldlStepM (flip f) b 2
@[inline] def foldSepArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run (s.foldSepArgsM f b)
@[inline] def forSepArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit :=
s.foldSepArgsM (fun s _ => f s) ()
@[inline] def foldSepRevArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β := do
let args := foldSepArgs s (fun arg (args : Array Syntax) => args.push arg) #[];
args.foldrM f b
@[inline] def foldSepRevArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β := do
Id.run $ foldSepRevArgsM s f b
end
end Syntax
end Lean
section
variables {β : Type} {m : Type → Type} [Monad m]
open Lean
open Lean.Syntax
@[inline] def Array.foldSepByM (args : Array Syntax) (f : Syntax → β → m β) (b : β) : m β :=
args.foldlStepM (flip f) b 2
@[inline] def Array.foldSepBy (args : Array Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run $ args.foldSepByM f b
end
|
6b171bec9fb83b888d7d4821eb84bc13e0d2f261 | 21871395eaf77834250a3f1b20624be105ae17be | /hty_rec.lean | 0d7f98a2f930f85256444100c88ccff7cc00fcd3 | [] | no_license | daniel-carranza/2-adj-lean-workspace | a60a16d99993351a08860575831ec7c5b801c39f | e3e9b99883e5056d2de1856b8adcb2f4625546e6 | refs/heads/master | 1,666,176,695,426 | 1,592,006,470,000 | 1,592,006,470,000 | 271,910,711 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,249 | lean | /-
Authors: Daniel Carranza, Jonathon Chang, Ryan Sandford
Under the supervision of Chris Kapulkin
Contains theorems for performing induction on homotopies which
is used in adj.lean and two_adj.lean to prove
full-adjoint equivalences are not mere propositions
Last updated: 2020-06-12
-/
import hott.init hott.types.equiv
open hott
hott_theory
universes u v
namespace homotopy
variable {A : Type u}
variable {B : A → Type v}
@[hott] protected def rec' (f : Π(x : A), B x) (P : Π(g : Π(x : A), B x), (f = g) → Type _) (c : P f rfl)
: Π(g : Π(x : A), B x) (p : f = g), P g p :=
λg p, by hinduction p; exact c
-- Based homotopy induction
@[hott, induction] def rec {f : Π(x : A), B x} (P : Π(g : Π(x : A), B x), (f ~ g) → Type _) (c : P f (λx, refl (f x)))
: Π(g : Π(x : A), B x) (H : f ~ g), P g H :=
λg H, transport (λX : f ~ g, P g X) (is_equiv.right_inv (eq_equiv_homotopy f g) H)
(homotopy.rec' f (λg p, P g (eq_equiv_homotopy f g p)) c g ((eq_equiv_homotopy f g).to_inv H))
-- Unbased homotopy induction
-- Note: this is not used in adj.lean or two_adj.lean but is included here for completeness
@[hott, induction] def rec_unbased {P : Π(f g : Π(x : A), B x), (f ~ g) → Type _} (c : Π(f : Π(x : A), B x), P f f (λx, refl (f x)))
: Π(f g : Π(x : A), B x) (H : f ~ g), P f g H :=
λf g H, rec (P f) (c f) g H
end homotopy
namespace is_trunc
variable {A : Type u}
variable {B : A → Type _}
@[hott, instance] def sigma_hty_is_contr (f : Π(x : A), B x) : is_contr (Σ(g : Π(x : A), B x), f ~ g) :=
is_trunc.is_contr.mk ⟨f, λx, rfl⟩
(λu, by induction u; apply @homotopy.rec _ _ f (λg H, @sigma.mk (Π(x : A), B x) (λg, f ~ g) f (λx, hott.eq.refl (f x)) = sigma.mk g (λx, H x)) rfl u_fst u_snd)
@[hott, instance] def sigma_hty_is_contr_right (f : Π(x : A), B x) : is_contr (Σ(g : Π(x : A), B x), g ~ f) :=
@is_trunc.is_trunc_equiv_closed (Σ(g : Π(x : A), B x), f ~ g) (Σ(g : Π(x : A), B x), g ~ f) -2
(sigma.sigma_equiv_sigma_right (λg, pi.pi_equiv_pi_right (λx, eq_equiv_eq_symm (f x) (g x))))
(sigma_hty_is_contr f)
end is_trunc |
a9e8738629fb3030984300439dca848d9167919c | 94e33a31faa76775069b071adea97e86e218a8ee | /src/ring_theory/algebraic_independent.lean | 0ee9b87995b14fa32952033fdbe0926f1aeb8b03 | [
"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 | 22,130 | lean | /-
Copyright (c) 2021 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import ring_theory.adjoin.basic
import linear_algebra.linear_independent
import ring_theory.mv_polynomial.basic
import data.mv_polynomial.supported
import ring_theory.algebraic
import data.mv_polynomial.equiv
/-!
# Algebraic Independence
This file defines algebraic independence of a family of element of an `R` algebra
## Main definitions
* `algebraic_independent` - `algebraic_independent R x` states the family of elements `x`
is algebraically independent over `R`, meaning that the canonical map out of the multivariable
polynomial ring is injective.
* `algebraic_independent.repr` - The canonical map from the subalgebra generated by an
algebraic independent family into the polynomial ring.
## References
* [Stacks: Transcendence](https://stacks.math.columbia.edu/tag/030D)
## TODO
Prove that a ring is an algebraic extension of the subalgebra generated by a transcendence basis.
## Tags
transcendence basis, transcendence degree, transcendence
-/
noncomputable theory
open function set subalgebra mv_polynomial algebra
open_locale classical big_operators
universes x u v w
variables {ι : Type*} {ι' : Type*} (R : Type*) {K : Type*}
variables {A : Type*} {A' A'' : Type*} {V : Type u} {V' : Type*}
variables (x : ι → A)
variables [comm_ring R] [comm_ring A] [comm_ring A'] [comm_ring A'']
variables [algebra R A] [algebra R A'] [algebra R A'']
variables {a b : R}
/-- `algebraic_independent R x` states the family of elements `x`
is algebraically independent over `R`, meaning that the canonical
map out of the multivariable polynomial ring is injective. -/
def algebraic_independent : Prop :=
injective (mv_polynomial.aeval x : mv_polynomial ι R →ₐ[R] A)
variables {R} {x}
theorem algebraic_independent_iff_ker_eq_bot : algebraic_independent R x ↔
(mv_polynomial.aeval x : mv_polynomial ι R →ₐ[R] A).to_ring_hom.ker = ⊥ :=
ring_hom.injective_iff_ker_eq_bot _
theorem algebraic_independent_iff : algebraic_independent R x ↔
∀p : mv_polynomial ι R, mv_polynomial.aeval (x : ι → A) p = 0 → p = 0 :=
injective_iff_map_eq_zero _
theorem algebraic_independent.eq_zero_of_aeval_eq_zero (h : algebraic_independent R x) :
∀p : mv_polynomial ι R, mv_polynomial.aeval (x : ι → A) p = 0 → p = 0 :=
algebraic_independent_iff.1 h
theorem algebraic_independent_iff_injective_aeval :
algebraic_independent R x ↔ injective (mv_polynomial.aeval x : mv_polynomial ι R →ₐ[R] A) :=
iff.rfl
@[simp] lemma algebraic_independent_empty_type_iff [is_empty ι] :
algebraic_independent R x ↔ injective (algebra_map R A) :=
have aeval x = (algebra.of_id R A).comp (@is_empty_alg_equiv R ι _ _).to_alg_hom,
by { ext i, exact is_empty.elim' ‹is_empty ι› i },
begin
rw [algebraic_independent, this,
← injective.of_comp_iff' _ (@is_empty_alg_equiv R ι _ _).bijective],
refl
end
namespace algebraic_independent
variables (hx : algebraic_independent R x)
include hx
lemma algebra_map_injective : injective (algebra_map R A) :=
by simpa [← mv_polynomial.algebra_map_eq, function.comp] using
(injective.of_comp_iff
(algebraic_independent_iff_injective_aeval.1 hx) (mv_polynomial.C)).2
(mv_polynomial.C_injective _ _)
lemma linear_independent : linear_independent R x :=
begin
rw [linear_independent_iff_injective_total],
have : finsupp.total ι A R x =
(mv_polynomial.aeval x).to_linear_map.comp (finsupp.total ι _ R X),
{ ext, simp },
rw this,
refine hx.comp _,
rw [← linear_independent_iff_injective_total],
exact linear_independent_X _ _
end
protected lemma injective [nontrivial R] : injective x :=
hx.linear_independent.injective
lemma ne_zero [nontrivial R] (i : ι) : x i ≠ 0 :=
hx.linear_independent.ne_zero i
lemma comp (f : ι' → ι) (hf : function.injective f) : algebraic_independent R (x ∘ f) :=
λ p q, by simpa [aeval_rename, (rename_injective f hf).eq_iff] using @hx (rename f p) (rename f q)
lemma coe_range : algebraic_independent R (coe : range x → A) :=
by simpa using hx.comp _ (range_splitting_injective x)
lemma map {f : A →ₐ[R] A'} (hf_inj : set.inj_on f (adjoin R (range x))) :
algebraic_independent R (f ∘ x) :=
have aeval (f ∘ x) = f.comp (aeval x), by ext; simp,
have h : ∀ p : mv_polynomial ι R, aeval x p ∈ (@aeval R _ _ _ _ _ (coe : range x → A)).range,
{ intro p,
rw [alg_hom.mem_range],
refine ⟨mv_polynomial.rename (cod_restrict x (range x) (mem_range_self)) p, _⟩,
simp [function.comp, aeval_rename] },
begin
intros x y hxy,
rw [this] at hxy,
rw [adjoin_eq_range] at hf_inj,
exact hx (hf_inj (h x) (h y) hxy)
end
lemma map' {f : A →ₐ[R] A'} (hf_inj : injective f) : algebraic_independent R (f ∘ x) :=
hx.map (inj_on_of_injective hf_inj _)
omit hx
lemma of_comp (f : A →ₐ[R] A') (hfv : algebraic_independent R (f ∘ x)) :
algebraic_independent R x :=
have aeval (f ∘ x) = f.comp (aeval x), by ext; simp,
by rw [algebraic_independent, this] at hfv; exact hfv.of_comp
end algebraic_independent
open algebraic_independent
lemma alg_hom.algebraic_independent_iff (f : A →ₐ[R] A') (hf : injective f) :
algebraic_independent R (f ∘ x) ↔ algebraic_independent R x :=
⟨λ h, h.of_comp f, λ h, h.map (inj_on_of_injective hf _)⟩
@[nontriviality]
lemma algebraic_independent_of_subsingleton [subsingleton R] : algebraic_independent R x :=
by haveI := @mv_polynomial.unique R ι;
exact algebraic_independent_iff.2 (λ l hl, subsingleton.elim _ _)
theorem algebraic_independent_equiv (e : ι ≃ ι') {f : ι' → A} :
algebraic_independent R (f ∘ e) ↔ algebraic_independent R f :=
⟨λ h, function.comp.right_id f ▸ e.self_comp_symm ▸ h.comp _ e.symm.injective,
λ h, h.comp _ e.injective⟩
theorem algebraic_independent_equiv' (e : ι ≃ ι') {f : ι' → A} {g : ι → A} (h : f ∘ e = g) :
algebraic_independent R g ↔ algebraic_independent R f :=
h ▸ algebraic_independent_equiv e
theorem algebraic_independent_subtype_range {ι} {f : ι → A} (hf : injective f) :
algebraic_independent R (coe : range f → A) ↔ algebraic_independent R f :=
iff.symm $ algebraic_independent_equiv' (equiv.of_injective f hf) rfl
alias algebraic_independent_subtype_range ↔ algebraic_independent.of_subtype_range _
theorem algebraic_independent_image {ι} {s : set ι} {f : ι → A} (hf : set.inj_on f s) :
algebraic_independent R (λ x : s, f x) ↔ algebraic_independent R (λ x : f '' s, (x : A)) :=
algebraic_independent_equiv' (equiv.set.image_of_inj_on _ _ hf) rfl
lemma algebraic_independent_adjoin (hs : algebraic_independent R x) :
@algebraic_independent ι R (adjoin R (range x))
(λ i : ι, ⟨x i, subset_adjoin (mem_range_self i)⟩) _ _ _ :=
algebraic_independent.of_comp (adjoin R (range x)).val hs
/-- A set of algebraically independent elements in an algebra `A` over a ring `K` is also
algebraically independent over a subring `R` of `K`. -/
lemma algebraic_independent.restrict_scalars {K : Type*} [comm_ring K] [algebra R K]
[algebra K A] [is_scalar_tower R K A]
(hinj : function.injective (algebra_map R K)) (ai : algebraic_independent K x) :
algebraic_independent R x :=
have (aeval x : mv_polynomial ι K →ₐ[K] A).to_ring_hom.comp
(mv_polynomial.map (algebra_map R K)) =
(aeval x : mv_polynomial ι R →ₐ[R] A).to_ring_hom,
by { ext; simp [algebra_map_eq_smul_one] },
begin
show injective (aeval x).to_ring_hom,
rw [← this],
exact injective.comp ai (mv_polynomial.map_injective _ hinj)
end
/-- Every finite subset of an algebraically independent set is algebraically independent. -/
lemma algebraic_independent_finset_map_embedding_subtype
(s : set A) (li : algebraic_independent R (coe : s → A)) (t : finset s) :
algebraic_independent R (coe : (finset.map (embedding.subtype s) t) → A) :=
begin
let f : t.map (embedding.subtype s) → s := λ x, ⟨x.1, begin
obtain ⟨x, h⟩ := x,
rw [finset.mem_map] at h,
obtain ⟨a, ha, rfl⟩ := h,
simp only [subtype.coe_prop, embedding.coe_subtype],
end⟩,
convert algebraic_independent.comp li f _,
rintros ⟨x, hx⟩ ⟨y, hy⟩,
rw [finset.mem_map] at hx hy,
obtain ⟨a, ha, rfl⟩ := hx,
obtain ⟨b, hb, rfl⟩ := hy,
simp only [imp_self, subtype.mk_eq_mk],
end
/--
If every finite set of algebraically independent element has cardinality at most `n`,
then the same is true for arbitrary sets of algebraically independent elements.
-/
lemma algebraic_independent_bounded_of_finset_algebraic_independent_bounded {n : ℕ}
(H : ∀ s : finset A, algebraic_independent R (λ i : s, (i : A)) → s.card ≤ n) :
∀ s : set A, algebraic_independent R (coe : s → A) → cardinal.mk s ≤ n :=
begin
intros s li,
apply cardinal.card_le_of,
intro t,
rw ← finset.card_map (embedding.subtype s),
apply H,
apply algebraic_independent_finset_map_embedding_subtype _ li,
end
section subtype
lemma algebraic_independent.restrict_of_comp_subtype {s : set ι}
(hs : algebraic_independent R (x ∘ coe : s → A)) :
algebraic_independent R (s.restrict x) :=
hs
variables (R A)
lemma algebraic_independent_empty_iff : algebraic_independent R (λ x, x : (∅ : set A) → A) ↔
injective (algebra_map R A) :=
by simp
variables {R A}
lemma algebraic_independent.mono {t s : set A} (h : t ⊆ s)
(hx : algebraic_independent R (λ x, x : s → A)) : algebraic_independent R (λ x, x : t → A) :=
by simpa [function.comp] using hx.comp (inclusion h) (inclusion_injective h)
end subtype
theorem algebraic_independent.to_subtype_range {ι} {f : ι → A} (hf : algebraic_independent R f) :
algebraic_independent R (coe : range f → A) :=
begin
nontriviality R,
{ rwa algebraic_independent_subtype_range hf.injective }
end
theorem algebraic_independent.to_subtype_range' {ι} {f : ι → A} (hf : algebraic_independent R f)
{t} (ht : range f = t) :
algebraic_independent R (coe : t → A) :=
ht ▸ hf.to_subtype_range
theorem algebraic_independent_comp_subtype {s : set ι} :
algebraic_independent R (x ∘ coe : s → A) ↔
∀ p ∈ (mv_polynomial.supported R s), aeval x p = 0 → p = 0 :=
have (aeval (x ∘ coe : s → A) : _ →ₐ[R] _) =
(aeval x).comp (rename coe), by ext; simp,
have ∀ p : mv_polynomial s R, rename (coe : s → ι) p = 0 ↔ p = 0,
from (injective_iff_map_eq_zero' (rename (coe : s → ι) : mv_polynomial s R →ₐ[R] _).to_ring_hom).1
(rename_injective _ subtype.val_injective),
by simp [algebraic_independent_iff, supported_eq_range_rename, *]
theorem algebraic_independent_subtype {s : set A} :
algebraic_independent R (λ x, x : s → A) ↔
∀ (p : mv_polynomial A R), p ∈ mv_polynomial.supported R s → aeval id p = 0 → p = 0 :=
by apply @algebraic_independent_comp_subtype _ _ _ id
lemma algebraic_independent_of_finite (s : set A)
(H : ∀ t ⊆ s, t.finite → algebraic_independent R (λ x, x : t → A)) :
algebraic_independent R (λ x, x : s → A) :=
algebraic_independent_subtype.2 $
λ p hp, algebraic_independent_subtype.1 (H _ (mem_supported.1 hp) (finset.finite_to_set _)) _
(by simp)
theorem algebraic_independent.image_of_comp {ι ι'} (s : set ι) (f : ι → ι') (g : ι' → A)
(hs : algebraic_independent R (λ x : s, g (f x))) :
algebraic_independent R (λ x : f '' s, g x) :=
begin
nontriviality R,
have : inj_on f s, from inj_on_iff_injective.2 hs.injective.of_comp,
exact (algebraic_independent_equiv' (equiv.set.image_of_inj_on f s this) rfl).1 hs
end
theorem algebraic_independent.image {ι} {s : set ι} {f : ι → A}
(hs : algebraic_independent R (λ x : s, f x)) : algebraic_independent R (λ x : f '' s, (x : A)) :=
by convert algebraic_independent.image_of_comp s f id hs
lemma algebraic_independent_Union_of_directed {η : Type*} [nonempty η]
{s : η → set A} (hs : directed (⊆) s)
(h : ∀ i, algebraic_independent R (λ x, x : s i → A)) :
algebraic_independent R (λ x, x : (⋃ i, s i) → A) :=
begin
refine algebraic_independent_of_finite (⋃ i, s i) (λ t ht ft, _),
rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩,
rcases hs.finset_le fi.to_finset with ⟨i, hi⟩,
exact (h i).mono (subset.trans hI $ Union₂_subset $
λ j hj, hi j (fi.mem_to_finset.2 hj))
end
lemma algebraic_independent_sUnion_of_directed {s : set (set A)}
(hsn : s.nonempty)
(hs : directed_on (⊆) s)
(h : ∀ a ∈ s, algebraic_independent R (λ x, x : (a : set A) → A)) :
algebraic_independent R (λ x, x : (⋃₀ s) → A) :=
by letI : nonempty s := nonempty.to_subtype hsn;
rw sUnion_eq_Union; exact
algebraic_independent_Union_of_directed hs.directed_coe (by simpa using h)
lemma exists_maximal_algebraic_independent
(s t : set A) (hst : s ⊆ t)
(hs : algebraic_independent R (coe : s → A)) :
∃ u : set A, algebraic_independent R (coe : u → A) ∧ s ⊆ u ∧ u ⊆ t ∧
∀ x : set A, algebraic_independent R (coe : x → A) →
u ⊆ x → x ⊆ t → x = u :=
begin
rcases zorn_subset_nonempty
{ u : set A | algebraic_independent R (coe : u → A) ∧ s ⊆ u ∧ u ⊆ t }
(λ c hc chainc hcn, ⟨⋃₀ c, begin
refine ⟨⟨algebraic_independent_sUnion_of_directed hcn
chainc.directed_on
(λ a ha, (hc ha).1), _, _⟩, _⟩,
{ cases hcn with x hx,
exact subset_sUnion_of_subset _ x (hc hx).2.1 hx },
{ exact sUnion_subset (λ x hx, (hc hx).2.2) },
{ intros s,
exact subset_sUnion_of_mem }
end⟩)
s ⟨hs, set.subset.refl s, hst⟩ with ⟨u, ⟨huai, hsu, hut⟩, hsu, hx⟩,
use [u, huai, hsu, hut],
intros x hxai huv hxt,
exact hx _ ⟨hxai, trans hsu huv, hxt⟩ huv,
end
section repr
variables (hx : algebraic_independent R x)
/-- Canonical isomorphism between polynomials and the subalgebra generated by
algebraically independent elements. -/
@[simps] def algebraic_independent.aeval_equiv (hx : algebraic_independent R x) :
(mv_polynomial ι R) ≃ₐ[R] algebra.adjoin R (range x) :=
begin
apply alg_equiv.of_bijective
(alg_hom.cod_restrict (@aeval R A ι _ _ _ x) (algebra.adjoin R (range x)) _),
swap,
{ intros x,
rw [adjoin_range_eq_range_aeval],
exact alg_hom.mem_range_self _ _ },
{ split,
{ exact (alg_hom.injective_cod_restrict _ _ _).2 hx },
{ rintros ⟨x, hx⟩,
rw [adjoin_range_eq_range_aeval] at hx,
rcases hx with ⟨y, rfl⟩,
use y,
ext,
simp } }
end
@[simp] lemma algebraic_independent.algebra_map_aeval_equiv (hx : algebraic_independent R x)
(p : mv_polynomial ι R) : algebra_map (algebra.adjoin R (range x)) A (hx.aeval_equiv p) =
aeval x p := rfl
/-- The canonical map from the subalgebra generated by an algebraic independent family
into the polynomial ring. -/
def algebraic_independent.repr (hx : algebraic_independent R x) :
algebra.adjoin R (range x) →ₐ[R] mv_polynomial ι R := hx.aeval_equiv.symm
@[simp] lemma algebraic_independent.aeval_repr (p) : aeval x (hx.repr p) = p :=
subtype.ext_iff.1 (alg_equiv.apply_symm_apply hx.aeval_equiv p)
lemma algebraic_independent.aeval_comp_repr :
(aeval x).comp hx.repr = subalgebra.val _ :=
alg_hom.ext $ hx.aeval_repr
lemma algebraic_independent.repr_ker :
(hx.repr : adjoin R (range x) →+* mv_polynomial ι R).ker = ⊥ :=
(ring_hom.injective_iff_ker_eq_bot _).1 (alg_equiv.injective _)
end repr
-- TODO - make this an `alg_equiv`
/-- The isomorphism between `mv_polynomial (option ι) R` and the polynomial ring over
the algebra generated by an algebraically independent family. -/
def algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin
(hx : algebraic_independent R x) :
mv_polynomial (option ι) R ≃+* polynomial (adjoin R (set.range x)) :=
(mv_polynomial.option_equiv_left _ _).to_ring_equiv.trans
(polynomial.map_equiv hx.aeval_equiv.to_ring_equiv)
@[simp]
lemma algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_apply
(hx : algebraic_independent R x) (y) :
hx.mv_polynomial_option_equiv_polynomial_adjoin y =
polynomial.map (hx.aeval_equiv : mv_polynomial ι R →+* adjoin R (range x))
(aeval (λ (o : option ι), o.elim polynomial.X (λ (s : ι), polynomial.C (X s))) y) :=
rfl
@[simp]
lemma algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_C
(hx : algebraic_independent R x) (r) :
hx.mv_polynomial_option_equiv_polynomial_adjoin (C r) =
polynomial.C (algebra_map _ _ r) :=
begin
-- TODO: this instance is slow to infer
have h : is_scalar_tower R (mv_polynomial ι R) (polynomial (mv_polynomial ι R)) :=
@polynomial.is_scalar_tower (mv_polynomial ι R) _ R _ _ _ _ _ _ _,
rw [algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_apply, aeval_C,
@is_scalar_tower.algebra_map_apply _ _ _ _ _ _ _ _ _ h, ← polynomial.C_eq_algebra_map,
polynomial.map_C, ring_hom.coe_coe, alg_equiv.commutes]
end
@[simp]
lemma algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_X_none
(hx : algebraic_independent R x) :
hx.mv_polynomial_option_equiv_polynomial_adjoin (X none) = polynomial.X :=
by rw [algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_apply, aeval_X,
option.elim, polynomial.map_X]
@[simp]
lemma algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_X_some
(hx : algebraic_independent R x) (i) :
hx.mv_polynomial_option_equiv_polynomial_adjoin (X (some i)) =
polynomial.C (hx.aeval_equiv (X i)) :=
by rw [algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_apply, aeval_X,
option.elim, polynomial.map_C, ring_hom.coe_coe]
lemma algebraic_independent.aeval_comp_mv_polynomial_option_equiv_polynomial_adjoin
(hx : algebraic_independent R x) (a : A) :
(ring_hom.comp (↑(polynomial.aeval a : polynomial (adjoin R (set.range x)) →ₐ[_] A) :
polynomial (adjoin R (set.range x)) →+* A)
hx.mv_polynomial_option_equiv_polynomial_adjoin.to_ring_hom) =
↑((mv_polynomial.aeval (λ o : option ι, o.elim a x)) :
mv_polynomial (option ι) R →ₐ[R] A) :=
begin
refine mv_polynomial.ring_hom_ext _ _;
simp only [ring_hom.comp_apply, ring_equiv.to_ring_hom_eq_coe, ring_equiv.coe_to_ring_hom,
alg_hom.coe_to_ring_hom, alg_hom.coe_to_ring_hom],
{ intro r,
rw [hx.mv_polynomial_option_equiv_polynomial_adjoin_C,
aeval_C, polynomial.aeval_C, is_scalar_tower.algebra_map_apply R (adjoin R (range x)) A] },
{ rintro (⟨⟩|⟨i⟩),
{ rw [hx.mv_polynomial_option_equiv_polynomial_adjoin_X_none,
aeval_X, polynomial.aeval_X, option.elim] },
{ rw [hx.mv_polynomial_option_equiv_polynomial_adjoin_X_some, polynomial.aeval_C,
hx.algebra_map_aeval_equiv, aeval_X, aeval_X, option.elim] } },
end
theorem algebraic_independent.option_iff (hx : algebraic_independent R x) (a : A) :
(algebraic_independent R (λ o : option ι, o.elim a x)) ↔
¬ is_algebraic (adjoin R (set.range x)) a :=
by erw [algebraic_independent_iff_injective_aeval, is_algebraic_iff_not_injective, not_not,
← alg_hom.coe_to_ring_hom,
← hx.aeval_comp_mv_polynomial_option_equiv_polynomial_adjoin,
ring_hom.coe_comp, injective.of_comp_iff' _ (ring_equiv.bijective _), alg_hom.coe_to_ring_hom]
variable (R)
/--
A family is a transcendence basis if it is a maximal algebraically independent subset.
-/
def is_transcendence_basis (x : ι → A) : Prop :=
algebraic_independent R x ∧
∀ (s : set A) (i' : algebraic_independent R (coe : s → A)) (h : range x ≤ s), range x = s
lemma exists_is_transcendence_basis (h : injective (algebra_map R A)) :
∃ s : set A, is_transcendence_basis R (coe : s → A) :=
begin
cases exists_maximal_algebraic_independent (∅ : set A) set.univ
(set.subset_univ _) ((algebraic_independent_empty_iff R A).2 h) with s hs,
use [s, hs.1],
intros t ht hr,
simp only [subtype.range_coe_subtype, set_of_mem_eq] at *,
exact eq.symm (hs.2.2.2 t ht hr (set.subset_univ _))
end
variable {R}
lemma algebraic_independent.is_transcendence_basis_iff
{ι : Type w} {R : Type u} [comm_ring R] [nontrivial R]
{A : Type v} [comm_ring A] [algebra R A] {x : ι → A} (i : algebraic_independent R x) :
is_transcendence_basis R x ↔ ∀ (κ : Type v) (w : κ → A) (i' : algebraic_independent R w)
(j : ι → κ) (h : w ∘ j = x), surjective j :=
begin
fsplit,
{ rintros p κ w i' j rfl,
have p := p.2 (range w) i'.coe_range (range_comp_subset_range _ _),
rw [range_comp, ←@image_univ _ _ w] at p,
exact range_iff_surjective.mp (image_injective.mpr i'.injective p) },
{ intros p,
use i,
intros w i' h,
specialize p w (coe : w → A) i'
(λ i, ⟨x i, range_subset_iff.mp h i⟩)
(by { ext, simp, }),
have q := congr_arg (λ s, (coe : w → A) '' s) p.range_eq,
dsimp at q,
rw [←image_univ, image_image] at q,
simpa using q, },
end
lemma is_transcendence_basis.is_algebraic [nontrivial R]
(hx : is_transcendence_basis R x) : is_algebraic (adjoin R (range x)) A :=
begin
intro a,
rw [← not_iff_comm.1 (hx.1.option_iff _).symm],
intro ai,
have h₁ : range x ⊆ range (λ o : option ι, o.elim a x),
{ rintros x ⟨y, rfl⟩, exact ⟨some y, rfl⟩ },
have h₂ : range x ≠ range (λ o : option ι, o.elim a x),
{ intro h,
have : a ∈ range x, { rw h, exact ⟨none, rfl⟩ },
rcases this with ⟨b, rfl⟩,
have : some b = none := ai.injective rfl,
simpa },
exact h₂ (hx.2 (set.range (λ o : option ι, o.elim a x))
((algebraic_independent_subtype_range ai.injective).2 ai) h₁)
end
section field
variables [field K] [algebra K A]
@[simp] lemma algebraic_independent_empty_type [is_empty ι] [nontrivial A] :
algebraic_independent K x :=
begin
rw [algebraic_independent_empty_type_iff],
exact ring_hom.injective _,
end
lemma algebraic_independent_empty [nontrivial A] :
algebraic_independent K (coe : ((∅ : set A) → A)) :=
algebraic_independent_empty_type
end field
|
275d6719173007ae9d695c60cf13bfcbd78d9dca | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/num/prime.lean | 4d49202c29edee9f6900dbdfcfc7b7c9d8f4697d | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,879 | lean | /-
Copyright (c) 2020 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.num.lemmas
import Mathlib.data.nat.prime
import Mathlib.tactic.ring
import Mathlib.PostPort
namespace Mathlib
/-!
# Primality for binary natural numbers
This file defines versions of `nat.min_fac` and `nat.prime` for `num` and `pos_num`. As with other
`num` definitions, they are not intended for general use (`nat` should be used instead of `num` in
most cases) but they can be used in contexts where kernel computation is required, such as proofs
by `rfl` and `dec_trivial`, as well as in `#reduce`.
The default decidable instance for `nat.prime` is optimized for VM evaluation, so it should be
preferred within `#eval` or in tactic execution, while for proofs the `norm_num` tactic can be used
to construct primality and non-primality proofs more efficiently than kernel computation.
Nevertheless, sometimes proof by computational reflection requires natural number computations, and
`num` implements algorithms directly on binary natural numbers for this purpose.
-/
namespace pos_num
/-- Auxiliary function for computing the smallest prime factor of a `pos_num`. Unlike
`nat.min_fac_aux`, we use a natural number `fuel` variable that is set to an upper bound on the
number of iterations. It is initialized to the number `n` we are determining primality for. Even
though this is exponential in the input (since it is a `nat`, not a `num`), it will get lazily
evaluated during kernel reduction, so we will only require about `sqrt n` unfoldings, for the
`sqrt n` iterations of the loop. -/
def min_fac_aux (n : pos_num) : ℕ → pos_num → pos_num :=
sorry
theorem min_fac_aux_to_nat {fuel : ℕ} {n : pos_num} {k : pos_num} (h : nat.sqrt ↑n < fuel + ↑(bit1 k)) : ↑(min_fac_aux n fuel k) = nat.min_fac_aux ↑n ↑(bit1 k) := sorry
/-- Returns the smallest prime factor of `n ≠ 1`. -/
def min_fac : pos_num → pos_num :=
sorry
@[simp] theorem min_fac_to_nat (n : pos_num) : ↑(min_fac n) = nat.min_fac ↑n := sorry
/-- Primality predicate for a `pos_num`. -/
@[simp] def prime (n : pos_num) :=
nat.prime ↑n
protected instance decidable_prime : decidable_pred prime :=
sorry
end pos_num
namespace num
/-- Returns the smallest prime factor of `n ≠ 1`. -/
def min_fac : num → pos_num :=
sorry
@[simp] theorem min_fac_to_nat (n : num) : ↑(min_fac n) = nat.min_fac ↑n :=
num.cases_on n (idRhs (↑(min_fac 0) = ↑(min_fac 0)) rfl)
fun (n : pos_num) => idRhs (↑(pos_num.min_fac n) = nat.min_fac ↑n) (pos_num.min_fac_to_nat n)
/-- Primality predicate for a `num`. -/
@[simp] def prime (n : num) :=
nat.prime ↑n
protected instance decidable_prime : decidable_pred prime :=
sorry
|
59d705f1e81f9189718f573d461d9f283dc4c3fd | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/topology/instances/real.lean | a52920934c5ecd2682e193e13fc78c4530b9ccd0 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,472 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import topology.metric_space.basic
import topology.algebra.uniform_group
import topology.algebra.ring
import ring_theory.subring
import group_theory.archimedean
/-!
# Topological properties of ℝ
-/
noncomputable theory
open classical set filter topological_space metric
open_locale classical
open_locale topological_space
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
instance : metric_space ℚ :=
metric_space.induced coe rat.cast_injective real.metric_space
theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl
@[norm_cast, simp] lemma rat.dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl
section low_prio
-- we want to ignore this instance for the next declaration
local attribute [instance, priority 10] int.uniform_space
instance : metric_space ℤ :=
begin
letI M := metric_space.induced coe int.cast_injective real.metric_space,
refine @metric_space.replace_uniformity _ int.uniform_space M
(le_antisymm refl_le_uniformity $ λ r ru,
mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h,
mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩),
have : (abs (↑a - ↑b) : ℝ) < 1 := h,
have : abs (a - b) < 1, by norm_cast at this; assumption,
have : abs (a - b) ≤ 0 := (@int.lt_add_one_iff _ 0).mp this,
norm_cast, assumption
end
end low_prio
theorem int.dist_eq (x y : ℤ) : dist x y = abs (x - y) := rfl
@[norm_cast, simp] theorem int.dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl
@[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y :=
by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast
instance : proper_space ℤ :=
⟨ begin
intros x r,
apply set.finite.is_compact,
have : closed_ball x r = coe ⁻¹' (closed_ball (x:ℝ) r) := rfl,
simp [this, closed_ball_Icc, set.Icc_ℤ_finite],
end ⟩
theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) :=
uniform_continuous_comap
theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) :=
uniform_embedding_comap rat.cast_injective
theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) :=
uniform_embedding_of_rat.dense_embedding $
λ x, mem_closure_iff_nhds.2 $ λ t ht,
let ⟨ε,ε0, hε⟩ := metric.mem_nhds_iff.1 ht in
let ⟨q, h⟩ := exists_rat_near x ε0 in
⟨_, hε (mem_ball'.2 h), q, rfl⟩
theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding
theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous
theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in
⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩
-- TODO(Mario): Find a way to use rat_add_continuous_lemma
theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) :=
uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact
real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk
(uniform_continuous_of_rat.comp uniform_continuous_snd))
theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) :=
metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h,
by rw dist_comm at h; simpa [real.dist_eq] using h⟩
theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) :=
metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h,
by rw dist_comm at h; simpa [rat.dist_eq] using h⟩
instance : uniform_add_group ℝ :=
uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg
instance : uniform_add_group ℚ :=
uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg
-- short-circuit type class inference
instance : topological_add_group ℝ := by apply_instance
instance : topological_add_group ℚ := by apply_instance
instance : order_topology ℚ :=
induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _)
instance : proper_space ℝ :=
{ compact_ball := λx r, by { rw closed_ball_Icc, apply compact_Icc } }
instance : second_countable_topology ℝ := second_countable_of_proper
lemma real.is_topological_basis_Ioo_rat :
@is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) :=
is_topological_basis_of_open_of_nhds
(by simp [is_open_Ioo] {contextual:=tt})
(assume a v hav hv,
let ⟨l, u, ⟨hl, hu⟩, h⟩ := mem_nhds_iff_exists_Ioo_subset.mp (is_open.mem_nhds hv hav),
⟨q, hlq, hqa⟩ := exists_rat_btwn hl,
⟨p, hap, hpu⟩ := exists_rat_btwn hu in
⟨Ioo q p,
by { simp only [mem_Union], exact ⟨q, p, rat.cast_lt.1 $ hqa.trans hap, rfl⟩ },
⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h ⟨hlq.trans hqa', ha'p.trans hpu⟩⟩)
/- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings
lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) :=
_
lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) :=
_ -/
lemma real.mem_closure_iff {s : set ℝ} {x : ℝ} :
x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, abs (y - x) < ε :=
by simp [mem_closure_iff_nhds_basis nhds_basis_ball, real.dist_eq]
lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) :
uniform_continuous (λp:s, p.1⁻¹) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in
⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩
lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩
lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
⟨ε, ε0, λ a b h, lt_of_le_of_lt
(by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩
lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) :=
by rw ← abs_pos at r0; exact
tendsto_of_uniform_continuous_subtype
(real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h))
(is_open.mem_nhds ((is_open_lt' (abs r / 2)).preimage continuous_abs) (half_lt_self r0))
lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) :=
continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩,
tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _)
lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) :
continuous (λa, (f a)⁻¹) :=
show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩),
from real.continuous_inv.comp (continuous_subtype_mk _ hf)
lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) :=
metric.uniform_continuous_iff.2 $ λ ε ε0, begin
cases no_top (abs x) with y xy,
have y0 := lt_of_le_of_lt (abs_nonneg _) xy,
refine ⟨_, div_pos ε0 y0, λ a b h, _⟩,
rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)],
exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0
end
lemma real.uniform_continuous_mul (s : set (ℝ × ℝ))
{r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) :
uniform_continuous (λp:s, p.1.1 * p.1.2) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in
⟨δ, δ0, λ a b h,
let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩
protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) :=
continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩,
tendsto_of_uniform_continuous_subtype
(real.uniform_continuous_mul
({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1})
(λ x, id))
(is_open.mem_nhds
(((is_open_gt' (abs a₁ + 1)).preimage continuous_abs).prod
((is_open_gt' (abs a₂ + 1)).preimage continuous_abs ))
⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩)
instance : topological_ring ℝ :=
{ continuous_mul := real.continuous_mul, ..real.topological_add_group }
instance : topological_semiring ℝ := by apply_instance -- short-circuit type class inference
lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) :=
embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact
real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk
(continuous_of_rat.comp continuous_snd))
instance : topological_ring ℚ :=
{ continuous_mul := rat.continuous_mul, ..rat.topological_add_group }
theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) :=
set.ext $ λ y, by rw [mem_ball, real.dist_eq,
abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl
theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) :=
by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add,
add_sub_cancel', add_self_div_two, ← add_div,
add_assoc, add_sub_cancel'_right, add_self_div_two]
instance : complete_space ℝ :=
begin
apply complete_of_cauchy_seq_tendsto,
intros u hu,
let c : cau_seq ℝ abs := ⟨u, metric.cauchy_seq_iff'.1 hu⟩,
refine ⟨c.lim, λ s h, _⟩,
rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩,
have := c.equiv_lim ε ε0,
simp only [mem_map, mem_at_top_sets, mem_set_of_eq],
refine this.imp (λ N hN n hn, hε (hN n hn))
end
lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) :=
by rw real.ball_eq_Ioo; apply totally_bounded_Ioo
lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) :=
begin
have := totally_bounded_preimage uniform_embedding_of_rat (totally_bounded_Icc a b),
rwa (set.ext (λ q, _) : Icc _ _ = _), simp
end
section
lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} :=
subset.antisymm
((is_closed_ge' _).closure_subset_iff.2
(image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $
λ x hx, mem_closure_iff_nhds.2 $ λ t ht,
let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in
let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in
⟨_, hε (show abs _ < _,
by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']),
p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩
/- TODO(Mario): Put these back only if needed later
lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} :=
_
lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) :
closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} :=
_-/
lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s :=
⟨begin
assume bdd,
rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r
rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r)
exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩
end,
begin
rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩,
have I : s ⊆ Icc m M := λx hx, ⟨hm hx, hM hx⟩,
have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) :=
by rw closed_ball_Icc; congr; ring,
rw this at I,
exact bounded.subset I bounded_closed_ball
end⟩
lemma real.image_Icc {f : ℝ → ℝ} {a b : ℝ} (hab : a ≤ b) (h : continuous_on f $ Icc a b) :
f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) :=
eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩
(compact_Icc.image_of_continuous_on h)
end
section subgroups
/-- Given a nontrivial subgroup `G ⊆ ℝ`, if `G ∩ ℝ_{>0}` has no minimum then `G` is dense. -/
lemma real.subgroup_dense_of_no_min {G : add_subgroup ℝ} {g₀ : ℝ} (g₀_in : g₀ ∈ G) (g₀_ne : g₀ ≠ 0)
(H' : ¬ ∃ a : ℝ, is_least {g : ℝ | g ∈ G ∧ 0 < g} a) :
dense (G : set ℝ) :=
begin
let G_pos := {g : ℝ | g ∈ G ∧ 0 < g},
push_neg at H',
intros x,
suffices : ∀ ε > (0 : ℝ), ∃ g ∈ G, abs (x - g) < ε,
by simpa only [real.mem_closure_iff, abs_sub],
intros ε ε_pos,
obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℝ, g₁ ∈ G ∧ 0 < g₁,
{ cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀,
{ exact ⟨-g₀, G.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ },
{ exact ⟨g₀, g₀_in, Hg₀⟩ } },
obtain ⟨a, ha⟩ : ∃ a, is_glb G_pos a :=
⟨Inf G_pos, is_glb_cInf ⟨g₁, g₁_in, g₁_pos⟩ ⟨0, λ _ hx, le_of_lt hx.2⟩⟩,
have a_notin : a ∉ G_pos,
{ intros H,
exact H' a ⟨H, ha.1⟩ },
obtain ⟨g₂, g₂_in, g₂_pos, g₂_lt⟩ : ∃ g₂ : ℝ, g₂ ∈ G ∧ 0 < g₂ ∧ g₂ < ε,
{ obtain ⟨b, hb, hb', hb''⟩ := ha.exists_between_self_add' a_notin ε_pos,
obtain ⟨c, hc, hc', hc''⟩ := ha.exists_between_self_add' a_notin (sub_pos.2 hb'),
refine ⟨b - c, G.sub_mem hb.1 hc.1, _, _⟩ ;
linarith },
refine ⟨floor (x/g₂) * g₂, _, _⟩,
{ exact add_subgroup.int_mul_mem _ g₂_in },
{ rw abs_of_nonneg (sub_floor_div_mul_nonneg x g₂_pos),
linarith [sub_floor_div_mul_lt x g₂_pos] }
end
/-- Subgroups of `ℝ` are either dense or cyclic. See `real.subgroup_dense_of_no_min` and
`subgroup_cyclic_of_min` for more precise statements. -/
lemma real.subgroup_dense_or_cyclic (G : add_subgroup ℝ) :
dense (G : set ℝ) ∨ ∃ a : ℝ, G = add_subgroup.closure {a} :=
begin
cases add_subgroup.bot_or_exists_ne_zero G with H H,
{ right,
use 0,
rw [H, add_subgroup.closure_singleton_zero] },
{ let G_pos := {g : ℝ | g ∈ G ∧ 0 < g},
by_cases H' : ∃ a, is_least G_pos a,
{ right,
rcases H' with ⟨a, ha⟩,
exact ⟨a, add_subgroup.cyclic_of_min ha⟩ },
{ left,
rcases H with ⟨g₀, g₀_in, g₀_ne⟩,
exact real.subgroup_dense_of_no_min g₀_in g₀_ne H' } }
end
end subgroups
|
842fdbdc3f58eaf893fa8c1d3204ee6f3f356d20 | 5756a081670ba9c1d1d3fca7bd47cb4e31beae66 | /Mathport/Syntax/Transform/Expr.lean | 563def22d5064ad202b6e8c395f463504bd1e246 | [
"Apache-2.0"
] | permissive | leanprover-community/mathport | 2c9bdc8292168febf59799efdc5451dbf0450d4a | 13051f68064f7638970d39a8fecaede68ffbf9e1 | refs/heads/master | 1,693,841,364,079 | 1,693,813,111,000 | 1,693,813,111,000 | 379,357,010 | 27 | 10 | Apache-2.0 | 1,691,309,132,000 | 1,624,384,521,000 | Lean | UTF-8 | Lean | false | false | 629 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Mathport.Syntax.Transform.Basic
mathport_rules
| `($x:term $args* <| fun $y:basicFun) => `($x:term $args* fun $y:basicFun)
| `($x:term $args* <| fun $y:matchAlts) => `($x:term $args* fun $y:matchAlts)
| `($x:term $args* <| do $s:doSeq) => `($x:term $args* do $s:doSeq)
| `($x:term <| fun $y:basicFun) => `($x:term fun $y:basicFun)
| `($x:term <| fun $y:matchAlts) => `($x:term fun $y:matchAlts)
| `($x:term <| do $s:doSeq) => `($x:term do $s:doSeq)
|
ccfb975f1641f5328751ddf388278621ba4cd937 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/num.lean | f3b8460075a85d9dbf02a3eda1fe4bdc117e0244 | [
"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 | 114 | lean | --
check 10
check 20
check 3
check 1
check 0
check 12
check 13
check 12138
check 1221
check 11
check 5
check 21
|
2afb0da3328c9f2ef4be3264f749423ecd1da848 | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/topology/uniform_space/uniform_embedding.lean | a9e8e16c8af2c22992c7e925bc33128ed1566d42 | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 20,238 | 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, Sébastien Gouëzel, Patrick Massot
Uniform embeddings of uniform spaces. Extension of uniform continuous functions.
-/
import topology.uniform_space.cauchy
import topology.uniform_space.separation
import topology.dense_embedding
open filter topological_space set classical
open_locale classical
open_locale uniformity topological_space
section
variables {α : Type*} {β : Type*} {γ : Type*}
[uniform_space α] [uniform_space β] [uniform_space γ]
universe u
structure uniform_inducing (f : α → β) : Prop :=
(comap_uniformity : comap (λx:α×α, (f x.1, f x.2)) (𝓤 β) = 𝓤 α)
lemma uniform_inducing.mk' {f : α → β} (h : ∀ s, s ∈ 𝓤 α ↔
∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s) : uniform_inducing f :=
⟨by simp [eq_comm, filter.ext_iff, subset_def, h]⟩
lemma uniform_inducing.comp {g : β → γ} (hg : uniform_inducing g)
{f : α → β} (hf : uniform_inducing f) : uniform_inducing (g ∘ f) :=
⟨ by rw [show (λ (x : α × α), ((g ∘ f) x.1, (g ∘ f) x.2)) =
(λ y : β × β, (g y.1, g y.2)) ∘ (λ x : α × α, (f x.1, f x.2)), by ext ; simp,
← filter.comap_comap_comp, hg.1, hf.1]⟩
structure uniform_embedding (f : α → β) extends uniform_inducing f : Prop :=
(inj : function.injective f)
lemma uniform_embedding_subtype_val {p : α → Prop} :
uniform_embedding (subtype.val : subtype p → α) :=
{ comap_uniformity := rfl,
inj := subtype.val_injective }
lemma uniform_embedding_subtype_coe {p : α → Prop} :
uniform_embedding (coe : subtype p → α) :=
uniform_embedding_subtype_val
lemma uniform_embedding_set_inclusion {s t : set α} (hst : s ⊆ t) :
uniform_embedding (inclusion hst) :=
{ comap_uniformity :=
by { erw [uniformity_subtype, uniformity_subtype, comap_comap_comp], congr },
inj := inclusion_injective hst }
lemma uniform_embedding.comp {g : β → γ} (hg : uniform_embedding g)
{f : α → β} (hf : uniform_embedding f) : uniform_embedding (g ∘ f) :=
{ inj := function.injective_comp hg.inj hf.inj,
..hg.to_uniform_inducing.comp hf.to_uniform_inducing }
theorem uniform_embedding_def {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ ∀ s, s ∈ 𝓤 α ↔
∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s :=
begin
split,
{ rintro ⟨⟨h⟩, h'⟩,
rw [eq_comm, filter.ext_iff] at h,
simp [*, subset_def] },
{ rintro ⟨h, h'⟩,
refine uniform_embedding.mk ⟨_⟩ h,
rw [eq_comm, filter.ext_iff],
simp [*, subset_def] }
end
theorem uniform_embedding_def' {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ s, s ∈ 𝓤 α →
∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s :=
by simp [uniform_embedding_def, uniform_continuous_def]; exact
⟨λ ⟨I, H⟩, ⟨I, λ s su, (H _).2 ⟨s, su, λ x y, id⟩, λ s, (H s).1⟩,
λ ⟨I, H₁, H₂⟩, ⟨I, λ s, ⟨H₂ s,
λ ⟨t, tu, h⟩, sets_of_superset _ (H₁ t tu) (λ ⟨a, b⟩, h a b)⟩⟩⟩
lemma uniform_inducing.uniform_continuous {f : α → β}
(hf : uniform_inducing f) : uniform_continuous f :=
by simp [uniform_continuous, hf.comap_uniformity.symm, tendsto_comap]
lemma uniform_inducing.uniform_continuous_iff {f : α → β} {g : β → γ} (hg : uniform_inducing g) :
uniform_continuous f ↔ uniform_continuous (g ∘ f) :=
by simp [uniform_continuous, tendsto]; rw [← hg.comap_uniformity, ← map_le_iff_le_comap, filter.map_map]
lemma uniform_inducing.inducing {f : α → β} (h : uniform_inducing f) : inducing f :=
begin
refine ⟨eq_of_nhds_eq_nhds $ assume a, _ ⟩,
rw [nhds_induced, nhds_eq_uniformity, nhds_eq_uniformity, ← h.comap_uniformity,
comap_lift'_eq, comap_lift'_eq2];
{ refl <|> exact monotone_preimage }
end
lemma uniform_inducing.prod {α' : Type*} {β' : Type*} [uniform_space α'] [uniform_space β']
{e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_inducing e₁) (h₂ : uniform_inducing e₂) :
uniform_inducing (λp:α×β, (e₁ p.1, e₂ p.2)) :=
⟨by simp [(∘), uniformity_prod, h₁.comap_uniformity.symm, h₂.comap_uniformity.symm,
comap_inf, comap_comap_comp]⟩
lemma uniform_inducing.dense_inducing {f : α → β} (h : uniform_inducing f) (hd : dense_range f) :
dense_inducing f :=
{ dense := hd,
induced := h.inducing.induced }
lemma uniform_embedding.embedding {f : α → β} (h : uniform_embedding f) : embedding f :=
{ induced := h.to_uniform_inducing.inducing.induced,
inj := h.inj }
lemma uniform_embedding.dense_embedding {f : α → β} (h : uniform_embedding f) (hd : dense_range f) :
dense_embedding f :=
{ dense := hd,
inj := h.inj,
induced := h.embedding.induced }
lemma closure_image_mem_nhds_of_uniform_inducing
{s : set (α×α)} {e : α → β} (b : β)
(he₁ : uniform_inducing e) (he₂ : dense_inducing e) (hs : s ∈ 𝓤 α) :
∃a, closure (e '' {a' | (a, a') ∈ s}) ∈ 𝓝 b :=
have s ∈ comap (λp:α×α, (e p.1, e p.2)) (𝓤 β),
from he₁.comap_uniformity.symm ▸ hs,
let ⟨t₁, ht₁u, ht₁⟩ := this in
have ht₁ : ∀p:α×α, (e p.1, e p.2) ∈ t₁ → p ∈ s, from ht₁,
let ⟨t₂, ht₂u, ht₂s, ht₂c⟩ := comp_symm_of_uniformity ht₁u in
let ⟨t, htu, hts, htc⟩ := comp_symm_of_uniformity ht₂u in
have preimage e {b' | (b, b') ∈ t₂} ∈ comap e (𝓝 b),
from preimage_mem_comap $ mem_nhds_left b ht₂u,
let ⟨a, (ha : (b, e a) ∈ t₂)⟩ := nonempty_of_mem_sets (he₂.comap_nhds_ne_bot) this in
have ∀b' (s' : set (β × β)), (b, b') ∈ t → s' ∈ 𝓤 β →
({y : β | (b', y) ∈ s'} ∩ e '' {a' : α | (a, a') ∈ s}).nonempty,
from assume b' s' hb' hs',
have preimage e {b'' | (b', b'') ∈ s' ∩ t} ∈ comap e (𝓝 b'),
from preimage_mem_comap $ mem_nhds_left b' $ inter_mem_sets hs' htu,
let ⟨a₂, ha₂s', ha₂t⟩ := nonempty_of_mem_sets (he₂.comap_nhds_ne_bot) this in
have (e a, e a₂) ∈ t₁,
from ht₂c $ prod_mk_mem_comp_rel (ht₂s ha) $ htc $ prod_mk_mem_comp_rel hb' ha₂t,
have e a₂ ∈ {b'':β | (b', b'') ∈ s'} ∩ e '' {a' | (a, a') ∈ s},
from ⟨ha₂s', mem_image_of_mem _ $ ht₁ (a, a₂) this⟩,
⟨_, this⟩,
have ∀b', (b, b') ∈ t → 𝓝 b' ⊓ principal (e '' {a' | (a, a') ∈ s}) ≠ ⊥,
begin
intros b' hb',
rw [nhds_eq_uniformity, lift'_inf_principal_eq, lift'_ne_bot_iff],
exact assume s, this b' s hb',
exact monotone_inter monotone_preimage monotone_const
end,
have ∀b', (b, b') ∈ t → b' ∈ closure (e '' {a' | (a, a') ∈ s}),
from assume b' hb', by rw [closure_eq_nhds]; exact this b' hb',
⟨a, (𝓝 b).sets_of_superset (mem_nhds_left b htu) this⟩
lemma uniform_embedding_subtype_emb (p : α → Prop) {e : α → β} (ue : uniform_embedding e)
(de : dense_embedding e) : uniform_embedding (dense_embedding.subtype_emb p e) :=
{ comap_uniformity := by simp [comap_comap_comp, (∘), dense_embedding.subtype_emb,
uniformity_subtype, ue.comap_uniformity.symm],
inj := (de.subtype p).inj }
lemma uniform_embedding.prod {α' : Type*} {β' : Type*} [uniform_space α'] [uniform_space β']
{e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_embedding e₁) (h₂ : uniform_embedding e₂) :
uniform_embedding (λp:α×β, (e₁ p.1, e₂ p.2)) :=
{ inj := h₁.inj.prod h₂.inj,
..h₁.to_uniform_inducing.prod h₂.to_uniform_inducing }
lemma is_complete_of_complete_image {m : α → β} {s : set α} (hm : uniform_inducing m)
(hs : is_complete (m '' s)) : is_complete s :=
begin
intros f hf hfs,
rw le_principal_iff at hfs,
obtain ⟨_, ⟨x, hx, rfl⟩, hyf⟩ : ∃ y ∈ m '' s, map m f ≤ 𝓝 y,
from hs (f.map m) (cauchy_map hm.uniform_continuous hf)
(le_principal_iff.2 (image_mem_map hfs)),
rw [map_le_iff_le_comap, ← nhds_induced, ← hm.inducing.induced] at hyf,
exact ⟨x, hx, hyf⟩
end
/-- A set is complete iff its image under a uniform embedding is complete. -/
lemma is_complete_image_iff {m : α → β} {s : set α} (hm : uniform_embedding m) :
is_complete (m '' s) ↔ is_complete s :=
begin
refine ⟨is_complete_of_complete_image hm.to_uniform_inducing, λ c f hf fs, _⟩,
rw filter.le_principal_iff at fs,
let f' := comap m f,
have cf' : cauchy f',
{ have : comap m f ≠ ⊥,
{ refine comap_ne_bot (λt ht, _),
have A : t ∩ m '' s ∈ f := filter.inter_mem_sets ht fs,
obtain ⟨x, ⟨xt, ⟨y, ys, rfl⟩⟩⟩ : (t ∩ m '' s).nonempty,
from nonempty_of_mem_sets hf.1 A,
exact ⟨y, xt⟩ },
apply cauchy_comap _ hf this,
simp only [hm.comap_uniformity, le_refl] },
have : f' ≤ principal s := by simp [f']; exact
⟨m '' s, by simpa using fs, by simp [preimage_image_eq s hm.inj]⟩,
rcases c f' cf' this with ⟨x, xs, hx⟩,
existsi [m x, mem_image_of_mem m xs],
rw [(uniform_embedding.embedding hm).induced, nhds_induced] at hx,
calc f = map m f' : (map_comap $ filter.mem_sets_of_superset fs $ image_subset_range _ _).symm
... ≤ map m (comap m (𝓝 (m x))) : map_mono hx
... ≤ 𝓝 (m x) : map_comap_le
end
lemma complete_space_iff_is_complete_range {f : α → β} (hf : uniform_embedding f) :
complete_space α ↔ is_complete (range f) :=
by rw [complete_space_iff_is_complete_univ, ← is_complete_image_iff hf, image_univ]
lemma complete_space_congr {e : α ≃ β} (he : uniform_embedding e) :
complete_space α ↔ complete_space β :=
by rw [complete_space_iff_is_complete_range he, e.range_eq_univ,
complete_space_iff_is_complete_univ]
lemma complete_space_coe_iff_is_complete {s : set α} :
complete_space s ↔ is_complete s :=
(complete_space_iff_is_complete_range uniform_embedding_subtype_coe).trans $
by rw [range_coe_subtype]
lemma is_complete.complete_space_coe {s : set α} (hs : is_complete s) :
complete_space s :=
complete_space_coe_iff_is_complete.2 hs
lemma is_closed.complete_space_coe [complete_space α] {s : set α} (hs : is_closed s) :
complete_space s :=
(is_complete_of_is_closed hs).complete_space_coe
lemma complete_space_extension {m : β → α} (hm : uniform_inducing m) (dense : dense_range m)
(h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ 𝓝 x) : complete_space α :=
⟨assume (f : filter α), assume hf : cauchy f,
let
p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s},
g := (𝓤 α).lift (λs, f.lift' (p s))
in
have mp₀ : monotone p,
from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩,
have mp₁ : ∀{s}, monotone (p s),
from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩,
have f ≤ g, from
le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
le_principal_iff.mpr $
mem_sets_of_superset ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩,
have g ≠ ⊥, from ne_bot_of_le_ne_bot hf.left this,
have comap m g ≠ ⊥, from comap_ne_bot $ assume t ht,
let ⟨t', ht', ht_mem⟩ := (mem_lift_sets $ monotone_lift' monotone_const mp₀).mp ht in
let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_sets mp₁).mp ht_mem in
let ⟨x, (hx : x ∈ t'')⟩ := nonempty_of_mem_sets hf.left ht'' in
have h₀ : 𝓝 x ⊓ principal (range m) ≠ ⊥,
by simpa [dense_range, closure_eq_nhds] using dense x,
have h₁ : {y | (x, y) ∈ t'} ∈ 𝓝 x ⊓ principal (range m),
from @mem_inf_sets_of_left α (𝓝 x) (principal (range m)) _ $ mem_nhds_left x ht',
have h₂ : range m ∈ 𝓝 x ⊓ principal (range m),
from @mem_inf_sets_of_right α (𝓝 x) (principal (range m)) _ $ subset.refl _,
have {y | (x, y) ∈ t'} ∩ range m ∈ 𝓝 x ⊓ principal (range m),
from @inter_mem_sets α (𝓝 x ⊓ principal (range m)) _ _ h₁ h₂,
let ⟨y, xyt', b, b_eq⟩ := nonempty_of_mem_sets h₀ this in
⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩,
have cauchy g, from
⟨‹g ≠ ⊥›, assume s hs,
let
⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs,
⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁,
⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂)
in
have hg₁ : p (preimage prod.swap s₁) t ∈ g,
from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht,
have hg₂ : p s₂ t ∈ g,
from mem_lift hs₂ $ @mem_lift' α α f _ t ht,
have hg : set.prod (p (preimage prod.swap s₁) t) (p s₂ t) ∈ filter.prod g g,
from @prod_mem_prod α α _ _ g g hg₁ hg₂,
(filter.prod g g).sets_of_superset hg
(assume ⟨a, b⟩ ⟨⟨c₁, c₁t, hc₁⟩, ⟨c₂, c₂t, hc₂⟩⟩,
have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩,
comp_s₁ $ prod_mk_mem_comp_rel hc₁ $
comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩,
have cauchy (filter.comap m g),
from cauchy_comap (le_of_eq hm.comap_uniformity) ‹cauchy g› (by assumption),
let ⟨x, (hx : map m (filter.comap m g) ≤ 𝓝 x)⟩ := h _ this in
have map m (filter.comap m g) ⊓ 𝓝 x ≠ ⊥,
from (le_nhds_iff_adhp_of_cauchy (cauchy_map hm.uniform_continuous this)).mp hx,
have g ⊓ 𝓝 x ≠ ⊥,
from ne_bot_of_le_ne_bot this (inf_le_inf_right _ (assume s hs, ⟨s, hs, subset.refl _⟩)),
⟨x, calc f ≤ g : by assumption
... ≤ 𝓝 x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩
lemma totally_bounded_preimage {f : α → β} {s : set β} (hf : uniform_embedding f)
(hs : totally_bounded s) : totally_bounded (f ⁻¹' s) :=
λ t ht, begin
rw ← hf.comap_uniformity at ht,
rcases mem_comap_sets.2 ht with ⟨t', ht', ts⟩,
rcases totally_bounded_iff_subset.1
(totally_bounded_subset (image_preimage_subset f s) hs) _ ht' with ⟨c, cs, hfc, hct⟩,
refine ⟨f ⁻¹' c, finite_preimage (hf.inj.inj_on _) hfc, λ x h, _⟩,
have := hct (mem_image_of_mem f h), simp at this ⊢,
rcases this with ⟨z, zc, zt⟩,
rcases cs zc with ⟨y, yc, rfl⟩,
exact ⟨y, zc, ts (by exact zt)⟩
end
end
lemma uniform_embedding_comap {α : Type*} {β : Type*} {f : α → β} [u : uniform_space β]
(hf : function.injective f) : @uniform_embedding α β (uniform_space.comap f u) u f :=
@uniform_embedding.mk _ _ (uniform_space.comap f u) _ _
(@uniform_inducing.mk _ _ (uniform_space.comap f u) _ _ rfl) hf
section uniform_extension
variables {α : Type*} {β : Type*} {γ : Type*}
[uniform_space α] [uniform_space β] [uniform_space γ]
{e : β → α}
(h_e : uniform_inducing e)
(h_dense : dense_range e)
{f : β → γ}
(h_f : uniform_continuous f)
local notation `ψ` := (h_e.dense_inducing h_dense).extend f
lemma uniformly_extend_exists [complete_space γ] (a : α) :
∃c, tendsto f (comap e (𝓝 a)) (𝓝 c) :=
let de := (h_e.dense_inducing h_dense) in
have cauchy (𝓝 a), from cauchy_nhds,
have cauchy (comap e (𝓝 a)), from
cauchy_comap (le_of_eq h_e.comap_uniformity) this de.comap_nhds_ne_bot,
have cauchy (map f (comap e (𝓝 a))), from
cauchy_map h_f this,
complete_space.complete this
lemma uniform_extend_subtype [complete_space γ]
{p : α → Prop} {e : α → β} {f : α → γ} {b : β} {s : set α}
(hf : uniform_continuous (λx:subtype p, f x.val))
(he : uniform_embedding e) (hd : ∀x:β, x ∈ closure (range e))
(hb : closure (e '' s) ∈ 𝓝 b) (hs : is_closed s) (hp : ∀x∈s, p x) :
∃c, tendsto f (comap e (𝓝 b)) (𝓝 c) :=
have de : dense_embedding e,
from he.dense_embedding hd,
have de' : dense_embedding (dense_embedding.subtype_emb p e),
by exact de.subtype p,
have ue' : uniform_embedding (dense_embedding.subtype_emb p e),
from uniform_embedding_subtype_emb _ he de,
have b ∈ closure (e '' {x | p x}),
from (closure_mono $ monotone_image $ hp) (mem_of_nhds hb),
let ⟨c, (hc : tendsto (f ∘ subtype.val) (comap (dense_embedding.subtype_emb p e) (𝓝 ⟨b, this⟩)) (𝓝 c))⟩ :=
uniformly_extend_exists ue'.to_uniform_inducing de'.dense hf _ in
begin
rw [nhds_subtype_eq_comap] at hc,
simp [comap_comap_comp] at hc,
change (tendsto (f ∘ @subtype.val α p) (comap (e ∘ @subtype.val α p) (𝓝 b)) (𝓝 c)) at hc,
rw [←comap_comap_comp, tendsto_comap'_iff] at hc,
exact ⟨c, hc⟩,
exact ⟨_, hb, assume x,
begin
change e x ∈ (closure (e '' s)) → x ∈ range subtype.val,
rw [←closure_induced, closure_eq_nhds, mem_set_of_eq, (≠), nhds_induced, ← de.to_dense_inducing.nhds_eq_comap],
change x ∈ {x | 𝓝 x ⊓ principal s ≠ ⊥} → x ∈ range subtype.val,
rw [←closure_eq_nhds, closure_eq_of_is_closed hs],
exact assume hxs, ⟨⟨x, hp x hxs⟩, rfl⟩,
exact de.inj
end⟩
end
variables [separated γ]
lemma uniformly_extend_of_ind (b : β) : ψ (e b) = f b :=
dense_inducing.extend_e_eq _ b (continuous_iff_continuous_at.1 h_f.continuous b)
include h_f
lemma uniformly_extend_spec [complete_space γ] (a : α) :
tendsto f (comap e (𝓝 a)) (𝓝 (ψ a)) :=
let de := (h_e.dense_inducing h_dense) in
begin
by_cases ha : a ∈ range e,
{ rcases ha with ⟨b, rfl⟩,
rw [uniformly_extend_of_ind _ _ h_f, ← de.nhds_eq_comap],
exact h_f.continuous.tendsto _ },
{ simp only [dense_inducing.extend, dif_neg ha],
exact (@lim_spec _ _ (id _) _ $ uniformly_extend_exists h_e h_dense h_f _) }
end
lemma uniform_continuous_uniformly_extend [cγ : complete_space γ] : uniform_continuous ψ :=
assume d hd,
let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $
monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in
have h_pnt : ∀{a m}, m ∈ 𝓝 a → ∃c, c ∈ f '' preimage e m ∧ (c, ψ a) ∈ s ∧ (ψ a, c) ∈ s,
from assume a m hm,
have nb : map f (comap e (𝓝 a)) ≠ ⊥,
from map_ne_bot (h_e.dense_inducing h_dense).comap_nhds_ne_bot,
have (f '' preimage e m) ∩ ({c | (c, ψ a) ∈ s } ∩ {c | (ψ a, c) ∈ s }) ∈ map f (comap e (𝓝 a)),
from inter_mem_sets (image_mem_map $ preimage_mem_comap $ hm)
(uniformly_extend_spec h_e h_dense h_f _ (inter_mem_sets (mem_nhds_right _ hs) (mem_nhds_left _ hs))),
nonempty_of_mem_sets nb this,
have preimage (λp:β×β, (f p.1, f p.2)) s ∈ 𝓤 β,
from h_f hs,
have preimage (λp:β×β, (f p.1, f p.2)) s ∈ comap (λx:β×β, (e x.1, e x.2)) (𝓤 α),
by rwa [h_e.comap_uniformity.symm] at this,
let ⟨t, ht, ts⟩ := this in
show preimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ 𝓤 α,
from (𝓤 α).sets_of_superset (interior_mem_uniformity ht) $
assume ⟨x₁, x₂⟩ hx_t,
have 𝓝 (x₁, x₂) ≤ principal (interior t),
from is_open_iff_nhds.mp is_open_interior (x₁, x₂) hx_t,
have interior t ∈ filter.prod (𝓝 x₁) (𝓝 x₂),
by rwa [nhds_prod_eq, le_principal_iff] at this,
let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in
let ⟨a, ha₁, _, ha₂⟩ := h_pnt hm₁ in
let ⟨b, hb₁, hb₂, _⟩ := h_pnt hm₂ in
have set.prod (preimage e m₁) (preimage e m₂) ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s,
from calc _ ⊆ preimage (λp:(β×β), (e p.1, e p.2)) (interior t) : preimage_mono hm
... ⊆ preimage (λp:(β×β), (e p.1, e p.2)) t : preimage_mono interior_subset
... ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s : ts,
have set.prod (f '' preimage e m₁) (f '' preimage e m₂) ⊆ s,
from calc set.prod (f '' preimage e m₁) (f '' preimage e m₂) =
(λp:(β×β), (f p.1, f p.2)) '' (set.prod (preimage e m₁) (preimage e m₂)) : prod_image_image_eq
... ⊆ (λp:(β×β), (f p.1, f p.2)) '' preimage (λp:(β×β), (f p.1, f p.2)) s : monotone_image this
... ⊆ s : image_subset_iff.mpr $ subset.refl _,
have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩,
hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s),
from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩
end uniform_extension
|
5c07f3162976ac3a4c84d295aced9f70582c4454 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Std/Data/HashSet.lean | a23aa6af23eb77a96686f4eb69689c0124a6582b | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 6,198 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
namespace Std
universe u v w
def HashSetBucket (α : Type u) :=
{ b : Array (List α) // b.size > 0 }
def HashSetBucket.update {α : Type u} (data : HashSetBucket α) (i : USize) (d : List α) (h : i.toNat < data.val.size) : HashSetBucket α :=
⟨ data.val.uset i d h,
by erw [Array.size_set]; apply data.property ⟩
structure HashSetImp (α : Type u) where
size : Nat
buckets : HashSetBucket α
def mkHashSetImp {α : Type u} (nbuckets := 8) : HashSetImp α :=
let n := if nbuckets = 0 then 8 else nbuckets
{ size := 0,
buckets :=
⟨ mkArray n [],
by rw [Array.size_mkArray]; cases nbuckets; decide; apply Nat.zero_lt_succ ⟩ }
namespace HashSetImp
variable {α : Type u}
def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } :=
⟨u % n, USize.modn_lt _ h⟩
@[inline] def reinsertAux (hashFn : α → UInt64) (data : HashSetBucket α) (a : α) : HashSetBucket α :=
let ⟨i, h⟩ := mkIdx data.property (hashFn a |>.toUSize)
data.update i (a :: data.val.uget i h) h
@[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashSetBucket α) (d : δ) (f : δ → α → m δ) : m δ :=
data.val.foldlM (init := d) fun d as => as.foldlM f d
@[inline] def foldBuckets {δ : Type w} (data : HashSetBucket α) (d : δ) (f : δ → α → δ) : δ :=
Id.run $ foldBucketsM data d f
@[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → m δ) (d : δ) (h : HashSetImp α) : m δ :=
foldBucketsM h.buckets d f
@[inline] def fold {δ : Type w} (f : δ → α → δ) (d : δ) (m : HashSetImp α) : δ :=
foldBuckets m.buckets d f
def find? [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : Option α :=
match m with
| ⟨_, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize)
(buckets.val.uget i h).find? (fun a' => a == a')
def contains [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : Bool :=
match m with
| ⟨_, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize)
(buckets.val.uget i h).contains a
-- TODO: remove `partial` by using well-founded recursion
partial def moveEntries [Hashable α] (i : Nat) (source : Array (List α)) (target : HashSetBucket α) : HashSetBucket α :=
if h : i < source.size then
let idx : Fin source.size := ⟨i, h⟩
let es : List α := source.get idx
-- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl
let source := source.set idx []
let target := es.foldl (reinsertAux hash) target
moveEntries (i+1) source target
else target
def expand [Hashable α] (size : Nat) (buckets : HashSetBucket α) : HashSetImp α :=
let nbuckets := buckets.val.size * 2
have : nbuckets > 0 := Nat.mul_pos buckets.property (by decide)
let new_buckets : HashSetBucket α := ⟨mkArray nbuckets [], by rw [Array.size_mkArray]; assumption⟩
{ size := size,
buckets := moveEntries 0 buckets.val new_buckets }
def insert [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : HashSetImp α :=
match m with
| ⟨size, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize)
let bkt := buckets.val.uget i h
if bkt.contains a
then ⟨size, buckets.update i (bkt.replace a a) h⟩
else
let size' := size + 1
let buckets' := buckets.update i (a :: bkt) h
if size' ≤ buckets.val.size
then { size := size', buckets := buckets' }
else expand size' buckets'
def erase [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : HashSetImp α :=
match m with
| ⟨ size, buckets ⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize)
let bkt := buckets.val.uget i h
if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩
else m
inductive WellFormed [BEq α] [Hashable α] : HashSetImp α → Prop where
| mkWff : ∀ n, WellFormed (mkHashSetImp n)
| insertWff : ∀ m a, WellFormed m → WellFormed (insert m a)
| eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a)
end HashSetImp
def HashSet (α : Type u) [BEq α] [Hashable α] :=
{ m : HashSetImp α // m.WellFormed }
open HashSetImp
def mkHashSet {α : Type u} [BEq α] [Hashable α] (nbuckets := 8) : HashSet α :=
⟨ mkHashSetImp nbuckets, WellFormed.mkWff nbuckets ⟩
namespace HashSet
@[inline] def empty [BEq α] [Hashable α] : HashSet α :=
mkHashSet
instance [BEq α] [Hashable α] : Inhabited (HashSet α) where
default := mkHashSet
instance [BEq α] [Hashable α] : EmptyCollection (HashSet α) := ⟨mkHashSet⟩
variable {α : Type u} {_ : BEq α} {_ : Hashable α}
@[inline] def insert (m : HashSet α) (a : α) : HashSet α :=
match m with
| ⟨ m, hw ⟩ => ⟨ m.insert a, WellFormed.insertWff m a hw ⟩
@[inline] def erase (m : HashSet α) (a : α) : HashSet α :=
match m with
| ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩
@[inline] def find? (m : HashSet α) (a : α) : Option α :=
match m with
| ⟨ m, _ ⟩ => m.find? a
@[inline] def contains (m : HashSet α) (a : α) : Bool :=
match m with
| ⟨ m, _ ⟩ => m.contains a
@[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → m δ) (init : δ) (h : HashSet α) : m δ :=
match h with
| ⟨ h, _ ⟩ => h.foldM f init
@[inline] def fold {δ : Type w} (f : δ → α → δ) (init : δ) (m : HashSet α) : δ :=
match m with
| ⟨ m, _ ⟩ => m.fold f init
@[inline] def size (m : HashSet α) : Nat :=
match m with
| ⟨ {size := sz, ..}, _ ⟩ => sz
@[inline] def isEmpty (m : HashSet α) : Bool :=
m.size = 0
def toList (m : HashSet α) : List α :=
m.fold (init := []) fun r a => a::r
def toArray (m : HashSet α) : Array α :=
m.fold (init := #[]) fun r a => r.push a
def numBuckets (m : HashSet α) : Nat :=
m.val.buckets.val.size
end HashSet
end Std
|
20712a9025001ca1b219f5e73038240a0863d323 | c062f1c97fdef9ac746f08754e7d766fd6789aa9 | /algebra/lattice/boolean_algebra.lean | f8a7497096cb76c890df8aa3e0a3d25ef76a07fe | [] | no_license | emberian/library_dev | 00c7a985b21bdebe912f4127a363f2874e1e7555 | f3abd7db0238edc18a397540e361a1da2f51503c | refs/heads/master | 1,624,153,474,804 | 1,490,147,180,000 | 1,490,147,180,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,439 | 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
Type class hierarchy for Boolean algebras.
-/
import .bounded_lattice
universes u
variables {α : Type u} {x y z : α}
namespace lattice
class distrib_lattice α extends lattice α :=
(sup_inf : ∀x y z : α, x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z))
section distrib_lattice
variables [distrib_lattice α]
lemma sup_inf_left : ∀{x y z : α}, x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) :=
distrib_lattice.sup_inf
lemma sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) :=
by simp [sup_inf_left, λy:α, @sup_comm α _ y x]
lemma inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) :=
calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self]
... = x ⊓ ((x ⊓ y) ⊔ z) : by simp [inf_assoc, sup_inf_right]
... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self]
... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm]
... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left]
lemma inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) :=
by simp [inf_sup_left, λy:α, @inf_comm α _ y x]
end distrib_lattice
class boolean_algebra α extends distrib_lattice α, bounded_lattice α, has_neg α, has_sub α :=
(inf_neg_eq_bot : ∀x:α, x ⊓ - x = ⊥)
(sup_neg_eq_top : ∀x:α, x ⊔ - x = ⊤)
(sub_eq : ∀x y:α, x - y = x ⊓ - y)
section boolean_algebra
variables [boolean_algebra α]
@[simp]
lemma inf_neg_eq_bot : x ⊓ - x = ⊥ :=
boolean_algebra.inf_neg_eq_bot x
@[simp]
lemma neg_inf_eq_bot : - x ⊓ x = ⊥ :=
eq.trans inf_comm inf_neg_eq_bot
@[simp]
lemma sup_neg_eq_top : x ⊔ - x = ⊤ :=
boolean_algebra.sup_neg_eq_top x
@[simp]
lemma neg_sup_eq_top : - x ⊔ x = ⊤ :=
eq.trans sup_comm sup_neg_eq_top
lemma sub_eq : x - y = x ⊓ - y :=
boolean_algebra.sub_eq x y
lemma neg_unique (i : x ⊓ y = ⊥) (s : x ⊔ y = ⊤) : - x = y :=
have (- x ⊓ x) ⊔ (- x ⊓ y) = (y ⊓ x) ⊔ (y ⊓ - x),
by rsimp,
have - x ⊓ (x ⊔ y) = y ⊓ (x ⊔ - x),
begin [smt] eblast_using inf_sup_left end,
by rsimp
@[simp]
lemma neg_top : - ⊤ = (⊥:α) :=
neg_unique (by simp) (by simp)
@[simp]
lemma neg_bot : - ⊥ = (⊤:α) :=
neg_unique (by simp) (by simp)
@[simp]
lemma neg_neg : - (- x) = x :=
neg_unique (by simp) (by simp)
lemma neg_eq_neg_of_eq (h : - x = - y) : x = y :=
have - - x = - - y,
from congr_arg neg h,
by simp [neg_neg] at this; assumption
@[simp]
lemma neg_eq_neg_iff : - x = - y ↔ x = y :=
⟨neg_eq_neg_of_eq, congr_arg neg⟩
@[simp]
lemma neg_inf : - (x ⊓ y) = -x ⊔ -y :=
neg_unique -- TODO: try rsimp if it supports custom lemmas
(calc (x ⊓ y) ⊓ (- x ⊔ - y) = (y ⊓ (x ⊓ - x)) ⊔ (x ⊓ (y ⊓ - y)) : by rw [inf_sup_left]; ac_refl
... = ⊥ : by simp)
(calc (x ⊓ y) ⊔ (- x ⊔ - y) = (- y ⊔ (x ⊔ - x)) ⊓ (- x ⊔ (y ⊔ - y)) : by rw [sup_inf_right]; ac_refl
... = ⊤ : by simp)
@[simp]
lemma neg_sup : - (x ⊔ y) = -x ⊓ -y :=
begin [smt] eblast_using [neg_neg, neg_inf] end
lemma neg_le_neg (h : y ≤ x) : - x ≤ - y :=
le_of_inf_eq $
calc -x ⊓ -y = - (x ⊔ y) : neg_sup^.symm
... = -x : congr_arg neg $ sup_of_le_left h
end boolean_algebra
end lattice
|
5a7a87385da6d38309629e5346056d5d17801c41 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/measure_theory/measure/measure_space.lean | 129c137bad6d328cefca570727bd217bed2dcd1c | [
"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 | 133,020 | 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 measure_theory.measure.measure_space_def
import measure_theory.measurable_space
/-!
# Measure spaces
The definition of a measure and a measure space are in `measure_theory.measure_space_def`, with
only a few basic properties. This file provides many more properties of these objects.
This separation allows the measurability tactic to import only the file `measure_space_def`, and to
be available in `measure_space` (through `measurable_space`).
Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the
extended nonnegative reals that satisfies the following conditions:
1. `μ ∅ = 0`;
2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint
sets is equal to the measure of the individual sets.
Every measure can be canonically extended to an outer measure, so that it assigns values to
all subsets, not just the measurable subsets. On the other hand, a measure that is countably
additive on measurable sets can be restricted to measurable sets to obtain a measure.
In this file a measure is defined to be an outer measure that is countably additive on
measurable sets, with the additional assumption that the outer measure is the canonical
extension of the restricted measure.
Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ℝ≥0∞`.
We introduce the following typeclasses for measures:
* `is_probability_measure μ`: `μ univ = 1`;
* `is_finite_measure μ`: `μ univ < ∞`;
* `sigma_finite μ`: there exists a countable collection of sets that cover `univ`
where `μ` is finite;
* `is_locally_finite_measure μ` : `∀ x, ∃ s ∈ 𝓝 x, μ s < ∞`;
* `has_no_atoms μ` : `∀ x, μ {x} = 0`; possibly should be redefined as
`∀ s, 0 < μ s → ∃ t ⊆ s, 0 < μ t ∧ μ t < μ s`.
Given a measure, the null sets are the sets where `μ s = 0`, where `μ` denotes the corresponding
outer measure (so `s` might not be measurable). We can then define the completion of `μ` as the
measure on the least `σ`-algebra that also contains all null sets, by defining the measure to be `0`
on the null sets.
## Main statements
* `completion` is the completion of a measure to all null measurable sets.
* `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure.
## Implementation notes
Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`.
This conveniently allows us to apply the measure to sets without proving that they are measurable.
We get countable subadditivity for all sets, but only countable additivity for measurable sets.
You often don't want to define a measure via its constructor.
Two ways that are sometimes more convenient:
* `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets
and proving the properties (1) and (2) mentioned above.
* `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that
all measurable sets in the measurable space are Carathéodory measurable.
To prove that two measures are equal, there are multiple options:
* `ext`: two measures are equal if they are equal on all measurable sets.
* `ext_of_generate_from_of_Union`: two measures are equal if they are equal on a π-system generating
the measurable sets, if the π-system contains a spanning increasing sequence of sets where the
measures take finite value (in particular the measures are σ-finite). This is a special case of
the more general `ext_of_generate_from_of_cover`
* `ext_of_generate_finite`: two finite measures are equal if they are equal on a π-system
generating the measurable sets. This is a special case of `ext_of_generate_from_of_Union` using
`C ∪ {univ}`, but is easier to work with.
A `measure_space` is a class that is a measurable space with a canonical measure.
The measure is denoted `volume`.
## References
* <https://en.wikipedia.org/wiki/Measure_(mathematics)>
* <https://en.wikipedia.org/wiki/Complete_measure>
* <https://en.wikipedia.org/wiki/Almost_everywhere>
## Tags
measure, almost everywhere, measure space, completion, null set, null measurable set
-/
noncomputable theory
open classical set filter (hiding map) function measurable_space
open_locale classical topological_space big_operators filter ennreal nnreal
variables {α β γ δ ι : Type*}
namespace measure_theory
section
variables {m : measurable_space α} {μ μ₁ μ₂ : measure α} {s s₁ s₂ t : set α}
instance ae_is_measurably_generated : is_measurably_generated μ.ae :=
⟨λ s hs, let ⟨t, hst, htm, htμ⟩ := exists_measurable_superset_of_null hs in
⟨tᶜ, compl_mem_ae_iff.2 htμ, htm.compl, compl_subset_comm.1 hst⟩⟩
lemma measure_Union [encodable β] {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 (hd : disjoint s₁ s₂) (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) :
μ (s₁ ∪ s₂) = μ s₁ + μ s₂ :=
begin
rw [union_eq_Union, measure_Union, tsum_fintype, fintype.sum_bool, cond, cond],
exacts [pairwise_disjoint_on_bool.2 hd, λ b, bool.cases_on b h₂ h₁]
end
lemma measure_add_measure_compl (h : measurable_set s) :
μ s + μ sᶜ = μ univ :=
by { rw [← union_compl_self s, measure_union _ h h.compl], exact disjoint_compl_right }
lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s)
(hd : pairwise_on s (disjoint on f)) (h : ∀ b ∈ s, measurable_set (f b)) :
μ (⋃ b ∈ s, f b) = ∑' p : s, μ (f p) :=
begin
haveI := hs.to_encodable,
rw bUnion_eq_Union,
exact measure_Union (hd.on_injective subtype.coe_injective $ λ x, x.2) (λ x, h x x.2)
end
lemma measure_sUnion {S : set (set α)} (hs : countable S)
(hd : pairwise_on S disjoint) (h : ∀ s ∈ S, measurable_set s) :
μ (⋃₀ S) = ∑' s : S, μ s :=
by rw [sUnion_eq_bUnion, measure_bUnion hs hd h]
lemma measure_bUnion_finset {s : finset ι} {f : ι → set α} (hd : pairwise_on ↑s (disjoint on f))
(hm : ∀ b ∈ s, measurable_set (f b)) :
μ (⋃ b ∈ s, f b) = ∑ p in s, μ (f p) :=
begin
rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype],
exact measure_bUnion s.countable_to_set hd hm
end
/-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
lemma tsum_measure_preimage_singleton {s : set β} (hs : countable s) {f : α → β}
(hf : ∀ y ∈ s, measurable_set (f ⁻¹' {y})) :
∑' b : s, μ (f ⁻¹' {↑b}) = μ (f ⁻¹' s) :=
by rw [← set.bUnion_preimage_singleton, measure_bUnion hs (pairwise_on_disjoint_fiber _ _) hf]
/-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
lemma sum_measure_preimage_singleton (s : finset β) {f : α → β}
(hf : ∀ y ∈ s, measurable_set (f ⁻¹' {y})) :
∑ b in s, μ (f ⁻¹' {b}) = μ (f ⁻¹' ↑s) :=
by simp only [← measure_bUnion_finset (pairwise_on_disjoint_fiber _ _) hf,
finset.set_bUnion_preimage_singleton]
lemma measure_diff_null' (h : μ (s₁ ∩ s₂) = 0) : μ (s₁ \ s₂) = μ s₁ :=
measure_congr $ diff_ae_eq_self.2 h
lemma measure_diff_null (h : μ s₂ = 0) : μ (s₁ \ s₂) = μ s₁ :=
measure_diff_null' $ measure_mono_null (inter_subset_right _ _) h
lemma measure_diff (h : s₂ ⊆ s₁) (h₁ : measurable_set s₁) (h₂ : measurable_set s₂)
(h_fin : μ s₂ ≠ ∞) :
μ (s₁ \ s₂) = μ s₁ - μ s₂ :=
begin
refine (ennreal.add_sub_self' h_fin).symm.trans _,
rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h]
end
lemma le_measure_diff : μ s₁ - μ s₂ ≤ μ (s₁ \ s₂) :=
ennreal.sub_le_iff_le_add'.2 $
calc μ s₁ ≤ μ (s₂ ∪ s₁) : measure_mono (subset_union_right _ _)
... = μ (s₂ ∪ s₁ \ s₂) : congr_arg μ union_diff_self.symm
... ≤ μ s₂ + μ (s₁ \ s₂) : measure_union_le _ _
lemma measure_diff_lt_of_lt_add (hs : measurable_set s) (ht : measurable_set t) (hst : s ⊆ t)
(hs' : μ s ≠ ∞) {ε : ℝ≥0∞} (h : μ t < μ s + ε) : μ (t \ s) < ε :=
begin
rw [measure_diff hst ht hs hs'], rw add_comm at h,
exact ennreal.sub_lt_of_lt_add (measure_mono hst) h
end
lemma meas_eq_meas_of_null_diff {s t : set α}
(hst : s ⊆ t) (h_nulldiff : μ (t.diff s) = 0) : μ s = μ t :=
by { rw [←diff_diff_cancel_left hst, ←@measure_diff_null _ _ _ t _ h_nulldiff], refl, }
lemma meas_eq_meas_of_between_null_diff {s₁ s₂ s₃ : set α}
(h12 : s₁ ⊆ s₂) (h23 : s₂ ⊆ s₃) (h_nulldiff : μ (s₃ \ s₁) = 0) :
(μ s₁ = μ s₂) ∧ (μ s₂ = μ s₃) :=
begin
have le12 : μ s₁ ≤ μ s₂ := measure_mono h12,
have le23 : μ s₂ ≤ μ s₃ := measure_mono h23,
have key : μ s₃ ≤ μ s₁ := calc
μ s₃ = μ ((s₃ \ s₁) ∪ s₁) : by rw (diff_union_of_subset (h12.trans h23))
... ≤ μ (s₃ \ s₁) + μ s₁ : measure_union_le _ _
... = μ s₁ : by simp only [h_nulldiff, zero_add],
exact ⟨le12.antisymm (le23.trans key), le23.antisymm (key.trans le12)⟩,
end
lemma meas_eq_meas_smaller_of_between_null_diff {s₁ s₂ s₃ : set α}
(h12 : s₁ ⊆ s₂) (h23 : s₂ ⊆ s₃) (h_nulldiff : μ (s₃.diff s₁) = 0) : μ s₁ = μ s₂ :=
(meas_eq_meas_of_between_null_diff h12 h23 h_nulldiff).1
lemma meas_eq_meas_larger_of_between_null_diff {s₁ s₂ s₃ : set α}
(h12 : s₁ ⊆ s₂) (h23 : s₂ ⊆ s₃) (h_nulldiff : μ (s₃.diff s₁) = 0) : μ s₂ = μ s₃ :=
(meas_eq_meas_of_between_null_diff h12 h23 h_nulldiff).2
lemma measure_compl (h₁ : measurable_set s) (h_fin : μ s ≠ ∞) : μ (sᶜ) = μ univ - μ s :=
by { rw compl_eq_univ_diff, exact measure_diff (subset_univ s) measurable_set.univ h₁ h_fin }
lemma sum_measure_le_measure_univ {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, measurable_set (t i))
(H : pairwise_on ↑s (disjoint on t)) :
∑ i in s, μ (t i) ≤ μ (univ : set α) :=
by { rw ← measure_bUnion_finset H h, exact measure_mono (subset_univ _) }
lemma tsum_measure_le_measure_univ {s : ι → set α} (hs : ∀ i, measurable_set (s i))
(H : pairwise (disjoint on s)) :
∑' i, μ (s i) ≤ μ (univ : set α) :=
begin
rw [ennreal.tsum_eq_supr_sum],
exact supr_le (λ s, sum_measure_le_measure_univ (λ i hi, hs i) (λ i hi j hj hij, H i j hij))
end
lemma measure_Union_of_null_inter [encodable ι] {f : ι → set α} (h : ∀ i, measurable_set (f i))
(hn : pairwise ((λ S T, μ (S ∩ T) = 0) on f)) : μ (⋃ i, f i) = ∑' i, μ (f i) :=
begin
have h_null : μ (⋃ (ij : ι × ι) (hij : ij.fst ≠ ij.snd), f ij.fst ∩ f ij.snd) = 0,
{ rw measure_Union_null_iff,
rintro ⟨i, j⟩,
by_cases hij : i = j,
{ simp [hij], },
{ suffices : μ (f i ∩ f j) = 0,
{ simpa [hij], },
apply hn i j hij, }, },
have h_pair : pairwise (disjoint on
(λ i, f i \ (⋃ (ij : ι × ι) (hij : ij.fst ≠ ij.snd), f ij.fst ∩ f ij.snd))),
{ intros i j hij x hx,
simp only [not_exists, exists_prop, mem_Union, mem_inter_eq, not_and,
inf_eq_inter, ne.def, mem_diff, prod.exists] at hx,
simp only [mem_empty_eq, bot_eq_empty],
rcases hx with ⟨⟨hx_left_left, hx_left_right⟩, hx_right_left, hx_right_right⟩,
exact hx_left_right _ _ hij hx_left_left hx_right_left, },
have h_meas :
∀ i, measurable_set (f i \ (⋃ (ij : ι × ι) (hij : ij.fst ≠ ij.snd), f ij.fst ∩ f ij.snd)),
{ intro w,
apply (h w).diff,
apply measurable_set.Union,
rintro ⟨i, j⟩,
by_cases hij : i = j,
{ simp [hij], },
{ simp [hij, measurable_set.inter (h i) (h j)], }, },
have : μ _ = _ := measure_Union h_pair h_meas,
rw ← Union_diff at this,
simp_rw measure_diff_null h_null at this,
exact this,
end
/-- Pigeonhole principle for measure spaces: if `∑' i, μ (s i) > μ univ`, then
one of the intersections `s i ∩ s j` is not empty. -/
lemma exists_nonempty_inter_of_measure_univ_lt_tsum_measure {m : measurable_space α} (μ : measure α)
{s : ι → set α} (hs : ∀ i, measurable_set (s i)) (H : μ (univ : set α) < ∑' i, μ (s i)) :
∃ i j (h : i ≠ j), (s i ∩ s j).nonempty :=
begin
contrapose! H,
apply tsum_measure_le_measure_univ hs,
exact λ i j hij x hx, H i j hij ⟨x, hx⟩
end
/-- Pigeonhole principle for measure spaces: if `s` is a `finset` and
`∑ i in s, μ (t i) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/
lemma exists_nonempty_inter_of_measure_univ_lt_sum_measure {m : measurable_space α} (μ : measure α)
{s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, measurable_set (t i))
(H : μ (univ : set α) < ∑ i in s, μ (t i)) :
∃ (i ∈ s) (j ∈ s) (h : i ≠ j), (t i ∩ t j).nonempty :=
begin
contrapose! H,
apply sum_measure_le_measure_univ h,
exact λ i hi j hj hij x hx, H i hi j hj hij ⟨x, hx⟩
end
/-- Continuity from below: the measure of the union of a directed sequence of measurable sets
is the supremum of the measures. -/
lemma measure_Union_eq_supr [encodable ι] {s : ι → set α} (h : ∀ i, measurable_set (s i))
(hd : directed (⊆) s) : μ (⋃ i, s i) = ⨆ i, μ (s i) :=
begin
casesI is_empty_or_nonempty ι,
{ simp only [supr_of_empty, Union], exact measure_empty },
refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _),
have : ∀ n, measurable_set (disjointed (λ n, ⋃ b ∈ encodable.decode₂ ι n, s b) n) :=
measurable_set.disjointed (measurable_set.bUnion_decode₂ h),
rw [← encodable.Union_decode₂, ← Union_disjointed, measure_Union (disjoint_disjointed _) this,
ennreal.tsum_eq_supr_nat],
simp only [← measure_bUnion_finset ((disjoint_disjointed _).pairwise_on _) (λ n _, this n)],
refine supr_le (λ n, _),
refine le_trans (_ : _ ≤ μ (⋃ (k ∈ finset.range n) (i ∈ encodable.decode₂ ι k), s i)) _,
exact measure_mono (bUnion_subset_bUnion_right (λ k hk, disjointed_subset _ _)),
simp only [← finset.set_bUnion_option_to_finset, ← finset.set_bUnion_bUnion],
generalize : (finset.range n).bUnion (λ k, (encodable.decode₂ ι k).to_finset) = t,
rcases hd.finset_le t with ⟨i, hi⟩,
exact le_supr_of_le i (measure_mono $ bUnion_subset hi)
end
lemma measure_bUnion_eq_supr {s : ι → set α} {t : set ι} (ht : countable t)
(h : ∀ i ∈ t, measurable_set (s i)) (hd : directed_on ((⊆) on s) t) :
μ (⋃ i ∈ t, s i) = ⨆ i ∈ t, μ (s i) :=
begin
haveI := ht.to_encodable,
rw [bUnion_eq_Union, measure_Union_eq_supr (set_coe.forall'.1 h) hd.directed_coe,
supr_subtype'],
refl
end
/-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable
sets is the infimum of the measures. -/
lemma measure_Inter_eq_infi [encodable ι] {s : ι → set α}
(h : ∀ i, measurable_set (s i)) (hd : directed (⊇) s) (hfin : ∃ i, μ (s i) ≠ ∞) :
μ (⋂ i, s i) = (⨅ i, μ (s i)) :=
begin
rcases hfin with ⟨k, hk⟩,
have : ∀ t ⊆ s k, μ t ≠ ∞, from λ t ht, ne_top_of_le_ne_top hk (measure_mono ht),
rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k), ennreal.sub_infi,
← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)),
← measure_diff (Inter_subset _ k) (h k) (measurable_set.Inter h) (this _ (Inter_subset _ k)),
diff_Inter, measure_Union_eq_supr],
{ congr' 1,
refine le_antisymm (supr_le_supr2 $ λ i, _) (supr_le_supr $ λ i, _),
{ rcases hd i k with ⟨j, hji, hjk⟩,
use j,
rw [← measure_diff hjk (h _) (h _) (this _ hjk)],
exact measure_mono (diff_subset_diff_right hji) },
{ rw [ennreal.sub_le_iff_le_add, ← measure_union disjoint_diff.symm ((h k).diff (h i)) (h i),
set.union_comm],
exact measure_mono (diff_subset_iff.1 $ subset.refl _) } },
{ exact λ i, (h k).diff (h i) },
{ exact hd.mono_comp _ (λ _ _, diff_subset_diff_right) }
end
lemma measure_eq_inter_diff (hs : measurable_set s) (ht : measurable_set t) :
μ s = μ (s ∩ t) + μ (s \ t) :=
have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs ,
by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t]
lemma measure_union_add_inter (hs : measurable_set s) (ht : measurable_set t) :
μ (s ∪ t) + μ (s ∩ t) = μ s + μ t :=
by { rw [measure_eq_inter_diff (hs.union ht) ht, set.union_inter_cancel_right,
union_diff_right, measure_eq_inter_diff hs ht], ac_refl }
/-- Continuity from below: the measure of the union of an increasing sequence of measurable sets
is the limit of the measures. -/
lemma tendsto_measure_Union [semilattice_sup ι] [encodable ι] {s : ι → set α}
(hs : ∀ n, measurable_set (s n)) (hm : monotone s) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋃ n, s n))) :=
begin
rw measure_Union_eq_supr hs (directed_of_sup hm),
exact tendsto_at_top_supr (assume n m hnm, measure_mono $ hm hnm)
end
/-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable
sets is the limit of the measures. -/
lemma tendsto_measure_Inter [encodable ι] [semilattice_sup ι] {s : ι → set α}
(hs : ∀ n, measurable_set (s n)) (hm : antitone s) (hf : ∃ i, μ (s i) ≠ ∞) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋂ n, s n))) :=
begin
rw measure_Inter_eq_infi hs (directed_of_sup hm) hf,
exact tendsto_at_top_infi (assume n m hnm, measure_mono $ hm hnm),
end
/-- One direction of the **Borel-Cantelli lemma**: if (sᵢ) is a sequence of measurable sets such
that ∑ μ sᵢ exists, then the limit superior of the sᵢ is a null set. -/
lemma measure_limsup_eq_zero {s : ℕ → set α} (hs : ∀ i, measurable_set (s i))
(hs' : ∑' i, μ (s i) ≠ ∞) : μ (limsup at_top s) = 0 :=
begin
simp only [limsup_eq_infi_supr_of_nat', set.infi_eq_Inter, set.supr_eq_Union],
-- We will show that both `μ (⨅ n, ⨆ i, s (i + n))` and `0` are the limit of `μ (⊔ i, s (i + n))`
-- as `n` tends to infinity. For the former, we use continuity from above.
refine tendsto_nhds_unique
(tendsto_measure_Inter (λ i, measurable_set.Union (λ b, hs (b + i))) _
⟨0, ne_top_of_le_ne_top hs' (measure_Union_le s)⟩) _,
{ intros n m hnm x,
simp only [set.mem_Union],
exact λ ⟨i, hi⟩, ⟨i + (m - n), by simpa only [add_assoc, nat.sub_add_cancel hnm] using hi⟩ },
{ -- For the latter, notice that, `μ (⨆ i, s (i + n)) ≤ ∑' s (i + n)`. Since the right hand side
-- converges to `0` by hypothesis, so does the former and the proof is complete.
exact (tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds
(ennreal.tendsto_sum_nat_add (μ ∘ s) hs')
(eventually_of_forall (by simp only [forall_const, zero_le]))
(eventually_of_forall (λ i, measure_Union_le _))) }
end
lemma measure_if {x : β} {t : set β} {s : set α} :
μ (if x ∈ t then s else ∅) = indicator t (λ _, μ s) x :=
by { split_ifs; simp [h] }
end
section outer_measure
variables [ms : measurable_space α] {s t : set α}
include ms
/-- Obtain a measure by giving an outer measure where all sets in the σ-algebra are
Carathéodory measurable. -/
def outer_measure.to_measure (m : outer_measure α) (h : ms ≤ m.caratheodory) : measure α :=
measure.of_measurable (λ s _, m s) m.empty
(λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd)
lemma le_to_outer_measure_caratheodory (μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory :=
begin
assume s hs,
rw to_outer_measure_eq_induced_outer_measure,
refine outer_measure.of_function_caratheodory (λ t, le_infi $ λ ht, _),
rw [← measure_eq_extend (ht.inter hs),
← measure_eq_extend (ht.diff hs),
← measure_union _ (ht.inter hs) (ht.diff hs),
inter_union_diff],
exact le_refl _,
exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁
end
@[simp] lemma to_measure_to_outer_measure (m : outer_measure α) (h : ms ≤ m.caratheodory) :
(m.to_measure h).to_outer_measure = m.trim := rfl
@[simp] lemma to_measure_apply (m : outer_measure α) (h : ms ≤ m.caratheodory)
{s : set α} (hs : measurable_set s) : m.to_measure h s = m s :=
m.trim_eq hs
lemma le_to_measure_apply (m : outer_measure α) (h : ms ≤ m.caratheodory) (s : set α) :
m s ≤ m.to_measure h s :=
m.le_trim s
@[simp] lemma to_outer_measure_to_measure {μ : measure α} :
μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ :=
measure.ext $ λ s, μ.to_outer_measure.trim_eq
@[simp] lemma bounded_by_measure (μ : measure α) :
outer_measure.bounded_by μ = μ.to_outer_measure :=
μ.to_outer_measure.bounded_by_eq_self
end outer_measure
variables {m0 : measurable_space α} [measurable_space β] [measurable_space γ]
variables {μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : measure α} {s s' t : set α}
namespace measure
protected lemma caratheodory {m : measurable_space α} (μ : measure α) (hs : measurable_set s) :
μ (t ∩ s) + μ (t \ s) = μ t :=
(le_to_outer_measure_caratheodory μ s hs t).symm
/-! ### The `ℝ≥0∞`-module of measures -/
instance [measurable_space α] : has_zero (measure α) :=
⟨{ to_outer_measure := 0,
m_Union := λ f hf hd, tsum_zero.symm,
trimmed := outer_measure.trim_zero }⟩
@[simp] theorem zero_to_outer_measure {m : measurable_space α} :
(0 : measure α).to_outer_measure = 0 := rfl
@[simp, norm_cast] theorem coe_zero {m : measurable_space α} : ⇑(0 : measure α) = 0 := rfl
lemma eq_zero_of_is_empty [is_empty α] {m : measurable_space α} (μ : measure α) : μ = 0 :=
ext $ λ s hs, by simp only [eq_empty_of_is_empty s, measure_empty]
instance [measurable_space α] : inhabited (measure α) := ⟨0⟩
instance [measurable_space α] : has_add (measure α) :=
⟨λ μ₁ μ₂, {
to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure,
m_Union := λ s hs hd,
show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑' i, (μ₁ (s i) + μ₂ (s i)),
by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs],
trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩
@[simp] theorem add_to_outer_measure {m : measurable_space α} (μ₁ μ₂ : measure α) :
(μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl
@[simp, norm_cast] theorem coe_add {m : measurable_space α} (μ₁ μ₂ : measure α) :
⇑(μ₁ + μ₂) = μ₁ + μ₂ := rfl
theorem add_apply {m : measurable_space α} (μ₁ μ₂ : measure α) (s : set α) :
(μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl
instance add_comm_monoid [measurable_space α] : add_comm_monoid (measure α) :=
to_outer_measure_injective.add_comm_monoid to_outer_measure zero_to_outer_measure
add_to_outer_measure
instance [measurable_space α] : has_scalar ℝ≥0∞ (measure α) :=
⟨λ c μ,
{ to_outer_measure := c • μ.to_outer_measure,
m_Union := λ s hs hd, by simp [measure_Union, *, ennreal.tsum_mul_left],
trimmed := by rw [outer_measure.trim_smul, μ.trimmed] }⟩
@[simp] theorem smul_to_outer_measure {m : measurable_space α} (c : ℝ≥0∞) (μ : measure α) :
(c • μ).to_outer_measure = c • μ.to_outer_measure :=
rfl
@[simp, norm_cast] theorem coe_smul {m : measurable_space α} (c : ℝ≥0∞) (μ : measure α) :
⇑(c • μ) = c • μ :=
rfl
theorem smul_apply {m : measurable_space α} (c : ℝ≥0∞) (μ : measure α) (s : set α) :
(c • μ) s = c * μ s :=
rfl
instance [measurable_space α] : module ℝ≥0∞ (measure α) :=
injective.module ℝ≥0∞ ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩
to_outer_measure_injective smul_to_outer_measure
@[simp, norm_cast] theorem coe_nnreal_smul {m : measurable_space α} (c : ℝ≥0) (μ : measure α) :
⇑(c • μ) = c • μ :=
rfl
/-! ### The complete lattice of measures -/
/-- Measures are partially ordered.
The definition of less equal here is equivalent to the definition without the
measurable set condition, and this is shown by `measure.le_iff'`. It is defined
this way since, to prove `μ ≤ ν`, we may simply `intros s hs` instead of rewriting followed
by `intros s hs`. -/
instance [measurable_space α] : partial_order (measure α) :=
{ le := λ m₁ m₂, ∀ s, measurable_set s → m₁ s ≤ m₂ s,
le_refl := assume m s hs, le_refl _,
le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs),
le_antisymm := assume m₁ m₂ h₁ h₂, ext $
assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) }
theorem le_iff : μ₁ ≤ μ₂ ↔ ∀ s, measurable_set s → μ₁ s ≤ μ₂ s := iff.rfl
theorem to_outer_measure_le : μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ :=
by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl
theorem le_iff' : μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s :=
to_outer_measure_le.symm
theorem lt_iff : μ < ν ↔ μ ≤ ν ∧ ∃ s, measurable_set s ∧ μ s < ν s :=
lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff, not_forall, not_le, exists_prop]
theorem lt_iff' : μ < ν ↔ μ ≤ ν ∧ ∃ s, μ s < ν s :=
lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff', not_forall, not_le]
instance covariant_add_le [measurable_space α] : covariant_class (measure α) (measure α) (+) (≤) :=
⟨λ ν μ₁ μ₂ hμ s hs, add_le_add_left (hμ s hs) _⟩
protected lemma le_add_left (h : μ ≤ ν) : μ ≤ ν' + ν :=
λ s hs, le_add_left (h s hs)
protected lemma le_add_right (h : μ ≤ ν) : μ ≤ ν + ν' :=
λ s hs, le_add_right (h s hs)
section Inf
variables {m : set (measure α)}
lemma Inf_caratheodory (s : set α) (hs : measurable_set s) :
(Inf (to_outer_measure '' m)).caratheodory.measurable_set' s :=
begin
rw [outer_measure.Inf_eq_bounded_by_Inf_gen],
refine outer_measure.bounded_by_caratheodory (λ t, _),
simp only [outer_measure.Inf_gen, le_infi_iff, ball_image_iff, coe_to_outer_measure,
measure_eq_infi t],
intros μ hμ u htu hu,
have hm : ∀ {s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t,
{ intros s t hst,
rw [outer_measure.Inf_gen_def],
refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _),
rw [to_outer_measure_apply],
refine measure_mono hst },
rw [measure_eq_inter_diff hu hs],
refine add_le_add (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu)
end
instance [measurable_space α] : has_Inf (measure α) :=
⟨λ m, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩
lemma Inf_apply (hs : measurable_set s) : Inf m s = Inf (to_outer_measure '' m) s :=
to_measure_apply _ _ hs
private lemma measure_Inf_le (h : μ ∈ m) : Inf m ≤ μ :=
have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h),
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
private lemma measure_le_Inf (h : ∀ μ' ∈ m, μ ≤ μ') : μ ≤ Inf m :=
have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) :=
le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ,
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
instance [measurable_space α] : complete_semilattice_Inf (measure α) :=
{ Inf_le := λ s a, measure_Inf_le,
le_Inf := λ s a, measure_le_Inf,
..(by apply_instance : partial_order (measure α)),
..(by apply_instance : has_Inf (measure α)), }
instance [measurable_space α] : complete_lattice (measure α) :=
{ bot := 0,
bot_le := assume a s hs, by exact bot_le,
/- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now
top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top),
le_top := assume a s hs,
by cases s.eq_empty_or_nonempty with h h;
simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply],
-/
.. complete_lattice_of_complete_semilattice_Inf (measure α) }
end Inf
protected lemma zero_le {m0 : measurable_space α} (μ : measure α) : 0 ≤ μ := bot_le
lemma nonpos_iff_eq_zero' : μ ≤ 0 ↔ μ = 0 :=
μ.zero_le.le_iff_eq
@[simp] lemma measure_univ_eq_zero : μ univ = 0 ↔ μ = 0 :=
⟨λ h, bot_unique $ λ s hs, trans_rel_left (≤) (measure_mono (subset_univ s)) h, λ h, h.symm ▸ rfl⟩
/-! ### Pushforward and pullback -/
/-- Lift a linear map between `outer_measure` spaces such that for each measure `μ` every measurable
set is caratheodory-measurable w.r.t. `f μ` to a linear map between `measure` spaces. -/
def lift_linear {m0 : measurable_space α} (f : outer_measure α →ₗ[ℝ≥0∞] outer_measure β)
(hf : ∀ μ : measure α, ‹_› ≤ (f μ.to_outer_measure).caratheodory) :
measure α →ₗ[ℝ≥0∞] measure β :=
{ to_fun := λ μ, (f μ.to_outer_measure).to_measure (hf μ),
map_add' := λ μ₁ μ₂, ext $ λ s hs, by simp [hs],
map_smul' := λ c μ, ext $ λ s hs, by simp [hs] }
@[simp] lemma lift_linear_apply {f : outer_measure α →ₗ[ℝ≥0∞] outer_measure β} (hf)
{s : set β} (hs : measurable_set s) : lift_linear f hf μ s = f μ.to_outer_measure s :=
to_measure_apply _ _ hs
lemma le_lift_linear_apply {f : outer_measure α →ₗ[ℝ≥0∞] outer_measure β} (hf) (s : set β) :
f μ.to_outer_measure s ≤ lift_linear f hf μ s :=
le_to_measure_apply _ _ s
/-- The pushforward of a measure. It is defined to be `0` if `f` is not a measurable function. -/
def map [measurable_space α] (f : α → β) : measure α →ₗ[ℝ≥0∞] measure β :=
if hf : measurable f then
lift_linear (outer_measure.map f) $ λ μ s hs t,
le_to_outer_measure_caratheodory μ _ (hf hs) (f ⁻¹' t)
else 0
/-- We can evaluate the pushforward on measurable sets. For non-measurable sets, see
`measure_theory.measure.le_map_apply` and `measurable_equiv.map_apply`. -/
@[simp] theorem map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) :
map f μ s = μ (f ⁻¹' s) :=
by simp [map, dif_pos hf, hs]
lemma map_to_outer_measure {f : α → β} (hf : measurable f) :
(map f μ).to_outer_measure = (outer_measure.map f μ.to_outer_measure).trim :=
begin
rw [← trimmed, outer_measure.trim_eq_trim_iff],
intros s hs,
rw [coe_to_outer_measure, map_apply hf hs, outer_measure.map_apply, coe_to_outer_measure]
end
theorem map_of_not_measurable {f : α → β} (hf : ¬measurable f) :
map f μ = 0 :=
by rw [map, dif_neg hf, linear_map.zero_apply]
@[simp] lemma map_id : map id μ = μ :=
ext $ λ s, map_apply measurable_id
lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) :
map g (map f μ) = map (g ∘ f) μ :=
ext $ λ s hs,
by simp [hf, hg, hs, hg hs, hg.comp hf, ← preimage_comp]
@[mono] lemma map_mono (f : α → β) (h : μ ≤ ν) : map f μ ≤ map f ν :=
if hf : measurable f then λ s hs, by simp only [map_apply hf hs, h _ (hf hs)]
else by simp only [map_of_not_measurable hf, le_rfl]
/-- Even if `s` is not measurable, we can bound `map f μ s` from below.
See also `measurable_equiv.map_apply`. -/
theorem le_map_apply {f : α → β} (hf : measurable f) (s : set β) : μ (f ⁻¹' s) ≤ map f μ s :=
begin
rw [measure_eq_infi' (map f μ)], refine le_infi _, rintro ⟨t, hst, ht⟩,
convert measure_mono (preimage_mono hst),
exact map_apply hf ht
end
/-- Even if `s` is not measurable, `map f μ s = 0` implies that `μ (f ⁻¹' s) = 0`. -/
lemma preimage_null_of_map_null {f : α → β} (hf : measurable f) {s : set β}
(hs : map f μ s = 0) : μ (f ⁻¹' s) = 0 :=
nonpos_iff_eq_zero.mp $ (le_map_apply hf s).trans_eq hs
lemma tendsto_ae_map {f : α → β} (hf : measurable f) : tendsto f μ.ae (map f μ).ae :=
λ s hs, preimage_null_of_map_null hf hs
/-- Pullback of a `measure`. If `f` sends each `measurable` set to a `measurable` set, then for each
measurable set `s` we have `comap f μ s = μ (f '' s)`. -/
def comap [measurable_space α] (f : α → β) : measure β →ₗ[ℝ≥0∞] measure α :=
if hf : injective f ∧ ∀ s, measurable_set s → measurable_set (f '' s) then
lift_linear (outer_measure.comap f) $ λ μ s hs t,
begin
simp only [coe_to_outer_measure, outer_measure.comap_apply, ← image_inter hf.1,
image_diff hf.1],
apply le_to_outer_measure_caratheodory,
exact hf.2 s hs
end
else 0
lemma comap_apply {β} [measurable_space α] {mβ : measurable_space β} (f : α → β) (hfi : injective f)
(hf : ∀ s, measurable_set s → measurable_set (f '' s)) (μ : measure β) (hs : measurable_set s) :
comap f μ s = μ (f '' s) :=
begin
rw [comap, dif_pos, lift_linear_apply _ hs, outer_measure.comap_apply, coe_to_outer_measure],
exact ⟨hfi, hf⟩
end
/-! ### Restricting a measure -/
/-- Restrict a measure `μ` to a set `s` as an `ℝ≥0∞`-linear map. -/
def restrictₗ {m0 : measurable_space α} (s : set α) : measure α →ₗ[ℝ≥0∞] measure α :=
lift_linear (outer_measure.restrict s) $ λ μ s' hs' t,
begin
suffices : μ (s ∩ t) = μ (s ∩ t ∩ s') + μ (s ∩ t \ s'),
{ simpa [← set.inter_assoc, set.inter_comm _ s, ← inter_diff_assoc] },
exact le_to_outer_measure_caratheodory _ _ hs' _,
end
/-- Restrict a measure `μ` to a set `s`. -/
def restrict {m0 : measurable_space α} (μ : measure α) (s : set α) : measure α := restrictₗ s μ
@[simp] lemma restrictₗ_apply {m0 : measurable_space α} (s : set α) (μ : measure α) :
restrictₗ s μ = μ.restrict s :=
rfl
/-- If `t` is a measurable set, then the measure of `t` with respect to the restriction of
the measure to `s` equals the outer measure of `t ∩ s`. An alternate version requiring that `s`
be measurable instead of `t` exists as `measure.restrict_apply'`. -/
@[simp] lemma restrict_apply (ht : measurable_set t) : μ.restrict s t = μ (t ∩ s) :=
by simp [← restrictₗ_apply, restrictₗ, ht]
lemma restrict_eq_self (h_meas_t : measurable_set t) (h : t ⊆ s) : μ.restrict s t = μ t :=
by rw [restrict_apply h_meas_t, inter_eq_left_iff_subset.mpr h]
lemma restrict_apply_self {m0 : measurable_space α} (μ : measure α) (h_meas_s : measurable_set s) :
(μ.restrict s) s = μ s := (restrict_eq_self h_meas_s (set.subset.refl _))
lemma restrict_apply_univ (s : set α) : μ.restrict s univ = μ s :=
by rw [restrict_apply measurable_set.univ, set.univ_inter]
lemma le_restrict_apply (s t : set α) :
μ (t ∩ s) ≤ μ.restrict s t :=
by { rw [restrict, restrictₗ], convert le_lift_linear_apply _ t, simp }
@[simp] lemma restrict_add {m0 : measurable_space α} (μ ν : measure α) (s : set α) :
(μ + ν).restrict s = μ.restrict s + ν.restrict s :=
(restrictₗ s).map_add μ ν
@[simp] lemma restrict_zero {m0 : measurable_space α} (s : set α) :
(0 : measure α).restrict s = 0 :=
(restrictₗ s).map_zero
@[simp] lemma restrict_smul {m0 : measurable_space α} (c : ℝ≥0∞) (μ : measure α) (s : set α) :
(c • μ).restrict s = c • μ.restrict s :=
(restrictₗ s).map_smul c μ
@[simp] lemma restrict_restrict (hs : measurable_set s) :
(μ.restrict t).restrict s = μ.restrict (s ∩ t) :=
ext $ λ u hu, by simp [*, set.inter_assoc]
lemma restrict_comm (hs : measurable_set s) (ht : measurable_set t) :
(μ.restrict t).restrict s = (μ.restrict s).restrict t :=
by rw [restrict_restrict hs, restrict_restrict ht, inter_comm]
lemma restrict_apply_eq_zero (ht : measurable_set t) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 :=
by rw [restrict_apply ht]
lemma measure_inter_eq_zero_of_restrict (h : μ.restrict s t = 0) : μ (t ∩ s) = 0 :=
nonpos_iff_eq_zero.1 (h ▸ le_restrict_apply _ _)
lemma restrict_apply_eq_zero' (hs : measurable_set s) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 :=
begin
refine ⟨measure_inter_eq_zero_of_restrict, λ h, _⟩,
rcases exists_measurable_superset_of_null h with ⟨t', htt', ht', ht'0⟩,
apply measure_mono_null ((inter_subset _ _ _).1 htt'),
rw [restrict_apply (hs.compl.union ht'), union_inter_distrib_right, compl_inter_self,
set.empty_union],
exact measure_mono_null (inter_subset_left _ _) ht'0
end
@[simp] lemma restrict_eq_zero : μ.restrict s = 0 ↔ μ s = 0 :=
by rw [← measure_univ_eq_zero, restrict_apply_univ]
lemma restrict_zero_set {s : set α} (h : μ s = 0) :
μ.restrict s = 0 :=
by simp only [measure.restrict_eq_zero, h]
@[simp] lemma restrict_empty : μ.restrict ∅ = 0 := ext $ λ s hs, by simp [hs]
@[simp] lemma restrict_univ : μ.restrict univ = μ := ext $ λ s hs, by simp [hs]
lemma restrict_eq_self_of_measurable_subset (ht : measurable_set t) (t_subset : t ⊆ s) :
μ.restrict s t = μ t :=
by rw [measure.restrict_apply ht, set.inter_eq_self_of_subset_left t_subset]
lemma restrict_union_apply (h : disjoint (t ∩ s) (t ∩ s')) (hs : measurable_set s)
(hs' : measurable_set s') (ht : measurable_set t) :
μ.restrict (s ∪ s') t = μ.restrict s t + μ.restrict s' t :=
begin
simp only [restrict_apply, ht, set.inter_union_distrib_left],
exact measure_union h (ht.inter hs) (ht.inter hs'),
end
lemma restrict_union (h : disjoint s t) (hs : measurable_set s) (ht : measurable_set t) :
μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t :=
ext $ λ t' ht', restrict_union_apply (h.mono inf_le_right inf_le_right) hs ht ht'
lemma restrict_union_add_inter (hs : measurable_set s) (ht : measurable_set t) :
μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t :=
begin
ext1 u hu,
simp only [add_apply, restrict_apply hu, inter_union_distrib_left],
convert measure_union_add_inter (hu.inter hs) (hu.inter ht) using 3,
rw [set.inter_left_comm (u ∩ s), set.inter_assoc, ← set.inter_assoc u u, set.inter_self]
end
@[simp] lemma restrict_add_restrict_compl (hs : measurable_set s) :
μ.restrict s + μ.restrict sᶜ = μ :=
by rw [← restrict_union (@disjoint_compl_right (set α) _ _) hs hs.compl,
union_compl_self, restrict_univ]
@[simp] lemma restrict_compl_add_restrict (hs : measurable_set s) :
μ.restrict sᶜ + μ.restrict s = μ :=
by rw [add_comm, restrict_add_restrict_compl hs]
lemma restrict_union_le (s s' : set α) : μ.restrict (s ∪ s') ≤ μ.restrict s + μ.restrict s' :=
begin
intros t ht,
suffices : μ (t ∩ s ∪ t ∩ s') ≤ μ (t ∩ s) + μ (t ∩ s'),
by simpa [ht, inter_union_distrib_left],
apply measure_union_le
end
lemma restrict_Union_apply [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ i, measurable_set (s i)) {t : set α} (ht : measurable_set t) :
μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t :=
begin
simp only [restrict_apply, ht, inter_Union],
exact measure_Union (λ i j hij, (hd i j hij).mono inf_le_right inf_le_right)
(λ i, ht.inter (hm i))
end
lemma restrict_Union_apply_eq_supr [encodable ι] {s : ι → set α}
(hm : ∀ i, measurable_set (s i)) (hd : directed (⊆) s) {t : set α} (ht : measurable_set t) :
μ.restrict (⋃ i, s i) t = ⨆ i, μ.restrict (s i) t :=
begin
simp only [restrict_apply ht, inter_Union],
rw [measure_Union_eq_supr],
exacts [λ i, ht.inter (hm i), hd.mono_comp _ (λ s₁ s₂, inter_subset_inter_right _)]
end
lemma restrict_map {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) :
(map f μ).restrict s = map f (μ.restrict $ f ⁻¹' s) :=
ext $ λ t ht, by simp [*, hf ht]
lemma map_comap_subtype_coe {m0 : measurable_space α} (hs : measurable_set s) :
(map (coe : s → α)).comp (comap coe) = restrictₗ s :=
linear_map.ext $ λ μ, ext $ λ t ht,
by rw [restrictₗ_apply, restrict_apply ht, linear_map.comp_apply,
map_apply measurable_subtype_coe ht,
comap_apply (coe : s → α) subtype.val_injective (λ _, hs.subtype_image) _
(measurable_subtype_coe ht), subtype.image_preimage_coe]
/-- Restriction of a measure to a subset is monotone both in set and in measure. -/
lemma restrict_mono' {m0 : measurable_space α} ⦃s s' : set α⦄ ⦃μ ν : measure α⦄
(hs : s ≤ᵐ[μ] s') (hμν : μ ≤ ν) :
μ.restrict s ≤ ν.restrict s' :=
assume t ht,
calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht
... ≤ μ (t ∩ s') : measure_mono_ae $ hs.mono $ λ x hx ⟨hxt, hxs⟩, ⟨hxt, hx hxs⟩
... ≤ ν (t ∩ s') : le_iff'.1 hμν (t ∩ s')
... = ν.restrict s' t : (restrict_apply ht).symm
/-- Restriction of a measure to a subset is monotone both in set and in measure. -/
@[mono] lemma restrict_mono {m0 : measurable_space α} ⦃s s' : set α⦄ (hs : s ⊆ s') ⦃μ ν : measure α⦄
(hμν : μ ≤ ν) :
μ.restrict s ≤ ν.restrict s' :=
restrict_mono' (ae_of_all _ hs) hμν
lemma restrict_le_self : μ.restrict s ≤ μ :=
assume t ht,
calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht
... ≤ μ t : measure_mono $ inter_subset_left t s
lemma restrict_congr_meas (hs : measurable_set s) :
μ.restrict s = ν.restrict s ↔ ∀ t ⊆ s, measurable_set t → μ t = ν t :=
⟨λ H t hts ht,
by rw [← inter_eq_self_of_subset_left hts, ← restrict_apply ht, H, restrict_apply ht],
λ H, ext $ λ t ht,
by rw [restrict_apply ht, restrict_apply ht, H _ (inter_subset_right _ _) (ht.inter hs)]⟩
lemma restrict_congr_mono (hs : s ⊆ t) (hm : measurable_set s) (h : μ.restrict t = ν.restrict t) :
μ.restrict s = ν.restrict s :=
by rw [← inter_eq_self_of_subset_left hs, ← restrict_restrict hm, h, restrict_restrict hm]
/-- If two measures agree on all measurable subsets of `s` and `t`, then they agree on all
measurable subsets of `s ∪ t`. -/
lemma restrict_union_congr (hsm : measurable_set s) (htm : measurable_set t) :
μ.restrict (s ∪ t) = ν.restrict (s ∪ t) ↔
μ.restrict s = ν.restrict s ∧ μ.restrict t = ν.restrict t :=
begin
refine ⟨λ h, ⟨restrict_congr_mono (subset_union_left _ _) hsm h,
restrict_congr_mono (subset_union_right _ _) htm h⟩, _⟩,
simp only [restrict_congr_meas, hsm, htm, hsm.union htm],
rintros ⟨hs, ht⟩ u hu hum,
rw [measure_eq_inter_diff hum hsm, measure_eq_inter_diff hum hsm,
hs _ (inter_subset_right _ _) (hum.inter hsm),
ht _ (diff_subset_iff.2 hu) (hum.diff hsm)]
end
lemma restrict_finset_bUnion_congr {s : finset ι} {t : ι → set α}
(htm : ∀ i ∈ s, measurable_set (t i)) :
μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔
∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) :=
begin
induction s using finset.induction_on with i s hi hs, { simp },
simp only [finset.mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at htm ⊢,
simp only [finset.set_bUnion_insert, ← hs htm.2],
exact restrict_union_congr htm.1 (s.measurable_set_bUnion htm.2)
end
lemma restrict_Union_congr [encodable ι] {s : ι → set α} (hm : ∀ i, measurable_set (s i)) :
μ.restrict (⋃ i, s i) = ν.restrict (⋃ i, s i) ↔
∀ i, μ.restrict (s i) = ν.restrict (s i) :=
begin
refine ⟨λ h i, restrict_congr_mono (subset_Union _ _) (hm i) h, λ h, _⟩,
ext1 t ht,
have M : ∀ t : finset ι, measurable_set (⋃ i ∈ t, s i) :=
λ t, t.measurable_set_bUnion (λ i _, hm i),
have D : directed (⊆) (λ t : finset ι, ⋃ i ∈ t, s i) :=
directed_of_sup (λ t₁ t₂ ht, bUnion_subset_bUnion_left ht),
rw [Union_eq_Union_finset],
simp only [restrict_Union_apply_eq_supr M D ht,
(restrict_finset_bUnion_congr (λ i hi, hm i)).2 (λ i hi, h i)],
end
lemma restrict_bUnion_congr {s : set ι} {t : ι → set α} (hc : countable s)
(htm : ∀ i ∈ s, measurable_set (t i)) :
μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔
∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) :=
begin
simp only [bUnion_eq_Union, set_coe.forall'] at htm ⊢,
haveI := hc.to_encodable,
exact restrict_Union_congr htm
end
lemma restrict_sUnion_congr {S : set (set α)} (hc : countable S) (hm : ∀ s ∈ S, measurable_set s) :
μ.restrict (⋃₀ S) = ν.restrict (⋃₀ S) ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s :=
by rw [sUnion_eq_bUnion, restrict_bUnion_congr hc hm]
/-- This lemma shows that `restrict` and `to_outer_measure` commute. Note that the LHS has a
restrict on measures and the RHS has a restrict on outer measures. -/
lemma restrict_to_outer_measure_eq_to_outer_measure_restrict (h : measurable_set s) :
(μ.restrict s).to_outer_measure = outer_measure.restrict s μ.to_outer_measure :=
by simp_rw [restrict, restrictₗ, lift_linear, linear_map.coe_mk, to_measure_to_outer_measure,
outer_measure.restrict_trim h, μ.trimmed]
/-- This lemma shows that `Inf` and `restrict` commute for measures. -/
lemma restrict_Inf_eq_Inf_restrict {m0 : measurable_space α} {m : set (measure α)}
(hm : m.nonempty) (ht : measurable_set t) :
(Inf m).restrict t = Inf ((λ μ : measure α, μ.restrict t) '' m) :=
begin
ext1 s hs,
simp_rw [Inf_apply hs, restrict_apply hs, Inf_apply (measurable_set.inter hs ht), set.image_image,
restrict_to_outer_measure_eq_to_outer_measure_restrict ht, ← set.image_image _ to_outer_measure,
← outer_measure.restrict_Inf_eq_Inf_restrict _ (hm.image _),
outer_measure.restrict_apply]
end
/-- If `s` is a measurable set, then the outer measure of `t` with respect to the restriction of
the measure to `s` equals the outer measure of `t ∩ s`. This is an alternate version of
`measure.restrict_apply`, requiring that `s` is measurable instead of `t`. -/
lemma restrict_apply' (hs : measurable_set s) : μ.restrict s t = μ (t ∩ s) :=
by rw [← coe_to_outer_measure, measure.restrict_to_outer_measure_eq_to_outer_measure_restrict hs,
outer_measure.restrict_apply s t _, coe_to_outer_measure]
lemma restrict_eq_self_of_subset_of_measurable (hs : measurable_set s) (t_subset : t ⊆ s) :
μ.restrict s t = μ t :=
by rw [restrict_apply' hs, set.inter_eq_self_of_subset_left t_subset]
/-! ### Extensionality results -/
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `Union`). -/
lemma ext_iff_of_Union_eq_univ [encodable ι] {s : ι → set α}
(hm : ∀ i, measurable_set (s i)) (hs : (⋃ i, s i) = univ) :
μ = ν ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) :=
by rw [← restrict_Union_congr hm, hs, restrict_univ, restrict_univ]
alias ext_iff_of_Union_eq_univ ↔ _ measure_theory.measure.ext_of_Union_eq_univ
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `bUnion`). -/
lemma ext_iff_of_bUnion_eq_univ {S : set ι} {s : ι → set α} (hc : countable S)
(hm : ∀ i ∈ S, measurable_set (s i)) (hs : (⋃ i ∈ S, s i) = univ) :
μ = ν ↔ ∀ i ∈ S, μ.restrict (s i) = ν.restrict (s i) :=
by rw [← restrict_bUnion_congr hc hm, hs, restrict_univ, restrict_univ]
alias ext_iff_of_bUnion_eq_univ ↔ _ measure_theory.measure.ext_of_bUnion_eq_univ
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `sUnion`). -/
lemma ext_iff_of_sUnion_eq_univ {S : set (set α)} (hc : countable S)
(hm : ∀ s ∈ S, measurable_set s) (hs : (⋃₀ S) = univ) :
μ = ν ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s :=
ext_iff_of_bUnion_eq_univ hc hm $ by rwa ← sUnion_eq_bUnion
alias ext_iff_of_sUnion_eq_univ ↔ _ measure_theory.measure.ext_of_sUnion_eq_univ
lemma ext_of_generate_from_of_cover {S T : set (set α)}
(h_gen : ‹_› = generate_from S) (hc : countable T)
(h_inter : is_pi_system S)
(hm : ∀ t ∈ T, measurable_set t) (hU : ⋃₀ T = univ) (htop : ∀ t ∈ T, μ t ≠ ∞)
(ST_eq : ∀ (t ∈ T) (s ∈ S), μ (s ∩ t) = ν (s ∩ t)) (T_eq : ∀ t ∈ T, μ t = ν t) :
μ = ν :=
begin
refine ext_of_sUnion_eq_univ hc hm hU (λ t ht, _),
ext1 u hu,
simp only [restrict_apply hu],
refine induction_on_inter h_gen h_inter _ (ST_eq t ht) _ _ hu,
{ simp only [set.empty_inter, measure_empty] },
{ intros v hv hvt,
have := T_eq t ht,
rw [set.inter_comm] at hvt ⊢,
rwa [measure_eq_inter_diff (hm _ ht) hv, measure_eq_inter_diff (hm _ ht) hv, ← hvt,
ennreal.add_right_inj] at this,
exact ne_top_of_le_ne_top (htop t ht) (measure_mono $ set.inter_subset_left _ _) },
{ intros f hfd hfm h_eq,
have : pairwise (disjoint on λ n, f n ∩ t) :=
λ m n hmn, (hfd m n hmn).mono (inter_subset_left _ _) (inter_subset_left _ _),
simp only [Union_inter, measure_Union this (λ n, (hfm n).inter (hm t ht)), h_eq] }
end
/-- Two measures are equal if they are equal on the π-system generating the σ-algebra,
and they are both finite on a increasing spanning sequence of sets in the π-system.
This lemma is formulated using `sUnion`. -/
lemma ext_of_generate_from_of_cover_subset {S T : set (set α)}
(h_gen : ‹_› = generate_from S)
(h_inter : is_pi_system S)
(h_sub : T ⊆ S) (hc : countable T) (hU : ⋃₀ T = univ) (htop : ∀ s ∈ T, μ s ≠ ∞)
(h_eq : ∀ s ∈ S, μ s = ν s) :
μ = ν :=
begin
refine ext_of_generate_from_of_cover h_gen hc h_inter _ hU htop _ (λ t ht, h_eq t (h_sub ht)),
{ intros t ht, rw [h_gen], exact generate_measurable.basic _ (h_sub ht) },
{ intros t ht s hs, cases (s ∩ t).eq_empty_or_nonempty with H H,
{ simp only [H, measure_empty] },
{ exact h_eq _ (h_inter _ _ hs (h_sub ht) H) } }
end
/-- Two measures are equal if they are equal on the π-system generating the σ-algebra,
and they are both finite on a increasing spanning sequence of sets in the π-system.
This lemma is formulated using `Union`.
`finite_spanning_sets_in.ext` is a reformulation of this lemma. -/
lemma ext_of_generate_from_of_Union (C : set (set α)) (B : ℕ → set α)
(hA : ‹_› = generate_from C) (hC : is_pi_system C) (h1B : (⋃ i, B i) = univ)
(h2B : ∀ i, B i ∈ C) (hμB : ∀ i, μ (B i) ≠ ∞) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν :=
begin
refine ext_of_generate_from_of_cover_subset hA hC _ (countable_range B) h1B _ h_eq,
{ rintro _ ⟨i, rfl⟩, apply h2B },
{ rintro _ ⟨i, rfl⟩, apply hμB }
end
section dirac
variable [measurable_space α]
/-- The dirac measure. -/
def dirac (a : α) : measure α :=
(outer_measure.dirac a).to_measure (by simp)
lemma le_dirac_apply {a} : s.indicator 1 a ≤ dirac a s :=
outer_measure.dirac_apply a s ▸ le_to_measure_apply _ _ _
@[simp] lemma dirac_apply' (a : α) (hs : measurable_set s) :
dirac a s = s.indicator 1 a :=
to_measure_apply _ _ hs
@[simp] lemma dirac_apply_of_mem {a : α} (h : a ∈ s) :
dirac a s = 1 :=
begin
have : ∀ t : set α, a ∈ t → t.indicator (1 : α → ℝ≥0∞) a = 1,
from λ t ht, indicator_of_mem ht 1,
refine le_antisymm (this univ trivial ▸ _) (this s h ▸ le_dirac_apply),
rw [← dirac_apply' a measurable_set.univ],
exact measure_mono (subset_univ s)
end
@[simp] lemma dirac_apply [measurable_singleton_class α] (a : α) (s : set α) :
dirac a s = s.indicator 1 a :=
begin
by_cases h : a ∈ s, by rw [dirac_apply_of_mem h, indicator_of_mem h, pi.one_apply],
rw [indicator_of_not_mem h, ← nonpos_iff_eq_zero],
calc dirac a s ≤ dirac a {a}ᶜ : measure_mono (subset_compl_comm.1 $ singleton_subset_iff.2 h)
... = 0 : by simp [dirac_apply' _ (measurable_set_singleton _).compl]
end
lemma map_dirac {f : α → β} (hf : measurable f) (a : α) :
map f (dirac a) = dirac (f a) :=
ext $ assume s hs, by simp [hs, map_apply hf hs, hf hs, indicator_apply]
end dirac
section sum
include m0
/-- Sum of an indexed family of measures. -/
def sum (f : ι → measure α) : measure α :=
(outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $
le_trans
(by exact le_infi (λ i, le_to_outer_measure_caratheodory _))
(outer_measure.le_sum_caratheodory _)
lemma le_sum_apply (f : ι → measure α) (s : set α) : (∑' i, f i s) ≤ sum f s :=
le_to_measure_apply _ _ _
@[simp] lemma sum_apply (f : ι → measure α) {s : set α} (hs : measurable_set s) :
sum f s = ∑' i, f i s :=
to_measure_apply _ _ hs
lemma le_sum (μ : ι → measure α) (i : ι) : μ i ≤ sum μ :=
λ s hs, by simp only [sum_apply μ hs, ennreal.le_tsum i]
@[simp] lemma sum_bool (f : bool → measure α) : sum f = f tt + f ff :=
ext $ λ s hs, by simp [hs, tsum_fintype]
@[simp] lemma sum_cond (μ ν : measure α) : sum (λ b, cond b μ ν) = μ + ν := sum_bool _
@[simp] lemma restrict_sum (μ : ι → measure α) {s : set α} (hs : measurable_set s) :
(sum μ).restrict s = sum (λ i, (μ i).restrict s) :=
ext $ λ t ht, by simp only [sum_apply, restrict_apply, ht, ht.inter hs]
lemma sum_congr {μ ν : ℕ → measure α} (h : ∀ n, μ n = ν n) : sum μ = sum ν :=
by { congr, ext1 n, exact h n }
lemma sum_add_sum (μ ν : ℕ → measure α) : sum μ + sum ν = sum (λ n, μ n + ν n) :=
begin
ext1 s hs,
simp only [add_apply, sum_apply _ hs, pi.add_apply, coe_add,
tsum_add ennreal.summable ennreal.summable],
end
/-- If `f` is a map with encodable codomain, then `map f μ` is the sum of Dirac measures -/
lemma map_eq_sum [encodable β] [measurable_singleton_class β]
(μ : measure α) (f : α → β) (hf : measurable f) :
map f μ = sum (λ b : β, μ (f ⁻¹' {b}) • dirac b) :=
begin
ext1 s hs,
have : ∀ y ∈ s, measurable_set (f ⁻¹' {y}), from λ y _, hf (measurable_set_singleton _),
simp [← tsum_measure_preimage_singleton (countable_encodable s) this, *,
tsum_subtype s (λ b, μ (f ⁻¹' {b})), ← indicator_mul_right s (λ b, μ (f ⁻¹' {b}))]
end
/-- A measure on an encodable type is a sum of dirac measures. -/
@[simp] lemma sum_smul_dirac [encodable α] [measurable_singleton_class α] (μ : measure α) :
sum (λ a, μ {a} • dirac a) = μ :=
by simpa using (map_eq_sum μ id measurable_id).symm
omit m0
end sum
lemma restrict_Union [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ i, measurable_set (s i)) :
μ.restrict (⋃ i, s i) = sum (λ i, μ.restrict (s i)) :=
ext $ λ t ht, by simp only [sum_apply _ ht, restrict_Union_apply hd hm ht]
lemma restrict_Union_le [encodable ι] {s : ι → set α} :
μ.restrict (⋃ i, s i) ≤ sum (λ i, μ.restrict (s i)) :=
begin
intros t ht,
suffices : μ (⋃ i, t ∩ s i) ≤ ∑' i, μ (t ∩ s i), by simpa [ht, inter_Union],
apply measure_Union_le
end
section count
variable [measurable_space α]
/-- Counting measure on any measurable space. -/
def count : measure α := sum dirac
lemma le_count_apply : (∑' i : s, 1 : ℝ≥0∞) ≤ count s :=
calc (∑' i : s, 1 : ℝ≥0∞) = ∑' i, indicator s 1 i : tsum_subtype s 1
... ≤ ∑' i, dirac i s : ennreal.tsum_le_tsum $ λ x, le_dirac_apply
... ≤ count s : le_sum_apply _ _
lemma count_apply (hs : measurable_set s) : count s = ∑' i : s, 1 :=
by simp only [count, sum_apply, hs, dirac_apply', ← tsum_subtype s 1, pi.one_apply]
@[simp] lemma count_apply_finset [measurable_singleton_class α] (s : finset α) :
count (↑s : set α) = s.card :=
calc count (↑s : set α) = ∑' i : (↑s : set α), 1 : count_apply s.measurable_set
... = ∑ i in s, 1 : s.tsum_subtype 1
... = s.card : by simp
lemma count_apply_finite [measurable_singleton_class α] (s : set α) (hs : finite s) :
count s = hs.to_finset.card :=
by rw [← count_apply_finset, finite.coe_to_finset]
/-- `count` measure evaluates to infinity at infinite sets. -/
lemma count_apply_infinite (hs : s.infinite) : count s = ∞ :=
begin
refine top_unique (le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, _),
rcases hs.exists_subset_card_eq n with ⟨t, ht, rfl⟩,
calc (t.card : ℝ≥0∞) = ∑ i in t, 1 : by simp
... = ∑' i : (t : set α), 1 : (t.tsum_subtype 1).symm
... ≤ count (t : set α) : le_count_apply
... ≤ count s : measure_mono ht
end
@[simp] lemma count_apply_eq_top [measurable_singleton_class α] : count s = ∞ ↔ s.infinite :=
begin
by_cases hs : s.finite,
{ simp [set.infinite, hs, count_apply_finite] },
{ change s.infinite at hs,
simp [hs, count_apply_infinite] }
end
@[simp] lemma count_apply_lt_top [measurable_singleton_class α] : count s < ∞ ↔ s.finite :=
calc count s < ∞ ↔ count s ≠ ∞ : lt_top_iff_ne_top
... ↔ ¬s.infinite : not_congr count_apply_eq_top
... ↔ s.finite : not_not
end count
/-! ### Absolute continuity -/
/-- We say that `μ` is absolutely continuous with respect to `ν`, or that `μ` is dominated by `ν`,
if `ν(A) = 0` implies that `μ(A) = 0`. -/
def absolutely_continuous {m0 : measurable_space α} (μ ν : measure α) : Prop :=
∀ ⦃s : set α⦄, ν s = 0 → μ s = 0
infix ` ≪ `:50 := absolutely_continuous
lemma absolutely_continuous_of_le (h : μ ≤ ν) : μ ≪ ν :=
λ s hs, nonpos_iff_eq_zero.1 $ hs ▸ le_iff'.1 h s
alias absolutely_continuous_of_le ← has_le.le.absolutely_continuous
lemma absolutely_continuous_of_eq (h : μ = ν) : μ ≪ ν :=
h.le.absolutely_continuous
alias absolutely_continuous_of_eq ← eq.absolutely_continuous
namespace absolutely_continuous
lemma mk (h : ∀ ⦃s : set α⦄, measurable_set s → ν s = 0 → μ s = 0) : μ ≪ ν :=
begin
intros s hs,
rcases exists_measurable_superset_of_null hs with ⟨t, h1t, h2t, h3t⟩,
exact measure_mono_null h1t (h h2t h3t),
end
@[refl] protected lemma refl {m0 : measurable_space α} (μ : measure α) : μ ≪ μ :=
rfl.absolutely_continuous
protected lemma rfl : μ ≪ μ := λ s hs, hs
@[trans] protected lemma trans (h1 : μ₁ ≪ μ₂) (h2 : μ₂ ≪ μ₃) : μ₁ ≪ μ₃ :=
λ s hs, h1 $ h2 hs
@[mono] protected lemma map (h : μ ≪ ν) (f : α → β) : map f μ ≪ map f ν :=
if hf : measurable f then absolutely_continuous.mk $ λ s hs, by simpa [hf, hs] using @h _
else by simp only [map_of_not_measurable hf]
end absolutely_continuous
lemma ae_le_iff_absolutely_continuous : μ.ae ≤ ν.ae ↔ μ ≪ ν :=
⟨λ h s, by { rw [measure_zero_iff_ae_nmem, measure_zero_iff_ae_nmem], exact λ hs, h hs },
λ h s hs, h hs⟩
alias ae_le_iff_absolutely_continuous ↔ has_le.le.absolutely_continuous_of_ae
measure_theory.measure.absolutely_continuous.ae_le
alias absolutely_continuous.ae_le ← ae_mono'
lemma absolutely_continuous.ae_eq (h : μ ≪ ν) {f g : α → δ} (h' : f =ᵐ[ν] g) : f =ᵐ[μ] g :=
h.ae_le h'
/-! ### Quasi measure preserving maps (a.k.a. non-singular maps) -/
/-- A map `f : α → β` is said to be *quasi measure preserving* (a.k.a. non-singular) w.r.t. measures
`μa` and `μb` if it is measurable and `μb s = 0` implies `μa (f ⁻¹' s) = 0`. -/
@[protect_proj]
structure quasi_measure_preserving {m0 : measurable_space α} (f : α → β)
(μa : measure α . volume_tac) (μb : measure β . volume_tac) : Prop :=
(measurable : measurable f)
(absolutely_continuous : map f μa ≪ μb)
namespace quasi_measure_preserving
protected lemma id {m0 : measurable_space α} (μ : measure α) : quasi_measure_preserving id μ μ :=
⟨measurable_id, map_id.absolutely_continuous⟩
variables {μa μa' : measure α} {μb μb' : measure β} {μc : measure γ} {f : α → β}
lemma mono_left (h : quasi_measure_preserving f μa μb)
(ha : μa' ≪ μa) : quasi_measure_preserving f μa' μb :=
⟨h.1, (ha.map f).trans h.2⟩
lemma mono_right (h : quasi_measure_preserving f μa μb)
(ha : μb ≪ μb') : quasi_measure_preserving f μa μb' :=
⟨h.1, h.2.trans ha⟩
@[mono] lemma mono (ha : μa' ≪ μa) (hb : μb ≪ μb') (h : quasi_measure_preserving f μa μb) :
quasi_measure_preserving f μa' μb' :=
(h.mono_left ha).mono_right hb
protected lemma comp {g : β → γ} {f : α → β} (hg : quasi_measure_preserving g μb μc)
(hf : quasi_measure_preserving f μa μb) :
quasi_measure_preserving (g ∘ f) μa μc :=
⟨hg.measurable.comp hf.measurable, by { rw ← map_map hg.1 hf.1, exact (hf.2.map g).trans hg.2 }⟩
protected lemma iterate {f : α → α} (hf : quasi_measure_preserving f μa μa) :
∀ n, quasi_measure_preserving (f^[n]) μa μa
| 0 := quasi_measure_preserving.id μa
| (n + 1) := (iterate n).comp hf
lemma ae_map_le (h : quasi_measure_preserving f μa μb) : (map f μa).ae ≤ μb.ae :=
h.2.ae_le
lemma tendsto_ae (h : quasi_measure_preserving f μa μb) : tendsto f μa.ae μb.ae :=
(tendsto_ae_map h.1).mono_right h.ae_map_le
lemma ae (h : quasi_measure_preserving f μa μb) {p : β → Prop} (hg : ∀ᵐ x ∂μb, p x) :
∀ᵐ x ∂μa, p (f x) :=
h.tendsto_ae hg
lemma ae_eq (h : quasi_measure_preserving f μa μb) {g₁ g₂ : β → δ} (hg : g₁ =ᵐ[μb] g₂) :
g₁ ∘ f =ᵐ[μa] g₂ ∘ f :=
h.ae hg
end quasi_measure_preserving
/-! ### The `cofinite` filter -/
/-- The filter of sets `s` such that `sᶜ` has finite measure. -/
def cofinite {m0 : measurable_space α} (μ : measure α) : filter α :=
{ sets := {s | μ sᶜ < ∞},
univ_sets := by simp,
inter_sets := λ s t hs ht, by { simp only [compl_inter, mem_set_of_eq],
calc μ (sᶜ ∪ tᶜ) ≤ μ sᶜ + μ tᶜ : measure_union_le _ _
... < ∞ : ennreal.add_lt_top.2 ⟨hs, ht⟩ },
sets_of_superset := λ s t hs hst, lt_of_le_of_lt (measure_mono $ compl_subset_compl.2 hst) hs }
lemma mem_cofinite : s ∈ μ.cofinite ↔ μ sᶜ < ∞ := iff.rfl
lemma compl_mem_cofinite : sᶜ ∈ μ.cofinite ↔ μ s < ∞ :=
by rw [mem_cofinite, compl_compl]
lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in μ.cofinite, p x) ↔ μ {x | ¬p x} < ∞ := iff.rfl
/-! ### Mutually singular measures -/
/-- Two measures `μ`, `ν` are said to be mutually singular if there exists a measurable set `s`
such that `μ s = 0` and `ν sᶜ = 0`. -/
def mutually_singular {m0 : measurable_space α} (μ ν : measure α) : Prop :=
∃ (s : set α), measurable_set s ∧ μ s = 0 ∧ ν sᶜ = 0
localized "infix ` ⊥ₘ `:60 := measure_theory.measure.mutually_singular" in measure_theory
namespace mutually_singular
lemma zero : μ ⊥ₘ 0 :=
⟨∅, measurable_set.empty, measure_empty, rfl⟩
lemma symm (h : ν ⊥ₘ μ) : μ ⊥ₘ ν :=
let ⟨i, hi, his, hit⟩ := h in
⟨iᶜ, measurable_set.compl hi, hit, (compl_compl i).symm ▸ his⟩
lemma add (h₁ : ν₁ ⊥ₘ μ) (h₂ : ν₂ ⊥ₘ μ) : ν₁ + ν₂ ⊥ₘ μ :=
begin
obtain ⟨s, hs, hs0, hs0'⟩ := h₁,
obtain ⟨t, ht, ht0, ht0'⟩ := h₂,
refine ⟨s ∩ t, hs.inter ht, _, _⟩,
{ simp only [pi.add_apply, add_eq_zero_iff, coe_add],
exact ⟨measure_mono_null (inter_subset_left s t) hs0,
measure_mono_null (inter_subset_right s t) ht0⟩ },
{ rw [compl_inter, ← nonpos_iff_eq_zero],
refine le_trans (measure_union_le _ _) _,
rw [hs0', ht0', zero_add],
exact le_refl _ }
end
lemma add_iff : ν₁ + ν₂ ⊥ₘ μ ↔ ν₁ ⊥ₘ μ ∧ ν₂ ⊥ₘ μ :=
begin
split,
{ rintro ⟨u, hmeas, hu₁, hu₂⟩,
rw [measure.add_apply, add_eq_zero_iff] at hu₁,
exact ⟨⟨u, hmeas, hu₁.1, hu₂⟩, u, hmeas, hu₁.2, hu₂⟩ },
{ exact λ ⟨h₁, h₂⟩, h₁.add h₂ }
end
lemma smul (r : ℝ≥0) (h : ν ⊥ₘ μ) : r • ν ⊥ₘ μ :=
let ⟨s, hs, hs0, hs0'⟩ := h in
⟨s, hs, by simp only [coe_nnreal_smul, pi.smul_apply, hs0, smul_zero], hs0'⟩
lemma of_absolutely_continuous (hms : ν₂ ⊥ₘ μ) (hac : ν₁ ≪ ν₂) : ν₁ ⊥ₘ μ :=
let ⟨u, hmeas, hu₁, hu₂⟩ := hms in ⟨u, hmeas, hac hu₁, hu₂⟩
end mutually_singular
end measure
open measure
@[simp] lemma ae_eq_bot : μ.ae = ⊥ ↔ μ = 0 :=
by rw [← empty_mem_iff_bot, mem_ae_iff, compl_empty, measure_univ_eq_zero]
@[simp] lemma ae_ne_bot : μ.ae.ne_bot ↔ μ ≠ 0 :=
ne_bot_iff.trans (not_congr ae_eq_bot)
@[simp] lemma ae_zero {m0 : measurable_space α} : (0 : measure α).ae = ⊥ := ae_eq_bot.2 rfl
@[mono] lemma ae_mono (h : μ ≤ ν) : μ.ae ≤ ν.ae := h.absolutely_continuous.ae_le
lemma mem_ae_map_iff {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) :
s ∈ (map f μ).ae ↔ (f ⁻¹' s) ∈ μ.ae :=
by simp only [mem_ae_iff, map_apply hf hs.compl, preimage_compl]
lemma mem_ae_of_mem_ae_map {f : α → β} (hf : measurable f) {s : set β} (hs : s ∈ (map f μ).ae) :
f ⁻¹' s ∈ μ.ae :=
begin
apply le_antisymm _ bot_le,
calc μ (f ⁻¹' sᶜ) ≤ (map f μ) sᶜ : le_map_apply hf sᶜ
... = 0 : hs
end
lemma ae_map_iff {f : α → β} (hf : measurable f) {p : β → Prop} (hp : measurable_set {x | p x}) :
(∀ᵐ y ∂ (map f μ), p y) ↔ ∀ᵐ x ∂ μ, p (f x) :=
mem_ae_map_iff hf hp
lemma ae_of_ae_map {f : α → β} (hf : measurable f) {p : β → Prop} (h : ∀ᵐ y ∂ (map f μ), p y) :
∀ᵐ x ∂ μ, p (f x) :=
mem_ae_of_mem_ae_map hf h
lemma ae_map_mem_range {m0 : measurable_space α} (f : α → β) (hf : measurable_set (range f))
(μ : measure α) :
∀ᵐ x ∂(map f μ), x ∈ range f :=
begin
by_cases h : measurable f,
{ change range f ∈ (map f μ).ae,
rw mem_ae_map_iff h hf,
apply eventually_of_forall,
exact mem_range_self },
{ simp [map_of_not_measurable h] }
end
lemma ae_restrict_iff {p : α → Prop} (hp : measurable_set {x | p x}) :
(∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x :=
begin
simp only [ae_iff, ← compl_set_of, restrict_apply hp.compl],
congr' with x, simp [and_comm]
end
lemma ae_imp_of_ae_restrict {s : set α} {p : α → Prop} (h : ∀ᵐ x ∂(μ.restrict s), p x) :
∀ᵐ x ∂μ, x ∈ s → p x :=
begin
simp only [ae_iff] at h ⊢,
simpa [set_of_and, inter_comm] using measure_inter_eq_zero_of_restrict h
end
lemma ae_restrict_iff' {s : set α} {p : α → Prop} (hs : measurable_set s) :
(∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x :=
begin
simp only [ae_iff, ← compl_set_of, restrict_apply_eq_zero' hs],
congr' with x, simp [and_comm]
end
lemma ae_restrict_mem {s : set α} (hs : measurable_set s) :
∀ᵐ x ∂(μ.restrict s), x ∈ s :=
(ae_restrict_iff' hs).2 (filter.eventually_of_forall (λ x, id))
lemma ae_restrict_of_ae {s : set α} {p : α → Prop} (h : ∀ᵐ x ∂μ, p x) :
(∀ᵐ x ∂(μ.restrict s), p x) :=
eventually.filter_mono (ae_mono measure.restrict_le_self) h
lemma ae_restrict_of_ae_restrict_of_subset {s t : set α} {p : α → Prop} (hst : s ⊆ t)
(h : ∀ᵐ x ∂(μ.restrict t), p x) :
(∀ᵐ x ∂(μ.restrict s), p x) :=
h.filter_mono (ae_mono $ measure.restrict_mono hst (le_refl μ))
lemma ae_of_ae_restrict_of_ae_restrict_compl {t : set α} (ht_meas : measurable_set t) {p : α → Prop}
(ht : ∀ᵐ x ∂(μ.restrict t), p x) (htc : ∀ᵐ x ∂(μ.restrict tᶜ), p x) :
∀ᵐ x ∂μ, p x :=
begin
rw ae_restrict_iff' ht_meas at ht,
rw ae_restrict_iff' ht_meas.compl at htc,
refine ht.mp (htc.mono (λ x hx1 hx2, _)),
by_cases hxt : x ∈ t,
{ exact hx2 hxt, },
{ exact hx1 hxt, },
end
lemma mem_map_restrict_ae_iff {β} {s : set α} {t : set β} {f : α → β} (hs : measurable_set s) :
t ∈ filter.map f (μ.restrict s).ae ↔ μ ((f ⁻¹' t)ᶜ ∩ s) = 0 :=
by rw [mem_map, mem_ae_iff, measure.restrict_apply' hs]
lemma ae_smul_measure {p : α → Prop} (h : ∀ᵐ x ∂μ, p x) (c : ℝ≥0∞) : ∀ᵐ x ∂(c • μ), p x :=
ae_iff.2 $ by rw [smul_apply, ae_iff.1 h, mul_zero]
lemma ae_smul_measure_iff {p : α → Prop} {c : ℝ≥0∞} (hc : c ≠ 0) :
(∀ᵐ x ∂(c • μ), p x) ↔ ∀ᵐ x ∂μ, p x :=
by simp [ae_iff, hc]
lemma ae_add_measure_iff {p : α → Prop} {ν} : (∀ᵐ x ∂μ + ν, p x) ↔ (∀ᵐ x ∂μ, p x) ∧ ∀ᵐ x ∂ν, p x :=
add_eq_zero_iff
lemma ae_eq_comp' {ν : measure β} {f : α → β} {g g' : β → δ} (hf : measurable f)
(h : g =ᵐ[ν] g') (h2 : map f μ ≪ ν) : g ∘ f =ᵐ[μ] g' ∘ f :=
(quasi_measure_preserving.mk hf h2).ae_eq h
lemma ae_eq_comp {f : α → β} {g g' : β → δ} (hf : measurable f)
(h : g =ᵐ[measure.map f μ] g') : g ∘ f =ᵐ[μ] g' ∘ f :=
ae_eq_comp' hf h absolutely_continuous.rfl
lemma sub_ae_eq_zero {β} [add_group β] (f g : α → β) : f - g =ᵐ[μ] 0 ↔ f =ᵐ[μ] g :=
begin
refine ⟨λ h, h.mono (λ x hx, _), λ h, h.mono (λ x hx, _)⟩,
{ rwa [pi.sub_apply, pi.zero_apply, sub_eq_zero] at hx, },
{ rwa [pi.sub_apply, pi.zero_apply, sub_eq_zero], },
end
lemma le_ae_restrict : μ.ae ⊓ 𝓟 s ≤ (μ.restrict s).ae :=
λ s hs, eventually_inf_principal.2 (ae_imp_of_ae_restrict hs)
@[simp] lemma ae_restrict_eq (hs : measurable_set s) : (μ.restrict s).ae = μ.ae ⊓ 𝓟 s :=
begin
ext t,
simp only [mem_inf_principal, mem_ae_iff, restrict_apply_eq_zero' hs, compl_set_of,
not_imp, and_comm (_ ∈ s)],
refl
end
@[simp] lemma ae_restrict_eq_bot {s} : (μ.restrict s).ae = ⊥ ↔ μ s = 0 :=
ae_eq_bot.trans restrict_eq_zero
@[simp] lemma ae_restrict_ne_bot {s} : (μ.restrict s).ae.ne_bot ↔ 0 < μ s :=
ne_bot_iff.trans $ (not_congr ae_restrict_eq_bot).trans pos_iff_ne_zero.symm
lemma self_mem_ae_restrict {s} (hs : measurable_set s) : s ∈ (μ.restrict s).ae :=
by simp only [ae_restrict_eq hs, exists_prop, mem_principal, mem_inf_iff];
exact ⟨_, univ_mem, s, subset.rfl, (univ_inter s).symm⟩
/-- A version of the Borel-Cantelli lemma: if `sᵢ` is a sequence of measurable sets such that
`∑ μ sᵢ` exists, then for almost all `x`, `x` does not belong to almost all `sᵢ`. -/
lemma ae_eventually_not_mem {s : ℕ → set α} (hs : ∀ i, measurable_set (s i))
(hs' : ∑' i, μ (s i) ≠ ∞) : ∀ᵐ x ∂ μ, ∀ᶠ n in at_top, x ∉ s n :=
begin
refine measure_mono_null _ (measure_limsup_eq_zero hs hs'),
rw ←set.le_eq_subset,
refine le_Inf (λ t ht x hx, _),
simp only [le_eq_subset, not_exists, eventually_map, exists_prop, ge_iff_le, mem_set_of_eq,
eventually_at_top, mem_compl_eq, not_forall, not_not_mem] at hx ht,
rcases ht with ⟨i, hi⟩,
rcases hx i with ⟨j, ⟨hj, hj'⟩⟩,
exact hi j hj hj'
end
section dirac
variable [measurable_space α]
lemma mem_ae_dirac_iff {a : α} (hs : measurable_set s) : s ∈ (dirac a).ae ↔ a ∈ s :=
by by_cases a ∈ s; simp [mem_ae_iff, dirac_apply', hs.compl, indicator_apply, *]
lemma ae_dirac_iff {a : α} {p : α → Prop} (hp : measurable_set {x | p x}) :
(∀ᵐ x ∂(dirac a), p x) ↔ p a :=
mem_ae_dirac_iff hp
@[simp] lemma ae_dirac_eq [measurable_singleton_class α] (a : α) : (dirac a).ae = pure a :=
by { ext s, simp [mem_ae_iff, imp_false] }
lemma ae_eq_dirac' [measurable_singleton_class β] {a : α} {f : α → β} (hf : measurable f) :
f =ᵐ[dirac a] const α (f a) :=
(ae_dirac_iff $ show measurable_set (f ⁻¹' {f a}), from hf $ measurable_set_singleton _).2 rfl
lemma ae_eq_dirac [measurable_singleton_class α] {a : α} (f : α → δ) :
f =ᵐ[dirac a] const α (f a) :=
by simp [filter.eventually_eq]
end dirac
lemma restrict_mono_ae (h : s ≤ᵐ[μ] t) : μ.restrict s ≤ μ.restrict t :=
begin
intros u hu,
simp only [restrict_apply hu],
exact measure_mono_ae (h.mono $ λ x hx, and.imp id hx)
end
lemma restrict_congr_set (H : s =ᵐ[μ] t) : μ.restrict s = μ.restrict t :=
le_antisymm (restrict_mono_ae H.le) (restrict_mono_ae H.symm.le)
section is_finite_measure
include m0
/-- A measure `μ` is called finite if `μ univ < ∞`. -/
class is_finite_measure (μ : measure α) : Prop := (measure_univ_lt_top : μ univ < ∞)
instance restrict.is_finite_measure (μ : measure α) [hs : fact (μ s < ∞)] :
is_finite_measure (μ.restrict s) :=
⟨by simp [hs.elim]⟩
lemma measure_lt_top (μ : measure α) [is_finite_measure μ] (s : set α) : μ s < ∞ :=
(measure_mono (subset_univ s)).trans_lt is_finite_measure.measure_univ_lt_top
lemma measure_ne_top (μ : measure α) [is_finite_measure μ] (s : set α) : μ s ≠ ∞ :=
ne_of_lt (measure_lt_top μ s)
lemma measure_compl_le_add_of_le_add [is_finite_measure μ] (hs : measurable_set s)
(ht : measurable_set t) {ε : ℝ≥0∞} (h : μ s ≤ μ t + ε) :
μ tᶜ ≤ μ sᶜ + ε :=
begin
rw [measure_compl ht (measure_ne_top μ _), measure_compl hs (measure_ne_top μ _),
ennreal.sub_le_iff_le_add],
calc μ univ = μ univ - μ s + μ s :
(ennreal.sub_add_cancel_of_le $ measure_mono s.subset_univ).symm
... ≤ μ univ - μ s + (μ t + ε) : add_le_add_left h _
... = _ : by rw [add_right_comm, add_assoc]
end
lemma measure_compl_le_add_iff [is_finite_measure μ] (hs : measurable_set s)
(ht : measurable_set t) {ε : ℝ≥0∞} :
μ sᶜ ≤ μ tᶜ + ε ↔ μ t ≤ μ s + ε :=
⟨λ h, compl_compl s ▸ compl_compl t ▸ measure_compl_le_add_of_le_add hs.compl ht.compl h,
measure_compl_le_add_of_le_add ht hs⟩
/-- The measure of the whole space with respect to a finite measure, considered as `ℝ≥0`. -/
def measure_univ_nnreal (μ : measure α) : ℝ≥0 := (μ univ).to_nnreal
@[simp] lemma coe_measure_univ_nnreal (μ : measure α) [is_finite_measure μ] :
↑(measure_univ_nnreal μ) = μ univ :=
ennreal.coe_to_nnreal (measure_ne_top μ univ)
instance is_finite_measure_zero : is_finite_measure (0 : measure α) := ⟨by simp⟩
@[priority 100]
instance is_finite_measure_of_is_empty [is_empty α] : is_finite_measure μ :=
by { rw eq_zero_of_is_empty μ, apply_instance }
@[simp] lemma measure_univ_nnreal_zero : measure_univ_nnreal (0 : measure α) = 0 := rfl
omit m0
instance is_finite_measure_add [is_finite_measure μ] [is_finite_measure ν] :
is_finite_measure (μ + ν) :=
{ measure_univ_lt_top :=
begin
rw [measure.coe_add, pi.add_apply, ennreal.add_lt_top],
exact ⟨measure_lt_top _ _, measure_lt_top _ _⟩,
end }
instance is_finite_measure_smul_nnreal [is_finite_measure μ] {r : ℝ≥0} :
is_finite_measure (r • μ) :=
{ measure_univ_lt_top := ennreal.mul_lt_top ennreal.coe_ne_top (measure_ne_top _ _) }
lemma is_finite_measure_of_le (μ : measure α) [is_finite_measure μ] (h : ν ≤ μ) :
is_finite_measure ν :=
{ measure_univ_lt_top := lt_of_le_of_lt (h set.univ measurable_set.univ) (measure_lt_top _ _) }
lemma measure.is_finite_measure_map {m : measurable_space α}
(μ : measure α) [is_finite_measure μ] {f : α → β} (hf : measurable f) :
is_finite_measure (map f μ) :=
⟨by { rw map_apply hf measurable_set.univ, exact measure_lt_top μ _ }⟩
@[simp] lemma measure_univ_nnreal_eq_zero [is_finite_measure μ] :
measure_univ_nnreal μ = 0 ↔ μ = 0 :=
begin
rw [← measure_theory.measure.measure_univ_eq_zero, ← coe_measure_univ_nnreal],
norm_cast
end
lemma measure_univ_nnreal_pos [is_finite_measure μ] (hμ : μ ≠ 0) : 0 < measure_univ_nnreal μ :=
begin
contrapose! hμ,
simpa [measure_univ_nnreal_eq_zero, le_zero_iff] using hμ
end
/-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`,
but it holds for measures with the additional assumption that μ is finite. -/
lemma measure.le_of_add_le_add_left [is_finite_measure μ] (A2 : μ + ν₁ ≤ μ + ν₂) : ν₁ ≤ ν₂ :=
λ S B1, ennreal.le_of_add_le_add_left (measure_theory.measure_ne_top μ S) (A2 S B1)
lemma summable_measure_to_real [hμ : is_finite_measure μ]
{f : ℕ → set α} (hf₁ : ∀ (i : ℕ), measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) :
summable (λ x, (μ (f x)).to_real) :=
begin
apply ennreal.summable_to_real,
rw ← measure_theory.measure_Union hf₂ hf₁,
exact ne_of_lt (measure_lt_top _ _)
end
end is_finite_measure
section is_probability_measure
include m0
/-- A measure `μ` is called a probability measure if `μ univ = 1`. -/
class is_probability_measure (μ : measure α) : Prop := (measure_univ : μ univ = 1)
export is_probability_measure (measure_univ)
@[priority 100]
instance is_probability_measure.to_is_finite_measure (μ : measure α) [is_probability_measure μ] :
is_finite_measure μ :=
⟨by simp only [measure_univ, ennreal.one_lt_top]⟩
lemma is_probability_measure.ne_zero (μ : measure α) [is_probability_measure μ] : μ ≠ 0 :=
mt measure_univ_eq_zero.2 $ by simp [measure_univ]
omit m0
instance measure.dirac.is_probability_measure [measurable_space α] {x : α} :
is_probability_measure (dirac x) :=
⟨dirac_apply_of_mem $ mem_univ x⟩
lemma prob_add_prob_compl [is_probability_measure μ]
(h : measurable_set s) : μ s + μ sᶜ = 1 :=
(measure_add_measure_compl h).trans measure_univ
lemma prob_le_one [is_probability_measure μ] : μ s ≤ 1 :=
(measure_mono $ set.subset_univ _).trans_eq measure_univ
end is_probability_measure
section no_atoms
/-- Measure `μ` *has no atoms* if the measure of each singleton is zero.
NB: Wikipedia assumes that for any measurable set `s` with positive `μ`-measure,
there exists a measurable `t ⊆ s` such that `0 < μ t < μ s`. While this implies `μ {x} = 0`,
the converse is not true. -/
class has_no_atoms {m0 : measurable_space α} (μ : measure α) : Prop :=
(measure_singleton : ∀ x, μ {x} = 0)
export has_no_atoms (measure_singleton)
attribute [simp] measure_singleton
variables [has_no_atoms μ]
lemma _root_.set.subsingleton.measure_zero {α : Type*} {m : measurable_space α} {s : set α}
(hs : s.subsingleton) (μ : measure α) [has_no_atoms μ] :
μ s = 0 :=
hs.induction_on measure_empty measure_singleton
@[simp] lemma measure.restrict_singleton' {a : α} :
μ.restrict {a} = 0 :=
by simp only [measure_singleton, measure.restrict_eq_zero]
instance (s : set α) : has_no_atoms (μ.restrict s) :=
begin
refine ⟨λ x, _⟩,
obtain ⟨t, hxt, ht1, ht2⟩ := exists_measurable_superset_of_null (measure_singleton x : μ {x} = 0),
apply measure_mono_null hxt,
rw measure.restrict_apply ht1,
apply measure_mono_null (inter_subset_left t s) ht2
end
lemma _root_.set.countable.measure_zero {α : Type*} {m : measurable_space α} {s : set α}
(h : countable s) (μ : measure α) [has_no_atoms μ] :
μ s = 0 :=
begin
rw [← bUnion_of_singleton s, ← nonpos_iff_eq_zero],
refine le_trans (measure_bUnion_le h _) _,
simp
end
lemma _root_.set.finite.measure_zero {α : Type*} {m : measurable_space α} {s : set α}
(h : s.finite) (μ : measure α) [has_no_atoms μ] : μ s = 0 :=
h.countable.measure_zero μ
lemma _root_.finset.measure_zero {α : Type*} {m : measurable_space α}
(s : finset α) (μ : measure α) [has_no_atoms μ] : μ s = 0 :=
s.finite_to_set.measure_zero μ
lemma insert_ae_eq_self (a : α) (s : set α) :
(insert a s : set α) =ᵐ[μ] s :=
union_ae_eq_right.2 $ measure_mono_null (diff_subset _ _) (measure_singleton _)
variables [partial_order α] {a b : α}
lemma Iio_ae_eq_Iic : Iio a =ᵐ[μ] Iic a :=
by simp only [← Iic_diff_right, diff_ae_eq_self,
measure_mono_null (set.inter_subset_right _ _) (measure_singleton a)]
lemma Ioi_ae_eq_Ici : Ioi a =ᵐ[μ] Ici a :=
@Iio_ae_eq_Iic (order_dual α) ‹_› ‹_› _ _ _
lemma Ioo_ae_eq_Ioc : Ioo a b =ᵐ[μ] Ioc a b :=
(ae_eq_refl _).inter Iio_ae_eq_Iic
lemma Ioc_ae_eq_Icc : Ioc a b =ᵐ[μ] Icc a b :=
Ioi_ae_eq_Ici.inter (ae_eq_refl _)
lemma Ioo_ae_eq_Ico : Ioo a b =ᵐ[μ] Ico a b :=
Ioi_ae_eq_Ici.inter (ae_eq_refl _)
lemma Ioo_ae_eq_Icc : Ioo a b =ᵐ[μ] Icc a b :=
Ioi_ae_eq_Ici.inter Iio_ae_eq_Iic
lemma Ico_ae_eq_Icc : Ico a b =ᵐ[μ] Icc a b :=
(ae_eq_refl _).inter Iio_ae_eq_Iic
lemma Ico_ae_eq_Ioc : Ico a b =ᵐ[μ] Ioc a b :=
Ioo_ae_eq_Ico.symm.trans Ioo_ae_eq_Ioc
end no_atoms
lemma ite_ae_eq_of_measure_zero {γ} (f : α → γ) (g : α → γ) (s : set α) (hs_zero : μ s = 0) :
(λ x, ite (x ∈ s) (f x) (g x)) =ᵐ[μ] g :=
begin
have h_ss : sᶜ ⊆ {a : α | ite (a ∈ s) (f a) (g a) = g a},
from λ x hx, by simp [(set.mem_compl_iff _ _).mp hx],
refine measure_mono_null _ hs_zero,
nth_rewrite 0 ←compl_compl s,
rwa set.compl_subset_compl,
end
lemma ite_ae_eq_of_measure_compl_zero {γ} (f : α → γ) (g : α → γ) (s : set α) (hs_zero : μ sᶜ = 0) :
(λ x, ite (x ∈ s) (f x) (g x)) =ᵐ[μ] f :=
by { filter_upwards [hs_zero], intros, split_ifs, refl }
namespace measure
/-- A measure is called finite at filter `f` if it is finite at some set `s ∈ f`.
Equivalently, it is eventually finite at `s` in `f.lift' powerset`. -/
def finite_at_filter {m0 : measurable_space α} (μ : measure α) (f : filter α) : Prop :=
∃ s ∈ f, μ s < ∞
lemma finite_at_filter_of_finite {m0 : measurable_space α} (μ : measure α) [is_finite_measure μ]
(f : filter α) :
μ.finite_at_filter f :=
⟨univ, univ_mem, measure_lt_top μ univ⟩
lemma finite_at_filter.exists_mem_basis {f : filter α} (hμ : finite_at_filter μ f)
{p : ι → Prop} {s : ι → set α} (hf : f.has_basis p s) :
∃ i (hi : p i), μ (s i) < ∞ :=
(hf.exists_iff (λ s t hst ht, (measure_mono hst).trans_lt ht)).1 hμ
lemma finite_at_bot {m0 : measurable_space α} (μ : measure α) : μ.finite_at_filter ⊥ :=
⟨∅, mem_bot, by simp only [measure_empty, with_top.zero_lt_top]⟩
/-- `μ` has finite spanning sets in `C` if there is a countable sequence of sets in `C` that have
finite measures. This structure is a type, which is useful if we want to record extra properties
about the sets, such as that they are monotone.
`sigma_finite` is defined in terms of this: `μ` is σ-finite if there exists a sequence of
finite spanning sets in the collection of all measurable sets. -/
@[protect_proj, nolint has_inhabited_instance]
structure finite_spanning_sets_in {m0 : measurable_space α} (μ : measure α) (C : set (set α)) :=
(set : ℕ → set α)
(set_mem : ∀ i, set i ∈ C)
(finite : ∀ i, μ (set i) < ∞)
(spanning : (⋃ i, set i) = univ)
end measure
open measure
/-- A measure `μ` is called σ-finite if there is a countable collection of sets
`{ A i | i ∈ ℕ }` such that `μ (A i) < ∞` and `⋃ i, A i = s`. -/
class sigma_finite {m0 : measurable_space α} (μ : measure α) : Prop :=
(out' : nonempty (μ.finite_spanning_sets_in univ))
theorem sigma_finite_iff :
sigma_finite μ ↔ nonempty (μ.finite_spanning_sets_in univ) :=
⟨λ h, h.1, λ h, ⟨h⟩⟩
theorem sigma_finite.out (h : sigma_finite μ) :
nonempty (μ.finite_spanning_sets_in univ) := h.1
include m0
/-- If `μ` is σ-finite it has finite spanning sets in the collection of all measurable sets. -/
def measure.to_finite_spanning_sets_in (μ : measure α) [h : sigma_finite μ] :
μ.finite_spanning_sets_in {s | measurable_set s} :=
{ set := λ n, to_measurable μ (h.out.some.set n),
set_mem := λ n, measurable_set_to_measurable _ _,
finite := λ n, by { rw measure_to_measurable, exact h.out.some.finite n },
spanning := eq_univ_of_subset (Union_subset_Union $ λ n, subset_to_measurable _ _)
h.out.some.spanning }
/-- A noncomputable way to get a monotone collection of sets that span `univ` and have finite
measure using `classical.some`. This definition satisfies monotonicity in addition to all other
properties in `sigma_finite`. -/
def spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) : set α :=
accumulate μ.to_finite_spanning_sets_in.set i
lemma monotone_spanning_sets (μ : measure α) [sigma_finite μ] :
monotone (spanning_sets μ) :=
monotone_accumulate
lemma measurable_spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) :
measurable_set (spanning_sets μ i) :=
measurable_set.Union $ λ j, measurable_set.Union_Prop $
λ hij, μ.to_finite_spanning_sets_in.set_mem j
lemma measure_spanning_sets_lt_top (μ : measure α) [sigma_finite μ] (i : ℕ) :
μ (spanning_sets μ i) < ∞ :=
measure_bUnion_lt_top (finite_le_nat i) $ λ j _, (μ.to_finite_spanning_sets_in.finite j).ne
lemma Union_spanning_sets (μ : measure α) [sigma_finite μ] :
(⋃ i : ℕ, spanning_sets μ i) = univ :=
by simp_rw [spanning_sets, Union_accumulate, μ.to_finite_spanning_sets_in.spanning]
lemma is_countably_spanning_spanning_sets (μ : measure α) [sigma_finite μ] :
is_countably_spanning (range (spanning_sets μ)) :=
⟨spanning_sets μ, mem_range_self, Union_spanning_sets μ⟩
/-- `spanning_sets_index μ x` is the least `n : ℕ` such that `x ∈ spanning_sets μ n`. -/
def spanning_sets_index (μ : measure α) [sigma_finite μ] (x : α) : ℕ :=
nat.find $ Union_eq_univ_iff.1 (Union_spanning_sets μ) x
lemma measurable_spanning_sets_index (μ : measure α) [sigma_finite μ] :
measurable (spanning_sets_index μ) :=
measurable_find _ $ measurable_spanning_sets μ
lemma preimage_spanning_sets_index_singleton (μ : measure α) [sigma_finite μ] (n : ℕ) :
spanning_sets_index μ ⁻¹' {n} = disjointed (spanning_sets μ) n :=
preimage_find_eq_disjointed _ _ _
lemma spanning_sets_index_eq_iff (μ : measure α) [sigma_finite μ] {x : α} {n : ℕ} :
spanning_sets_index μ x = n ↔ x ∈ disjointed (spanning_sets μ) n :=
by convert set.ext_iff.1 (preimage_spanning_sets_index_singleton μ n) x
lemma mem_disjointed_spanning_sets_index (μ : measure α) [sigma_finite μ] (x : α) :
x ∈ disjointed (spanning_sets μ) (spanning_sets_index μ x) :=
(spanning_sets_index_eq_iff μ).1 rfl
lemma mem_spanning_sets_index (μ : measure α) [sigma_finite μ] (x : α) :
x ∈ spanning_sets μ (spanning_sets_index μ x) :=
disjointed_subset _ _ (mem_disjointed_spanning_sets_index μ x)
omit m0
namespace measure
lemma supr_restrict_spanning_sets [sigma_finite μ] (hs : measurable_set s) :
(⨆ i, μ.restrict (spanning_sets μ i) s) = μ s :=
begin
convert (restrict_Union_apply_eq_supr (measurable_spanning_sets μ) _ hs).symm,
{ simp [Union_spanning_sets] },
{ exact directed_of_sup (monotone_spanning_sets μ) }
end
namespace finite_spanning_sets_in
variables {C D : set (set α)}
/-- If `μ` has finite spanning sets in `C` and `C ∩ {s | μ s < ∞} ⊆ D` then `μ` has finite spanning
sets in `D`. -/
protected def mono' (h : μ.finite_spanning_sets_in C) (hC : C ∩ {s | μ s < ∞} ⊆ D) :
μ.finite_spanning_sets_in D :=
⟨h.set, λ i, hC ⟨h.set_mem i, h.finite i⟩, h.finite, h.spanning⟩
/-- If `μ` has finite spanning sets in `C` and `C ⊆ D` then `μ` has finite spanning sets in `D`. -/
protected def mono (h : μ.finite_spanning_sets_in C) (hC : C ⊆ D) : μ.finite_spanning_sets_in D :=
h.mono' (λ s hs, hC hs.1)
/-- If `μ` has finite spanning sets in the collection of measurable sets `C`, then `μ` is σ-finite.
-/
protected lemma sigma_finite (h : μ.finite_spanning_sets_in C) :
sigma_finite μ :=
⟨⟨h.mono $ subset_univ C⟩⟩
/-- An extensionality for measures. It is `ext_of_generate_from_of_Union` formulated in terms of
`finite_spanning_sets_in`. -/
protected lemma ext {ν : measure α} {C : set (set α)} (hA : ‹_› = generate_from C)
(hC : is_pi_system C) (h : μ.finite_spanning_sets_in C) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν :=
ext_of_generate_from_of_Union C _ hA hC h.spanning h.set_mem (λ i, (h.finite i).ne) h_eq
protected lemma is_countably_spanning (h : μ.finite_spanning_sets_in C) : is_countably_spanning C :=
⟨h.set, h.set_mem, h.spanning⟩
end finite_spanning_sets_in
lemma sigma_finite_of_countable {S : set (set α)} (hc : countable S)
(hμ : ∀ s ∈ S, μ s < ∞) (hU : ⋃₀ S = univ) :
sigma_finite μ :=
begin
obtain ⟨s, hμ, hs⟩ : ∃ s : ℕ → set α, (∀ n, μ (s n) < ∞) ∧ (⋃ n, s n) = univ,
from (exists_seq_cover_iff_countable ⟨∅, by simp⟩).2 ⟨S, hc, hμ, hU⟩,
exact ⟨⟨⟨λ n, s n, λ n, trivial, hμ, hs⟩⟩⟩,
end
/-- Given measures `μ`, `ν` where `ν ≤ μ`, `finite_spanning_sets_in.of_le` provides the induced
`finite_spanning_set` with respect to `ν` from a `finite_spanning_set` with respect to `μ`. -/
def finite_spanning_sets_in.of_le (h : ν ≤ μ) {C : set (set α)}
(S : μ.finite_spanning_sets_in C) : ν.finite_spanning_sets_in C :=
{ set := S.set,
set_mem := S.set_mem,
finite := λ n, lt_of_le_of_lt (le_iff'.1 h _) (S.finite n),
spanning := S.spanning }
lemma sigma_finite_of_le (μ : measure α) [hs : sigma_finite μ]
(h : ν ≤ μ) : sigma_finite ν :=
⟨hs.out.map $ finite_spanning_sets_in.of_le h⟩
end measure
include m0
/-- Every finite measure is σ-finite. -/
@[priority 100]
instance is_finite_measure.to_sigma_finite (μ : measure α) [is_finite_measure μ] :
sigma_finite μ :=
⟨⟨⟨λ _, univ, λ _, trivial, λ _, measure_lt_top μ _, Union_const _⟩⟩⟩
instance restrict.sigma_finite (μ : measure α) [sigma_finite μ] (s : set α) :
sigma_finite (μ.restrict s) :=
begin
refine ⟨⟨⟨spanning_sets μ, λ _, trivial, λ i, _, Union_spanning_sets μ⟩⟩⟩,
rw [restrict_apply (measurable_spanning_sets μ i)],
exact (measure_mono $ inter_subset_left _ _).trans_lt (measure_spanning_sets_lt_top μ i)
end
instance sum.sigma_finite {ι} [fintype ι] (μ : ι → measure α) [∀ i, sigma_finite (μ i)] :
sigma_finite (sum μ) :=
begin
haveI : encodable ι := fintype.encodable ι,
have : ∀ n, measurable_set (⋂ (i : ι), spanning_sets (μ i) n) :=
λ n, measurable_set.Inter (λ i, measurable_spanning_sets (μ i) n),
refine ⟨⟨⟨λ n, ⋂ i, spanning_sets (μ i) n, λ _, trivial, λ n, _, _⟩⟩⟩,
{ rw [sum_apply _ (this n), tsum_fintype, ennreal.sum_lt_top_iff],
rintro i -,
exact (measure_mono $ Inter_subset _ i).trans_lt (measure_spanning_sets_lt_top (μ i) n) },
{ rw [Union_Inter_of_monotone], simp_rw [Union_spanning_sets, Inter_univ],
exact λ i, monotone_spanning_sets (μ i), }
end
instance add.sigma_finite (μ ν : measure α) [sigma_finite μ] [sigma_finite ν] :
sigma_finite (μ + ν) :=
by { rw [← sum_cond], refine @sum.sigma_finite _ _ _ _ _ (bool.rec _ _); simpa }
lemma sigma_finite.of_map (μ : measure α) {f : α → β} (hf : measurable f)
(h : sigma_finite (map f μ)) :
sigma_finite μ :=
⟨⟨⟨λ n, f ⁻¹' (spanning_sets (map f μ) n),
λ n, trivial,
λ n, by simp only [← map_apply hf, measurable_spanning_sets, measure_spanning_sets_lt_top],
by rw [← preimage_Union, Union_spanning_sets, preimage_univ]⟩⟩⟩
/-- A measure is called locally finite if it is finite in some neighborhood of each point. -/
class is_locally_finite_measure [topological_space α] (μ : measure α) : Prop :=
(finite_at_nhds : ∀ x, μ.finite_at_filter (𝓝 x))
@[priority 100] -- see Note [lower instance priority]
instance is_finite_measure.to_is_locally_finite_measure [topological_space α] (μ : measure α)
[is_finite_measure μ] :
is_locally_finite_measure μ :=
⟨λ x, finite_at_filter_of_finite _ _⟩
lemma measure.finite_at_nhds [topological_space α] (μ : measure α)
[is_locally_finite_measure μ] (x : α) :
μ.finite_at_filter (𝓝 x) :=
is_locally_finite_measure.finite_at_nhds x
lemma measure.smul_finite (μ : measure α) [is_finite_measure μ] {c : ℝ≥0∞} (hc : c ≠ ∞) :
is_finite_measure (c • μ) :=
begin
lift c to ℝ≥0 using hc,
exact measure_theory.is_finite_measure_smul_nnreal,
end
lemma measure.exists_is_open_measure_lt_top [topological_space α] (μ : measure α)
[is_locally_finite_measure μ] (x : α) :
∃ s : set α, x ∈ s ∧ is_open s ∧ μ s < ∞ :=
by simpa only [exists_prop, and.assoc]
using (μ.finite_at_nhds x).exists_mem_basis (nhds_basis_opens x)
omit m0
@[priority 100] -- see Note [lower instance priority]
instance sigma_finite_of_locally_finite [topological_space α]
[topological_space.second_countable_topology α] [is_locally_finite_measure μ] :
sigma_finite μ :=
begin
choose s hsx hsμ using μ.finite_at_nhds,
rcases topological_space.countable_cover_nhds hsx with ⟨t, htc, htU⟩,
refine measure.sigma_finite_of_countable (htc.image s) (ball_image_iff.2 $ λ x hx, hsμ x) _,
rwa sUnion_image
end
/-- If two finite measures give the same mass to the whole space and coincide on a π-system made
of measurable sets, then they coincide on all sets in the σ-algebra generated by the π-system. -/
lemma ext_on_measurable_space_of_generate_finite {α} (m₀ : measurable_space α)
{μ ν : measure α} [is_finite_measure μ]
(C : set (set α)) (hμν : ∀ s ∈ C, μ s = ν s) {m : measurable_space α}
(h : m ≤ m₀) (hA : m = measurable_space.generate_from C) (hC : is_pi_system C)
(h_univ : μ set.univ = ν set.univ) {s : set α} (hs : m.measurable_set' s) :
μ s = ν s :=
begin
haveI : is_finite_measure ν := begin
constructor,
rw ← h_univ,
apply is_finite_measure.measure_univ_lt_top,
end,
refine induction_on_inter hA hC (by simp) hμν _ _ hs,
{ intros t h1t h2t,
have h1t_ : @measurable_set α m₀ t, from h _ h1t,
rw [@measure_compl α m₀ μ t h1t_ (@measure_ne_top α m₀ μ _ t),
@measure_compl α m₀ ν t h1t_ (@measure_ne_top α m₀ ν _ t), h_univ, h2t], },
{ intros f h1f h2f h3f,
have h2f_ : ∀ (i : ℕ), @measurable_set α m₀ (f i), from (λ i, h _ (h2f i)),
have h_Union : @measurable_set α m₀ (⋃ (i : ℕ), f i),from @measurable_set.Union α ℕ m₀ _ f h2f_,
simp [measure_Union, h_Union, h1f, h3f, h2f_], },
end
/-- Two finite measures are equal if they are equal on the π-system generating the σ-algebra
(and `univ`). -/
lemma ext_of_generate_finite (C : set (set α)) (hA : m0 = generate_from C) (hC : is_pi_system C)
[is_finite_measure μ] (hμν : ∀ s ∈ C, μ s = ν s) (h_univ : μ univ = ν univ) :
μ = ν :=
measure.ext (λ s hs, ext_on_measurable_space_of_generate_finite m0 C hμν le_rfl hA hC h_univ hs)
namespace measure
section disjointed
include m0
/-- Given `S : μ.finite_spanning_sets_in {s | measurable_set s}`,
`finite_spanning_sets_in.disjointed` provides a `finite_spanning_sets_in {s | measurable_set s}`
such that its underlying sets are pairwise disjoint. -/
protected def finite_spanning_sets_in.disjointed {μ : measure α}
(S : μ.finite_spanning_sets_in {s | measurable_set s}) :
μ.finite_spanning_sets_in {s | measurable_set s} :=
⟨disjointed S.set, measurable_set.disjointed S.set_mem,
λ n, lt_of_le_of_lt (measure_mono (disjointed_subset S.set n)) (S.finite _),
S.spanning ▸ Union_disjointed⟩
lemma finite_spanning_sets_in.disjointed_set_eq {μ : measure α}
(S : μ.finite_spanning_sets_in {s | measurable_set s}) :
S.disjointed.set = disjointed S.set :=
rfl
lemma exists_eq_disjoint_finite_spanning_sets_in
(μ ν : measure α) [sigma_finite μ] [sigma_finite ν] :
∃ (S : μ.finite_spanning_sets_in {s | measurable_set s})
(T : ν.finite_spanning_sets_in {s | measurable_set s}),
S.set = T.set ∧ pairwise (disjoint on S.set) :=
let S := (μ + ν).to_finite_spanning_sets_in.disjointed in
⟨S.of_le (measure.le_add_right le_rfl), S.of_le (measure.le_add_left le_rfl),
rfl, disjoint_disjointed _⟩
end disjointed
namespace finite_at_filter
variables {f g : filter α}
lemma filter_mono (h : f ≤ g) : μ.finite_at_filter g → μ.finite_at_filter f :=
λ ⟨s, hs, hμ⟩, ⟨s, h hs, hμ⟩
lemma inf_of_left (h : μ.finite_at_filter f) : μ.finite_at_filter (f ⊓ g) :=
h.filter_mono inf_le_left
lemma inf_of_right (h : μ.finite_at_filter g) : μ.finite_at_filter (f ⊓ g) :=
h.filter_mono inf_le_right
@[simp] lemma inf_ae_iff : μ.finite_at_filter (f ⊓ μ.ae) ↔ μ.finite_at_filter f :=
begin
refine ⟨_, λ h, h.filter_mono inf_le_left⟩,
rintros ⟨s, ⟨t, ht, u, hu, rfl⟩, hμ⟩,
suffices : μ t ≤ μ (t ∩ u), from ⟨t, ht, this.trans_lt hμ⟩,
exact measure_mono_ae (mem_of_superset hu (λ x hu ht, ⟨ht, hu⟩))
end
alias inf_ae_iff ↔ measure_theory.measure.finite_at_filter.of_inf_ae _
lemma filter_mono_ae (h : f ⊓ μ.ae ≤ g) (hg : μ.finite_at_filter g) : μ.finite_at_filter f :=
inf_ae_iff.1 (hg.filter_mono h)
protected lemma measure_mono (h : μ ≤ ν) : ν.finite_at_filter f → μ.finite_at_filter f :=
λ ⟨s, hs, hν⟩, ⟨s, hs, (measure.le_iff'.1 h s).trans_lt hν⟩
@[mono] protected lemma mono (hf : f ≤ g) (hμ : μ ≤ ν) :
ν.finite_at_filter g → μ.finite_at_filter f :=
λ h, (h.filter_mono hf).measure_mono hμ
protected lemma eventually (h : μ.finite_at_filter f) : ∀ᶠ s in f.lift' powerset, μ s < ∞ :=
(eventually_lift'_powerset' $ λ s t hst ht, (measure_mono hst).trans_lt ht).2 h
lemma filter_sup : μ.finite_at_filter f → μ.finite_at_filter g → μ.finite_at_filter (f ⊔ g) :=
λ ⟨s, hsf, hsμ⟩ ⟨t, htg, htμ⟩,
⟨s ∪ t, union_mem_sup hsf htg, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hsμ, htμ⟩)⟩
end finite_at_filter
lemma finite_at_nhds_within [topological_space α] {m0 : measurable_space α} (μ : measure α)
[is_locally_finite_measure μ] (x : α) (s : set α) :
μ.finite_at_filter (𝓝[s] x) :=
(finite_at_nhds μ x).inf_of_left
@[simp] lemma finite_at_principal : μ.finite_at_filter (𝓟 s) ↔ μ s < ∞ :=
⟨λ ⟨t, ht, hμ⟩, (measure_mono ht).trans_lt hμ, λ h, ⟨s, mem_principal_self s, h⟩⟩
/-! ### Subtraction of measures -/
/-- The measure `μ - ν` is defined to be the least measure `τ` such that `μ ≤ τ + ν`.
It is the equivalent of `(μ - ν) ⊔ 0` if `μ` and `ν` were signed measures.
Compare with `ennreal.has_sub`.
Specifically, note that if you have `α = {1,2}`, and `μ {1} = 2`, `μ {2} = 0`, and
`ν {2} = 2`, `ν {1} = 0`, then `(μ - ν) {1, 2} = 2`. However, if `μ ≤ ν`, and
`ν univ ≠ ∞`, then `(μ - ν) + ν = μ`. -/
noncomputable instance has_sub {α : Type*} [measurable_space α] : has_sub (measure α) :=
⟨λ μ ν, Inf {τ | μ ≤ τ + ν} ⟩
section measure_sub
lemma sub_def : μ - ν = Inf {d | μ ≤ d + ν} := rfl
lemma sub_eq_zero_of_le (h : μ ≤ ν) : μ - ν = 0 :=
begin
rw [← nonpos_iff_eq_zero', measure.sub_def],
apply @Inf_le (measure α) _ _,
simp [h],
end
/-- This application lemma only works in special circumstances. Given knowledge of
when `μ ≤ ν` and `ν ≤ μ`, a more general application lemma can be written. -/
lemma sub_apply [is_finite_measure ν] (h₁ : measurable_set s) (h₂ : ν ≤ μ) :
(μ - ν) s = μ s - ν s :=
begin
-- We begin by defining `measure_sub`, which will be equal to `(μ - ν)`.
let measure_sub : measure α := @measure_theory.measure.of_measurable α _
(λ (t : set α) (h_t_measurable_set : measurable_set t), (μ t - ν t))
begin
simp
end
begin
intros g h_meas h_disj, simp only, rw ennreal.tsum_sub,
repeat { rw ← measure_theory.measure_Union h_disj h_meas },
exacts [measure_theory.measure_ne_top _ _, λ i, h₂ _ (h_meas _)]
end,
-- Now, we demonstrate `μ - ν = measure_sub`, and apply it.
begin
have h_measure_sub_add : (ν + measure_sub = μ),
{ ext t h_t_measurable_set,
simp only [pi.add_apply, coe_add],
rw [measure_theory.measure.of_measurable_apply _ h_t_measurable_set, add_comm,
ennreal.sub_add_cancel_of_le (h₂ t h_t_measurable_set)] },
have h_measure_sub_eq : (μ - ν) = measure_sub,
{ rw measure_theory.measure.sub_def, apply le_antisymm,
{ apply @Inf_le (measure α) measure.complete_semilattice_Inf,
simp [le_refl, add_comm, h_measure_sub_add] },
apply @le_Inf (measure α) measure.complete_semilattice_Inf,
intros d h_d, rw [← h_measure_sub_add, mem_set_of_eq, add_comm d] at h_d,
apply measure.le_of_add_le_add_left h_d },
rw h_measure_sub_eq,
apply measure.of_measurable_apply _ h₁,
end
end
lemma sub_add_cancel_of_le [is_finite_measure ν] (h₁ : ν ≤ μ) : μ - ν + ν = μ :=
begin
ext s h_s_meas,
rw [add_apply, sub_apply h_s_meas h₁, ennreal.sub_add_cancel_of_le (h₁ s h_s_meas)],
end
lemma sub_le : μ - ν ≤ μ :=
Inf_le (measure.le_add_right (le_refl _))
end measure_sub
lemma restrict_sub_eq_restrict_sub_restrict (h_meas_s : measurable_set s) :
(μ - ν).restrict s = (μ.restrict s) - (ν.restrict s) :=
begin
repeat {rw sub_def},
have h_nonempty : {d | μ ≤ d + ν}.nonempty,
{ apply @set.nonempty_of_mem _ _ μ, rw mem_set_of_eq, intros t h_meas,
exact le_self_add },
rw restrict_Inf_eq_Inf_restrict h_nonempty h_meas_s,
apply le_antisymm,
{ apply @Inf_le_Inf_of_forall_exists_le (measure α) _,
intros ν' h_ν'_in, rw mem_set_of_eq at h_ν'_in, apply exists.intro (ν'.restrict s),
split,
{ rw mem_image, apply exists.intro (ν' + (⊤ : measure_theory.measure α).restrict sᶜ),
rw mem_set_of_eq,
split,
{ rw [add_assoc, add_comm _ ν, ← add_assoc, measure_theory.measure.le_iff],
intros t h_meas_t,
have h_inter_inter_eq_inter : ∀ t' : set α , t ∩ t' ∩ t' = t ∩ t',
{ intro t', rw set.inter_eq_self_of_subset_left, apply set.inter_subset_right t t' },
have h_meas_t_inter_s : measurable_set (t ∩ s) :=
h_meas_t.inter h_meas_s,
repeat {rw measure_eq_inter_diff h_meas_t h_meas_s, rw set.diff_eq},
refine add_le_add _ _,
{ rw add_apply,
apply le_add_right _,
rw add_apply,
rw ← @restrict_eq_self _ _ μ s _ h_meas_t_inter_s (set.inter_subset_right _ _),
rw ← @restrict_eq_self _ _ ν s _ h_meas_t_inter_s (set.inter_subset_right _ _),
apply h_ν'_in _ h_meas_t_inter_s },
cases (@set.eq_empty_or_nonempty _ (t ∩ sᶜ)) with h_inter_empty h_inter_nonempty,
{ simp [h_inter_empty] },
{ rw add_apply,
have h_meas_inter_compl :=
h_meas_t.inter (measurable_set.compl h_meas_s),
rw [restrict_apply h_meas_inter_compl, h_inter_inter_eq_inter sᶜ],
have h_mu_le_add_top : μ ≤ ν' + ν + ⊤,
{ rw add_comm,
have h_le_top : μ ≤ ⊤ := le_top,
apply (λ t₂ h_meas, le_add_right (h_le_top t₂ h_meas)) },
apply h_mu_le_add_top _ h_meas_inter_compl } },
{ ext1 t h_meas_t,
simp [restrict_apply h_meas_t,
restrict_apply (h_meas_t.inter h_meas_s),
set.inter_assoc] } },
{ apply restrict_le_self } },
{ apply @Inf_le_Inf_of_forall_exists_le (measure α) _,
intros s h_s_in, cases h_s_in with t h_t, cases h_t with h_t_in h_t_eq, subst s,
apply exists.intro (t.restrict s), split,
{ rw [set.mem_set_of_eq, ← restrict_add],
apply restrict_mono (set.subset.refl _) h_t_in },
{ apply le_refl _ } },
end
lemma sub_apply_eq_zero_of_restrict_le_restrict
(h_le : μ.restrict s ≤ ν.restrict s) (h_meas_s : measurable_set s) :
(μ - ν) s = 0 :=
begin
rw [← restrict_apply_self _ h_meas_s, restrict_sub_eq_restrict_sub_restrict,
sub_eq_zero_of_le],
repeat {simp [*]},
end
instance is_finite_measure_sub [is_finite_measure μ] : is_finite_measure (μ - ν) :=
{ measure_univ_lt_top := lt_of_le_of_lt
(measure.sub_le set.univ measurable_set.univ) (measure_lt_top _ _) }
end measure
end measure_theory
open measure_theory measure_theory.measure
namespace measurable_equiv
/-! Interactions of measurable equivalences and measures -/
open equiv measure_theory.measure
variables [measurable_space α] [measurable_space β] {μ : measure α} {ν : measure β}
/-- If we map a measure along a measurable equivalence, we can compute the measure on all sets
(not just the measurable ones). -/
protected theorem map_apply (f : α ≃ᵐ β) (s : set β) : map f μ s = μ (f ⁻¹' s) :=
begin
refine le_antisymm _ (le_map_apply f.measurable s),
rw [measure_eq_infi' μ],
refine le_infi _, rintro ⟨t, hst, ht⟩,
rw [subtype.coe_mk],
have : f.symm '' s = f ⁻¹' s := f.symm.to_equiv.image_eq_preimage s,
rw [← this, image_subset_iff] at hst,
convert measure_mono hst,
rw [map_apply, preimage_preimage],
{ refine congr_arg μ (eq.symm _), convert preimage_id, exact funext f.left_inv },
exacts [f.measurable, f.measurable_inv_fun ht]
end
@[simp] lemma map_symm_map (e : α ≃ᵐ β) : map e.symm (map e μ) = μ :=
by simp [map_map e.symm.measurable e.measurable]
@[simp] lemma map_map_symm (e : α ≃ᵐ β) : map e (map e.symm ν) = ν :=
by simp [map_map e.measurable e.symm.measurable]
lemma map_measurable_equiv_injective (e : α ≃ᵐ β) : injective (map e) :=
by { intros μ₁ μ₂ hμ, apply_fun map e.symm at hμ, simpa [map_symm_map e] using hμ }
lemma map_apply_eq_iff_map_symm_apply_eq (e : α ≃ᵐ β) : map e μ = ν ↔ map e.symm ν = μ :=
by rw [← (map_measurable_equiv_injective e).eq_iff, map_map_symm, eq_comm]
lemma restrict_map (e : α ≃ᵐ β) (s : set β) : (map e μ).restrict s = map e (μ.restrict $ e ⁻¹' s) :=
measure.ext $ λ t ht, by simp [e.map_apply, ht, e.measurable ht]
end measurable_equiv
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_theory.measure.is_complete {_ : measurable_space α} (μ : measure α) : Prop :=
(out' : ∀ s, μ s = 0 → measurable_set s)
theorem measure_theory.measure.is_complete_iff {_ : measurable_space α} {μ : measure α} :
μ.is_complete ↔ ∀ s, μ s = 0 → measurable_set s := ⟨λ h, h.1, λ h, ⟨h⟩⟩
theorem measure_theory.measure.is_complete.out {_ : measurable_space α} {μ : measure α}
(h : μ.is_complete) : ∀ s, μ s = 0 → measurable_set s := h.1
variables [measurable_space α] {μ : measure α} {s t z : set α}
/-- A set is null measurable if it is the union of a null set and a measurable set. -/
def null_measurable_set (μ : measure α) (s : set α) : Prop :=
∃ t z, s = t ∪ z ∧ measurable_set t ∧ μ z = 0
theorem null_measurable_set_iff : null_measurable_set μ s ↔
∃ t, t ⊆ s ∧ measurable_set t ∧ μ (s \ t) = 0 :=
begin
split,
{ rintro ⟨t, z, rfl, ht, hz⟩,
refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩,
simp [union_diff_left, diff_subset] },
{ rintro ⟨t, st, ht, hz⟩,
exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ }
end
theorem null_measurable_set_measure_eq (st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t :=
begin
refine le_antisymm _ (measure_mono st),
have := measure_union_le t (s \ t),
rw [union_diff_cancel st, hz] at this, simpa
end
theorem measurable_set.null_measurable_set (μ : measure α) (hs : measurable_set s) :
null_measurable_set μ s :=
⟨s, ∅, by simp, hs, μ.empty⟩
theorem null_measurable_set_of_complete (μ : measure α) [c : μ.is_complete] :
null_measurable_set μ s ↔ measurable_set s :=
⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact
measurable_set.union ht (c.out _ hz),
λ h, h.null_measurable_set _⟩
theorem null_measurable_set.union_null (hs : null_measurable_set μ s) (hz : μ z = 0) :
null_measurable_set μ (s ∪ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, nonpos_iff_eq_zero.1
(le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩
end
theorem null_null_measurable_set (hz : μ z = 0) : null_measurable_set μ z :=
by simpa using (measurable_set.empty.null_measurable_set _).union_null hz
theorem null_measurable_set.Union_nat {s : ℕ → set α} (hs : ∀ i, null_measurable_set μ (s i)) :
null_measurable_set μ (Union s) :=
begin
choose t ht using assume i, null_measurable_set_iff.1 (hs i),
simp [forall_and_distrib] at ht,
rcases ht with ⟨st, ht, hz⟩,
refine null_measurable_set_iff.2
⟨Union t, Union_subset_Union st, measurable_set.Union ht,
measure_mono_null _ (measure_Union_null hz)⟩,
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff)
end
theorem measurable_set.diff_null (hs : measurable_set s) (hz : μ z = 0) :
null_measurable_set μ (s \ z) :=
begin
rw measure_eq_infi at hz,
choose f hf using show ∀ q : {q : ℚ // q > 0}, ∃ t : set α,
z ⊆ t ∧ measurable_set t ∧ μ t < (real.to_nnreal q.1 : ℝ≥0∞),
{ rintro ⟨ε, ε0⟩,
have : 0 < (real.to_nnreal ε : ℝ≥0∞), { simpa using ε0 },
rw ← hz at this, simpa [infi_lt_iff] },
refine null_measurable_set_iff.2 ⟨s \ Inter f,
diff_subset_diff_right (subset_Inter (λ i, (hf i).1)),
hs.diff (measurable_set.Inter (λ i, (hf i).2.1)),
measure_mono_null _ (nonpos_iff_eq_zero.1 $ le_of_not_lt $ λ h, _)⟩,
{ exact Inter f },
{ rw [diff_subset_iff, diff_union_self],
exact subset.trans (diff_subset _ _) (subset_union_left _ _) },
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩,
simp at ε0,
apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h),
exact measure_mono (Inter_subset _ _)
end
theorem null_measurable_set.diff_null (hs : null_measurable_set μ s) (hz : μ z = 0) :
null_measurable_set μ (s \ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
rw [set.union_diff_distrib],
exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz')
end
theorem null_measurable_set.compl (hs : null_measurable_set μ s) : null_measurable_set μ sᶜ :=
begin
rcases hs with ⟨t, z, rfl, ht, hz⟩,
rw compl_union,
exact ht.compl.diff_null hz
end
theorem null_measurable_set_iff_ae {s : set α} :
null_measurable_set μ s ↔ ∃ t, measurable_set t ∧ s =ᵐ[μ] t :=
begin
simp only [ae_eq_set],
split,
{ assume h,
rcases null_measurable_set_iff.1 h with ⟨t, ts, tmeas, ht⟩,
refine ⟨t, tmeas, ht, _⟩,
rw [diff_eq_empty.2 ts, measure_empty] },
{ rintros ⟨t, tmeas, h₁, h₂⟩,
have : null_measurable_set μ (t ∪ (s \ t)) :=
null_measurable_set.union_null (tmeas.null_measurable_set _) h₁,
have A : null_measurable_set μ ((t ∪ (s \ t)) \ (t \ s)) :=
null_measurable_set.diff_null this h₂,
have : (t ∪ (s \ t)) \ (t \ s) = s,
{ apply subset.antisymm,
{ assume x hx,
simp only [mem_union_eq, not_and, mem_diff, not_not_mem] at hx,
cases hx.1, { exact hx.2 h }, { exact h.1 } },
{ assume x hx,
simp [hx, classical.em (x ∈ t)] } },
rwa this at A }
end
theorem null_measurable_set_iff_sandwich {s : set α} :
null_measurable_set μ s ↔
∃ (t u : set α), measurable_set t ∧ measurable_set u ∧ t ⊆ s ∧ s ⊆ u ∧ μ (u \ t) = 0 :=
begin
split,
{ assume h,
rcases null_measurable_set_iff.1 h with ⟨t, ts, tmeas, ht⟩,
rcases null_measurable_set_iff.1 h.compl with ⟨u', u's, u'meas, hu'⟩,
have A : s ⊆ u'ᶜ := subset_compl_comm.mp u's,
refine ⟨t, u'ᶜ, tmeas, u'meas.compl, ts, A, _⟩,
have : sᶜ \ u' = u'ᶜ \ s, by simp [compl_eq_univ_diff, diff_diff, union_comm],
rw this at hu',
apply le_antisymm _ bot_le,
calc μ (u'ᶜ \ t) ≤ μ ((u'ᶜ \ s) ∪ (s \ t)) :
begin
apply measure_mono,
assume x hx,
simp at hx,
simp [hx, or_comm, classical.em],
end
... ≤ μ (u'ᶜ \ s) + μ (s \ t) : measure_union_le _ _
... = 0 : by rw [ht, hu', zero_add] },
{ rintros ⟨t, u, tmeas, umeas, ts, su, hμ⟩,
refine null_measurable_set_iff.2 ⟨t, ts, tmeas, _⟩,
apply le_antisymm _ bot_le,
calc μ (s \ t) ≤ μ (u \ t) : measure_mono (diff_subset_diff_left su)
... = 0 : hμ }
end
lemma restrict_apply_of_null_measurable_set {s t : set α}
(ht : null_measurable_set (μ.restrict s) t) : μ.restrict s t = μ (t ∩ s) :=
begin
rcases null_measurable_set_iff_sandwich.1 ht with ⟨u, v, umeas, vmeas, ut, tv, huv⟩,
apply le_antisymm _ (le_restrict_apply _ _),
calc μ.restrict s t ≤ μ.restrict s v : measure_mono tv
... = μ (v ∩ s) : restrict_apply vmeas
... ≤ μ ((u ∩ s) ∪ ((v \ u) ∩ s)) : measure_mono $
by { assume x hx, simp at hx, simp [hx, classical.em] }
... ≤ μ (u ∩ s) + μ ((v \ u) ∩ s) : measure_union_le _ _
... = μ (u ∩ s) + μ.restrict s (v \ u) : by rw measure.restrict_apply (vmeas.diff umeas)
... = μ (u ∩ s) : by rw [huv, add_zero]
... ≤ μ (t ∩ s) : measure_mono $ inter_subset_inter_left s ut
end
/-- The measurable space of all null measurable sets. -/
def null_measurable (μ : measure α) : measurable_space α :=
{ measurable_set' := null_measurable_set μ,
measurable_set_empty := measurable_set.empty.null_measurable_set _,
measurable_set_compl := λ s hs, hs.compl,
measurable_set_Union := λ f, null_measurable_set.Union_nat }
/-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/
def completion (μ : measure α) : @measure_theory.measure α (null_measurable μ) :=
{ to_outer_measure := μ.to_outer_measure,
m_Union := λ s hs hd, show μ (Union s) = ∑' i, μ (s i), begin
choose t ht using assume i, null_measurable_set_iff.1 (hs i),
simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩,
rw null_measurable_set_measure_eq (Union_subset_Union st),
{ rw measure_Union _ ht,
{ congr, funext i,
exact (null_measurable_set_measure_eq (st i) (hz i)).symm },
{ rintro i j ij x ⟨h₁, h₂⟩,
exact hd i j ij ⟨st i h₁, st j h₂⟩ } },
{ refine measure_mono_null _ (measure_Union_null hz),
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff) }
end,
trimmed := begin
letI := null_measurable μ,
refine le_antisymm (λ s, _) (outer_measure.le_trim _),
rw outer_measure.trim_eq_infi,
dsimp,
clear _inst,
resetI,
rw measure_eq_infi s,
exact infi_le_infi (λ t, infi_le_infi $ λ st,
infi_le_infi2 $ λ ht, ⟨ht.null_measurable_set _, le_refl _⟩)
end }
instance completion.is_complete (μ : measure α) : (completion μ).is_complete :=
⟨λ z hz, null_null_measurable_set hz⟩
lemma measurable.ae_eq {α β} [measurable_space α] [measurable_space β] {μ : measure α}
[hμ : μ.is_complete] {f g : α → β} (hf : measurable f) (hfg : f =ᵐ[μ] g) :
measurable g :=
begin
intros s hs,
let t := {x | f x = g x},
have ht_compl : μ tᶜ = 0, by rwa [filter.eventually_eq, ae_iff] at hfg,
rw (set.inter_union_compl (g ⁻¹' s) t).symm,
refine measurable_set.union _ _,
{ have h_g_to_f : (g ⁻¹' s) ∩ t = (f ⁻¹' s) ∩ t,
{ ext,
simp only [set.mem_inter_iff, set.mem_preimage, and.congr_left_iff, set.mem_set_of_eq],
exact λ hx, by rw hx, },
rw h_g_to_f,
exact measurable_set.inter (hf hs) (measurable_set.compl_iff.mp (hμ.out tᶜ ht_compl)), },
{ exact hμ.out (g ⁻¹' s ∩ tᶜ) (measure_mono_null (set.inter_subset_right _ _) ht_compl), },
end
end is_complete
namespace measure_theory
lemma outer_measure.to_measure_zero [measurable_space α] : (0 : outer_measure α).to_measure
((le_top).trans outer_measure.zero_caratheodory.symm.le) = 0 :=
by rw [← measure.measure_univ_eq_zero, to_measure_apply _ _ measurable_set.univ,
outer_measure.coe_zero, pi.zero_apply]
section trim
/-- Restriction of a measure to a sub-sigma algebra.
It is common to see a measure `μ` on a measurable space structure `m0` as being also a measure on
any `m ≤ m0`. Since measures in mathlib have to be trimmed to the measurable space, `μ` itself
cannot be a measure on `m`, hence the definition of `μ.trim hm`.
This notion is related to `outer_measure.trim`, see the lemma
`to_outer_measure_trim_eq_trim_to_outer_measure`. -/
def measure.trim {m m0 : measurable_space α} (μ : @measure α m0) (hm : m ≤ m0) : @measure α m :=
@outer_measure.to_measure α m μ.to_outer_measure (hm.trans (le_to_outer_measure_caratheodory μ))
@[simp] lemma trim_eq_self [measurable_space α] {μ : measure α} : μ.trim le_rfl = μ :=
by simp [measure.trim]
variables {m m0 : measurable_space α} {μ : measure α} {s : set α}
lemma to_outer_measure_trim_eq_trim_to_outer_measure (μ : measure α) (hm : m ≤ m0) :
@measure.to_outer_measure _ m (μ.trim hm) = @outer_measure.trim _ m μ.to_outer_measure :=
by rw [measure.trim, to_measure_to_outer_measure]
@[simp] lemma zero_trim (hm : m ≤ m0) : (0 : measure α).trim hm = (0 : @measure α m) :=
by simp [measure.trim, outer_measure.to_measure_zero]
lemma trim_measurable_set_eq (hm : m ≤ m0) (hs : @measurable_set α m s) : μ.trim hm s = μ s :=
by simp [measure.trim, hs]
lemma le_trim (hm : m ≤ m0) : μ s ≤ μ.trim hm s :=
by { simp_rw [measure.trim], exact (@le_to_measure_apply _ m _ _ _), }
lemma measure_eq_zero_of_trim_eq_zero (hm : m ≤ m0) (h : μ.trim hm s = 0) : μ s = 0 :=
le_antisymm ((le_trim hm).trans (le_of_eq h)) (zero_le _)
lemma measure_trim_to_measurable_eq_zero {hm : m ≤ m0} (hs : μ.trim hm s = 0) :
μ (@to_measurable α m (μ.trim hm) s) = 0 :=
measure_eq_zero_of_trim_eq_zero hm (by rwa measure_to_measurable)
lemma ae_eq_of_ae_eq_trim {E} {hm : m ≤ m0} {f₁ f₂ : α → E}
(h12 : f₁ =ᶠ[@measure.ae α m (μ.trim hm)] f₂) :
f₁ =ᵐ[μ] f₂ :=
measure_eq_zero_of_trim_eq_zero hm h12
lemma restrict_trim (hm : m ≤ m0) (μ : measure α) (hs : @measurable_set α m s) :
@measure.restrict α m (μ.trim hm) s = (μ.restrict s).trim hm :=
begin
ext1 t ht,
rw [@measure.restrict_apply α m _ _ _ ht, trim_measurable_set_eq hm ht,
measure.restrict_apply (hm t ht),
trim_measurable_set_eq hm (@measurable_set.inter α m t s ht hs)],
end
instance is_finite_measure_trim (hm : m ≤ m0) [is_finite_measure μ] :
is_finite_measure (μ.trim hm) :=
{ measure_univ_lt_top :=
by { rw trim_measurable_set_eq hm (@measurable_set.univ _ m), exact measure_lt_top _ _, } }
end trim
end measure_theory
/-!
# Almost everywhere measurable functions
A function is almost everywhere measurable if it coincides almost everywhere with a measurable
function. This property, called `ae_measurable f μ`, is defined in the file `measure_space_def`.
We discuss several of its properties that are analogous to properties of measurable functions.
-/
section
open measure_theory
variables [measurable_space α] [measurable_space β]
{f g : α → β} {μ ν : measure α}
@[nontriviality, measurability]
lemma subsingleton.ae_measurable [subsingleton α] : ae_measurable f μ :=
subsingleton.measurable.ae_measurable
@[simp, measurability] lemma ae_measurable_zero_measure : ae_measurable f (0 : measure α) :=
begin
nontriviality α, inhabit α,
exact ⟨λ x, f (default α), measurable_const, rfl⟩
end
lemma ae_measurable_iff_measurable [μ.is_complete] :
ae_measurable f μ ↔ measurable f :=
begin
split; intro h,
{ rcases h with ⟨g, hg_meas, hfg⟩,
exact hg_meas.ae_eq hfg.symm, },
{ exact h.ae_measurable, },
end
namespace ae_measurable
lemma mono_measure (h : ae_measurable f μ) (h' : ν ≤ μ) : ae_measurable f ν :=
⟨h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk⟩
lemma mono_set {s t} (h : s ⊆ t) (ht : ae_measurable f (μ.restrict t)) :
ae_measurable f (μ.restrict s) :=
ht.mono_measure (restrict_mono h le_rfl)
protected lemma mono' (h : ae_measurable f μ) (h' : ν ≪ μ) : ae_measurable f ν :=
⟨h.mk f, h.measurable_mk, h' h.ae_eq_mk⟩
lemma ae_mem_imp_eq_mk {s} (h : ae_measurable f (μ.restrict s)) :
∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x :=
ae_imp_of_ae_restrict h.ae_eq_mk
lemma ae_inf_principal_eq_mk {s} (h : ae_measurable f (μ.restrict s)) :
f =ᶠ[μ.ae ⊓ 𝓟 s] h.mk f :=
le_ae_restrict h.ae_eq_mk
@[measurability]
lemma add_measure {f : α → β} (hμ : ae_measurable f μ) (hν : ae_measurable f ν) :
ae_measurable f (μ + ν) :=
begin
let s := {x | f x ≠ hμ.mk f x},
have : μ s = 0 := hμ.ae_eq_mk,
obtain ⟨t, st, t_meas, μt⟩ : ∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = 0 :=
exists_measurable_superset_of_null this,
let g : α → β := t.piecewise (hν.mk f) (hμ.mk f),
refine ⟨g, measurable.piecewise t_meas hν.measurable_mk hμ.measurable_mk, _⟩,
change μ {x | f x ≠ g x} + ν {x | f x ≠ g x} = 0,
suffices : μ {x | f x ≠ g x} = 0 ∧ ν {x | f x ≠ g x} = 0, by simp [this.1, this.2],
have ht : {x | f x ≠ g x} ⊆ t,
{ assume x hx,
by_contra h,
simp only [g, h, mem_set_of_eq, ne.def, not_false_iff, piecewise_eq_of_not_mem] at hx,
exact h (st hx) },
split,
{ have : μ {x | f x ≠ g x} ≤ μ t := measure_mono ht,
rw μt at this,
exact le_antisymm this bot_le },
{ have : {x | f x ≠ g x} ⊆ {x | f x ≠ hν.mk f x},
{ assume x hx,
simpa [ht hx, g] using hx },
apply le_antisymm _ bot_le,
calc ν {x | f x ≠ g x} ≤ ν {x | f x ≠ hν.mk f x} : measure_mono this
... = 0 : hν.ae_eq_mk }
end
@[measurability]
lemma smul_measure (h : ae_measurable f μ) (c : ℝ≥0∞) :
ae_measurable f (c • μ) :=
⟨h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c⟩
lemma comp_measurable [measurable_space δ] {f : α → δ} {g : δ → β}
(hg : ae_measurable g (map f μ)) (hf : measurable f) : ae_measurable (g ∘ f) μ :=
⟨hg.mk g ∘ f, hg.measurable_mk.comp hf, ae_eq_comp hf hg.ae_eq_mk⟩
lemma comp_measurable' {δ} [measurable_space δ] {ν : measure δ} {f : α → δ} {g : δ → β}
(hg : ae_measurable g ν) (hf : measurable f) (h : map f μ ≪ ν) : ae_measurable (g ∘ f) μ :=
(hg.mono' h).comp_measurable hf
@[measurability]
lemma prod_mk {γ : Type*} [measurable_space γ] {f : α → β} {g : α → γ}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, (f x, g x)) μ :=
⟨λ a, (hf.mk f a, hg.mk g a), hf.measurable_mk.prod_mk hg.measurable_mk,
eventually_eq.prod_mk hf.ae_eq_mk hg.ae_eq_mk⟩
protected lemma null_measurable_set (h : ae_measurable f μ) {s : set β} (hs : measurable_set s) :
null_measurable_set μ (f ⁻¹' s) :=
begin
apply null_measurable_set_iff_ae.2,
refine ⟨(h.mk f) ⁻¹' s, h.measurable_mk hs, _⟩,
filter_upwards [h.ae_eq_mk],
assume x hx,
change (f x ∈ s) = ((h.mk f) x ∈ s),
rwa hx
end
end ae_measurable
@[simp] lemma ae_measurable_add_measure_iff :
ae_measurable f (μ + ν) ↔ ae_measurable f μ ∧ ae_measurable f ν :=
⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)),
h.mono_measure (measure.le_add_left (le_refl _))⟩,
λ h, h.1.add_measure h.2⟩
@[simp, to_additive] lemma ae_measurable_one [has_one β] : ae_measurable (λ a : α, (1 : β)) μ :=
measurable_one.ae_measurable
@[simp] lemma ae_measurable_smul_measure_iff {c : ℝ≥0∞} (hc : c ≠ 0) :
ae_measurable f (c • μ) ↔ ae_measurable f μ :=
⟨λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk⟩,
λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk⟩⟩
lemma ae_measurable_of_ae_measurable_trim {α} {m m0 : measurable_space α}
{μ : measure α} (hm : m ≤ m0) {f : α → β} (hf : ae_measurable f (μ.trim hm)) :
ae_measurable f μ :=
⟨hf.mk f, measurable.mono hf.measurable_mk hm le_rfl, ae_eq_of_ae_eq_trim hf.ae_eq_mk⟩
lemma ae_measurable_restrict_of_measurable_subtype {s : set α}
(hs : measurable_set s) (hf : measurable (λ x : s, f x)) : ae_measurable f (μ.restrict s) :=
begin
casesI is_empty_or_nonempty β,
{ exact (measurable_of_empty_codomain f).ae_measurable },
refine ⟨s.piecewise f (λ x, classical.choice h), _, (ae_restrict_iff' hs).mpr $ ae_of_all _
(λ x hx, (piecewise_eq_of_mem s _ _ hx).symm)⟩,
intros t ht,
rw piecewise_preimage,
refine measurable_set.union _ ((measurable_const ht).diff hs),
rw [← subtype.image_preimage_coe, ← preimage_comp],
exact hs.subtype_image (hf ht)
end
lemma ae_measurable_map_equiv_iff [measurable_space γ] (e : α ≃ᵐ β) {f : β → γ} :
ae_measurable f (map e μ) ↔ ae_measurable (f ∘ e) μ :=
begin
refine ⟨λ h, h.comp_measurable e.measurable, λ h, _⟩,
rw [← (e.map_symm_map : _ = μ)] at h,
convert h.comp_measurable e.symm.measurable,
simp [(∘)]
end
end
namespace is_compact
variables [topological_space α] [measurable_space α] {μ : measure α} {s : set α}
/-- If `s` is a compact set and `μ` is finite at `𝓝 x` for every `x ∈ s`, then `s` admits an open
superset of finite measure. -/
lemma exists_open_superset_measure_lt_top' (h : is_compact s)
(hμ : ∀ x ∈ s, μ.finite_at_filter (𝓝 x)) :
∃ U ⊇ s, is_open U ∧ μ U < ∞ :=
begin
refine is_compact.induction_on h _ _ _ _,
{ use ∅, simp [superset] },
{ rintro s t hst ⟨U, htU, hUo, hU⟩, exact ⟨U, hst.trans htU, hUo, hU⟩ },
{ rintro s t ⟨U, hsU, hUo, hU⟩ ⟨V, htV, hVo, hV⟩,
refine ⟨U ∪ V, union_subset_union hsU htV, hUo.union hVo,
(measure_union_le _ _).trans_lt $ ennreal.add_lt_top.2 ⟨hU, hV⟩⟩ },
{ intros x hx,
rcases (hμ x hx).exists_mem_basis (nhds_basis_opens _) with ⟨U, ⟨hx, hUo⟩, hU⟩,
exact ⟨U, nhds_within_le_nhds (hUo.mem_nhds hx), U, subset.rfl, hUo, hU⟩ }
end
/-- If `s` is a compact set and `μ` is a locally finite measure, then `s` admits an open superset of
finite measure. -/
lemma exists_open_superset_measure_lt_top (h : is_compact s)
(μ : measure α) [is_locally_finite_measure μ] :
∃ U ⊇ s, is_open U ∧ μ U < ∞ :=
h.exists_open_superset_measure_lt_top' $ λ x hx, μ.finite_at_nhds x
lemma measure_lt_top_of_nhds_within (h : is_compact s) (hμ : ∀ x ∈ s, μ.finite_at_filter (𝓝[s] x)) :
μ s < ∞ :=
is_compact.induction_on h (by simp) (λ s t hst ht, (measure_mono hst).trans_lt ht)
(λ s t hs ht, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hs, ht⟩)) hμ
lemma measure_lt_top (h : is_compact s) {μ : measure α} [is_locally_finite_measure μ] :
μ s < ∞ :=
h.measure_lt_top_of_nhds_within $ λ x hx, μ.finite_at_nhds_within _ _
lemma measure_zero_of_nhds_within (hs : is_compact s) :
(∀ a ∈ s, ∃ t ∈ 𝓝[s] a, μ t = 0) → μ s = 0 :=
by simpa only [← compl_mem_ae_iff] using hs.compl_mem_sets_of_nhds_within
end is_compact
/-- Compact covering of a `σ`-compact topological space as
`measure_theory.measure.finite_spanning_sets_in`. -/
def measure_theory.measure.finite_spanning_sets_in_compact [topological_space α]
[sigma_compact_space α] {m : measurable_space α} (μ : measure α) [is_locally_finite_measure μ] :
μ.finite_spanning_sets_in {K | is_compact K} :=
{ set := compact_covering α,
set_mem := is_compact_compact_covering α,
finite := λ n, (is_compact_compact_covering α n).measure_lt_top,
spanning := Union_compact_covering α }
/-- A locally finite measure on a `σ`-compact topological space admits a finite spanning sequence
of open sets. -/
def measure_theory.measure.finite_spanning_sets_in_open [topological_space α]
[sigma_compact_space α] {m : measurable_space α} (μ : measure α) [is_locally_finite_measure μ] :
μ.finite_spanning_sets_in {K | is_open K} :=
{ set := λ n, ((is_compact_compact_covering α n).exists_open_superset_measure_lt_top μ).some,
set_mem := λ n,
((is_compact_compact_covering α n).exists_open_superset_measure_lt_top μ).some_spec.snd.1,
finite := λ n,
((is_compact_compact_covering α n).exists_open_superset_measure_lt_top μ).some_spec.snd.2,
spanning := eq_univ_of_subset (Union_subset_Union $ λ n,
((is_compact_compact_covering α n).exists_open_superset_measure_lt_top μ).some_spec.fst)
(Union_compact_covering α) }
section measure_Ixx
variables [conditionally_complete_linear_order α] [topological_space α] [order_topology α]
{m : measurable_space α} {μ : measure α} [is_locally_finite_measure μ] {a b : α}
lemma measure_Icc_lt_top : μ (Icc a b) < ∞ := is_compact_Icc.measure_lt_top
lemma measure_Ico_lt_top : μ (Ico a b) < ∞ :=
(measure_mono Ico_subset_Icc_self).trans_lt measure_Icc_lt_top
lemma measure_Ioc_lt_top : μ (Ioc a b) < ∞ :=
(measure_mono Ioc_subset_Icc_self).trans_lt measure_Icc_lt_top
lemma measure_Ioo_lt_top : μ (Ioo a b) < ∞ :=
(measure_mono Ioo_subset_Icc_self).trans_lt measure_Icc_lt_top
end measure_Ixx
lemma metric.bounded.measure_lt_top [metric_space α] [proper_space α]
[measurable_space α] {μ : measure α} [is_locally_finite_measure μ] {s : set α}
(hs : metric.bounded s) :
μ s < ∞ :=
(measure_mono subset_closure).trans_lt (metric.compact_iff_closed_bounded.2
⟨is_closed_closure, metric.bounded_closure_of_bounded hs⟩).measure_lt_top
section piecewise
variables [measurable_space α] {μ : measure α} {s t : set α} {f g : α → β}
lemma piecewise_ae_eq_restrict (hs : measurable_set s) : piecewise s f g =ᵐ[μ.restrict s] f :=
begin
rw [ae_restrict_eq hs],
exact (piecewise_eq_on s f g).eventually_eq.filter_mono inf_le_right
end
lemma piecewise_ae_eq_restrict_compl (hs : measurable_set s) :
piecewise s f g =ᵐ[μ.restrict sᶜ] g :=
begin
rw [ae_restrict_eq hs.compl],
exact (piecewise_eq_on_compl s f g).eventually_eq.filter_mono inf_le_right
end
lemma piecewise_ae_eq_of_ae_eq_set (hst : s =ᵐ[μ] t) : s.piecewise f g =ᵐ[μ] t.piecewise f g :=
begin
filter_upwards [hst],
intros x hx,
replace hx : x ∈ s ↔ x ∈ t := iff_of_eq hx,
by_cases h : x ∈ s; have h' := h; rw hx at h'; simp [h, h']
end
end piecewise
section indicator_function
variables [measurable_space α] {μ : measure α} {s t : set α} {f : α → β}
lemma mem_map_indicator_ae_iff_mem_map_restrict_ae_of_zero_mem [has_zero β] {t : set β}
(ht : (0 : β) ∈ t) (hs : measurable_set s) :
t ∈ filter.map (s.indicator f) μ.ae ↔ t ∈ filter.map f (μ.restrict s).ae :=
begin
simp_rw [mem_map, mem_ae_iff],
rw [measure.restrict_apply' hs, set.indicator_preimage, set.ite],
simp_rw [set.compl_union, set.compl_inter],
change μ (((f ⁻¹' t)ᶜ ∪ sᶜ) ∩ ((λ x, (0 : β)) ⁻¹' t \ s)ᶜ) = 0 ↔ μ ((f ⁻¹' t)ᶜ ∩ s) = 0,
simp only [ht, ← set.compl_eq_univ_diff, compl_compl, set.compl_union, if_true,
set.preimage_const],
simp_rw [set.union_inter_distrib_right, set.compl_inter_self s, set.union_empty],
end
lemma mem_map_indicator_ae_iff_of_zero_nmem [has_zero β] {t : set β} (ht : (0 : β) ∉ t) :
t ∈ filter.map (s.indicator f) μ.ae ↔ μ ((f ⁻¹' t)ᶜ ∪ sᶜ) = 0 :=
begin
rw [mem_map, mem_ae_iff, set.indicator_preimage, set.ite, set.compl_union, set.compl_inter],
change μ (((f ⁻¹' t)ᶜ ∪ sᶜ) ∩ ((λ x, (0 : β)) ⁻¹' t \ s)ᶜ) = 0 ↔ μ ((f ⁻¹' t)ᶜ ∪ sᶜ) = 0,
simp only [ht, if_false, set.compl_empty, set.empty_diff, set.inter_univ, set.preimage_const],
end
lemma map_restrict_ae_le_map_indicator_ae [has_zero β] (hs : measurable_set s) :
filter.map f (μ.restrict s).ae ≤ filter.map (s.indicator f) μ.ae :=
begin
intro t,
by_cases ht : (0 : β) ∈ t,
{ rw mem_map_indicator_ae_iff_mem_map_restrict_ae_of_zero_mem ht hs, exact id, },
rw [mem_map_indicator_ae_iff_of_zero_nmem ht, mem_map_restrict_ae_iff hs],
exact λ h, measure_mono_null ((set.inter_subset_left _ _).trans (set.subset_union_left _ _)) h,
end
lemma ae_measurable.restrict [measurable_space β] (hfm : ae_measurable f μ) {s} :
ae_measurable f (μ.restrict s) :=
⟨ae_measurable.mk f hfm, hfm.measurable_mk, ae_restrict_of_ae hfm.ae_eq_mk⟩
variables [has_zero β]
lemma indicator_ae_eq_restrict (hs : measurable_set s) : indicator s f =ᵐ[μ.restrict s] f :=
piecewise_ae_eq_restrict hs
lemma indicator_ae_eq_restrict_compl (hs : measurable_set s) : indicator s f =ᵐ[μ.restrict sᶜ] 0 :=
piecewise_ae_eq_restrict_compl hs
lemma indicator_ae_eq_of_ae_eq_set (hst : s =ᵐ[μ] t) : s.indicator f =ᵐ[μ] t.indicator f :=
piecewise_ae_eq_of_ae_eq_set hst
variables [measurable_space β]
lemma ae_measurable_indicator_iff {s} (hs : measurable_set s) :
ae_measurable (indicator s f) μ ↔ ae_measurable f (μ.restrict s) :=
begin
split,
{ assume h,
exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) },
{ assume h,
refine ⟨indicator s (h.mk f), h.measurable_mk.indicator hs, _⟩,
have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (ae_measurable.mk f h) :=
(indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm),
have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) :=
(indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm,
have : s.indicator f =ᵐ[μ.restrict s + μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) :=
ae_add_measure_iff.2 ⟨A, B⟩,
simpa only [hs, measure.restrict_add_restrict_compl] using this },
end
@[measurability]
lemma ae_measurable.indicator (hfm : ae_measurable f μ) {s} (hs : measurable_set s) :
ae_measurable (s.indicator f) μ :=
(ae_measurable_indicator_iff hs).mpr hfm.restrict
end indicator_function
|
66199f672c192aa0de70ba6053b0b52c9ccd38c3 | 36c7a18fd72e5b57229bd8ba36493daf536a19ce | /tests/lean/hott/len_eq.hlean | 33414d1813e6e14f9ef365079cf7de0763060a63 | [
"Apache-2.0"
] | permissive | YHVHvx/lean | 732bf0fb7a298cd7fe0f15d82f8e248c11db49e9 | 038369533e0136dd395dc252084d3c1853accbf2 | refs/heads/master | 1,610,701,080,210 | 1,449,128,595,000 | 1,449,128,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,059 | hlean | import init.ua
open nat unit equiv is_trunc
inductive vector (A : Type) : nat → Type :=
| nil {} : vector A zero
| cons : Π {n}, A → vector A n → vector A (succ n)
open vector
notation a :: b := cons a b
definition const {A : Type} : Π (n : nat), A → vector A n
| zero a := nil
| (succ n) a := a :: const n a
definition head {A : Type} : Π {n : nat}, vector A (succ n) → A
| n (x :: xs) := x
theorem singlenton_vector_unit : ∀ {n : nat} (v w : vector unit n), v = w
| zero nil nil := rfl
| (succ n) (star::xs) (star::ys) :=
begin
have h₁ : xs = ys, from singlenton_vector_unit xs ys,
rewrite h₁
end
private definition f (n m : nat) (v : vector unit n) : vector unit m := const m star
theorem vn_eqv_vm (n m : nat) : vector unit n ≃ vector unit m :=
equiv.MK (f n m) (f m n)
(take v : vector unit m, singlenton_vector_unit (f n m (f m n v)) v)
(take v : vector unit n, singlenton_vector_unit (f m n (f n m v)) v)
theorem vn_eq_vm (n m : nat) : vector unit n = vector unit m :=
ua (vn_eqv_vm n m)
definition vector_inj (A : Type) := ∀ (n m : nat), vector A n = vector A m → n = m
theorem not_vector_inj : ¬ vector_inj unit :=
assume H : vector_inj unit,
have aux₁ : 0 = 1, from H 0 1 (vn_eq_vm 0 1),
lift.down (nat.no_confusion aux₁)
definition cast {A B : Type} (H : A = B) (a : A) : B :=
eq.rec_on H a
open sigma
definition heq {A B : Type} (a : A) (b : B) :=
Σ (H : A = B), cast H a = b
infix `==`:50 := heq
definition heq.type_eq {A B : Type} {a : A} {b : B} : a == b → A = B
| ⟨H, e⟩ := H
definition heq.symm : ∀ {A B : Type} {a : A} {b : B}, a == b → b == a
| A A a a ⟨eq.refl A, eq.refl a⟩ := ⟨eq.refl A, eq.refl a⟩
definition heq.trans : ∀ {A B C : Type} {a : A} {b : B} {c : C}, a == b → b == c → a == c
| A A A a a a ⟨eq.refl A, eq.refl a⟩ ⟨eq.refl A, eq.refl a⟩ := ⟨eq.refl A, eq.refl a⟩
theorem cast_heq : ∀ {A B : Type} (H : A = B) (a : A), cast H a == a
| A A (eq.refl A) a := ⟨eq.refl A, eq.refl a⟩
definition default (A : Type) [H : inhabited A] : A :=
inhabited.rec_on H (λ a, a)
definition lem_eq (A : Type) : Type :=
∀ (n m : nat) (v : vector A n) (w : vector A m), v == w → n = m
theorem lem_eq_iff_vector_inj (A : Type) [inh : inhabited A] : lem_eq A ↔ vector_inj A :=
iff.intro
(assume Hl : lem_eq A,
assume n m he,
assert a : A, from default A,
assert v : vector A n, from const n a,
have e₁ : v == cast he v, from heq.symm (cast_heq he v),
Hl n m v (cast he v) e₁)
(assume Hr : vector_inj A,
assume n m v w he,
Hr n m (heq.type_eq he))
theorem lem_eq_of_not_inhabited (A : Type) [ninh : inhabited A → empty] : lem_eq A :=
take (n m : nat),
match n with
| zero :=
match m with
| zero := take v w He, rfl
| (succ m₁) :=
take (v : vector A zero) (w : vector A (succ m₁)),
empty.elim (ninh (inhabited.mk (head w)))
end
| (succ n₁) :=
take (v : vector A (succ n₁)) (w : vector A m),
empty.elim (ninh (inhabited.mk (head v)))
end
|
48c50dea9bd0e4d88d5897dac726d5d81edcb4c9 | 947b78d97130d56365ae2ec264df196ce769371a | /stage0/src/Lean/Compiler/IR.lean | 2ecb72ed28a47b7cdba14774ccf962a69be06606 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,643 | 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.Compiler.IR.Basic
import Lean.Compiler.IR.Format
import Lean.Compiler.IR.CompilerM
import Lean.Compiler.IR.PushProj
import Lean.Compiler.IR.ElimDeadVars
import Lean.Compiler.IR.SimpCase
import Lean.Compiler.IR.ResetReuse
import Lean.Compiler.IR.NormIds
import Lean.Compiler.IR.Checker
import Lean.Compiler.IR.Borrow
import Lean.Compiler.IR.Boxing
import Lean.Compiler.IR.RC
import Lean.Compiler.IR.ExpandResetReuse
import Lean.Compiler.IR.UnboxResult
import Lean.Compiler.IR.ElimDeadBranches
import Lean.Compiler.IR.EmitC
import Lean.Compiler.IR.CtorLayout
namespace Lean
namespace IR
private def compileAux (decls : Array Decl) : CompilerM Unit := do
logDecls `init decls;
checkDecls decls;
decls ← elimDeadBranches decls;
logDecls `elim_dead_branches decls;
let decls := decls.map Decl.pushProj;
logDecls `push_proj decls;
let decls := decls.map Decl.insertResetReuse;
logDecls `reset_reuse decls;
let decls := decls.map Decl.elimDead;
logDecls `elim_dead decls;
let decls := decls.map Decl.simpCase;
logDecls `simp_case decls;
let decls := decls.map Decl.normalizeIds;
decls ← inferBorrow decls;
logDecls `borrow decls;
decls ← explicitBoxing decls;
logDecls `boxing decls;
decls ← explicitRC decls;
logDecls `rc decls;
let decls := decls.map Decl.expandResetReuse;
logDecls `expand_reset_reuse decls;
let decls := decls.map Decl.pushProj;
logDecls `push_proj decls;
logDecls `result decls;
checkDecls decls;
addDecls decls;
pure ()
@[export lean_ir_compile]
def compile (env : Environment) (opts : Options) (decls : Array Decl) : Log × (Except String Environment) :=
match (compileAux decls opts).run { env := env } with
| EStateM.Result.ok _ s => (s.log, Except.ok s.env)
| EStateM.Result.error msg s => (s.log, Except.error msg)
def addBoxedVersionAux (decl : Decl) : CompilerM Unit := do
env ← getEnv;
if !ExplicitBoxing.requiresBoxedVersion env decl then pure ()
else do
let decl := ExplicitBoxing.mkBoxedVersion decl;
let decls : Array Decl := #[decl];
decls ← explicitRC decls;
decls.forM $ fun decl => modifyEnv $ fun env => addDeclAux env decl;
pure ()
-- Remark: we are ignoring the `Log` here. This should be fine.
@[export lean_ir_add_boxed_version]
def addBoxedVersion (env : Environment) (decl : Decl) : Except String Environment :=
match (addBoxedVersionAux decl Options.empty).run { env := env } with
| EStateM.Result.ok _ s => Except.ok s.env
| EStateM.Result.error msg s => Except.error msg
end IR
end Lean
|
e4e8540470f535804b0e787f1d55d696dcd6c4fd | 94637389e03c919023691dcd05bd4411b1034aa5 | /src/inClassNotes/final/arith_expr_test.lean | b6a2d21d1e000f8662bedb7d9f7fa1aad0f928ca | [] | no_license | kevinsullivan/complogic-s21 | 7c4eef2105abad899e46502270d9829d913e8afc | 99039501b770248c8ceb39890be5dfe129dc1082 | refs/heads/master | 1,682,985,669,944 | 1,621,126,241,000 | 1,621,126,241,000 | 335,706,272 | 0 | 38 | null | 1,618,325,669,000 | 1,612,374,118,000 | Lean | UTF-8 | Lean | false | false | 693 | lean | import .bool_expr
import .var_test
example :
arith_expr_eval
init_env
([3] + [5]) =
8 :=
rfl
example :
arith_expr_eval
init_env
([3] + [5] + [@var.mk nat 0]) =
8 :=
rfl
def st := override_nat init_env X [7]
#eval st.nat_var_interp X
#eval st.nat_var_interp Y
#eval st.nat_var_interp Z
def st' := override_nat st Y [8]
#eval st'.nat_var_interp X
#eval st'.nat_var_interp Y
#eval st'.nat_var_interp Z
def st'' := override_nat st' Z [9]
#eval st''.nat_var_interp X
#eval st''.nat_var_interp Y
#eval st''.nat_var_interp Z
def st''' := override_nat st'' X [10]
#eval st'''.nat_var_interp X
#eval st'''.nat_var_interp Y
#eval st'''.nat_var_interp Z |
ca82e35830749eaae46e76a7c04c5a0fcfa3af36 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/topology/algebra/module/character_space.lean | 52af6ec0680fba278939969b718ff9a42b1ce515 | [
"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 | 4,897 | lean | /-
Copyright (c) 2022 Frédéric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Frédéric Dupuis
-/
import topology.algebra.module.weak_dual
import algebra.algebra.spectrum
/-!
# Character space of a topological algebra
The character space of a topological algebra is the subset of elements of the weak dual that
are also algebra homomorphisms. This space is used in the Gelfand transform, which gives an
isomorphism between a commutative C⋆-algebra and continuous functions on the character space
of the algebra. This, in turn, is used to construct the continuous functional calculus on
C⋆-algebras.
## Implementation notes
We define `character_space 𝕜 A` as a subset of the weak dual, which automatically puts the
correct topology on the space. We then define `to_alg_hom` which provides the algebra homomorphism
corresponding to any element. We also provide `to_clm` which provides the element as a
continuous linear map. (Even though `weak_dual 𝕜 A` is a type copy of `A →L[𝕜] 𝕜`, this is
often more convenient.)
## TODO
* Prove that the character space is a compact subset of the weak dual. This requires the
Banach-Alaoglu theorem.
## Tags
character space, Gelfand transform, functional calculus
-/
namespace weak_dual
/-- The character space of a topological algebra is the subset of elements of the weak dual that
are also algebra homomorphisms. -/
def character_space (𝕜 : Type*) (A : Type*) [comm_semiring 𝕜] [topological_space 𝕜]
[has_continuous_add 𝕜] [has_continuous_const_smul 𝕜 𝕜]
[non_unital_non_assoc_semiring A] [topological_space A] [module 𝕜 A] :=
{φ : weak_dual 𝕜 A | (φ ≠ 0) ∧ (∀ (x y : A), φ (x * y) = (φ x) * (φ y))}
variables {𝕜 : Type*} {A : Type*}
namespace character_space
section non_unital_non_assoc_semiring
variables [comm_semiring 𝕜] [topological_space 𝕜] [has_continuous_add 𝕜]
[has_continuous_const_smul 𝕜 𝕜] [non_unital_non_assoc_semiring A] [topological_space A]
[module 𝕜 A]
lemma coe_apply (φ : character_space 𝕜 A) (x : A) : (φ : weak_dual 𝕜 A) x = φ x := rfl
/-- An element of the character space, as a continuous linear map. -/
def to_clm (φ : character_space 𝕜 A) : A →L[𝕜] 𝕜 := (φ : weak_dual 𝕜 A)
lemma to_clm_apply (φ : character_space 𝕜 A) (x : A) : φ x = to_clm φ x := rfl
/-- An element of the character space, as an non-unital algebra homomorphism. -/
@[simps] def to_non_unital_alg_hom (φ : character_space 𝕜 A) : A →ₙₐ[𝕜] 𝕜 :=
{ to_fun := (φ : A → 𝕜),
map_mul' := φ.prop.2,
map_smul' := (to_clm φ).map_smul,
map_zero' := continuous_linear_map.map_zero _,
map_add' := continuous_linear_map.map_add _ }
lemma map_zero (φ : character_space 𝕜 A) : φ 0 = 0 := (to_non_unital_alg_hom φ).map_zero
lemma map_add (φ : character_space 𝕜 A) (x y : A) : φ (x + y) = φ x + φ y :=
(to_non_unital_alg_hom φ).map_add _ _
lemma map_smul (φ : character_space 𝕜 A) (r : 𝕜) (x : A) : φ (r • x) = r • (φ x) :=
(to_clm φ).map_smul _ _
lemma map_mul (φ : character_space 𝕜 A) (x y : A) : φ (x * y) = φ x * φ y :=
(to_non_unital_alg_hom φ).map_mul _ _
lemma continuous (φ : character_space 𝕜 A) : continuous φ := (to_clm φ).continuous
end non_unital_non_assoc_semiring
section unital
variables [comm_ring 𝕜] [no_zero_divisors 𝕜] [topological_space 𝕜] [has_continuous_add 𝕜]
[has_continuous_const_smul 𝕜 𝕜] [topological_space A] [semiring A] [algebra 𝕜 A]
lemma map_one (φ : character_space 𝕜 A) : φ 1 = 1 :=
begin
have h₁ : (φ 1) * (1 - φ 1) = 0 := by rw [mul_sub, sub_eq_zero, mul_one, ←map_mul φ, one_mul],
rcases mul_eq_zero.mp h₁ with h₂|h₂,
{ exfalso,
apply φ.prop.1,
ext,
rw [continuous_linear_map.zero_apply, ←one_mul x, coe_apply, map_mul φ, h₂, zero_mul] },
{ rw [sub_eq_zero] at h₂,
exact h₂.symm },
end
/-- An element of the character space, as an algebra homomorphism. -/
@[simps] def to_alg_hom (φ : character_space 𝕜 A) : A →ₐ[𝕜] 𝕜 :=
{ map_one' := map_one φ,
commutes' := λ r, by
{ rw [algebra.algebra_map_eq_smul_one, algebra.id.map_eq_id, ring_hom.id_apply],
change ((φ : weak_dual 𝕜 A) : A →L[𝕜] 𝕜) (r • 1) = r,
rw [continuous_linear_map.map_smul, algebra.id.smul_eq_mul, coe_apply, map_one φ, mul_one] },
..to_non_unital_alg_hom φ }
end unital
section ring
variables [comm_ring 𝕜] [no_zero_divisors 𝕜] [topological_space 𝕜] [has_continuous_add 𝕜]
[has_continuous_const_smul 𝕜 𝕜] [topological_space A] [ring A] [algebra 𝕜 A]
lemma apply_mem_spectrum [nontrivial 𝕜] (φ : character_space 𝕜 A) (a : A) : φ a ∈ spectrum 𝕜 a :=
(to_alg_hom φ).apply_mem_spectrum a
end ring
end character_space
end weak_dual
|
11e880eef1f60682ed7368be96b64e5cb735e380 | 2fb7334a212c3858db44039b5fa6cd57fd5d1443 | /src/sheaf.lean | e34e8ab027573e198a442f909f2c368d12249c1f | [] | no_license | ImperialCollegeLondon/condensed-sets | 24514be041533b07fd62d337b1d6a5ce2b09c78c | e308291646396003dbed3896e5fbb40cb57c7050 | refs/heads/master | 1,628,397,992,041 | 1,601,549,576,000 | 1,601,549,576,000 | 224,198,323 | 3 | 1 | null | 1,601,549,578,000 | 1,574,774,780,000 | Lean | UTF-8 | Lean | false | false | 3,568 | lean | import sieve
import sites
import category_theory.limits.shapes.equalizers
import category_theory.const
namespace category_theory
namespace category_theory.limits
namespace category_theory.functor
section sheaves
universes w v u
open opposite
variables {C : Type u} [CCat : category.{v} C]
variables {D : Type w} [DCat : category.{max u v} D]
variables [products : limits.has_products.{max u v} D]
include CCat products
def restriction_map (F : Cᵒᵖ ⥤ D) {U : C} (S : @sieve.{v} C CCat U) :
F.obj (op U) ⟶ ∏ (λ k : sieve_domain S, F.obj (op k.Y)) :=
limits.pi.lift (λ k : sieve_domain S, F.map k.f.op)
include DCat
structure separated_presheaf (J : @grothendieck_topology C CCat) :=
(F : Cᵒᵖ ⥤ D)
(identity : ∀ {U : C} (S : sieve.{v} U) (S ∈ J.coverings U),
mono (restriction_map F S))
omit CCat products
end sheaves
open opposite
universes u v
variables {C : Type u} [𝒞 : category.{v} C]
variables {D : Type u} [Dc : category.{max u v} D]
variables (F : Cᵒᵖ ⥤ D) {J : @grothendieck_topology C 𝒞}
include 𝒞
/- Now we define the notion of a sheaf from a category with a grothendieck topology
Want to define it as an equalizer of a certain sequence
TODO:
1. define objects of the sequence.
2. get the "natural" maps induced by universal properties + functor
3. define sheaf :)
-/
structure domain (X : C) (S : sieve.{v} X) :=
(Y : C)
(f : Y ⟶ X)
(in_cover : f ∈ S.map Y)
set_option pp.universes true
/- Defining maps which "chooses" elements of C that are in the products which are in the "sheaf" sequence -/
def fan_prod (X : C) (S : sieve.{v} X) := λ k : domain X S, F.obj (op k.Y)
def fan_prod_pullback (X : C) (S : sieve.{v} X) [limits.has_pullbacks.{v} C] := λ k : domain X S × domain X S, F.obj (op (limits.pullback k.1.f k.2.f))
variable [products : limits.has_products.{max u v} D]
include Dc products
/- Defining elements of the "sheaf" sequence -/
def id_prod (X : C) (S : sieve.{v} X) := ∏ (fan_prod F X S)
def gluing_prod (X : C) (S : sieve.{v} X) [limits.has_pullbacks.{v} C] := ∏ (fan_prod_pullback F X S)
/- Defining maps of the sequence-/
def cover_proj (X : C) (S : sieve.{v} X) : F.obj (op X) ⟶ (∏ (fan_prod F X S)) := limits.pi.lift (λ k : domain X S, F.map k.f.op)
def proj_map_1' (X : C) (S : sieve.{v} X) [limits.has_pullbacks.{v} C] : Π k : domain X S × domain X S, ∏ (fan_prod F X S) ⟶ (fan_prod_pullback F X S) k :=
λ k : domain X S × domain X S, (limits.pi.π (fan_prod F X S) k.1) ≫ F.map (limits.pullback.fst.op)
def proj_map_1 (X : C) (S : sieve.{v} X) [limits.has_pullbacks.{v} C] : ∏ (fan_prod F X S) ⟶ ∏ (fan_prod_pullback F X S) := limits.pi.lift (proj_map_1' F X S)
def proj_map_2' (X : C) (S : sieve.{v} X) [limits.has_pullbacks.{v} C] : Π k : domain X S × domain X S, ∏ (fan_prod F X S) ⟶ (fan_prod_pullback F X S) k :=
λ k : domain X S × domain X S, (limits.pi.π (fan_prod F X S) k.2) ≫ F.map (limits.pullback.snd.op)
def proj_map_2 (X : C) (S : sieve.{v} X) [limits.has_pullbacks.{v} C] : ∏ (fan_prod F X S) ⟶ ∏ (fan_prod_pullback F X S) := limits.pi.lift (proj_map_2' F X S)
class sheaf (F : Cᵒᵖ ⥤ D) [limits.has_pullbacks.{v} C] :=
(commuting : ∀ (X : C) (S ∈ J.coverings X), (cover_proj F X S) ≫ (proj_map_1 F X S) = (cover_proj F X S) ≫ (proj_map_2 F X S))
(limit : ∀ (X : C) (S : sieve.{v} X) (covering : S ∈ J.coverings X),
limits.is_limit (limits.fork.of_ι (cover_proj F X S) (commuting X S covering)))
end category_theory.functor
end category_theory.limits
end category_theory |
de326a2325f5b9a4e6d8cd5ca78cedad449a9bb0 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/module/bimodule.lean | 7c5acc489e8c978726a0997901caf16a387a80be | [
"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 | 5,328 | lean | /-
Copyright (c) 2022 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import ring_theory.tensor_product
/-!
# Bimodules
One frequently encounters situations in which several sets of scalars act on a single space, subject
to compatibility condition(s). A distinguished instance of this is the theory of bimodules: one has
two rings `R`, `S` acting on an additive group `M`, with `R` acting covariantly ("on the left")
and `S` acting contravariantly ("on the right"). The compatibility condition is just:
`(r • m) • s = r • (m • s)` for all `r : R`, `s : S`, `m : M`.
This situation can be set up in Mathlib as:
```lean
variables (R S M : Type*) [ring R] [ring S]
variables [add_comm_group M] [module R M] [module Sᵐᵒᵖ M] [smul_comm_class R Sᵐᵒᵖ M]
```
The key fact is:
```lean
example : module (R ⊗[ℕ] Sᵐᵒᵖ) M := tensor_product.algebra.module
```
Note that the corresponding result holds for the canonically isomorphic ring `R ⊗[ℤ] Sᵐᵒᵖ` but it is
preferable to use the `R ⊗[ℕ] Sᵐᵒᵖ` instance since it works without additive inverses.
Bimodules are thus just a special case of `module`s and most of their properties follow from the
theory of `module`s`. In particular a two-sided submodule of a bimodule is simply a term of type
`submodule (R ⊗[ℕ] Sᵐᵒᵖ) M`.
This file is a place to collect results which are specific to bimodules.
## Main definitions
* `subbimodule.mk`
* `subbimodule.smul_mem`
* `subbimodule.smul_mem'`
* `subbimodule.to_submodule`
* `subbimodule.to_submodule'`
## Implementation details
For many definitions and lemmas it is preferable to set things up without opposites, i.e., as:
`[module S M] [smul_comm_class R S M]` rather than `[module Sᵐᵒᵖ M] [smul_comm_class R Sᵐᵒᵖ M]`.
The corresponding results for opposites then follow automatically and do not require taking
advantage of the fact that `(Sᵐᵒᵖ)ᵐᵒᵖ` is defeq to `S`.
## TODO
Develop the theory of two-sided ideals, which have type `submodule (R ⊗[ℕ] Rᵐᵒᵖ) R`.
-/
open_locale tensor_product
local attribute [instance] tensor_product.algebra.module
namespace subbimodule
section algebra
variables {R A B M : Type*}
variables [comm_semiring R] [add_comm_monoid M] [module R M]
variables [semiring A] [semiring B] [module A M] [module B M]
variables [algebra R A] [algebra R B]
variables [is_scalar_tower R A M] [is_scalar_tower R B M]
variables [smul_comm_class A B M]
/-- A constructor for a subbimodule which demands closure under the two sets of scalars
individually, rather than jointly via their tensor product.
Note that `R` plays no role but it is convenient to make this generalisation to support the cases
`R = ℕ` and `R = ℤ` which both show up naturally. See also `base_change`. -/
@[simps] def mk (p : add_submonoid M)
(hA : ∀ (a : A) {m : M}, m ∈ p → a • m ∈ p)
(hB : ∀ (b : B) {m : M}, m ∈ p → b • m ∈ p) : submodule (A ⊗[R] B) M :=
{ carrier := p,
smul_mem' := λ ab m, tensor_product.induction_on ab
(λ hm, by simpa only [zero_smul] using p.zero_mem)
(λ a b hm, by simpa only [tensor_product.algebra.smul_def] using hA a (hB b hm))
(λ z w hz hw hm, by simpa only [add_smul] using p.add_mem (hz hm) (hw hm)),
.. p }
lemma smul_mem (p : submodule (A ⊗[R] B) M) (a : A) {m : M} (hm : m ∈ p) : a • m ∈ p :=
begin
suffices : a • m = a ⊗ₜ[R] (1 : B) • m, { exact this.symm ▸ p.smul_mem _ hm, },
simp [tensor_product.algebra.smul_def],
end
lemma smul_mem' (p : submodule (A ⊗[R] B) M) (b : B) {m : M} (hm : m ∈ p) : b • m ∈ p :=
begin
suffices : b • m = (1 : A) ⊗ₜ[R] b • m, { exact this.symm ▸ p.smul_mem _ hm, },
simp [tensor_product.algebra.smul_def],
end
/-- If `A` and `B` are also `algebra`s over yet another set of scalars `S` then we may "base change"
from `R` to `S`. -/
@[simps] def base_change (S : Type*) [comm_semiring S] [module S M] [algebra S A] [algebra S B]
[is_scalar_tower S A M] [is_scalar_tower S B M] (p : submodule (A ⊗[R] B) M) :
submodule (A ⊗[S] B) M :=
mk p.to_add_submonoid (smul_mem p) (smul_mem' p)
/-- Forgetting the `B` action, a `submodule` over `A ⊗[R] B` is just a `submodule` over `A`. -/
@[simps] def to_submodule (p : submodule (A ⊗[R] B) M) : submodule A M :=
{ carrier := p,
smul_mem' := smul_mem p,
.. p }
/-- Forgetting the `A` action, a `submodule` over `A ⊗[R] B` is just a `submodule` over `B`. -/
@[simps] def to_submodule' (p : submodule (A ⊗[R] B) M) : submodule B M :=
{ carrier := p,
smul_mem' := smul_mem' p,
.. p }
end algebra
section ring
variables (R S M : Type*) [ring R] [ring S]
variables [add_comm_group M] [module R M] [module S M] [smul_comm_class R S M]
/-- A `submodule` over `R ⊗[ℕ] S` is naturally also a `submodule` over the canonically-isomorphic
ring `R ⊗[ℤ] S`. -/
@[simps] def to_subbimodule_int (p : submodule (R ⊗[ℕ] S) M) : submodule (R ⊗[ℤ] S) M :=
base_change ℤ p
/-- A `submodule` over `R ⊗[ℤ] S` is naturally also a `submodule` over the canonically-isomorphic
ring `R ⊗[ℕ] S`. -/
@[simps] def to_subbimodule_nat (p : submodule (R ⊗[ℤ] S) M) : submodule (R ⊗[ℕ] S) M :=
base_change ℕ p
end ring
end subbimodule
|
e3a2c0f48266f6e657582e43a95eb466d7969eeb | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/free_module/norm.lean | f9366158ef8a6f86970ef968fc7b7363c160a809 | [
"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,238 | lean | /-
Copyright (c) 2023 Junyan Xu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Junyan Xu
-/
import linear_algebra.free_module.ideal_quotient
import ring_theory.norm
/-!
# Norms on free modules over principal ideal domains
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
open ideal polynomial
open_locale big_operators polynomial
variables {R S ι : Type*} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] [comm_ring S]
[is_domain S] [algebra R S]
section comm_ring
variables (F : Type*) [comm_ring F] [algebra F R] [algebra F S] [is_scalar_tower F R S]
/-- For a nonzero element `f` in an algebra `S` over a principal ideal domain `R` that is finite and
free as an `R`-module, the norm of `f` relative to `R` is associated to the product of the Smith
coefficients of the ideal generated by `f`. -/
lemma associated_norm_prod_smith [fintype ι] (b : basis ι R S) {f : S} (hf : f ≠ 0) :
associated (algebra.norm R f) (∏ i, smith_coeffs b _ (span_singleton_eq_bot.not.2 hf) i) :=
begin
have hI := span_singleton_eq_bot.not.2 hf,
let b' := ring_basis b (span {f}) hI,
classical,
rw [← matrix.det_diagonal, ← linear_map.det_to_lin b'],
let e := (b'.equiv ((span {f}).self_basis b hI) $ equiv.refl _).trans
((linear_equiv.coord S S f hf).restrict_scalars R),
refine (linear_map.associated_det_of_eq_comp e _ _ _).symm,
dsimp only [e, linear_equiv.trans_apply],
simp_rw [← linear_equiv.coe_to_linear_map, ← linear_map.comp_apply, ← linear_map.ext_iff],
refine b'.ext (λ i, _),
simp_rw [linear_map.comp_apply, linear_equiv.coe_to_linear_map, matrix.to_lin_apply,
basis.repr_self, finsupp.single_eq_pi_single, matrix.diagonal_mul_vec_single, pi.single_apply,
ite_smul, zero_smul, finset.sum_ite_eq', mul_one, if_pos (finset.mem_univ _), b'.equiv_apply],
change _ = f * _,
rw [mul_comm, ← smul_eq_mul, linear_equiv.restrict_scalars_apply, linear_equiv.coord_apply_smul,
ideal.self_basis_def],
refl
end
end comm_ring
section field
variables {F : Type*} [field F] [algebra F[X] S] [finite ι]
instance (b : basis ι F[X] S) {I : ideal S} (hI : I ≠ ⊥) (i : ι) :
finite_dimensional F (F[X] ⧸ span ({I.smith_coeffs b hI i} : set F[X])) :=
(adjoin_root.power_basis $ I.smith_coeffs_ne_zero b hI i).finite_dimensional
/-- For a nonzero element `f` in a `F[X]`-module `S`, the dimension of $S/\langle f \rangle$ as an
`F`-vector space is the degree of the norm of `f` relative to `F[X]`. -/
lemma finrank_quotient_span_eq_nat_degree_norm [algebra F S] [is_scalar_tower F F[X] S]
(b : basis ι F[X] S) {f : S} (hf : f ≠ 0) :
finite_dimensional.finrank F (S ⧸ span ({f} : set S)) = (algebra.norm F[X] f).nat_degree :=
begin
haveI := fintype.of_finite ι,
have h := span_singleton_eq_bot.not.2 hf,
rw [nat_degree_eq_of_degree_eq (degree_eq_degree_of_associated $ associated_norm_prod_smith b hf),
nat_degree_prod _ _ (λ i _, smith_coeffs_ne_zero b _ h i), finrank_quotient_eq_sum F h b],
-- finrank_quotient_eq_sum slow
congr' with i,
exact (adjoin_root.power_basis $ smith_coeffs_ne_zero b _ h i).finrank
end
end field
|
02299938df55dc31e23e3eb7b74b1dae59ea82b7 | 5a6ff5f8d173cbfe51967eb4c96837e3a791fe3d | /mm0-lean/mm0/fol.lean | 8d94a1962c4089d13138ed82cf635a0a083cf7a0 | [
"CC0-1.0"
] | permissive | digama0/mm0 | 491ac09146708aa1bb775007bf3dbe339ffc0096 | 98496badaf6464e56ed7b4204e7d54b85667cb01 | refs/heads/master | 1,692,321,030,902 | 1,686,254,458,000 | 1,686,254,458,000 | 172,456,790 | 273 | 38 | CC0-1.0 | 1,689,939,563,000 | 1,551,080,059,000 | Rust | UTF-8 | Lean | false | false | 25,230 | lean | import zfc
def deps := list bool
def deps.single (n : ℕ) : deps :=
nat.rec ([tt]) (λ _, list.cons ff) n
-- | 0 := [tt]
-- | (n+1) := ff :: deps.single n
def deps.union (d1 : deps) : deps → deps :=
list.rec id (λ a l₁ IH l₂,
list.cases_on l₂ l₁ (λ b l₂, (a || b) :: IH l₂)) d1
-- | [] l := l
-- | l [] := l
-- | (a :: l₁) (b :: l₂) := (a || b) :: deps.union l₁ l₂
def deps.contains (d : deps) : ℕ → bool :=
list.rec (λ _, ff) (λ a l₁ IH n, nat.cases_on n a IH) d
def deps.disjoint (d : deps) (l : list ℕ) : bool :=
l.all (λ n, bnot (d.contains n))
def deps.filter_out (d : deps) {α} : list α → list α :=
list.rec id (λ a d' IH l,
list.cases_on l ([]) $ λ b l', cond a (IH l') (b :: IH l')) d
def deps.below (d : deps) (n : ℕ) : bool := d.length ≤ n
inductive mm0_sort | set | wff | Class
inductive {u} mm0_context : ℕ → Type
| empty : mm0_context 0
| lvar {n} : mm0_context n → mm0_context (n + 1)
| rvar {n} (d : deps) : mm0_sort → d.below n → mm0_context n → mm0_context n
def mm0_context.rsize : ∀ {n}, mm0_context n → ℕ
| _ mm0_context.empty := 0
| _ (mm0_context.lvar c) := c.rsize
| _ (mm0_context.rvar _ _ _ c) := c.rsize.succ
def mm0_context.sort_rev : ∀ {n} (c : mm0_context n), ℕ → option mm0_sort
| _ mm0_context.empty _ := none
| _ (mm0_context.lvar c) i := c.sort_rev i
| _ (mm0_context.rvar d s h c) 0 := some s
| _ (mm0_context.rvar d s h c) (i+1) := c.sort_rev i
def mm0_context.sort {n} (c : mm0_context n) (i : ℕ) : option mm0_sort :=
c.rsize.psub i.succ >>= c.sort_rev
def mm0_context.rvar_deps_rev : ∀ {n} (c : mm0_context n), ℕ → deps
| _ mm0_context.empty _ := ([])
| _ (mm0_context.lvar c) i := c.rvar_deps_rev i
| _ (mm0_context.rvar d s h c) 0 := d
| _ (mm0_context.rvar d s h c) (i+1) := c.rvar_deps_rev i
def mm0_context.rvar_deps {n} (c : mm0_context n) (i : ℕ) : deps :=
c.rvar_deps_rev (c.rsize - i.succ)
def mm0_value : mm0_sort → Type 1
| mm0_sort.set := ulift ℕ
| mm0_sort.wff := fol.formula zfc.L_ZFC
| mm0_sort.Class := fol.formula zfc.L_ZFC
local infix ` ∈' `:100 := fol.formula_of_relation zfc.ZFC_el
namespace fol
def move0 (k n : ℕ) : ℕ := if n = k then 0 else n + 1
def map_lift (f : ℕ → ℕ) (k n : ℕ) : ℕ := if n < k then n else f (n - k) + k
def subst_lift {L} (f : ℕ → term L) (k n : ℕ) : term L := if n < k then &n else f (n - k) ↑ k
theorem subst_lift_zero {L} (f : ℕ → term L) : subst_lift f 0 = f :=
by funext; rw [subst_lift, if_neg (nat.not_lt_zero _), lift_term_zero]; refl
namespace preterm
def subst_all {L} (f : ℕ → term L) : ∀ {l}, preterm L l → preterm L l
| _ &k := f k
| _ (func f) := func f
| _ (app t₁ t₂) := app (subst_all t₁) (subst_all t₂)
theorem subst_all_subst_all {L} (f : ℕ → term L) (g : ℕ → term L) : ∀ {l} (t : preterm L l),
subst_all f (subst_all g t) = subst_all (subst_all f ∘ g) t
| _ &k := rfl
| _ (func f) := rfl
| _ (app t₁ t₂) := by rw [subst_all, subst_all, subst_all_subst_all, subst_all_subst_all]; refl
theorem lift_term_at_eq_subst_all {L} (n m) : ∀ {l} (t : preterm L l),
t ↑' n # m = subst_all (subst_lift (λ k, &(k+n)) m) t
| _ &k := begin
unfold subst_all subst_lift lift_term_at,
simp only [not_lt.symm], split_ifs, {refl},
rw [lift_term, lift_term_at, if_pos (zero_le _), add_right_comm,
nat.sub_add_cancel (le_of_not_lt h)],
end
| _ (func f) := rfl
| _ (app t₁ t₂) := _root_.congr
(congr_arg app (lift_term_at_eq_subst_all t₁)) (lift_term_at_eq_subst_all t₂)
theorem lift_term_eq_subst_all {L} (n) {l} (t : preterm L l) :
t ↑ n = subst_all (λ k, &(k+n)) t :=
by rw [lift_term, lift_term_at_eq_subst_all, subst_lift_zero]
theorem subst_all_subst_lift {L} (f : ℕ → term L) (m n k x) :
subst_all (subst_lift (λ (k : ℕ), &(k + m)) k) (subst_lift f n x) =
subst_all (subst_lift f (n + m)) (subst_lift (λ (k : ℕ), &(k + m)) k x) :=
begin
unfold subst_lift, split_ifs; simp only [subst_all, lift_term, lift_term_at,
zero_le, if_true, if_false, subst_lift, h, h_1],
{ rw if_pos (lt_of_lt_of_le h (nat.le_add_right _ _)) },
{ rw if_pos, rwa [add_right_comm,
nat.sub_add_cancel (le_of_not_lt h_1), add_lt_add_iff_right] },
{ },
end
theorem lift_at_subst_lift_all {L} (f : ℕ → term L) {l} (t : preterm L l) (n m k) :
subst_all (subst_lift f n) t ↑' m # k = subst_all (subst_lift f (n + m)) (t ↑' m # k) :=
begin
rw [lift_term_at_eq_subst_all, subst_all_subst_all, lift_term_at_eq_subst_all, subst_all_subst_all],
congr' 1, funext, simp only [(∘), subst_all, subst_all_subst_lift],
end
end preterm
def preterm.deps {L} : ∀ {n}, preterm L n → deps
| _ (preterm.var k) := deps.single k
| _ (preterm.func f) := ([])
| _ (preterm.app t s) := t.deps.union s.deps
def preformula.deps {L} : ∀ {n}, preformula L n → deps
| _ preformula.falsum := ([])
| _ (preformula.equal t₁ t₂) := t₁.deps.union t₂.deps
| _ (preformula.rel R) := ([])
| _ (preformula.apprel f t) := f.deps.union f.deps
| _ (preformula.imp f₁ f₂) := f₁.deps.union f₂.deps
| _ (preformula.all f) := f.deps.tail
namespace preformula
def subst_all {L} (f : ℕ → term L) : ∀ {l}, ℕ → preformula L l → preformula L l
| _ m falsum := falsum
| _ m (t₁ ≃ t₂) := t₁.subst_all (subst_lift f m) ≃ t₂.subst_all (subst_lift f m)
| _ m (rel R) := rel R
| _ m (apprel r t) := apprel (subst_all m r) (t.subst_all (subst_lift f m))
| _ m (f₁ ⟹ f₂) := subst_all m f₁ ⟹ subst_all m f₂
| _ m (∀' f) := ∀' subst_all (m+1) f
def lower {L} (x : ℕ) {l} (f : preformula L l) : preformula L l :=
f.subst_all (λ i, &(fol.move0 x i)) 0
theorem lift_at_eq_subst_all {L} : ∀ {l} (f : preformula L l) (n m),
f ↑' n # m = subst_all (λ k, &(k+n)) m f
| _ falsum n m := rfl
| _ (t₁ ≃ t₂) n m := _root_.congr (congr_arg equal
(preterm.lift_term_at_eq_subst_all _ _ _)) (preterm.lift_term_at_eq_subst_all _ _ _)
| _ (rel R) n m := rfl
| _ (apprel r t) n m := _root_.congr (congr_arg apprel
(lift_at_eq_subst_all _ _ _)) (preterm.lift_term_at_eq_subst_all _ _ _)
| _ (f₁ ⟹ f₂) n m := _root_.congr (congr_arg imp
(lift_at_eq_subst_all _ _ _)) (lift_at_eq_subst_all _ _ _)
| _ (∀' f) n m := congr_arg all (lift_at_eq_subst_all _ _ _)
theorem lift_eq_subst_all {L} (n) {l} (t : preterm L l) :
t ↑ n = subst_all (λ k, &(k+n)) t :=
by rw [lift_term, lift_term_at_eq_subst_all, subst_lift_zero]
theorem lift_at_subst_all {L} (f : ℕ → term L) : ∀ {l} (t : preformula L l) (n m k),
t.subst_all f n ↑' m # k = (t ↑' m # k).subst_all f (n + m)
| _ falsum n m k := rfl
| _ (t₁ ≃ t₂) n m k := _root_.congr (congr_arg equal
(preterm.lift_at_subst_lift_all _ _ _ _ _)) (preterm.lift_at_subst_lift_all _ _ _ _ _)
| _ (rel R) n m k := rfl
| _ (apprel r t) n m k := _root_.congr (congr_arg apprel
(lift_at_subst_all _ _ _ _)) (preterm.lift_at_subst_lift_all _ _ _ _ _)
| _ (f₁ ⟹ f₂) n m k := _root_.congr (congr_arg imp
(lift_at_subst_all _ _ _ _)) (lift_at_subst_all _ _ _ _)
| _ (∀' f) n m k := congr_arg all (by rw add_right_comm; apply lift_at_subst_all)
end preformula
namespace prf
def subst_all {L} (f : ℕ → term L) {Γ} {A : formula L} {n}
(p : Γ ⊢ A) : preformula.subst_all f n '' Γ ⊢ preformula.subst_all f n A :=
begin
induction p generalizing n,
{ exact axm (set.mem_image_of_mem _ p_h) },
{ apply impI, rw ← set.image_insert_eq, apply p_ih },
{ exact impE _ p_ih_h₁ p_ih_h₂ },
{ have := p_ih, rw set.image_insert_eq at this, exact falsumE this },
{ apply allI, convert @p_ih (n+1) using 1,
rw [← set.image_comp, ← set.image_comp],
congr' 1, funext, },
end
end prf
def ax_1 {L} {Γ : set (formula L)} {A B : formula L} : Γ ⊢ A ⟹ (B ⟹ A) :=
impI $ impI axm2
def ax_2 {L} {Γ : set (formula L)} {A B C : formula L} :
Γ ⊢ (A ⟹ (B ⟹ C)) ⟹ ((A ⟹ B) ⟹ (A ⟹ C)) :=
impI $ impI $ impI $ impE _ (impE _ (weakening1 axm2) axm1) $ impE _ axm2 axm1
def ax_3 {L} {Γ : set (formula L)} {A B : formula L} :
Γ ⊢ (∼A ⟹ ∼B) ⟹ (B ⟹ A) :=
impI $ impI $ falsumE $ impE _ (impE _ (weakening1 axm2) axm1) axm2
def ax_gen {L} {Γ : set (formula L)} {A : formula L} {x} (h : Γ ⊢ A) :
Γ ⊢ ∀' A.lower x :=
_
end fol
def mm0_value.deps : ∀ {s}, mm0_value s → deps
| mm0_sort.set ⟨n⟩ := deps.single n
| mm0_sort.wff f := fol.preformula.deps f
| mm0_sort.Class f := (fol.preformula.deps f).tail
inductive mm0_context.value_empty (bv : list ℕ) : list ℕ → Type 1
| refl : mm0_context.value_empty bv
def mm0_context.value : ∀ {n}, mm0_context n → Type 1
| _ mm0_context.empty := punit
| _ (mm0_context.lvar c) := mm0_context.value c × ℕ
| _ (mm0_context.rvar d s h c) := mm0_context.value c × mm0_value s
def mm0_context.value_bv : ∀ {n c}, @mm0_context.value n c → list ℕ → list ℕ
| _ mm0_context.empty _ r := r
| _ (@mm0_context.lvar n c) v r := mm0_context.value_bv v.1 (v.2 :: r)
| _ (mm0_context.rvar d s h c) v r := mm0_context.value_bv v.1 r
def mm0_context.value.ok_aux (bv : list ℕ) : ∀ {n c}, @mm0_context.value n c → bool
| _ mm0_context.empty _ := true
| _ (mm0_context.lvar c) v := v.1.ok_aux
| _ (mm0_context.rvar d s h c) v :=
v.2.deps.disjoint (deps.filter_out d bv) && v.1.ok_aux
def mm0_context.value.ok {n c} (v : @mm0_context.value n c) : bool :=
let bv := mm0_context.value_bv v ([]) in bv.nodup && v.ok_aux bv
inductive mm0_prim_term : Type
| wtru : mm0_prim_term
| wi : mm0_prim_term
| wn : mm0_prim_term
| wal : mm0_prim_term
| wceq : mm0_prim_term
| wcel : mm0_prim_term
| cv : mm0_prim_term
| cab : mm0_prim_term
def mm0_prim_term.tgt : mm0_prim_term → mm0_sort
| mm0_prim_term.wtru := mm0_sort.wff
| mm0_prim_term.wi := mm0_sort.wff
| mm0_prim_term.wn := mm0_sort.wff
| mm0_prim_term.wal := mm0_sort.wff
| mm0_prim_term.wceq := mm0_sort.wff
| mm0_prim_term.wcel := mm0_sort.wff
| mm0_prim_term.cv := mm0_sort.Class
| mm0_prim_term.cab := mm0_sort.Class
def mm0_prim_term.args : ∀ t : mm0_prim_term, Σ n, mm0_context n
| mm0_prim_term.wtru := ⟨0, mm0_context.empty⟩
| mm0_prim_term.wi := ⟨0,
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.empty⟩
| mm0_prim_term.wn := ⟨0,
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.empty⟩
| mm0_prim_term.wal := ⟨1,
mm0_context.rvar ([tt]) mm0_sort.wff rfl $
mm0_context.lvar $ mm0_context.empty⟩
| mm0_prim_term.wceq := ⟨0,
mm0_context.rvar ([]) mm0_sort.Class rfl $
mm0_context.rvar ([]) mm0_sort.Class rfl $
mm0_context.empty⟩
| mm0_prim_term.wcel := ⟨0,
mm0_context.rvar ([]) mm0_sort.Class rfl $
mm0_context.rvar ([]) mm0_sort.Class rfl $
mm0_context.empty⟩
| mm0_prim_term.cv := ⟨0,
mm0_context.rvar ([]) mm0_sort.set rfl $
mm0_context.empty⟩
| mm0_prim_term.cab := ⟨1,
mm0_context.rvar ([tt]) mm0_sort.wff rfl $
mm0_context.lvar $ mm0_context.empty⟩
def mm0_prim_term.value : ∀ (t : mm0_prim_term), t.args.2.value → mm0_value t.tgt
| mm0_prim_term.wtru _ := ⊤
| mm0_prim_term.wi ⟨⟨_, f₁⟩, f₂⟩ := f₁ ⟹ f₂
| mm0_prim_term.wn ⟨_, f⟩ := ∼f
| mm0_prim_term.wal ⟨⟨_, x⟩, f⟩ := ∀' f.lower x
| mm0_prim_term.wceq ⟨⟨_, e₁⟩, e₂⟩ := ∀' (e₁ ⇔ e₂)
| mm0_prim_term.wcel ⟨⟨_, A⟩, B⟩ := ∃' (∀' (&0 ∈' &1 ⇔ A ↑' 1 # 1) ⊓ B)
| mm0_prim_term.cv ⟨_, ⟨x⟩⟩ := &0 ∈' &x.succ
| mm0_prim_term.cab ⟨⟨_, x⟩, f⟩ := f.lower x
inductive mm0_preterm : ∀ {γ} (Γ : mm0_context γ) {m}, mm0_context m → mm0_sort → Type
| lvar {γ Γ} (i) : i < γ → @mm0_preterm γ Γ _ mm0_context.empty mm0_sort.set
| rvar {γ Γ} (i) {s} : @mm0_context.sort γ Γ i = some s → mm0_preterm Γ mm0_context.empty s
| prim {γ Γ} (t : mm0_prim_term) : @mm0_preterm γ Γ _ t.args.2 t.tgt
| lapp {γ Γ n c s} (i) :
@mm0_preterm γ Γ _ (@mm0_context.lvar n c) s → i < γ → mm0_preterm Γ c s
| rapp {γ Γ n d' s' h c s} :
@mm0_preterm γ Γ _ (@mm0_context.rvar n d' s' h c) s →
mm0_preterm Γ mm0_context.empty s' →
mm0_preterm Γ c s
| defn {γ Γ n c s} : mm0_preterm c mm0_context.empty s → @mm0_preterm γ Γ n c s
def mm0_term {γ} (Γ : mm0_context γ) : mm0_sort → Type := mm0_preterm Γ mm0_context.empty
def mm0_preterm.weak_deps : ∀ {γ Γ m c s}, @mm0_preterm γ Γ m c s → deps
| _ _ _ _ _ (@mm0_preterm.lvar _ _ i _) := deps.single i
| _ _ _ _ _ (@mm0_preterm.rvar _ Γ i _ _) := Γ.rvar_deps i
| _ _ _ _ _ (@mm0_preterm.prim _ _ t) := ([])
| _ _ _ _ _ (@mm0_preterm.lapp _ _ _ _ _ i f _) := f.weak_deps.union (deps.single i)
| _ _ _ _ _ (@mm0_preterm.rapp _ _ _ _ _ _ _ _ f t) := f.weak_deps.union t.weak_deps
| _ _ _ _ _ (@mm0_preterm.defn _ _ _ _ _ t) := ([])
def mm0_context.value.lnth_rev : ∀ {n} {c : mm0_context n} (i : ℕ), c.value → ℕ
| _ mm0_context.empty i _ := 0
| _ (mm0_context.lvar c) 0 v := v.2
| _ (mm0_context.lvar c) (n+1) v := v.1.lnth_rev n
| _ (mm0_context.rvar d s h c) n v := v.1.lnth_rev n
def mm0_context.value.lnth {n} {c : mm0_context n} (i : ℕ) (v : c.value) : ℕ :=
v.lnth_rev (n - i.succ)
def mm0_ovalue : option mm0_sort → Type 1
| none := punit
| (some s) := mm0_value s
def mm0_context.value.rnth_rev :
∀ {n} {c : mm0_context n}, c.value → ∀ i, mm0_ovalue (c.sort_rev i)
| _ mm0_context.empty _ i := ⟨⟩
| _ (mm0_context.lvar c) v i := v.1.rnth_rev i
| _ (mm0_context.rvar d s h c) v 0 := v.2
| _ (mm0_context.rvar d s h c) v (i+1) := v.1.rnth_rev i
theorem mm0_context.sort_rev_eq {n} (c : mm0_context n) {i s}
(h : mm0_context.sort c i = some s) :
c.sort_rev (c.rsize - i.succ) = some s :=
begin
unfold mm0_context.sort at h,
rw nat.sub_eq_psub,
cases c.rsize.psub i.succ, {cases h},
exact h
end
def mm0_context.value.rnth {n} {c : mm0_context n} (v : c.value)
{i s} (h : mm0_context.sort c i = some s) : mm0_value s :=
begin
have := v.rnth_rev (c.rsize - i.succ),
rwa c.sort_rev_eq h at this
end
def mm0_preterm.value : ∀ {γ} {Γ : mm0_context γ} (V : Γ.value)
{m c s}, @mm0_preterm _ Γ m c s → c.value → mm0_value s
| _ _ V _ _ _ (@mm0_preterm.lvar _ _ i h) v := ⟨V.lnth i⟩
| _ _ V _ _ s (@mm0_preterm.rvar _ _ i _ h) v := V.rnth h
| _ _ V _ _ s (@mm0_preterm.prim _ _ t) v := mm0_prim_term.value _ v
| _ _ V m c s (@mm0_preterm.lapp _ _ n c' _ i f t) v :=
mm0_preterm.value V f $ by exact (v, V.lnth i)
| _ _ V m c s (@mm0_preterm.rapp _ _ n d' s' h c' _ f t) v :=
mm0_preterm.value V f $ by exact (v, mm0_preterm.value V t $ by split)
| _ _ V m c s (@mm0_preterm.defn _ _ _ _ _ t) v :=
mm0_preterm.value v t $ by split
def mm0_term.value {γ} {Γ : mm0_context γ} (V : Γ.value)
{s} (t : mm0_term Γ s) : mm0_value s := mm0_preterm.value V t $ by split
section
open tactic
meta def name.is_numeric : name → bool
| (name.mk_numeral _ name.anonymous) := tt
| (name.mk_numeral _ n) := n.is_numeric
| (name.mk_string _ n) := n.is_numeric
| _ := ff
meta def is_forall_domain : pexpr → bool
| (expr.const n ([])) := n.is_numeric
| _ := ff
meta def ref_apply (r : ref expr) (n : name) : tactic unit := do
m ← read_ref r,
e ← mk_const n,
m' ← mk_mvar,
to_expr ```(%%e %%m') >>= unify m,
write_ref r m'
meta def tactic.mk_term : expr → pexpr → tactic unit
| m (expr.pi x@(name.mk_string v name.anonymous) bi b t) := do
if is_forall_domain b then do
m' ← mk_mvar,
let i := v.mk_iterator.next.next_to_string.to_nat,
e ← mk_mvar,
to_expr ```(((mm0_preterm.prim mm0_prim_term.wal).rapp %%m').lapp %%(reflect i) %%e) >>= unify m,
et ← infer_type e,
to_expr ```(dec_trivial : %%et) >>= unify e,
tactic.mk_term m' $ (expr.lam x bi b t).subst (expr.local_const x x bi ``(ℕ))
else do
m1 ← mk_mvar,
m2 ← mk_mvar,
to_expr ```(((mm0_preterm.prim mm0_prim_term.wi).rapp %%m2).rapp %%m1) tt ff >>= unify m,
tactic.mk_term m1 b,
tactic.mk_term m2 $
(expr.lam x bi b t).subst (expr.local_const x x bi ``(ℕ))
| m (expr.local_const _ (name.mk_string v name.anonymous) _ _) :=
if v.front = 'v' then do
let i := v.mk_iterator.next.next_to_string.to_nat,
e ← mk_mvar,
to_expr ```(mm0_preterm.rvar %%(reflect i) %%e) >>= unify m,
to_expr ```(rfl) >>= unify e
else if v.front = 'x' then do
let i := v.mk_iterator.next.next_to_string.to_nat,
e ← mk_mvar,
to_expr ```(mm0_preterm.lvar %%(reflect i) %%e) >>= unify m,
t ← infer_type e,
to_expr ```(dec_trivial : %%t) >>= unify e
else fail v
| m e@(expr.app e1 e2) := match expr.erase_annotations e1 with
| (expr.const `not ([])) := do
m' ← mk_mvar,
to_expr ```((mm0_preterm.prim mm0_prim_term.wn).rapp %%m') tt ff >>= unify m,
tactic.mk_term m' e2
| (expr.const `coe _) := do
m' ← mk_mvar,
to_expr ```((mm0_preterm.prim mm0_prim_term.cv).rapp %%m') tt ff >>= unify m,
tactic.mk_term m' e2
| (expr.app e1' e2') := match expr.erase_annotations e1' with
| (expr.const `eq _) := do
m1 ← mk_mvar,
m2 ← mk_mvar,
to_expr ```(((mm0_preterm.prim mm0_prim_term.wceq).rapp %%m2).rapp %%m1) tt ff >>= unify m,
tactic.mk_term m1 e2',
tactic.mk_term m2 e2
| (expr.app e1' e2') := trace e1'.to_raw_fmt >> failed
| _ := trace e.to_raw_fmt >> failed
end
| _ := trace e.to_raw_fmt >> failed
end
| m e := match expr.is_annotation e with
| some (_, e') := tactic.mk_term m e'
| none := trace e.to_raw_fmt >> failed
end
meta def tactic.interactive.mk_term :
interactive.parse interactive.types.texpr → tactic unit
| e := do m ← get_goals, tactic.mk_term m.head e
end
inductive mm0_stmt {γ} (Γ : mm0_context γ) : Type
| proof : mm0_term Γ mm0_sort.wff → mm0_stmt
| conv {s} : mm0_term Γ s → mm0_term Γ s → mm0_stmt
def mm0_stmt.value {γ} {Γ : mm0_context γ} : mm0_stmt Γ → Type 1
| (mm0_stmt.proof t) := Π V : Γ.value, V.ok → fol.Theory.fst zfc.ZFC ⊢ t.value V
| (mm0_stmt.conv t₁ t₂) := Π V : Γ.value, V.ok → plift (t₁.value V = t₂.value V)
def mm0_thm.value {γ} {Γ : mm0_context γ} :
list (mm0_term Γ mm0_sort.wff) → mm0_term Γ mm0_sort.wff → Type 1
| ([]) conc := (mm0_stmt.proof conc).value
| (h :: hs) conc := (mm0_stmt.proof h).value → mm0_thm.value hs conc
def mm0_subst {γ} (Γ : mm0_context γ) : ∀ {n}, mm0_context n → Type
| _ mm0_context.empty := punit
| _ (mm0_context.lvar c) := mm0_subst c × {i // i < γ}
| _ (mm0_context.rvar d s h c) := mm0_subst c × mm0_term Γ s
def mm0_subst.lnth_rev {γ Γ} : ∀ {n c}, ℕ → @mm0_subst γ Γ n c → ℕ
| _ mm0_context.empty i σ := 0
| _ (mm0_context.lvar c) 0 σ := σ.2.1
| _ (mm0_context.lvar c) (n+1) σ := σ.1.lnth_rev n
| _ (mm0_context.rvar d s h c) n σ := σ.1.lnth_rev n
def mm0_subst.lnth {γ Γ n c} (i : ℕ) (σ : @mm0_subst γ Γ n c) : ℕ :=
σ.lnth_rev (n - i.succ)
theorem mm0_subst.lnth_rev_lt {γ Γ} : ∀ {n c i} (σ : @mm0_subst γ Γ n c),
i < n → mm0_subst.lnth_rev i σ < γ
| _ (mm0_context.lvar c) 0 σ h := σ.2.2
| _ (mm0_context.lvar c) (n+1) σ h := σ.1.lnth_rev_lt (nat.lt_of_succ_lt_succ h)
| _ (mm0_context.rvar _ _ _ c) n σ h := σ.1.lnth_rev_lt h
theorem mm0_subst.lnth_lt {γ Γ n c i} (σ : @mm0_subst γ Γ n c)
(h : i < n) : mm0_subst.lnth i σ < γ :=
σ.lnth_rev_lt (nat.sub_lt (lt_of_le_of_lt (zero_le _) h) (nat.succ_pos _))
def mm0_oterm {γ} (Γ : mm0_context γ) : option mm0_sort → Type
| none := punit
| (some s) := mm0_term Γ s
def mm0_subst.rnth_rev {γ Γ} : ∀ {n c} (i : ℕ),
@mm0_subst γ Γ n c → mm0_oterm Γ (c.sort_rev i)
| _ mm0_context.empty i σ := ⟨⟩
| _ (mm0_context.lvar c) i σ := σ.1.rnth_rev i
| _ (mm0_context.rvar d s h c) 0 σ := σ.2
| _ (mm0_context.rvar d s h c) (i+1) σ := σ.1.rnth_rev i
def mm0_subst.rnth {γ Γ n c} (σ : @mm0_subst γ Γ n c)
(i) {s} (h : mm0_context.sort c i = some s) : mm0_term Γ s :=
begin
have := σ.rnth_rev (c.rsize - i.succ),
rwa c.sort_rev_eq h at this
end
def mm0_subst.apply : ∀ {γ Γ δ Δ} (σ : @mm0_subst γ Γ δ Δ),
∀ {n c s}, @mm0_preterm _ Δ n c s → mm0_preterm Γ c s
| γ Γ δ Δ σ _ _ _ (mm0_preterm.lvar i h) :=
mm0_preterm.lvar (σ.lnth i) (σ.lnth_lt h)
| γ Γ δ Δ σ _ _ _ (mm0_preterm.rvar i h) := σ.rnth i h
| γ Γ δ Δ σ _ _ _ (mm0_preterm.prim t) := mm0_preterm.prim t
| γ Γ δ Δ σ _ _ _ (mm0_preterm.lapp i f h) :=
(σ.apply f).lapp (σ.lnth i) (σ.lnth_lt h)
| γ Γ δ Δ σ _ _ _ (mm0_preterm.rapp f t) := (σ.apply f).rapp (σ.apply t)
| γ Γ δ Δ σ _ _ _ (mm0_preterm.defn t) := mm0_preterm.defn t
inductive mm0_axiom : Type
| ax_1 | ax_2 | ax_3 | ax_mp | ax_gen | ax_4 | ax_5 | ax_6
def mm0_axiom.args : ∀ t : mm0_axiom, Σ n, mm0_context n
| mm0_axiom.ax_1 := ⟨0,
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.empty⟩
| mm0_axiom.ax_2 := ⟨0,
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.empty⟩
| mm0_axiom.ax_3 := ⟨0,
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.empty⟩
| mm0_axiom.ax_mp := ⟨0,
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.empty⟩
| mm0_axiom.ax_gen := ⟨1,
mm0_context.rvar ([tt]) mm0_sort.wff rfl $
mm0_context.lvar mm0_context.empty⟩
| mm0_axiom.ax_4 := ⟨1,
mm0_context.rvar ([tt]) mm0_sort.wff rfl $
mm0_context.rvar ([tt]) mm0_sort.wff rfl $
mm0_context.lvar mm0_context.empty⟩
| mm0_axiom.ax_5 := ⟨1,
mm0_context.rvar ([]) mm0_sort.wff rfl $
mm0_context.lvar mm0_context.empty⟩
| mm0_axiom.ax_6 := ⟨1,
mm0_context.rvar ([]) mm0_sort.set rfl $
mm0_context.lvar $ mm0_context.empty⟩
def mm0_axiom.ty : ∀ t : mm0_axiom, list (mm0_term t.args.2 mm0_sort.wff) × mm0_term t.args.2 mm0_sort.wff
| mm0_axiom.ax_1 := ([], by mk_term v0 → v1 → v0)
| mm0_axiom.ax_2 := ([], by mk_term (v0 → v1 → v2) → (v0 → v1) → v0 → v2)
| mm0_axiom.ax_3 := ([], by mk_term (¬ v0 → ¬ v1) → v1 → v0)
| mm0_axiom.ax_mp := ([by mk_term v0, by mk_term v0 → v1], by mk_term v1)
| mm0_axiom.ax_gen := ([by mk_term v0], by mk_term ∀ x0, v0)
| mm0_axiom.ax_4 := ([], by mk_term (∀ x0, v0 → v1) → (∀ x0, v0) → ∀ x0, v1)
| mm0_axiom.ax_5 := ([], by mk_term v0 → ∀ x0, v0)
| mm0_axiom.ax_6 := ([], by mk_term ¬ ∀ x0, ¬ ↑x0 = ↑v0)
def mm0_axiom.sound : ∀ t : mm0_axiom, mm0_thm.value t.ty.1 t.ty.2
| mm0_axiom.ax_1 := λ V _, fol.ax_1
| mm0_axiom.ax_2 := λ V _, fol.ax_2
| mm0_axiom.ax_3 := λ V _, fol.ax_3
| mm0_axiom.ax_mp := λ h₁ h₂ V ok, fol.prf.impE _ (h₂ V ok) (h₁ V ok)
| mm0_axiom.ax_gen := λ h V ok, fol.prf.allI (by rw fol.lift_Theory_irrel; exact h _ _)
inductive mm0_preproof {γ Γ}
(hyps : list (@mm0_term γ Γ mm0_sort.wff)) :
list (mm0_term Γ mm0_sort.wff) → mm0_term Γ mm0_sort.wff → Type
| Axiom (A : mm0_axiom) (σ : mm0_subst Γ A.args.2) :
mm0_preproof (A.ty.1.map σ.apply) (σ.apply A.ty.2)
| app {h hs p} : mm0_preproof (h :: hs) p → mm0_preproof ([]) h → mm0_preproof hs p
| hyp (i h) : mm0_preproof ([]) (hyps.nth_le i h)
def mm0_proof {γ Γ} (hyps : list (mm0_term Γ mm0_sort.wff)) :
@mm0_term γ Γ mm0_sort.wff → Type :=
mm0_preproof hyps ([])
def mm0_thm.weaken1 {γ Γ} : ∀ hyps {t},
(mm0_stmt.proof t).value → @mm0_thm.value γ Γ hyps t
| ([]) t h := h
| (l::ls) t h := λ _, mm0_thm.weaken1 ls h
def mm0_thm.weaken {γ Γ} : ∀ {hs hyps t},
mm0_thm.value hs t → @mm0_thm.value γ Γ (hs ++ hyps) t
| ([]) ls t h := mm0_thm.weaken1 ls h
| (e::es) ls t h := λ x, mm0_thm.weaken (h x)
def mm0_subst.sound {γ Γ} : ∀ {n c} (σ : @mm0_subst γ Γ n c) {hs t},
mm0_thm.value hs t → mm0_thm.value (hs.map σ.apply) (σ.apply t) :=
sorry
def mm0_preproof.app_sound1 {γ Γ s} : ∀ {hs p},
((@mm0_stmt.proof γ Γ s).value → @mm0_thm.value γ Γ hs p) →
mm0_thm.value hs s → mm0_thm.value hs p
| ([]) t f v := f v
| (h::hs) t f v := λ x, mm0_preproof.app_sound1 (λ y, f y x) (v x)
def mm0_preproof.app_sound {γ Γ}
(hyps : list (@mm0_term γ Γ mm0_sort.wff)) : ∀ {s hs p},
((mm0_stmt.proof s).value → mm0_thm.value (hs ++ hyps) p) →
mm0_thm.value hyps s → mm0_thm.value (hs ++ hyps) p
| s ([]) t f v := mm0_preproof.app_sound1 f v
| s (h::hs) t f v := λ x, mm0_preproof.app_sound (λ y, f y x) v
def mm0_preproof.hyp_sound {γ Γ} : ∀ hs i h, @mm0_thm.value γ Γ hs (list.nth_le hs i h)
| ([]) _ h' := absurd h' (nat.not_lt_zero _)
| (h::hs) 0 h' := λ x, mm0_thm.weaken1 _ x
| (h::hs) (n+1) h' := λ x, mm0_preproof.hyp_sound _ _ _
def mm0_preproof.sound {γ Γ hyps} :
∀ {hs t}, @mm0_preproof γ Γ hyps hs t → mm0_thm.value (hs ++ hyps) t
| _ _ (mm0_preproof.Axiom _ A σ) := mm0_thm.weaken $ σ.sound A.sound
| _ _ (mm0_preproof.app P p) := mm0_preproof.app_sound _ P.sound p.sound
| _ _ (mm0_preproof.hyp i h) := mm0_preproof.hyp_sound _ _ _
|
192c0b42fedee173582bc67bc939f3bed89205a1 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/analysis/normed_space/extend.lean | 9671569b0aeb6e5b6997748e5a11d8a3b2098eb3 | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,858 | lean | /-
Copyright (c) 2020 Ruben Van de Velde. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ruben Van de Velde
-/
import algebra.algebra.restrict_scalars
import data.complex.is_R_or_C
/-!
# Extending a continuous `ℝ`-linear map to a continuous `𝕜`-linear map
In this file we provide a way to extend a continuous `ℝ`-linear map to a continuous `𝕜`-linear map
in a way that bounds the norm by the norm of the original map, when `𝕜` is either `ℝ` (the
extension is trivial) or `ℂ`. We formulate the extension uniformly, by assuming `is_R_or_C 𝕜`.
We motivate the form of the extension as follows. Note that `fc : F →ₗ[𝕜] 𝕜` is determined fully by
`Re fc`: for all `x : F`, `fc (I • x) = I * fc x`, so `Im (fc x) = -Re (fc (I • x))`. Therefore,
given an `fr : F →ₗ[ℝ] ℝ`, we define `fc x = fr x - fr (I • x) * I`.
## Main definitions
* `linear_map.extend_to_𝕜`
* `continuous_linear_map.extend_to_𝕜`
## Implementation details
For convenience, the main definitions above operate in terms of `restrict_scalars ℝ 𝕜 F`.
Alternate forms which operate on `[is_scalar_tower ℝ 𝕜 F]` instead are provided with a primed name.
-/
open is_R_or_C
variables {𝕜 : Type*} [is_R_or_C 𝕜] {F : Type*} [semi_normed_group F] [semi_normed_space 𝕜 F]
local notation `abs𝕜` := @is_R_or_C.abs 𝕜 _
/-- Extend `fr : F →ₗ[ℝ] ℝ` to `F →ₗ[𝕜] 𝕜` in a way that will also be continuous and have its norm
bounded by `∥fr∥` if `fr` is continuous. -/
noncomputable def linear_map.extend_to_𝕜'
[module ℝ F] [is_scalar_tower ℝ 𝕜 F] (fr : F →ₗ[ℝ] ℝ) : F →ₗ[𝕜] 𝕜 :=
begin
let fc : F → 𝕜 := λ x, (fr x : 𝕜) - (I : 𝕜) * (fr ((I : 𝕜) • x)),
have add : ∀ x y : F, fc (x + y) = fc x + fc y,
{ assume x y,
simp only [fc],
unfold_coes,
simp only [smul_add, ring_hom.map_add, ring_hom.to_fun_eq_coe, linear_map.to_fun_eq_coe,
linear_map.map_add],
rw mul_add,
abel, },
have A : ∀ (c : ℝ) (x : F), (fr ((c : 𝕜) • x) : 𝕜) = (c : 𝕜) * (fr x : 𝕜),
{ assume c x,
rw [← of_real_mul],
congr' 1,
rw [is_R_or_C.of_real_alg, smul_assoc, fr.map_smul, algebra.id.smul_eq_mul, one_smul] },
have smul_ℝ : ∀ (c : ℝ) (x : F), fc ((c : 𝕜) • x) = (c : 𝕜) * fc x,
{ assume c x,
simp only [fc, A],
rw A c x,
rw [smul_smul, mul_comm I (c : 𝕜), ← smul_smul, A, mul_sub],
ring },
have smul_I : ∀ x : F, fc ((I : 𝕜) • x) = (I : 𝕜) * fc x,
{ assume x,
simp only [fc],
cases @I_mul_I_ax 𝕜 _ with h h, { simp [h] },
rw [mul_sub, ← mul_assoc, smul_smul, h],
simp only [neg_mul_eq_neg_mul_symm, linear_map.map_neg, one_mul, one_smul,
mul_neg_eq_neg_mul_symm, of_real_neg, neg_smul, sub_neg_eq_add, add_comm] },
have smul_𝕜 : ∀ (c : 𝕜) (x : F), fc (c • x) = c • fc x,
{ assume c x,
rw [← re_add_im c, add_smul, add_smul, add, smul_ℝ, ← smul_smul, smul_ℝ, smul_I, ← mul_assoc],
refl },
exact { to_fun := fc, map_add' := add, map_smul' := smul_𝕜 }
end
lemma linear_map.extend_to_𝕜'_apply [module ℝ F] [is_scalar_tower ℝ 𝕜 F]
(fr : F →ₗ[ℝ] ℝ) (x : F) :
fr.extend_to_𝕜' x = (fr x : 𝕜) - (I : 𝕜) * fr ((I : 𝕜) • x) := rfl
/-- The norm of the extension is bounded by `∥fr∥`. -/
lemma norm_bound [semi_normed_space ℝ F] [is_scalar_tower ℝ 𝕜 F] (fr : F →L[ℝ] ℝ) (x : F) :
∥(fr.to_linear_map.extend_to_𝕜' x : 𝕜)∥ ≤ ∥fr∥ * ∥x∥ :=
begin
let lm : F →ₗ[𝕜] 𝕜 := fr.to_linear_map.extend_to_𝕜',
-- We aim to find a `t : 𝕜` such that
-- * `lm (t • x) = fr (t • x)` (so `lm (t • x) = t * lm x ∈ ℝ`)
-- * `∥lm x∥ = ∥lm (t • x)∥` (so `t.abs` must be 1)
-- If `lm x ≠ 0`, `(lm x)⁻¹` satisfies the first requirement, and after normalizing, it
-- satisfies the second.
-- (If `lm x = 0`, the goal is trivial.)
classical,
by_cases h : lm x = 0,
{ rw [h, norm_zero],
apply mul_nonneg; exact norm_nonneg _ },
let fx := (lm x)⁻¹,
let t := fx / (abs𝕜 fx : 𝕜),
have ht : abs𝕜 t = 1, by field_simp [abs_of_real, of_real_inv, is_R_or_C.abs_inv,
is_R_or_C.abs_div, is_R_or_C.abs_abs, h],
have h1 : (fr (t • x) : 𝕜) = lm (t • x),
{ apply ext,
{ simp only [lm, of_real_re, linear_map.extend_to_𝕜'_apply, mul_re, I_re, of_real_im, zero_mul,
add_monoid_hom.map_sub, sub_zero, mul_zero],
refl },
{ symmetry,
calc im (lm (t • x))
= im (t * lm x) : by rw [lm.map_smul, smul_eq_mul]
... = im ((lm x)⁻¹ / (abs𝕜 (lm x)⁻¹) * lm x) : rfl
... = im (1 / (abs𝕜 (lm x)⁻¹ : 𝕜)) : by rw [div_mul_eq_mul_div, inv_mul_cancel h]
... = 0 : by rw [← of_real_one, ← of_real_div, of_real_im]
... = im (fr (t • x) : 𝕜) : by rw [of_real_im] } },
calc ∥lm x∥ = abs𝕜 t * ∥lm x∥ : by rw [ht, one_mul]
... = ∥t * lm x∥ : by rw [← norm_eq_abs, normed_field.norm_mul]
... = ∥lm (t • x)∥ : by rw [←smul_eq_mul, lm.map_smul]
... = ∥(fr (t • x) : 𝕜)∥ : by rw h1
... = ∥fr (t • x)∥ : by rw [norm_eq_abs, abs_of_real, norm_eq_abs, abs_to_real]
... ≤ ∥fr∥ * ∥t • x∥ : continuous_linear_map.le_op_norm _ _
... = ∥fr∥ * (∥t∥ * ∥x∥) : by rw norm_smul
... ≤ ∥fr∥ * ∥x∥ : by rw [norm_eq_abs, ht, one_mul]
end
/-- Extend `fr : F →L[ℝ] ℝ` to `F →L[𝕜] 𝕜`. -/
noncomputable def continuous_linear_map.extend_to_𝕜' [semi_normed_space ℝ F] [is_scalar_tower ℝ 𝕜 F]
(fr : F →L[ℝ] ℝ) :
F →L[𝕜] 𝕜 :=
linear_map.mk_continuous _ (∥fr∥) (norm_bound _)
lemma continuous_linear_map.extend_to_𝕜'_apply [semi_normed_space ℝ F] [is_scalar_tower ℝ 𝕜 F]
(fr : F →L[ℝ] ℝ) (x : F) :
fr.extend_to_𝕜' x = (fr x : 𝕜) - (I : 𝕜) * fr ((I : 𝕜) • x) := rfl
/-- Extend `fr : restrict_scalars ℝ 𝕜 F →ₗ[ℝ] ℝ` to `F →ₗ[𝕜] 𝕜`. -/
noncomputable def linear_map.extend_to_𝕜 (fr : (restrict_scalars ℝ 𝕜 F) →ₗ[ℝ] ℝ) : F →ₗ[𝕜] 𝕜 :=
fr.extend_to_𝕜'
lemma linear_map.extend_to_𝕜_apply (fr : (restrict_scalars ℝ 𝕜 F) →ₗ[ℝ] ℝ) (x : F) :
fr.extend_to_𝕜 x = (fr x : 𝕜) - (I : 𝕜) * fr ((I : 𝕜) • x) := rfl
/-- Extend `fr : restrict_scalars ℝ 𝕜 F →L[ℝ] ℝ` to `F →L[𝕜] 𝕜`. -/
noncomputable def continuous_linear_map.extend_to_𝕜 (fr : (restrict_scalars ℝ 𝕜 F) →L[ℝ] ℝ) :
F →L[𝕜] 𝕜 :=
fr.extend_to_𝕜'
lemma continuous_linear_map.extend_to_𝕜_apply (fr : (restrict_scalars ℝ 𝕜 F) →L[ℝ] ℝ) (x : F) :
fr.extend_to_𝕜 x = (fr x : 𝕜) - (I : 𝕜) * fr ((I : 𝕜) • x) := rfl
|
bdf02fbc0c17e6a43ab1bdd4c6eba63295ed2c8f | 367134ba5a65885e863bdc4507601606690974c1 | /src/field_theory/normal.lean | a2b9e446a6a1b0993bcfbacbe799745ebc15dbc0 | [
"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 | 14,409 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import field_theory.adjoin
import field_theory.minpoly
import field_theory.splitting_field
import field_theory.tower
/-!
# Normal field extensions
In this file we define normal field extensions and prove that for a finite extension, being normal
is the same as being a splitting field (`normal.of_is_splitting_field` and
`normal.exists_is_splitting_field`).
## Main Definitions
- `normal F K` where `K` is a field extension of `F`.
-/
noncomputable theory
open_locale classical
open polynomial is_scalar_tower
variables (F K : Type*) [field F] [field K] [algebra F K]
--TODO(Commelin): refactor normal to extend `is_algebraic`??
/-- Typeclass for normal field extension: `K` is a normal extension of `F` iff the minimal
polynomial of every element `x` in `K` splits in `K`, i.e. every conjugate of `x` is in `K`. -/
class normal : Prop :=
(is_integral' (x : K) : is_integral F x)
(splits' (x : K) : splits (algebra_map F K) (minpoly F x))
variables {F K}
theorem normal.is_integral (h : normal F K) (x : K) : is_integral F x := normal.is_integral' x
theorem normal.splits (h : normal F K) (x : K) :
splits (algebra_map F K) (minpoly F x) := normal.splits' x
theorem normal_iff : normal F K ↔
∀ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) :=
⟨λ h x, ⟨h.is_integral x, h.splits x⟩, λ h, ⟨λ x, (h x).1, λ x, (h x).2⟩⟩
theorem normal.out : normal F K →
∀ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) := normal_iff.1
variables (F K)
instance normal_self : normal F F :=
⟨λ x, is_integral_algebra_map, λ x, by { rw minpoly.eq_X_sub_C', exact splits_X_sub_C _ }⟩
variables {K}
variables (K)
theorem normal.exists_is_splitting_field [h : normal F K] [finite_dimensional F K] :
∃ p : polynomial F, is_splitting_field F K p :=
begin
obtain ⟨s, hs⟩ := finite_dimensional.exists_is_basis_finset F K,
refine ⟨s.prod $ λ x, minpoly F x,
splits_prod _ $ λ x hx, h.splits x,
subalgebra.to_submodule_injective _⟩,
rw [algebra.coe_top, eq_top_iff, ← hs.2, submodule.span_le, set.range_subset_iff],
refine λ x, algebra.subset_adjoin (multiset.mem_to_finset.mpr $
(mem_roots $ mt (map_eq_zero $ algebra_map F K).1 $
finset.prod_ne_zero_iff.2 $ λ x hx, _).2 _),
{ exact minpoly.ne_zero (h.is_integral x) },
rw [is_root.def, eval_map, ← aeval_def, alg_hom.map_prod],
exact finset.prod_eq_zero x.2 (minpoly.aeval _ _)
end
section normal_tower
variables (E : Type*) [field E] [algebra F E] [algebra K E] [is_scalar_tower F K E]
lemma normal.tower_top_of_normal [h : normal F E] : normal K E :=
normal_iff.2 $ λ x, begin
cases h.out x with hx hhx,
rw algebra_map_eq F K E at hhx,
exact ⟨is_integral_of_is_scalar_tower x hx, polynomial.splits_of_splits_of_dvd (algebra_map K E)
(polynomial.map_ne_zero (minpoly.ne_zero hx))
((polynomial.splits_map_iff (algebra_map F K) (algebra_map K E)).mpr hhx)
(minpoly.dvd_map_of_is_scalar_tower F K x)⟩,
end
lemma alg_hom.normal_bijective [h : normal F E] (ϕ : E →ₐ[F] K) : function.bijective ϕ :=
⟨ϕ.to_ring_hom.injective, λ x, by
{ letI : algebra E K := ϕ.to_ring_hom.to_algebra,
obtain ⟨h1, h2⟩ := h.out (algebra_map K E x),
cases minpoly.mem_range_of_degree_eq_one E x (or.resolve_left h2 (minpoly.ne_zero h1)
(minpoly.irreducible (is_integral_of_is_scalar_tower x
((is_integral_algebra_map_iff (algebra_map K E).injective).mp h1)))
(minpoly.dvd E x ((algebra_map K E).injective (by
{ rw [ring_hom.map_zero, aeval_map, ←is_scalar_tower.to_alg_hom_apply F K E,
←alg_hom.comp_apply, ←aeval_alg_hom],
exact minpoly.aeval F (algebra_map K E x) })))) with y hy,
exact ⟨y, hy.2⟩ }⟩
variables {F} {E} {E' : Type*} [field E'] [algebra F E']
lemma normal.of_alg_equiv [h : normal F E] (f : E ≃ₐ[F] E') : normal F E' :=
normal_iff.2 $ λ x, begin
cases h.out (f.symm x) with hx hhx,
have H := is_integral_alg_hom f.to_alg_hom hx,
rw [alg_equiv.to_alg_hom_eq_coe, alg_equiv.coe_alg_hom, alg_equiv.apply_symm_apply] at H,
use H,
apply polynomial.splits_of_splits_of_dvd (algebra_map F E') (minpoly.ne_zero hx),
{ rw ← alg_hom.comp_algebra_map f.to_alg_hom,
exact polynomial.splits_comp_of_splits (algebra_map F E) f.to_alg_hom.to_ring_hom hhx },
{ apply minpoly.dvd _ _,
rw ← add_equiv.map_eq_zero_iff f.symm.to_add_equiv,
exact eq.trans (polynomial.aeval_alg_hom_apply f.symm.to_alg_hom x
(minpoly F (f.symm x))).symm (minpoly.aeval _ _) },
end
lemma alg_equiv.transfer_normal (f : E ≃ₐ[F] E') : normal F E ↔ normal F E' :=
⟨λ h, by exactI normal.of_alg_equiv f, λ h, by exactI normal.of_alg_equiv f.symm⟩
lemma normal.of_is_splitting_field (p : polynomial F) [hFEp : is_splitting_field F E p] :
normal F E :=
begin
by_cases hp : p = 0,
{ haveI : is_splitting_field F F p := by { rw hp, exact ⟨splits_zero _, subsingleton.elim _ _⟩ },
exactI (alg_equiv.transfer_normal ((is_splitting_field.alg_equiv F p).trans
(is_splitting_field.alg_equiv E p).symm)).mp (normal_self F) },
refine normal_iff.2 (λ x, _),
haveI hFE : finite_dimensional F E := is_splitting_field.finite_dimensional E p,
have Hx : is_integral F x := is_integral_of_noetherian hFE x,
refine ⟨Hx, or.inr _⟩,
rintros q q_irred ⟨r, hr⟩,
let D := adjoin_root q,
let pbED := adjoin_root.power_basis q_irred.ne_zero,
haveI : finite_dimensional E D := power_basis.finite_dimensional pbED,
have findimED : finite_dimensional.findim E D = q.nat_degree := power_basis.findim pbED,
letI : algebra F D := ring_hom.to_algebra ((algebra_map E D).comp (algebra_map F E)),
haveI : is_scalar_tower F E D := of_algebra_map_eq (λ _, rfl),
haveI : finite_dimensional F D := finite_dimensional.trans F E D,
suffices : nonempty (D →ₐ[F] E),
{ cases this with ϕ,
rw [←with_bot.coe_one, degree_eq_iff_nat_degree_eq q_irred.ne_zero, ←findimED],
have nat_lemma : ∀ a b c : ℕ, a * b = c → c ≤ a → 0 < c → b = 1,
{ intros a b c h1 h2 h3, nlinarith },
exact nat_lemma _ _ _ (finite_dimensional.findim_mul_findim F E D)
(linear_map.findim_le_findim_of_injective (show function.injective ϕ.to_linear_map,
from ϕ.to_ring_hom.injective)) finite_dimensional.findim_pos, },
let C := adjoin_root (minpoly F x),
have Hx_irred := minpoly.irreducible Hx,
letI : algebra C D := ring_hom.to_algebra (adjoin_root.lift
(algebra_map F D) (adjoin_root.root q) (by rw [algebra_map_eq F E D, ←eval₂_map, hr,
adjoin_root.algebra_map_eq, eval₂_mul, adjoin_root.eval₂_root, zero_mul])),
letI : algebra C E := ring_hom.to_algebra (adjoin_root.lift
(algebra_map F E) x (minpoly.aeval F x)),
haveI : is_scalar_tower F C D := of_algebra_map_eq (λ x, adjoin_root.lift_of.symm),
haveI : is_scalar_tower F C E := of_algebra_map_eq (λ x, adjoin_root.lift_of.symm),
suffices : nonempty (D →ₐ[C] E),
{ exact nonempty.map (alg_hom.restrict_scalars F) this },
let S : set D := ((p.map (algebra_map F E)).roots.map (algebra_map E D)).to_finset,
suffices : ⊤ ≤ intermediate_field.adjoin C S,
{ refine intermediate_field.alg_hom_mk_adjoin_splits' (top_le_iff.mp this) (λ y hy, _),
rcases multiset.mem_map.mp (multiset.mem_to_finset.mp hy) with ⟨z, hz1, hz2⟩,
have Hz : is_integral F z := is_integral_of_noetherian hFE z,
use (show is_integral C y, from is_integral_of_noetherian (finite_dimensional.right F C D) y),
apply splits_of_splits_of_dvd (algebra_map C E) (map_ne_zero (minpoly.ne_zero Hz)),
{ rw [splits_map_iff, ←algebra_map_eq F C E],
exact splits_of_splits_of_dvd _ hp hFEp.splits (minpoly.dvd F z
(eq.trans (eval₂_eq_eval_map _) ((mem_roots (map_ne_zero hp)).mp hz1))) },
{ apply minpoly.dvd,
rw [←hz2, aeval_def, eval₂_map, ←algebra_map_eq F C D, algebra_map_eq F E D, ←hom_eval₂,
←aeval_def, minpoly.aeval F z, ring_hom.map_zero] } },
rw [←intermediate_field.to_subalgebra_le_to_subalgebra, intermediate_field.top_to_subalgebra],
apply ge_trans (intermediate_field.algebra_adjoin_le_adjoin C S),
suffices : (algebra.adjoin C S).res F = (algebra.adjoin E {adjoin_root.root q}).res F,
{ rw [adjoin_root.adjoin_root_eq_top, subalgebra.res_top, ←@subalgebra.res_top F C] at this,
exact top_le_iff.mpr (subalgebra.res_inj F this) },
dsimp only [S],
rw [←finset.image_to_finset, finset.coe_image],
apply eq.trans (algebra.adjoin_res_eq_adjoin_res F E C D
hFEp.adjoin_roots adjoin_root.adjoin_root_eq_top),
rw [set.image_singleton, ring_hom.algebra_map_to_algebra, adjoin_root.lift_root]
end
instance (p : polynomial F) : normal F p.splitting_field := normal.of_is_splitting_field p
end normal_tower
variables {F} {K} (ϕ ψ : K →ₐ[F] K) (χ ω : K ≃ₐ[F] K)
section restrict
variables (E : Type*) [field E] [algebra F E] [algebra E K] [is_scalar_tower F E K]
/-- Restrict algebra homomorphism to image of normal subfield -/
def alg_hom.restrict_normal_aux [h : normal F E] :
(to_alg_hom F E K).range →ₐ[F] (to_alg_hom F E K).range :=
{ to_fun := λ x, ⟨ϕ x, by
{ suffices : (to_alg_hom F E K).range.map ϕ ≤ _,
{ exact this ⟨x, subtype.mem x, rfl⟩ },
rintros x ⟨y, ⟨z, -, hy⟩, hx⟩,
rw [←hx, ←hy],
apply minpoly.mem_range_of_degree_eq_one E,
exact or.resolve_left (h.splits z) (minpoly.ne_zero (h.is_integral z))
(minpoly.irreducible $ is_integral_of_is_scalar_tower _ $
is_integral_alg_hom ϕ $ is_integral_alg_hom _ $ h.is_integral z)
(minpoly.dvd E _ $ by rw [aeval_map, aeval_alg_hom, aeval_alg_hom, alg_hom.comp_apply,
alg_hom.comp_apply, minpoly.aeval, alg_hom.map_zero, alg_hom.map_zero]) }⟩,
map_zero' := subtype.ext ϕ.map_zero,
map_one' := subtype.ext ϕ.map_one,
map_add' := λ x y, subtype.ext (ϕ.map_add x y),
map_mul' := λ x y, subtype.ext (ϕ.map_mul x y),
commutes' := λ x, subtype.ext (ϕ.commutes x) }
/-- Restrict algebra homomorphism to normal subfield -/
def alg_hom.restrict_normal [normal F E] : E →ₐ[F] E :=
((alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)).symm.to_alg_hom.comp
(ϕ.restrict_normal_aux E)).comp
(alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)).to_alg_hom
@[simp] lemma alg_hom.restrict_normal_commutes [normal F E] (x : E) :
algebra_map E K (ϕ.restrict_normal E x) = ϕ (algebra_map E K x) :=
subtype.ext_iff.mp (alg_equiv.apply_symm_apply (alg_equiv.of_injective_field
(is_scalar_tower.to_alg_hom F E K)) (ϕ.restrict_normal_aux E
⟨is_scalar_tower.to_alg_hom F E K x, ⟨x, ⟨subsemiring.mem_top x, rfl⟩⟩⟩))
lemma alg_hom.restrict_normal_comp [normal F E] :
(ϕ.restrict_normal E).comp (ψ.restrict_normal E) = (ϕ.comp ψ).restrict_normal E :=
alg_hom.ext (λ _, (algebra_map E K).injective
(by simp only [alg_hom.comp_apply, alg_hom.restrict_normal_commutes]))
/-- Restrict algebra isomorphism to a normal subfield -/
def alg_equiv.restrict_normal [h : normal F E] : E ≃ₐ[F] E :=
alg_equiv.of_bijective (χ.to_alg_hom.restrict_normal E) (alg_hom.normal_bijective F E E _)
@[simp] lemma alg_equiv.restrict_normal_commutes [normal F E] (x : E) :
algebra_map E K (χ.restrict_normal E x) = χ (algebra_map E K x) :=
χ.to_alg_hom.restrict_normal_commutes E x
lemma alg_equiv.restrict_normal_trans [normal F E] :
(χ.trans ω).restrict_normal E = (χ.restrict_normal E).trans (ω.restrict_normal E) :=
alg_equiv.ext (λ _, (algebra_map E K).injective
(by simp only [alg_equiv.trans_apply, alg_equiv.restrict_normal_commutes]))
/-- Restriction to an normal subfield as a group homomorphism -/
def alg_equiv.restrict_normal_hom [normal F E] : (K ≃ₐ[F] K) →* (E ≃ₐ[F] E) :=
monoid_hom.mk' (λ χ, χ.restrict_normal E) (λ ω χ, (χ.restrict_normal_trans ω E))
end restrict
section lift
variables {F} {K} (E : Type*) [field E] [algebra F E] [algebra K E] [is_scalar_tower F K E]
/-- If `E/K/F` is a tower of fields with `E/F` normal then we can lift
an algebra homomorphism `ϕ : K →ₐ[F] K` to `ϕ.lift_normal E : E →ₐ[F] E`. -/
noncomputable def alg_hom.lift_normal [h : normal F E] : E →ₐ[F] E :=
@alg_hom.restrict_scalars F K E E _ _ _ _ _ _
((is_scalar_tower.to_alg_hom F K E).comp ϕ).to_ring_hom.to_algebra _ _ _ _
(nonempty.some (@intermediate_field.alg_hom_mk_adjoin_splits' K E E _ _ _ _
((is_scalar_tower.to_alg_hom F K E).comp ϕ).to_ring_hom.to_algebra ⊤ rfl
(λ x hx, ⟨is_integral_of_is_scalar_tower x (h.out x).1,
splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero (h.out x).1))
(by { rw [splits_map_iff, ←is_scalar_tower.algebra_map_eq], exact (h.out x).2 })
(minpoly.dvd_map_of_is_scalar_tower F K x)⟩)))
@[simp] lemma alg_hom.lift_normal_commutes [normal F E] (x : K) :
ϕ.lift_normal E (algebra_map K E x) = algebra_map K E (ϕ x) :=
@alg_hom.commutes K E E _ _ _ _
((is_scalar_tower.to_alg_hom F K E).comp ϕ).to_ring_hom.to_algebra _ x
@[simp] lemma alg_hom.restrict_lift_normal [normal F K] [normal F E] :
(ϕ.lift_normal E).restrict_normal K = ϕ :=
alg_hom.ext (λ x, (algebra_map K E).injective
(eq.trans (alg_hom.restrict_normal_commutes _ K x) (ϕ.lift_normal_commutes E x)))
/-- If `E/K/F` is a tower of fields with `E/F` normal then we can lift
an algebra isomorphism `ϕ : K ≃ₐ[F] K` to `ϕ.lift_normal E : E ≃ₐ[F] E`. -/
noncomputable def alg_equiv.lift_normal [normal F E] : E ≃ₐ[F] E :=
alg_equiv.of_bijective (χ.to_alg_hom.lift_normal E) (alg_hom.normal_bijective F E E _)
@[simp] lemma alg_equiv.lift_normal_commutes [normal F E] (x : K) :
χ.lift_normal E (algebra_map K E x) = algebra_map K E (χ x) :=
χ.to_alg_hom.lift_normal_commutes E x
@[simp] lemma alg_equiv.restrict_lift_normal [normal F K] [normal F E] :
(χ.lift_normal E).restrict_normal K = χ :=
alg_equiv.ext (λ x, (algebra_map K E).injective
(eq.trans (alg_equiv.restrict_normal_commutes _ K x) (χ.lift_normal_commutes E x)))
lemma alg_equiv.restrict_normal_hom_surjective [normal F K] [normal F E] :
function.surjective (alg_equiv.restrict_normal_hom K : (E ≃ₐ[F] E) → (K ≃ₐ[F] K)) :=
λ χ, ⟨χ.lift_normal E, χ.restrict_lift_normal E⟩
end lift
|
a2abf3ccd66b7ddcd20e250f6781ec8c017a8196 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/ring_theory/adjoin_root.lean | 2a5c9aa80da78c9c444b50da82acb9f505a6d30a | [
"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 | 20,438 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Chris Hughes
-/
import data.polynomial.field_division
import linear_algebra.finite_dimensional
import ring_theory.adjoin.basic
import ring_theory.power_basis
import ring_theory.principal_ideal_domain
/-!
# Adjoining roots of polynomials
This file defines the commutative ring `adjoin_root f`, the ring R[X]/(f) obtained from a
commutative ring `R` and a polynomial `f : R[X]`. If furthermore `R` is a field and `f` is
irreducible, the field structure on `adjoin_root f` is constructed.
## Main definitions and results
The main definitions are in the `adjoin_root` namespace.
* `mk f : R[X] →+* adjoin_root f`, the natural ring homomorphism.
* `of f : R →+* adjoin_root f`, the natural ring homomorphism.
* `root f : adjoin_root f`, the image of X in R[X]/(f).
* `lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S`, the ring
homomorphism from R[X]/(f) to S extending `i : R →+* S` and sending `X` to `x`.
* `lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S`, the algebra
homomorphism from R[X]/(f) to S extending `algebra_map R S` and sending `X` to `x`
* `equiv : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots}` a
bijection between algebra homomorphisms from `adjoin_root` and roots of `f` in `S`
-/
noncomputable theory
open_locale classical
open_locale big_operators polynomial
universes u v w
variables {R : Type u} {S : Type v} {K : Type w}
open polynomial ideal
/-- Adjoin a root of a polynomial `f` to a commutative ring `R`. We define the new ring
as the quotient of `polynomial R` by the principal ideal generated by `f`. -/
def adjoin_root [comm_ring R] (f : R[X]) : Type u :=
polynomial R ⧸ (span {f} : ideal R[X])
namespace adjoin_root
section comm_ring
variables [comm_ring R] (f : R[X])
instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _
instance : inhabited (adjoin_root f) := ⟨0⟩
instance : decidable_eq (adjoin_root f) := classical.dec_eq _
protected lemma nontrivial [is_domain R] (h : degree f ≠ 0) : nontrivial (adjoin_root f) :=
ideal.quotient.nontrivial
begin
simp_rw [ne.def, span_singleton_eq_top, polynomial.is_unit_iff, not_exists, not_and],
rintro x hx rfl,
exact h (degree_C hx.ne_zero),
end
/-- Ring homomorphism from `R[x]` to `adjoin_root f` sending `X` to the `root`. -/
def mk : R[X] →+* adjoin_root f := ideal.quotient.mk _
@[elab_as_eliminator]
theorem induction_on {C : adjoin_root f → Prop} (x : adjoin_root f)
(ih : ∀ p : R[X], C (mk f p)) : C x :=
quotient.induction_on' x ih
/-- Embedding of the original ring `R` into `adjoin_root f`. -/
def of : R →+* adjoin_root f := (mk f).comp C
instance [comm_semiring S] [algebra S R] : algebra S (adjoin_root f) :=
ideal.quotient.algebra S
instance [comm_semiring S] [comm_semiring K] [has_smul S K] [algebra S R] [algebra K R]
[is_scalar_tower S K R] :
is_scalar_tower S K (adjoin_root f) :=
submodule.quotient.is_scalar_tower _ _
instance [comm_semiring S] [comm_semiring K] [algebra S R] [algebra K R] [smul_comm_class S K R] :
smul_comm_class S K (adjoin_root f) :=
submodule.quotient.smul_comm_class _ _
@[simp] lemma algebra_map_eq : algebra_map R (adjoin_root f) = of f := rfl
variables (S)
lemma algebra_map_eq' [comm_semiring S] [algebra S R] :
algebra_map S (adjoin_root f) = (of f).comp (algebra_map S R) := rfl
variables {S}
/-- The adjoined root. -/
def root : adjoin_root f := mk f X
variables {f}
instance adjoin_root.has_coe_t : has_coe_t R (adjoin_root f) := ⟨of f⟩
@[simp] lemma mk_eq_mk {g h : R[X]} : mk f g = mk f h ↔ f ∣ g - h :=
ideal.quotient.eq.trans ideal.mem_span_singleton
@[simp] lemma mk_self : mk f f = 0 :=
quotient.sound' $ quotient_add_group.left_rel_apply.mpr (mem_span_singleton.2 $ by simp)
@[simp] lemma mk_C (x : R) : mk f (C x) = x := rfl
@[simp] lemma mk_X : mk f X = root f := rfl
@[simp] lemma aeval_eq (p : R[X]) : aeval (root f) p = mk f p :=
polynomial.induction_on p (λ x, by { rw aeval_C, refl })
(λ p q ihp ihq, by rw [alg_hom.map_add, ring_hom.map_add, ihp, ihq])
(λ n x ih, by { rw [alg_hom.map_mul, aeval_C, alg_hom.map_pow, aeval_X,
ring_hom.map_mul, mk_C, ring_hom.map_pow, mk_X], refl })
theorem adjoin_root_eq_top : algebra.adjoin R ({root f} : set (adjoin_root f)) = ⊤ :=
algebra.eq_top_iff.2 $ λ x, induction_on f x $ λ p,
(algebra.adjoin_singleton_eq_range_aeval R (root f)).symm ▸ ⟨p, aeval_eq p⟩
@[simp] lemma eval₂_root (f : R[X]) : f.eval₂ (of f) (root f) = 0 :=
by rw [← algebra_map_eq, ← aeval_def, aeval_eq, mk_self]
lemma is_root_root (f : R[X]) : is_root (f.map (of f)) (root f) :=
by rw [is_root, eval_map, eval₂_root]
lemma is_algebraic_root (hf : f ≠ 0) : is_algebraic R (root f) :=
⟨f, hf, eval₂_root f⟩
variables [comm_ring S]
/-- Lift a ring homomorphism `i : R →+* S` to `adjoin_root f →+* S`. -/
def lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S :=
begin
apply ideal.quotient.lift _ (eval₂_ring_hom i x),
intros g H,
rcases mem_span_singleton.1 H with ⟨y, hy⟩,
rw [hy, ring_hom.map_mul, coe_eval₂_ring_hom, h, zero_mul]
end
variables {i : R →+* S} {a : S} (h : f.eval₂ i a = 0)
@[simp] lemma lift_mk (g : R[X]) : lift i a h (mk f g) = g.eval₂ i a :=
ideal.quotient.lift_mk _ _ _
@[simp] lemma lift_root : lift i a h (root f) = a := by rw [root, lift_mk, eval₂_X]
@[simp] lemma lift_of {x : R} : lift i a h x = i x :=
by rw [← mk_C x, lift_mk, eval₂_C]
@[simp] lemma lift_comp_of : (lift i a h).comp (of f) = i :=
ring_hom.ext $ λ _, @lift_of _ _ _ _ _ _ _ h _
variables (f) [algebra R S]
/-- Produce an algebra homomorphism `adjoin_root f →ₐ[R] S` sending `root f` to
a root of `f` in `S`. -/
def lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S :=
{ commutes' := λ r, show lift _ _ hfx r = _, from lift_of hfx,
.. lift (algebra_map R S) x hfx }
@[simp] lemma coe_lift_hom (x : S) (hfx : aeval x f = 0) :
(lift_hom f x hfx : adjoin_root f →+* S) = lift (algebra_map R S) x hfx := rfl
@[simp] lemma aeval_alg_hom_eq_zero (ϕ : adjoin_root f →ₐ[R] S) : aeval (ϕ (root f)) f = 0 :=
begin
have h : ϕ.to_ring_hom.comp (of f) = algebra_map R S := ring_hom.ext_iff.mpr (ϕ.commutes),
rw [aeval_def, ←h, ←ring_hom.map_zero ϕ.to_ring_hom, ←eval₂_root f, hom_eval₂],
refl,
end
@[simp] lemma lift_hom_eq_alg_hom (f : R[X]) (ϕ : adjoin_root f →ₐ[R] S) :
lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ) = ϕ :=
begin
suffices : ϕ.equalizer (lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ)) = ⊤,
{ exact (alg_hom.ext (λ x, (set_like.ext_iff.mp (this) x).mpr algebra.mem_top)).symm },
rw [eq_top_iff, ←adjoin_root_eq_top, algebra.adjoin_le_iff, set.singleton_subset_iff],
exact (@lift_root _ _ _ _ _ _ _ (aeval_alg_hom_eq_zero f ϕ)).symm,
end
variables (hfx : aeval a f = 0)
@[simp] lemma lift_hom_mk {g : R[X]} : lift_hom f a hfx (mk f g) = aeval a g :=
lift_mk hfx g
@[simp] lemma lift_hom_root : lift_hom f a hfx (root f) = a :=
lift_root hfx
@[simp] lemma lift_hom_of {x : R} : lift_hom f a hfx (of f x) = algebra_map _ _ x :=
lift_of hfx
end comm_ring
section irreducible
variables [field K] {f : K[X]}
instance span_maximal_of_irreducible [fact (irreducible f)] : (span {f}).is_maximal :=
principal_ideal_ring.is_maximal_of_irreducible $ fact.out _
noncomputable instance field [fact (irreducible f)] : field (adjoin_root f) :=
{ ..adjoin_root.comm_ring f,
..ideal.quotient.field (span {f} : ideal K[X]) }
lemma coe_injective (h : degree f ≠ 0) : function.injective (coe : K → adjoin_root f) :=
have _ := adjoin_root.nontrivial f h, by exactI (of f).injective
lemma coe_injective' [fact (irreducible f)] : function.injective (coe : K → adjoin_root f) :=
(of f).injective
variable (f)
lemma mul_div_root_cancel [fact (irreducible f)] :
((X - C (root f)) * (f.map (of f) / (X - C (root f)))) = f.map (of f) :=
mul_div_eq_iff_is_root.2 $ is_root_root _
end irreducible
section power_basis
variables [comm_ring R] {g : R[X]}
lemma is_integral_root' (hg : g.monic) : is_integral R (root g) :=
⟨g, hg, eval₂_root g⟩
/-- `adjoin_root.mod_by_monic_hom` sends the equivalence class of `f` mod `g` to `f %ₘ g`.
This is a well-defined right inverse to `adjoin_root.mk`, see `adjoin_root.mk_left_inverse`. -/
def mod_by_monic_hom (hg : g.monic) :
adjoin_root g →ₗ[R] R[X] :=
(submodule.liftq _ (polynomial.mod_by_monic_hom g)
(λ f (hf : f ∈ (ideal.span {g}).restrict_scalars R),
(mem_ker_mod_by_monic hg).mpr (ideal.mem_span_singleton.mp hf))).comp $
(submodule.quotient.restrict_scalars_equiv R (ideal.span {g} : ideal R[X]))
.symm.to_linear_map
@[simp] lemma mod_by_monic_hom_mk (hg : g.monic) (f : R[X]) :
mod_by_monic_hom hg (mk g f) = f %ₘ g := rfl
lemma mk_left_inverse (hg : g.monic) :
function.left_inverse (mk g) (mod_by_monic_hom hg) :=
λ f, induction_on g f $ λ f, begin
rw [mod_by_monic_hom_mk hg, mk_eq_mk, mod_by_monic_eq_sub_mul_div _ hg,
sub_sub_cancel_left, dvd_neg],
apply dvd_mul_right
end
lemma mk_surjective (hg : g.monic) : function.surjective (mk g) :=
(mk_left_inverse hg).surjective
/-- The elements `1, root g, ..., root g ^ (d - 1)` form a basis for `adjoin_root g`,
where `g` is a monic polynomial of degree `d`. -/
@[simps] def power_basis_aux' (hg : g.monic) :
basis (fin g.nat_degree) R (adjoin_root g) :=
basis.of_equiv_fun
{ to_fun := λ f i, (mod_by_monic_hom hg f).coeff i,
inv_fun := λ c, mk g $ ∑ (i : fin g.nat_degree), monomial i (c i),
map_add' := λ f₁ f₂, funext $ λ i,
by simp only [(mod_by_monic_hom hg).map_add, coeff_add, pi.add_apply],
map_smul' := λ f₁ f₂, funext $ λ i,
by simp only [(mod_by_monic_hom hg).map_smul, coeff_smul, pi.smul_apply, ring_hom.id_apply],
left_inv := λ f, induction_on g f (λ f, eq.symm $ mk_eq_mk.mpr $
by { simp only [mod_by_monic_hom_mk, sum_mod_by_monic_coeff hg degree_le_nat_degree],
rw [mod_by_monic_eq_sub_mul_div _ hg, sub_sub_cancel],
exact dvd_mul_right _ _ }),
right_inv := λ x, funext $ λ i, begin
nontriviality R,
simp only [mod_by_monic_hom_mk],
rw [(mod_by_monic_eq_self_iff hg).mpr, finset_sum_coeff, finset.sum_eq_single i];
try { simp only [coeff_monomial, eq_self_iff_true, if_true] },
{ intros j _ hj, exact if_neg (fin.coe_injective.ne hj) },
{ intros, have := finset.mem_univ i, contradiction },
{ refine (degree_sum_le _ _).trans_lt ((finset.sup_lt_iff _).mpr (λ j _, _)),
{ exact bot_lt_iff_ne_bot.mpr (mt degree_eq_bot.mp hg.ne_zero) },
{ refine (degree_monomial_le _ _).trans_lt _,
rw [degree_eq_nat_degree hg.ne_zero, with_bot.coe_lt_coe],
exact j.2 } },
end}
/-- The power basis `1, root g, ..., root g ^ (d - 1)` for `adjoin_root g`,
where `g` is a monic polynomial of degree `d`. -/
@[simps] def power_basis' (hg : g.monic) : power_basis R (adjoin_root g) :=
{ gen := root g,
dim := g.nat_degree,
basis := power_basis_aux' hg,
basis_eq_pow := λ i, begin
simp only [power_basis_aux', basis.coe_of_equiv_fun, linear_equiv.coe_symm_mk],
rw finset.sum_eq_single i,
{ rw [function.update_same, monomial_one_right_eq_X_pow, (mk g).map_pow, mk_X] },
{ intros j _ hj,
rw ← monomial_zero_right _,
convert congr_arg _ (function.update_noteq hj _ _) }, -- Fix `decidable_eq` mismatch
{ intros, have := finset.mem_univ i, contradiction },
end}
variables [field K] {f : K[X]}
lemma is_integral_root (hf : f ≠ 0) : is_integral K (root f) :=
is_algebraic_iff_is_integral.mp (is_algebraic_root hf)
lemma minpoly_root (hf : f ≠ 0) : minpoly K (root f) = f * C (f.leading_coeff⁻¹) :=
begin
have f'_monic : monic _ := monic_mul_leading_coeff_inv hf,
refine (minpoly.unique K _ f'_monic _ _).symm,
{ rw [alg_hom.map_mul, aeval_eq, mk_self, zero_mul] },
intros q q_monic q_aeval,
have commutes : (lift (algebra_map K (adjoin_root f)) (root f) q_aeval).comp (mk q) = mk f,
{ ext,
{ simp only [ring_hom.comp_apply, mk_C, lift_of], refl },
{ simp only [ring_hom.comp_apply, mk_X, lift_root] } },
rw [degree_eq_nat_degree f'_monic.ne_zero, degree_eq_nat_degree q_monic.ne_zero,
with_bot.coe_le_coe, nat_degree_mul hf, nat_degree_C, add_zero],
apply nat_degree_le_of_dvd,
{ have : mk f q = 0, by rw [←commutes, ring_hom.comp_apply, mk_self, ring_hom.map_zero],
rwa [←ideal.mem_span_singleton, ←ideal.quotient.eq_zero_iff_mem] },
{ exact q_monic.ne_zero },
{ rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] },
end
/-- The elements `1, root f, ..., root f ^ (d - 1)` form a basis for `adjoin_root f`,
where `f` is an irreducible polynomial over a field of degree `d`. -/
def power_basis_aux (hf : f ≠ 0) : basis (fin f.nat_degree) K (adjoin_root f) :=
begin
set f' := f * C (f.leading_coeff⁻¹) with f'_def,
have deg_f' : f'.nat_degree = f.nat_degree,
{ rw [nat_degree_mul hf, nat_degree_C, add_zero],
{ rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] } },
have minpoly_eq : minpoly K (root f) = f' := minpoly_root hf,
apply @basis.mk _ _ _ (λ (i : fin f.nat_degree), (root f ^ i.val)),
{ rw [← deg_f', ← minpoly_eq],
exact (is_integral_root hf).linear_independent_pow },
{ rw _root_.eq_top_iff,
rintros y -,
rw [← deg_f', ← minpoly_eq],
apply (is_integral_root hf).mem_span_pow,
obtain ⟨g⟩ := y,
use g,
rw aeval_eq,
refl }
end
/-- The power basis `1, root f, ..., root f ^ (d - 1)` for `adjoin_root f`,
where `f` is an irreducible polynomial over a field of degree `d`. -/
@[simps] def power_basis (hf : f ≠ 0) :
power_basis K (adjoin_root f) :=
{ gen := root f,
dim := f.nat_degree,
basis := power_basis_aux hf,
basis_eq_pow := basis.mk_apply _ _ }
lemma minpoly_power_basis_gen (hf : f ≠ 0) :
minpoly K (power_basis hf).gen = f * C (f.leading_coeff⁻¹) :=
by rw [power_basis_gen, minpoly_root hf]
lemma minpoly_power_basis_gen_of_monic (hf : f.monic) (hf' : f ≠ 0 := hf.ne_zero) :
minpoly K (power_basis hf').gen = f :=
by rw [minpoly_power_basis_gen hf', hf.leading_coeff, inv_one, C.map_one, mul_one]
end power_basis
section equiv
section is_domain
variables [comm_ring R] [is_domain R] [comm_ring S] [is_domain S] [algebra R S]
variables (g : R[X]) (pb : _root_.power_basis R S)
/-- If `S` is an extension of `R` with power basis `pb` and `g` is a monic polynomial over `R`
such that `pb.gen` has a minimal polynomial `g`, then `S` is isomorphic to `adjoin_root g`.
Compare `power_basis.equiv_of_root`, which would require
`h₂ : aeval pb.gen (minpoly R (root g)) = 0`; that minimal polynomial is not
guaranteed to be identical to `g`. -/
@[simps {fully_applied := ff}]
def equiv' (h₁ : aeval (root g) (minpoly R pb.gen) = 0) (h₂ : aeval pb.gen g = 0) :
adjoin_root g ≃ₐ[R] S :=
{ to_fun := adjoin_root.lift_hom g pb.gen h₂,
inv_fun := pb.lift (root g) h₁,
left_inv := λ x, induction_on g x $ λ f, by rw [lift_hom_mk, pb.lift_aeval, aeval_eq],
right_inv := λ x, begin
obtain ⟨f, hf, rfl⟩ := pb.exists_eq_aeval x,
rw [pb.lift_aeval, aeval_eq, lift_hom_mk]
end,
.. adjoin_root.lift_hom g pb.gen h₂ }
@[simp] lemma equiv'_to_alg_hom
(h₁ : aeval (root g) (minpoly R pb.gen) = 0) (h₂ : aeval pb.gen g = 0) :
(equiv' g pb h₁ h₂).to_alg_hom = adjoin_root.lift_hom g pb.gen h₂ :=
rfl
@[simp] lemma equiv'_symm_to_alg_hom
(h₁ : aeval (root g) (minpoly R pb.gen) = 0) (h₂ : aeval pb.gen g = 0) :
(equiv' g pb h₁ h₂).symm.to_alg_hom = pb.lift (root g) h₁ :=
rfl
end is_domain
section field
variables (K) (L F : Type*) [field F] [field K] [field L] [algebra F K] [algebra F L]
variables (pb : _root_.power_basis F K)
/-- If `L` is a field extension of `F` and `f` is a polynomial over `F` then the set
of maps from `F[x]/(f)` into `L` is in bijection with the set of roots of `f` in `L`. -/
def equiv (f : F[X]) (hf : f ≠ 0) :
(adjoin_root f →ₐ[F] L) ≃ {x // x ∈ (f.map (algebra_map F L)).roots} :=
(power_basis hf).lift_equiv'.trans ((equiv.refl _).subtype_equiv (λ x,
begin
rw [power_basis_gen, minpoly_root hf, polynomial.map_mul, roots_mul,
polynomial.map_C, roots_C, add_zero, equiv.refl_apply],
{ rw ← polynomial.map_mul, exact map_monic_ne_zero (monic_mul_leading_coeff_inv hf) }
end))
end field
end equiv
section
open ideal double_quot polynomial
variables [comm_ring R] (I : ideal R) (f : polynomial R)
/-- The natural isomorphism `R[α]/(I[α]) ≅ R[α]/((I[x] ⊔ (f)) / (f))` for `α` a root of
`f : polynomial R` and `I : ideal R`.
See `adjoin_root.quot_map_of_equiv` for the isomorphism with `(R/I)[X] / (f mod I)`. -/
def quot_map_of_equiv_quot_map_C_map_span_mk :
adjoin_root f ⧸ I.map (of f) ≃+*
adjoin_root f ⧸ (I.map (C : R →+* R[X])).map (span {f})^.quotient.mk :=
ideal.quot_equiv_of_eq (by rw [of, adjoin_root.mk, ideal.map_map])
@[simp]
lemma quot_map_of_equiv_quot_map_C_map_span_mk_mk (x : adjoin_root f) :
quot_map_of_equiv_quot_map_C_map_span_mk I f (ideal.quotient.mk (I.map (of f)) x) =
ideal.quotient.mk _ x :=
rfl
/-- The natural isomorphism `R[α]/((I[x] ⊔ (f)) / (f)) ≅ (R[x]/I[x])/((f) ⊔ I[x] / I[x])`
for `α` a root of `f : polynomial R` and `I : ideal R`-/
def quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk :
(adjoin_root f) ⧸ (I.map (C : R →+* R[X])).map (span ({f} : set R[X]))^.quotient.mk ≃+*
(R[X] ⧸ I.map (C : R →+* R[X])) ⧸ (span ({f} : set R[X])).map
(I.map (C : R →+* R[X]))^.quotient.mk :=
quot_quot_equiv_comm (ideal.span ({f} : set (polynomial R))) (I.map (C : R →+* polynomial R))
@[simp]
lemma quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk_mk (p : R[X]) :
quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk I f (ideal.quotient.mk _ (mk f p)) =
quot_quot_mk (I.map C) (span {f}) p :=
rfl
/-- The natural isomorphism `(R/I)[x]/(f mod I) ≅ (R[x]/I*R[x])/(f mod I[x])` where
`f : polynomial R` and `I : ideal R`-/
def polynomial.quot_quot_equiv_comm :
(R ⧸ I)[X] ⧸ span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I))) ≃+*
(R[X] ⧸ map C I) ⧸ span ({(ideal.quotient.mk (I.map C)) f} : set (R[X] ⧸ map C I)) :=
quotient_equiv (span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I))))
(span {ideal.quotient.mk (I.map polynomial.C) f})
(polynomial_quotient_equiv_quotient_polynomial I)
(by rw [map_span, set.image_singleton, ring_equiv.coe_to_ring_hom,
polynomial_quotient_equiv_quotient_polynomial_map_mk I f])
@[simp]
lemma polynomial.quot_quot_equiv_comm_mk_mk (p : R[X]) :
(polynomial.quot_quot_equiv_comm I f).symm (ideal.quotient.mk _ (ideal.quotient.mk _ p)) =
(ideal.quotient.mk _ (p.map I^.quotient.mk)) :=
by simp only [polynomial.quot_quot_equiv_comm, quotient_equiv_symm_mk,
polynomial_quotient_equiv_quotient_polynomial_symm_mk]
/-- The natural isomorphism `R[α]/I[α] ≅ (R/I)[X]/(f mod I)` for `α` a root of `f : polynomial R`
and `I : ideal R`-/
def quot_map_of_equiv : (adjoin_root f) ⧸ (I.map (of f)) ≃+*
polynomial (R ⧸ I) ⧸ (span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I)))) :=
(quot_map_of_equiv_quot_map_C_map_span_mk I f).trans
((quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk I f).trans
((ideal.quot_equiv_of_eq
(show (span ({f} : set (polynomial R))).map (I.map (C : R →+* polynomial R))^.quotient.mk =
span ({(ideal.quotient.mk (I.map polynomial.C)) f} : set (polynomial R ⧸ map C I)),
from by rw [map_span, set.image_singleton])).trans
(polynomial.quot_quot_equiv_comm I f).symm))
@[simp]
lemma quot_adjoin_root_equiv_quot_polynomial_quot_mk_of (p : R[X]) :
quot_map_of_equiv I f (ideal.quotient.mk (I.map (of f)) (mk f p)) =
ideal.quotient.mk (span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I))))
(p.map I^.quotient.mk) :=
by rw [quot_map_of_equiv, ring_equiv.trans_apply, ring_equiv.trans_apply, ring_equiv.trans_apply,
quot_map_of_equiv_quot_map_C_map_span_mk_mk,
quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk_mk,quot_quot_mk, ring_hom.comp_apply,
quot_equiv_of_eq_mk, polynomial.quot_quot_equiv_comm_mk_mk]
end
end adjoin_root
|
b676be33e5a21f8c782a4ea4d9f753f172f976a8 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/bilinear_form.lean | c2aff4436f65f3faa2aad085c26a076493040b22 | [
"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 | 54,851 | lean | /-
Copyright (c) 2018 Andreas Swerdlow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andreas Swerdlow, Kexing Ying
-/
import linear_algebra.dual
import linear_algebra.free_module.finite.matrix
/-!
# Bilinear form
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines a bilinear form over a module. Basic ideas
such as orthogonality are also introduced, as well as reflexivive,
symmetric, non-degenerate and alternating bilinear forms. Adjoints of
linear maps with respect to a bilinear form are also introduced.
A bilinear form on an R-(semi)module M, is a function from M x M to R,
that is linear in both arguments. Comments will typically abbreviate
"(semi)module" as just "module", but the definitions should be as general as
possible.
The result that there exists an orthogonal basis with respect to a symmetric,
nondegenerate bilinear form can be found in `quadratic_form.lean` with
`exists_orthogonal_basis`.
## Notations
Given any term B of type bilin_form, due to a coercion, can use
the notation B x y to refer to the function field, ie. B x y = B.bilin x y.
In this file we use the following type variables:
- `M`, `M'`, ... are modules over the semiring `R`,
- `M₁`, `M₁'`, ... are modules over the ring `R₁`,
- `M₂`, `M₂'`, ... are modules over the commutative semiring `R₂`,
- `M₃`, `M₃'`, ... are modules over the commutative ring `R₃`,
- `V`, ... is a vector space over the field `K`.
## References
* <https://en.wikipedia.org/wiki/Bilinear_form>
## Tags
Bilinear form,
-/
open_locale big_operators
universes u v w
/-- `bilin_form R M` is the type of `R`-bilinear functions `M → M → R`. -/
structure bilin_form (R : Type*) (M : Type*) [semiring R] [add_comm_monoid M] [module R M] :=
(bilin : M → M → R)
(bilin_add_left : ∀ (x y z : M), bilin (x + y) z = bilin x z + bilin y z)
(bilin_smul_left : ∀ (a : R) (x y : M), bilin (a • x) y = a * (bilin x y))
(bilin_add_right : ∀ (x y z : M), bilin x (y + z) = bilin x y + bilin x z)
(bilin_smul_right : ∀ (a : R) (x y : M), bilin x (a • y) = a * (bilin x y))
variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M]
variables {R₁ : Type*} {M₁ : Type*} [ring R₁] [add_comm_group M₁] [module R₁ M₁]
variables {R₂ : Type*} {M₂ : Type*} [comm_semiring R₂] [add_comm_monoid M₂] [module R₂ M₂]
variables {R₃ : Type*} {M₃ : Type*} [comm_ring R₃] [add_comm_group M₃] [module R₃ M₃]
variables {V : Type*} {K : Type*} [field K] [add_comm_group V] [module K V]
variables {B : bilin_form R M} {B₁ : bilin_form R₁ M₁} {B₂ : bilin_form R₂ M₂}
namespace bilin_form
instance : has_coe_to_fun (bilin_form R M) (λ _, M → M → R) := ⟨bilin⟩
initialize_simps_projections bilin_form (bilin -> apply)
@[simp] lemma coe_fn_mk (f : M → M → R) (h₁ h₂ h₃ h₄) :
(bilin_form.mk f h₁ h₂ h₃ h₄ : M → M → R) = f :=
rfl
lemma coe_fn_congr : Π {x x' y y' : M}, x = x' → y = y' → B x y = B x' y'
| _ _ _ _ rfl rfl := rfl
@[simp]
lemma add_left (x y z : M) : B (x + y) z = B x z + B y z := bilin_add_left B x y z
@[simp]
lemma smul_left (a : R) (x y : M) : B (a • x) y = a * (B x y) := bilin_smul_left B a x y
@[simp]
lemma add_right (x y z : M) : B x (y + z) = B x y + B x z := bilin_add_right B x y z
@[simp]
lemma smul_right (a : R) (x y : M) : B x (a • y) = a * (B x y) := bilin_smul_right B a x y
@[simp]
lemma zero_left (x : M) : B 0 x = 0 :=
by { rw [←@zero_smul R _ _ _ _ (0 : M), smul_left, zero_mul] }
@[simp]
lemma zero_right (x : M) : B x 0 = 0 :=
by rw [←@zero_smul _ _ _ _ _ (0 : M), smul_right, zero_mul]
@[simp]
lemma neg_left (x y : M₁) : B₁ (-x) y = -(B₁ x y) :=
by rw [←@neg_one_smul R₁ _ _, smul_left, neg_one_mul]
@[simp]
lemma neg_right (x y : M₁) : B₁ x (-y) = -(B₁ x y) :=
by rw [←@neg_one_smul R₁ _ _, smul_right, neg_one_mul]
@[simp]
lemma sub_left (x y z : M₁) : B₁ (x - y) z = B₁ x z - B₁ y z :=
by rw [sub_eq_add_neg, sub_eq_add_neg, add_left, neg_left]
@[simp]
lemma sub_right (x y z : M₁) : B₁ x (y - z) = B₁ x y - B₁ x z :=
by rw [sub_eq_add_neg, sub_eq_add_neg, add_right, neg_right]
variables {D : bilin_form R M} {D₁ : bilin_form R₁ M₁}
-- TODO: instantiate `fun_like`
lemma coe_injective : function.injective (coe_fn : bilin_form R M → (M → M → R)) :=
λ B D h, by { cases B, cases D, congr' }
@[ext] lemma ext (H : ∀ (x y : M), B x y = D x y) : B = D :=
coe_injective $ by { funext, exact H _ _ }
lemma congr_fun (h : B = D) (x y : M) : B x y = D x y := h ▸ rfl
lemma ext_iff : B = D ↔ (∀ x y, B x y = D x y) := ⟨congr_fun, ext⟩
instance : has_zero (bilin_form R M) :=
{ zero := { bilin := λ x y, 0,
bilin_add_left := λ x y z, (add_zero 0).symm,
bilin_smul_left := λ a x y, (mul_zero a).symm,
bilin_add_right := λ x y z, (zero_add 0).symm,
bilin_smul_right := λ a x y, (mul_zero a).symm } }
@[simp] lemma coe_zero : ⇑(0 : bilin_form R M) = 0 := rfl
@[simp] lemma zero_apply (x y : M) : (0 : bilin_form R M) x y = 0 := rfl
variables (B D B₁ D₁)
instance : has_add (bilin_form R M) :=
{ add := λ B D, { bilin := λ x y, B x y + D x y,
bilin_add_left := λ x y z, by rw [add_left, add_left, add_add_add_comm],
bilin_smul_left := λ a x y, by rw [smul_left, smul_left, mul_add],
bilin_add_right := λ x y z, by rw [add_right, add_right, add_add_add_comm],
bilin_smul_right := λ a x y, by rw [smul_right, smul_right, mul_add] } }
@[simp] lemma coe_add : ⇑(B + D) = B + D := rfl
@[simp] lemma add_apply (x y : M) : (B + D) x y = B x y + D x y := rfl
/-- `bilin_form R M` inherits the scalar action by `α` on `R` if this is compatible with
multiplication.
When `R` itself is commutative, this provides an `R`-action via `algebra.id`. -/
instance {α} [monoid α] [distrib_mul_action α R] [smul_comm_class α R R] :
has_smul α (bilin_form R M) :=
{ smul := λ c B,
{ bilin := λ x y, c • B x y,
bilin_add_left := λ x y z, by { rw [add_left, smul_add] },
bilin_smul_left := λ a x y, by { rw [smul_left, ←mul_smul_comm] },
bilin_add_right := λ x y z, by { rw [add_right, smul_add] },
bilin_smul_right := λ a x y, by { rw [smul_right, ←mul_smul_comm] } } }
@[simp] lemma coe_smul {α} [monoid α] [distrib_mul_action α R] [smul_comm_class α R R]
(a : α) (B : bilin_form R M) : ⇑(a • B) = a • B := rfl
@[simp] lemma smul_apply {α} [monoid α] [distrib_mul_action α R] [smul_comm_class α R R]
(a : α) (B : bilin_form R M) (x y : M) :
(a • B) x y = a • (B x y) :=
rfl
instance : add_comm_monoid (bilin_form R M) :=
function.injective.add_comm_monoid _ coe_injective coe_zero coe_add (λ n x, coe_smul _ _)
instance : has_neg (bilin_form R₁ M₁) :=
{ neg := λ B, { bilin := λ x y, -(B x y),
bilin_add_left := λ x y z, by rw [add_left, neg_add],
bilin_smul_left := λ a x y, by rw [smul_left, mul_neg],
bilin_add_right := λ x y z, by rw [add_right, neg_add],
bilin_smul_right := λ a x y, by rw [smul_right, mul_neg] } }
@[simp] lemma coe_neg : ⇑(-B₁) = -B₁ := rfl
@[simp] lemma neg_apply (x y : M₁) : (-B₁) x y = -(B₁ x y) := rfl
instance : has_sub (bilin_form R₁ M₁) :=
{ sub := λ B D, { bilin := λ x y, B x y - D x y,
bilin_add_left := λ x y z, by rw [add_left, add_left, add_sub_add_comm],
bilin_smul_left := λ a x y, by rw [smul_left, smul_left, mul_sub],
bilin_add_right := λ x y z, by rw [add_right, add_right, add_sub_add_comm],
bilin_smul_right := λ a x y, by rw [smul_right, smul_right, mul_sub] } }
@[simp] lemma coe_sub : ⇑(B₁ - D₁) = B₁ - D₁ := rfl
@[simp] lemma sub_apply (x y : M₁) : (B₁ - D₁) x y = B₁ x y - D₁ x y := rfl
instance : add_comm_group (bilin_form R₁ M₁) :=
function.injective.add_comm_group _ coe_injective coe_zero coe_add coe_neg coe_sub
(λ n x, coe_smul _ _) (λ n x, coe_smul _ _)
instance : inhabited (bilin_form R M) := ⟨0⟩
/-- `coe_fn` as an `add_monoid_hom` -/
def coe_fn_add_monoid_hom : bilin_form R M →+ (M → M → R) :=
{ to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add }
instance {α} [monoid α] [distrib_mul_action α R] [smul_comm_class α R R] :
distrib_mul_action α (bilin_form R M) :=
function.injective.distrib_mul_action coe_fn_add_monoid_hom coe_injective coe_smul
instance {α} [semiring α] [module α R] [smul_comm_class α R R] :
module α (bilin_form R M) :=
function.injective.module _ coe_fn_add_monoid_hom coe_injective coe_smul
section flip
variables (R₂)
/-- Auxiliary construction for the flip of a bilinear form, obtained by exchanging the left and
right arguments. This version is a `linear_map`; it is later upgraded to a `linear_equiv`
in `flip_hom`. -/
def flip_hom_aux [algebra R₂ R] : bilin_form R M →ₗ[R₂] bilin_form R M :=
{ to_fun := λ A,
{ bilin := λ i j, A j i,
bilin_add_left := λ x y z, A.bilin_add_right z x y,
bilin_smul_left := λ a x y, A.bilin_smul_right a y x,
bilin_add_right := λ x y z, A.bilin_add_left y z x,
bilin_smul_right := λ a x y, A.bilin_smul_left a y x },
map_add' := λ A₁ A₂, by { ext, simp } ,
map_smul' := λ c A, by { ext, simp } }
variables {R₂}
lemma flip_flip_aux [algebra R₂ R] (A : bilin_form R M) :
(flip_hom_aux R₂) (flip_hom_aux R₂ A) = A :=
by { ext A x y, simp [flip_hom_aux] }
variables (R₂)
/-- The flip of a bilinear form, obtained by exchanging the left and right arguments. This is a
less structured version of the equiv which applies to general (noncommutative) rings `R` with a
distinguished commutative subring `R₂`; over a commutative ring use `flip`. -/
def flip_hom [algebra R₂ R] : bilin_form R M ≃ₗ[R₂] bilin_form R M :=
{ inv_fun := flip_hom_aux R₂,
left_inv := flip_flip_aux,
right_inv := flip_flip_aux,
.. flip_hom_aux R₂ }
variables {R₂}
@[simp] lemma flip_apply [algebra R₂ R] (A : bilin_form R M) (x y : M) :
flip_hom R₂ A x y = A y x :=
rfl
lemma flip_flip [algebra R₂ R] :
(flip_hom R₂).trans (flip_hom R₂) = linear_equiv.refl R₂ (bilin_form R M) :=
by { ext A x y, simp }
/-- The flip of a bilinear form over a ring, obtained by exchanging the left and right arguments,
here considered as an `ℕ`-linear equivalence, i.e. an additive equivalence. -/
abbreviation flip' : bilin_form R M ≃ₗ[ℕ] bilin_form R M := flip_hom ℕ
/-- The `flip` of a bilinear form over a commutative ring, obtained by exchanging the left and
right arguments. -/
abbreviation flip : bilin_form R₂ M₂ ≃ₗ[R₂] bilin_form R₂ M₂ := flip_hom R₂
end flip
section to_lin'
variables [algebra R₂ R] [module R₂ M] [is_scalar_tower R₂ R M]
/-- Auxiliary definition to define `to_lin_hom`; see below. -/
def to_lin_hom_aux₁ (A : bilin_form R M) (x : M) : M →ₗ[R] R :=
{ to_fun := λ y, A x y,
map_add' := A.bilin_add_right x,
map_smul' := λ c, A.bilin_smul_right c x }
/-- Auxiliary definition to define `to_lin_hom`; see below. -/
def to_lin_hom_aux₂ (A : bilin_form R M) : M →ₗ[R₂] M →ₗ[R] R :=
{ to_fun := to_lin_hom_aux₁ A,
map_add' := λ x₁ x₂, linear_map.ext $ λ x, by simp only [to_lin_hom_aux₁, linear_map.coe_mk,
linear_map.add_apply, add_left],
map_smul' := λ c x, linear_map.ext $
begin
dsimp [to_lin_hom_aux₁],
intros,
simp only [← algebra_map_smul R c x, algebra.smul_def, linear_map.coe_mk,
linear_map.smul_apply, smul_left]
end }
variables (R₂)
/-- The linear map obtained from a `bilin_form` by fixing the left co-ordinate and evaluating in
the right.
This is the most general version of the construction; it is `R₂`-linear for some distinguished
commutative subsemiring `R₂` of the scalar ring. Over a semiring with no particular distinguished
such subsemiring, use `to_lin'`, which is `ℕ`-linear. Over a commutative semiring, use `to_lin`,
which is linear. -/
def to_lin_hom : bilin_form R M →ₗ[R₂] M →ₗ[R₂] M →ₗ[R] R :=
{ to_fun := to_lin_hom_aux₂,
map_add' := λ A₁ A₂, linear_map.ext $ λ x,
begin
dsimp only [to_lin_hom_aux₁, to_lin_hom_aux₂],
apply linear_map.ext,
intros y,
simp only [to_lin_hom_aux₂, to_lin_hom_aux₁, linear_map.coe_mk,
linear_map.add_apply, add_apply],
end ,
map_smul' := λ c A,
begin
dsimp [to_lin_hom_aux₁, to_lin_hom_aux₂],
apply linear_map.ext,
intros x,
apply linear_map.ext,
intros y,
simp only [to_lin_hom_aux₂, to_lin_hom_aux₁,
linear_map.coe_mk, linear_map.smul_apply, smul_apply],
end }
variables {R₂}
@[simp] lemma to_lin'_apply (A : bilin_form R M) (x : M) :
⇑(to_lin_hom R₂ A x) = A x :=
rfl
/-- The linear map obtained from a `bilin_form` by fixing the left co-ordinate and evaluating in
the right.
Over a commutative semiring, use `to_lin`, which is linear rather than `ℕ`-linear. -/
abbreviation to_lin' : bilin_form R M →ₗ[ℕ] M →ₗ[ℕ] M →ₗ[R] R := to_lin_hom ℕ
@[simp]
lemma sum_left {α} (t : finset α) (g : α → M) (w : M) :
B (∑ i in t, g i) w = ∑ i in t, B (g i) w :=
(bilin_form.to_lin' B).map_sum₂ t g w
@[simp]
lemma sum_right {α} (t : finset α) (w : M) (g : α → M) :
B w (∑ i in t, g i) = ∑ i in t, B w (g i) :=
(bilin_form.to_lin' B w).map_sum
variables (R₂)
/-- The linear map obtained from a `bilin_form` by fixing the right co-ordinate and evaluating in
the left.
This is the most general version of the construction; it is `R₂`-linear for some distinguished
commutative subsemiring `R₂` of the scalar ring. Over semiring with no particular distinguished
such subsemiring, use `to_lin'_flip`, which is `ℕ`-linear. Over a commutative semiring, use
`to_lin_flip`, which is linear. -/
def to_lin_hom_flip : bilin_form R M →ₗ[R₂] M →ₗ[R₂] M →ₗ[R] R :=
(to_lin_hom R₂).comp (flip_hom R₂).to_linear_map
variables {R₂}
@[simp] lemma to_lin'_flip_apply (A : bilin_form R M) (x : M) :
⇑(to_lin_hom_flip R₂ A x) = λ y, A y x :=
rfl
/-- The linear map obtained from a `bilin_form` by fixing the right co-ordinate and evaluating in
the left.
Over a commutative semiring, use `to_lin_flip`, which is linear rather than `ℕ`-linear. -/
abbreviation to_lin'_flip : bilin_form R M →ₗ[ℕ] M →ₗ[ℕ] M →ₗ[R] R := to_lin_hom_flip ℕ
end to_lin'
end bilin_form
section equiv_lin
/-- A map with two arguments that is linear in both is a bilinear form.
This is an auxiliary definition for the full linear equivalence `linear_map.to_bilin`.
-/
def linear_map.to_bilin_aux (f : M₂ →ₗ[R₂] M₂ →ₗ[R₂] R₂) : bilin_form R₂ M₂ :=
{ bilin := λ x y, f x y,
bilin_add_left := λ x y z, (linear_map.map_add f x y).symm ▸ linear_map.add_apply (f x) (f y) z,
bilin_smul_left := λ a x y, by rw [linear_map.map_smul, linear_map.smul_apply, smul_eq_mul],
bilin_add_right := λ x y z, linear_map.map_add (f x) y z,
bilin_smul_right := λ a x y, linear_map.map_smul (f x) a y }
/-- Bilinear forms are linearly equivalent to maps with two arguments that are linear in both. -/
def bilin_form.to_lin : bilin_form R₂ M₂ ≃ₗ[R₂] (M₂ →ₗ[R₂] M₂ →ₗ[R₂] R₂) :=
{ inv_fun := linear_map.to_bilin_aux,
left_inv := λ B, by { ext, simp [linear_map.to_bilin_aux] },
right_inv := λ B, by { ext, simp [linear_map.to_bilin_aux] },
.. bilin_form.to_lin_hom R₂ }
/-- A map with two arguments that is linear in both is linearly equivalent to bilinear form. -/
def linear_map.to_bilin : (M₂ →ₗ[R₂] M₂ →ₗ[R₂] R₂) ≃ₗ[R₂] bilin_form R₂ M₂ :=
bilin_form.to_lin.symm
@[simp] lemma linear_map.to_bilin_aux_eq (f : M₂ →ₗ[R₂] M₂ →ₗ[R₂] R₂) :
linear_map.to_bilin_aux f = linear_map.to_bilin f :=
rfl
@[simp] lemma linear_map.to_bilin_symm :
(linear_map.to_bilin.symm : bilin_form R₂ M₂ ≃ₗ[R₂] _) = bilin_form.to_lin := rfl
@[simp] lemma bilin_form.to_lin_symm :
(bilin_form.to_lin.symm : _ ≃ₗ[R₂] bilin_form R₂ M₂) = linear_map.to_bilin :=
linear_map.to_bilin.symm_symm
@[simp, norm_cast]
lemma bilin_form.to_lin_apply (x : M₂) : ⇑(bilin_form.to_lin B₂ x) = B₂ x := rfl
end equiv_lin
namespace linear_map
variables {R' : Type*} [comm_semiring R'] [algebra R' R] [module R' M] [is_scalar_tower R' R M]
/-- Apply a linear map on the output of a bilinear form. -/
@[simps]
def comp_bilin_form (f : R →ₗ[R'] R') (B : bilin_form R M) : bilin_form R' M :=
{ bilin := λ x y, f (B x y),
bilin_add_left := λ x y z, by rw [bilin_form.add_left, map_add],
bilin_smul_left := λ r x y, by rw [←smul_one_smul R r (_ : M), bilin_form.smul_left,
smul_one_mul r (_ : R), map_smul, smul_eq_mul],
bilin_add_right := λ x y z, by rw [bilin_form.add_right, map_add],
bilin_smul_right := λ r x y, by rw [←smul_one_smul R r (_ : M), bilin_form.smul_right,
smul_one_mul r (_ : R), map_smul, smul_eq_mul] }
end linear_map
namespace bilin_form
section comp
variables {M' : Type w} [add_comm_monoid M'] [module R M']
/-- Apply a linear map on the left and right argument of a bilinear form. -/
def comp (B : bilin_form R M') (l r : M →ₗ[R] M') : bilin_form R M :=
{ bilin := λ x y, B (l x) (r y),
bilin_add_left := λ x y z, by rw [linear_map.map_add, add_left],
bilin_smul_left := λ x y z, by rw [linear_map.map_smul, smul_left],
bilin_add_right := λ x y z, by rw [linear_map.map_add, add_right],
bilin_smul_right := λ x y z, by rw [linear_map.map_smul, smul_right] }
/-- Apply a linear map to the left argument of a bilinear form. -/
def comp_left (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M :=
B.comp f linear_map.id
/-- Apply a linear map to the right argument of a bilinear form. -/
def comp_right (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M :=
B.comp linear_map.id f
lemma comp_comp {M'' : Type*} [add_comm_monoid M''] [module R M'']
(B : bilin_form R M'') (l r : M →ₗ[R] M') (l' r' : M' →ₗ[R] M'') :
(B.comp l' r').comp l r = B.comp (l'.comp l) (r'.comp r) := rfl
@[simp] lemma comp_left_comp_right (B : bilin_form R M) (l r : M →ₗ[R] M) :
(B.comp_left l).comp_right r = B.comp l r := rfl
@[simp] lemma comp_right_comp_left (B : bilin_form R M) (l r : M →ₗ[R] M) :
(B.comp_right r).comp_left l = B.comp l r := rfl
@[simp] lemma comp_apply (B : bilin_form R M') (l r : M →ₗ[R] M') (v w) :
B.comp l r v w = B (l v) (r w) := rfl
@[simp] lemma comp_left_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) :
B.comp_left f v w = B (f v) w := rfl
@[simp] lemma comp_right_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) :
B.comp_right f v w = B v (f w) := rfl
@[simp] lemma comp_id_left (B : bilin_form R M) (r : M →ₗ[R] M) :
B.comp linear_map.id r = B.comp_right r :=
by { ext, refl }
@[simp] lemma comp_id_right (B : bilin_form R M) (l : M →ₗ[R] M) :
B.comp l linear_map.id = B.comp_left l :=
by { ext, refl }
@[simp] lemma comp_left_id (B : bilin_form R M) :
B.comp_left linear_map.id = B :=
by { ext, refl }
@[simp] lemma comp_right_id (B : bilin_form R M) :
B.comp_right linear_map.id = B :=
by { ext, refl }
-- Shortcut for `comp_id_{left,right}` followed by `comp_{right,left}_id`,
-- has to be declared after the former two to get the right priority
@[simp] lemma comp_id_id (B : bilin_form R M) :
B.comp linear_map.id linear_map.id = B :=
by { ext, refl }
lemma comp_inj (B₁ B₂ : bilin_form R M') {l r : M →ₗ[R] M'}
(hₗ : function.surjective l) (hᵣ : function.surjective r) :
B₁.comp l r = B₂.comp l r ↔ B₁ = B₂ :=
begin
split; intros h,
{ -- B₁.comp l r = B₂.comp l r → B₁ = B₂
ext,
cases hₗ x with x' hx, subst hx,
cases hᵣ y with y' hy, subst hy,
rw [←comp_apply, ←comp_apply, h], },
{ -- B₁ = B₂ → B₁.comp l r = B₂.comp l r
subst h, },
end
end comp
variables {M₂' M₂'' : Type*}
variables [add_comm_monoid M₂'] [add_comm_monoid M₂''] [module R₂ M₂'] [module R₂ M₂'']
section congr
/-- Apply a linear equivalence on the arguments of a bilinear form. -/
def congr (e : M₂ ≃ₗ[R₂] M₂') : bilin_form R₂ M₂ ≃ₗ[R₂] bilin_form R₂ M₂' :=
{ to_fun := λ B, B.comp e.symm e.symm,
inv_fun := λ B, B.comp e e,
left_inv :=
λ B, ext (λ x y, by simp only [comp_apply, linear_equiv.coe_coe, e.symm_apply_apply]),
right_inv :=
λ B, ext (λ x y, by simp only [comp_apply, linear_equiv.coe_coe, e.apply_symm_apply]),
map_add' := λ B B', ext (λ x y, by simp only [comp_apply, add_apply]),
map_smul' := λ B B', ext (λ x y, by simp [comp_apply, smul_apply]) }
@[simp] lemma congr_apply (e : M₂ ≃ₗ[R₂] M₂') (B : bilin_form R₂ M₂) (x y : M₂') :
congr e B x y = B (e.symm x) (e.symm y) := rfl
@[simp] lemma congr_symm (e : M₂ ≃ₗ[R₂] M₂') :
(congr e).symm = congr e.symm :=
by { ext B x y, simp only [congr_apply, linear_equiv.symm_symm], refl }
@[simp] lemma congr_refl : congr (linear_equiv.refl R₂ M₂) = linear_equiv.refl R₂ _ :=
linear_equiv.ext $ λ B, ext $ λ x y, rfl
lemma congr_trans (e : M₂ ≃ₗ[R₂] M₂') (f : M₂' ≃ₗ[R₂] M₂'') :
(congr e).trans (congr f) = congr (e.trans f) := rfl
lemma congr_congr (e : M₂' ≃ₗ[R₂] M₂'') (f : M₂ ≃ₗ[R₂] M₂') (B : bilin_form R₂ M₂) :
congr e (congr f B) = congr (f.trans e) B := rfl
lemma congr_comp (e : M₂ ≃ₗ[R₂] M₂') (B : bilin_form R₂ M₂) (l r : M₂'' →ₗ[R₂] M₂') :
(congr e B).comp l r = B.comp
(linear_map.comp (e.symm : M₂' →ₗ[R₂] M₂) l)
(linear_map.comp (e.symm : M₂' →ₗ[R₂] M₂) r) :=
rfl
lemma comp_congr (e : M₂' ≃ₗ[R₂] M₂'') (B : bilin_form R₂ M₂) (l r : M₂' →ₗ[R₂] M₂) :
congr e (B.comp l r) = B.comp
(l.comp (e.symm : M₂'' →ₗ[R₂] M₂'))
(r.comp (e.symm : M₂'' →ₗ[R₂] M₂')) :=
rfl
end congr
section lin_mul_lin
/-- `lin_mul_lin f g` is the bilinear form mapping `x` and `y` to `f x * g y` -/
def lin_mul_lin (f g : M₂ →ₗ[R₂] R₂) : bilin_form R₂ M₂ :=
{ bilin := λ x y, f x * g y,
bilin_add_left := λ x y z, by rw [linear_map.map_add, add_mul],
bilin_smul_left := λ x y z, by rw [linear_map.map_smul, smul_eq_mul, mul_assoc],
bilin_add_right := λ x y z, by rw [linear_map.map_add, mul_add],
bilin_smul_right := λ x y z, by rw [linear_map.map_smul, smul_eq_mul, mul_left_comm] }
variables {f g : M₂ →ₗ[R₂] R₂}
@[simp] lemma lin_mul_lin_apply (x y) : lin_mul_lin f g x y = f x * g y := rfl
@[simp] lemma lin_mul_lin_comp (l r : M₂' →ₗ[R₂] M₂) :
(lin_mul_lin f g).comp l r = lin_mul_lin (f.comp l) (g.comp r) :=
rfl
@[simp] lemma lin_mul_lin_comp_left (l : M₂ →ₗ[R₂] M₂) :
(lin_mul_lin f g).comp_left l = lin_mul_lin (f.comp l) g :=
rfl
@[simp] lemma lin_mul_lin_comp_right (r : M₂ →ₗ[R₂] M₂) :
(lin_mul_lin f g).comp_right r = lin_mul_lin f (g.comp r) :=
rfl
end lin_mul_lin
/-- The proposition that two elements of a bilinear form space are orthogonal. For orthogonality
of an indexed set of elements, use `bilin_form.is_Ortho`. -/
def is_ortho (B : bilin_form R M) (x y : M) : Prop :=
B x y = 0
lemma is_ortho_def {B : bilin_form R M} {x y : M} :
B.is_ortho x y ↔ B x y = 0 := iff.rfl
lemma is_ortho_zero_left (x : M) : is_ortho B (0 : M) x :=
zero_left x
lemma is_ortho_zero_right (x : M) : is_ortho B x (0 : M) :=
zero_right x
lemma ne_zero_of_not_is_ortho_self {B : bilin_form K V}
(x : V) (hx₁ : ¬ B.is_ortho x x) : x ≠ 0 :=
λ hx₂, hx₁ (hx₂.symm ▸ is_ortho_zero_left _)
/-- A set of vectors `v` is orthogonal with respect to some bilinear form `B` if and only
if for all `i ≠ j`, `B (v i) (v j) = 0`. For orthogonality between two elements, use
`bilin_form.is_ortho` -/
def is_Ortho {n : Type w} (B : bilin_form R M) (v : n → M) : Prop :=
pairwise (B.is_ortho on v)
lemma is_Ortho_def {n : Type w} {B : bilin_form R M} {v : n → M} :
B.is_Ortho v ↔ ∀ i j : n, i ≠ j → B (v i) (v j) = 0 := iff.rfl
section
variables {R₄ M₄ : Type*} [ring R₄] [is_domain R₄]
variables [add_comm_group M₄] [module R₄ M₄] {G : bilin_form R₄ M₄}
@[simp]
theorem is_ortho_smul_left {x y : M₄} {a : R₄} (ha : a ≠ 0) :
is_ortho G (a • x) y ↔ is_ortho G x y :=
begin
dunfold is_ortho,
split; intro H,
{ rw [smul_left, mul_eq_zero] at H,
cases H,
{ trivial },
{ exact H }},
{ rw [smul_left, H, mul_zero] },
end
@[simp]
theorem is_ortho_smul_right {x y : M₄} {a : R₄} (ha : a ≠ 0) :
is_ortho G x (a • y) ↔ is_ortho G x y :=
begin
dunfold is_ortho,
split; intro H,
{ rw [smul_right, mul_eq_zero] at H,
cases H,
{ trivial },
{ exact H }},
{ rw [smul_right, H, mul_zero] },
end
/-- A set of orthogonal vectors `v` with respect to some bilinear form `B` is linearly independent
if for all `i`, `B (v i) (v i) ≠ 0`. -/
lemma linear_independent_of_is_Ortho
{n : Type w} {B : bilin_form K V} {v : n → V}
(hv₁ : B.is_Ortho v) (hv₂ : ∀ i, ¬ B.is_ortho (v i) (v i)) :
linear_independent K v :=
begin
classical,
rw linear_independent_iff',
intros s w hs i hi,
have : B (s.sum $ λ (i : n), w i • v i) (v i) = 0,
{ rw [hs, zero_left] },
have hsum : s.sum (λ (j : n), w j * B (v j) (v i)) = w i * B (v i) (v i),
{ apply finset.sum_eq_single_of_mem i hi,
intros j hj hij,
rw [is_Ortho_def.1 hv₁ _ _ hij, mul_zero], },
simp_rw [sum_left, smul_left, hsum] at this,
exact eq_zero_of_ne_zero_of_mul_right_eq_zero (hv₂ i) this,
end
end
section basis
variables {F₂ : bilin_form R₂ M₂}
variables {ι : Type*} (b : basis ι R₂ M₂)
/-- Two bilinear forms are equal when they are equal on all basis vectors. -/
lemma ext_basis (h : ∀ i j, B₂ (b i) (b j) = F₂ (b i) (b j)) : B₂ = F₂ :=
to_lin.injective $ b.ext $ λ i, b.ext $ λ j, h i j
/-- Write out `B x y` as a sum over `B (b i) (b j)` if `b` is a basis. -/
lemma sum_repr_mul_repr_mul (x y : M₂) :
(b.repr x).sum (λ i xi, (b.repr y).sum (λ j yj, xi • yj • B₂ (b i) (b j))) = B₂ x y :=
begin
conv_rhs { rw [← b.total_repr x, ← b.total_repr y] },
simp_rw [finsupp.total_apply, finsupp.sum, sum_left, sum_right,
smul_left, smul_right, smul_eq_mul],
end
end basis
/-! ### Reflexivity, symmetry, and alternativity -/
/-- The proposition that a bilinear form is reflexive -/
def is_refl (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = 0 → B y x = 0
namespace is_refl
variable (H : B.is_refl)
lemma eq_zero : ∀ {x y : M}, B x y = 0 → B y x = 0 := λ x y, H x y
lemma ortho_comm {x y : M} :
is_ortho B x y ↔ is_ortho B y x := ⟨eq_zero H, eq_zero H⟩
protected lemma neg {B : bilin_form R₁ M₁} (hB : B.is_refl) : (-B).is_refl :=
λ x y, neg_eq_zero.mpr ∘ hB x y ∘ neg_eq_zero.mp
protected lemma smul {α} [semiring α] [module α R] [smul_comm_class α R R]
[no_zero_smul_divisors α R] (a : α) {B : bilin_form R M} (hB : B.is_refl) : (a • B).is_refl :=
λ x y h, (smul_eq_zero.mp h).elim
(λ ha, smul_eq_zero_of_left ha _)
(λ hBz, smul_eq_zero_of_right _ (hB _ _ hBz))
protected lemma group_smul {α} [group α] [distrib_mul_action α R] [smul_comm_class α R R]
(a : α) {B : bilin_form R M} (hB : B.is_refl) : (a • B).is_refl :=
λ x y, (smul_eq_zero_iff_eq _).mpr ∘ hB x y ∘ (smul_eq_zero_iff_eq _).mp
end is_refl
@[simp] lemma is_refl_zero : (0 : bilin_form R M).is_refl := λ _ _ _, rfl
@[simp] lemma is_refl_neg {B : bilin_form R₁ M₁} : (-B).is_refl ↔ B.is_refl :=
⟨λ h, neg_neg B ▸ h.neg, is_refl.neg⟩
/-- The proposition that a bilinear form is symmetric -/
def is_symm (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = B y x
namespace is_symm
variable (H : B.is_symm)
protected lemma eq (x y : M) : B x y = B y x := H x y
lemma is_refl : B.is_refl := λ x y H1, H x y ▸ H1
lemma ortho_comm {x y : M} :
is_ortho B x y ↔ is_ortho B y x := H.is_refl.ortho_comm
protected lemma add {B₁ B₂ : bilin_form R M} (hB₁ : B₁.is_symm) (hB₂ : B₂.is_symm) :
(B₁ + B₂).is_symm :=
λ x y, (congr_arg2 (+) (hB₁ x y) (hB₂ x y) : _)
protected lemma sub {B₁ B₂ : bilin_form R₁ M₁} (hB₁ : B₁.is_symm) (hB₂ : B₂.is_symm) :
(B₁ - B₂).is_symm :=
λ x y, (congr_arg2 has_sub.sub (hB₁ x y) (hB₂ x y) : _)
protected lemma neg {B : bilin_form R₁ M₁} (hB : B.is_symm) :
(-B).is_symm :=
λ x y, congr_arg has_neg.neg (hB x y)
protected lemma smul {α} [monoid α] [distrib_mul_action α R] [smul_comm_class α R R]
(a : α) {B : bilin_form R M} (hB : B.is_symm) :
(a • B).is_symm :=
λ x y, congr_arg ((•) a) (hB x y)
end is_symm
@[simp] lemma is_symm_zero : (0 : bilin_form R M).is_symm := λ _ _, rfl
@[simp] lemma is_symm_neg {B : bilin_form R₁ M₁} : (-B).is_symm ↔ B.is_symm :=
⟨λ h, neg_neg B ▸ h.neg, is_symm.neg⟩
lemma is_symm_iff_flip' [algebra R₂ R] : B.is_symm ↔ flip_hom R₂ B = B :=
begin
split,
{ intros h,
ext x y,
exact h y x },
{ intros h x y,
conv_lhs { rw ← h },
simp }
end
/-- The proposition that a bilinear form is alternating -/
def is_alt (B : bilin_form R M) : Prop := ∀ (x : M), B x x = 0
namespace is_alt
lemma self_eq_zero (H : B.is_alt) (x : M) : B x x = 0 := H x
lemma neg_eq (H : B₁.is_alt) (x y : M₁) :
- B₁ x y = B₁ y x :=
begin
have H1 : B₁ (x + y) (x + y) = 0,
{ exact self_eq_zero H (x + y) },
rw [add_left, add_right, add_right,
self_eq_zero H, self_eq_zero H, ring.zero_add,
ring.add_zero, add_eq_zero_iff_neg_eq] at H1,
exact H1,
end
lemma is_refl (H : B₁.is_alt) : B₁.is_refl :=
begin
intros x y h,
rw [←neg_eq H, h, neg_zero],
end
lemma ortho_comm (H : B₁.is_alt) {x y : M₁} :
is_ortho B₁ x y ↔ is_ortho B₁ y x := H.is_refl.ortho_comm
protected lemma add {B₁ B₂ : bilin_form R M} (hB₁ : B₁.is_alt) (hB₂ : B₂.is_alt) :
(B₁ + B₂).is_alt :=
λ x, (congr_arg2 (+) (hB₁ x) (hB₂ x) : _).trans $ add_zero _
protected lemma sub {B₁ B₂ : bilin_form R₁ M₁} (hB₁ : B₁.is_alt) (hB₂ : B₂.is_alt) :
(B₁ - B₂).is_alt :=
λ x, (congr_arg2 has_sub.sub (hB₁ x) (hB₂ x)).trans $ sub_zero _
protected lemma neg {B : bilin_form R₁ M₁} (hB : B.is_alt) :
(-B).is_alt :=
λ x, neg_eq_zero.mpr $ hB x
protected lemma smul {α} [monoid α] [distrib_mul_action α R] [smul_comm_class α R R]
(a : α) {B : bilin_form R M} (hB : B.is_alt) :
(a • B).is_alt :=
λ x, (congr_arg ((•) a) (hB x)).trans $ smul_zero _
end is_alt
@[simp] lemma is_alt_zero : (0 : bilin_form R M).is_alt := λ _, rfl
@[simp] lemma is_alt_neg {B : bilin_form R₁ M₁} : (-B).is_alt ↔ B.is_alt :=
⟨λ h, neg_neg B ▸ h.neg, is_alt.neg⟩
/-! ### Linear adjoints -/
section linear_adjoints
variables (B) (F : bilin_form R M)
variables {M' : Type*} [add_comm_monoid M'] [module R M']
variables (B' : bilin_form R M') (f f' : M →ₗ[R] M') (g g' : M' →ₗ[R] M)
/-- Given a pair of modules equipped with bilinear forms, this is the condition for a pair of
maps between them to be mutually adjoint. -/
def is_adjoint_pair := ∀ ⦃x y⦄, B' (f x) y = B x (g y)
variables {B B' B₂ f f' g g'}
lemma is_adjoint_pair.eq (h : is_adjoint_pair B B' f g) :
∀ {x y}, B' (f x) y = B x (g y) := h
lemma is_adjoint_pair_iff_comp_left_eq_comp_right (f g : module.End R M) :
is_adjoint_pair B F f g ↔ F.comp_left f = B.comp_right g :=
begin
split; intros h,
{ ext x y, rw [comp_left_apply, comp_right_apply], apply h, },
{ intros x y, rw [←comp_left_apply, ←comp_right_apply], rw h, },
end
lemma is_adjoint_pair_zero : is_adjoint_pair B B' 0 0 :=
λ x y, by simp only [bilin_form.zero_left, bilin_form.zero_right, linear_map.zero_apply]
lemma is_adjoint_pair_id : is_adjoint_pair B B 1 1 := λ x y, rfl
lemma is_adjoint_pair.add (h : is_adjoint_pair B B' f g) (h' : is_adjoint_pair B B' f' g') :
is_adjoint_pair B B' (f + f') (g + g') :=
λ x y, by rw [linear_map.add_apply, linear_map.add_apply, add_left, add_right, h, h']
variables {M₁' : Type*} [add_comm_group M₁'] [module R₁ M₁']
variables {B₁' : bilin_form R₁ M₁'} {f₁ f₁' : M₁ →ₗ[R₁] M₁'} {g₁ g₁' : M₁' →ₗ[R₁] M₁}
lemma is_adjoint_pair.sub (h : is_adjoint_pair B₁ B₁' f₁ g₁) (h' : is_adjoint_pair B₁ B₁' f₁' g₁') :
is_adjoint_pair B₁ B₁' (f₁ - f₁') (g₁ - g₁') :=
λ x y, by rw [linear_map.sub_apply, linear_map.sub_apply, sub_left, sub_right, h, h']
variables {B₂' : bilin_form R₂ M₂'} {f₂ f₂' : M₂ →ₗ[R₂] M₂'} {g₂ g₂' : M₂' →ₗ[R₂] M₂}
lemma is_adjoint_pair.smul (c : R₂) (h : is_adjoint_pair B₂ B₂' f₂ g₂) :
is_adjoint_pair B₂ B₂' (c • f₂) (c • g₂) :=
λ x y, by rw [linear_map.smul_apply, linear_map.smul_apply, smul_left, smul_right, h]
variables {M'' : Type*} [add_comm_monoid M''] [module R M'']
variables (B'' : bilin_form R M'')
lemma is_adjoint_pair.comp {f' : M' →ₗ[R] M''} {g' : M'' →ₗ[R] M'}
(h : is_adjoint_pair B B' f g) (h' : is_adjoint_pair B' B'' f' g') :
is_adjoint_pair B B'' (f'.comp f) (g.comp g') :=
λ x y, by rw [linear_map.comp_apply, linear_map.comp_apply, h', h]
lemma is_adjoint_pair.mul
{f g f' g' : module.End R M} (h : is_adjoint_pair B B f g) (h' : is_adjoint_pair B B f' g') :
is_adjoint_pair B B (f * f') (g' * g) :=
λ x y, by rw [linear_map.mul_apply, linear_map.mul_apply, h, h']
variables (B B' B₁ B₂) (F₂ : bilin_form R₂ M₂)
/-- The condition for an endomorphism to be "self-adjoint" with respect to a pair of bilinear forms
on the underlying module. In the case that these two forms are identical, this is the usual concept
of self adjointness. In the case that one of the forms is the negation of the other, this is the
usual concept of skew adjointness. -/
def is_pair_self_adjoint (f : module.End R M) := is_adjoint_pair B F f f
/-- The set of pair-self-adjoint endomorphisms are a submodule of the type of all endomorphisms. -/
def is_pair_self_adjoint_submodule : submodule R₂ (module.End R₂ M₂) :=
{ carrier := { f | is_pair_self_adjoint B₂ F₂ f },
zero_mem' := is_adjoint_pair_zero,
add_mem' := λ f g hf hg, hf.add hg,
smul_mem' := λ c f h, h.smul c, }
@[simp] lemma mem_is_pair_self_adjoint_submodule (f : module.End R₂ M₂) :
f ∈ is_pair_self_adjoint_submodule B₂ F₂ ↔ is_pair_self_adjoint B₂ F₂ f :=
by refl
lemma is_pair_self_adjoint_equiv (e : M₂' ≃ₗ[R₂] M₂) (f : module.End R₂ M₂) :
is_pair_self_adjoint B₂ F₂ f ↔
is_pair_self_adjoint (B₂.comp ↑e ↑e) (F₂.comp ↑e ↑e) (e.symm.conj f) :=
begin
have hₗ : (F₂.comp ↑e ↑e).comp_left (e.symm.conj f) = (F₂.comp_left f).comp ↑e ↑e :=
by { ext, simp [linear_equiv.symm_conj_apply], },
have hᵣ : (B₂.comp ↑e ↑e).comp_right (e.symm.conj f) = (B₂.comp_right f).comp ↑e ↑e :=
by { ext, simp [linear_equiv.conj_apply], },
have he : function.surjective (⇑(↑e : M₂' →ₗ[R₂] M₂) : M₂' → M₂) := e.surjective,
show bilin_form.is_adjoint_pair _ _ _ _ ↔ bilin_form.is_adjoint_pair _ _ _ _,
rw [is_adjoint_pair_iff_comp_left_eq_comp_right, is_adjoint_pair_iff_comp_left_eq_comp_right,
hᵣ, hₗ, comp_inj _ _ he he],
end
/-- An endomorphism of a module is self-adjoint with respect to a bilinear form if it serves as an
adjoint for itself. -/
def is_self_adjoint (f : module.End R M) := is_adjoint_pair B B f f
/-- An endomorphism of a module is skew-adjoint with respect to a bilinear form if its negation
serves as an adjoint. -/
def is_skew_adjoint (f : module.End R₁ M₁) := is_adjoint_pair B₁ B₁ f (-f)
lemma is_skew_adjoint_iff_neg_self_adjoint (f : module.End R₁ M₁) :
B₁.is_skew_adjoint f ↔ is_adjoint_pair (-B₁) B₁ f f :=
show (∀ x y, B₁ (f x) y = B₁ x ((-f) y)) ↔ ∀ x y, B₁ (f x) y = (-B₁) x (f y),
by simp only [linear_map.neg_apply, bilin_form.neg_apply, bilin_form.neg_right]
/-- The set of self-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact
it is a Jordan subalgebra.) -/
def self_adjoint_submodule := is_pair_self_adjoint_submodule B₂ B₂
@[simp] lemma mem_self_adjoint_submodule (f : module.End R₂ M₂) :
f ∈ B₂.self_adjoint_submodule ↔ B₂.is_self_adjoint f := iff.rfl
variables (B₃ : bilin_form R₃ M₃)
/-- The set of skew-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact
it is a Lie subalgebra.) -/
def skew_adjoint_submodule := is_pair_self_adjoint_submodule (-B₃) B₃
@[simp] lemma mem_skew_adjoint_submodule (f : module.End R₃ M₃) :
f ∈ B₃.skew_adjoint_submodule ↔ B₃.is_skew_adjoint f :=
by { rw is_skew_adjoint_iff_neg_self_adjoint, exact iff.rfl, }
end linear_adjoints
end bilin_form
namespace bilin_form
section orthogonal
/-- The orthogonal complement of a submodule `N` with respect to some bilinear form is the set of
elements `x` which are orthogonal to all elements of `N`; i.e., for all `y` in `N`, `B x y = 0`.
Note that for general (neither symmetric nor antisymmetric) bilinear forms this definition has a
chirality; in addition to this "left" orthogonal complement one could define a "right" orthogonal
complement for which, for all `y` in `N`, `B y x = 0`. This variant definition is not currently
provided in mathlib. -/
def orthogonal (B : bilin_form R M) (N : submodule R M) : submodule R M :=
{ carrier := { m | ∀ n ∈ N, is_ortho B n m },
zero_mem' := λ x _, is_ortho_zero_right x,
add_mem' := λ x y hx hy n hn,
by rw [is_ortho, add_right, show B n x = 0, by exact hx n hn,
show B n y = 0, by exact hy n hn, zero_add],
smul_mem' := λ c x hx n hn,
by rw [is_ortho, smul_right, show B n x = 0, by exact hx n hn, mul_zero] }
variables {N L : submodule R M}
@[simp] lemma mem_orthogonal_iff {N : submodule R M} {m : M} :
m ∈ B.orthogonal N ↔ ∀ n ∈ N, is_ortho B n m := iff.rfl
lemma orthogonal_le (h : N ≤ L) : B.orthogonal L ≤ B.orthogonal N :=
λ _ hn l hl, hn l (h hl)
lemma le_orthogonal_orthogonal (b : B.is_refl) :
N ≤ B.orthogonal (B.orthogonal N) :=
λ n hn m hm, b _ _ (hm n hn)
-- ↓ This lemma only applies in fields as we require `a * b = 0 → a = 0 ∨ b = 0`
lemma span_singleton_inf_orthogonal_eq_bot
{B : bilin_form K V} {x : V} (hx : ¬ B.is_ortho x x) :
(K ∙ x) ⊓ B.orthogonal (K ∙ x) = ⊥ :=
begin
rw ← finset.coe_singleton,
refine eq_bot_iff.2 (λ y h, _),
rcases mem_span_finset.1 h.1 with ⟨μ, rfl⟩,
have := h.2 x _,
{ rw finset.sum_singleton at this ⊢,
suffices hμzero : μ x = 0,
{ rw [hμzero, zero_smul, submodule.mem_bot] },
change B x (μ x • x) = 0 at this, rw [smul_right] at this,
exact or.elim (zero_eq_mul.mp this.symm) id (λ hfalse, false.elim $ hx hfalse) },
{ rw submodule.mem_span; exact λ _ hp, hp $ finset.mem_singleton_self _ }
end
-- ↓ This lemma only applies in fields since we use the `mul_eq_zero`
lemma orthogonal_span_singleton_eq_to_lin_ker {B : bilin_form K V} (x : V) :
B.orthogonal (K ∙ x) = (bilin_form.to_lin B x).ker :=
begin
ext y,
simp_rw [mem_orthogonal_iff, linear_map.mem_ker,
submodule.mem_span_singleton ],
split,
{ exact λ h, h x ⟨1, one_smul _ _⟩ },
{ rintro h _ ⟨z, rfl⟩,
rw [is_ortho, smul_left, mul_eq_zero],
exact or.intro_right _ h }
end
lemma span_singleton_sup_orthogonal_eq_top {B : bilin_form K V}
{x : V} (hx : ¬ B.is_ortho x x) :
(K ∙ x) ⊔ B.orthogonal (K ∙ x) = ⊤ :=
begin
rw orthogonal_span_singleton_eq_to_lin_ker,
exact linear_map.span_singleton_sup_ker_eq_top _ hx,
end
/-- Given a bilinear form `B` and some `x` such that `B x x ≠ 0`, the span of the singleton of `x`
is complement to its orthogonal complement. -/
lemma is_compl_span_singleton_orthogonal {B : bilin_form K V}
{x : V} (hx : ¬ B.is_ortho x x) : is_compl (K ∙ x) (B.orthogonal $ K ∙ x) :=
{ disjoint := disjoint_iff.2 $ span_singleton_inf_orthogonal_eq_bot hx,
codisjoint := codisjoint_iff.2 $ span_singleton_sup_orthogonal_eq_top hx }
end orthogonal
/-- The restriction of a bilinear form on a submodule. -/
@[simps apply]
def restrict (B : bilin_form R M) (W : submodule R M) : bilin_form R W :=
{ bilin := λ a b, B a b,
bilin_add_left := λ _ _ _, add_left _ _ _,
bilin_smul_left := λ _ _ _, smul_left _ _ _,
bilin_add_right := λ _ _ _, add_right _ _ _,
bilin_smul_right := λ _ _ _, smul_right _ _ _}
/-- The restriction of a symmetric bilinear form on a submodule is also symmetric. -/
lemma restrict_symm (B : bilin_form R M) (b : B.is_symm)
(W : submodule R M) : (B.restrict W).is_symm :=
λ x y, b x y
/-- A nondegenerate bilinear form is a bilinear form such that the only element that is orthogonal
to every other element is `0`; i.e., for all nonzero `m` in `M`, there exists `n` in `M` with
`B m n ≠ 0`.
Note that for general (neither symmetric nor antisymmetric) bilinear forms this definition has a
chirality; in addition to this "left" nondegeneracy condition one could define a "right"
nondegeneracy condition that in the situation described, `B n m ≠ 0`. This variant definition is
not currently provided in mathlib. In finite dimension either definition implies the other. -/
def nondegenerate (B : bilin_form R M) : Prop :=
∀ m : M, (∀ n : M, B m n = 0) → m = 0
section
variables (R M)
/-- In a non-trivial module, zero is not non-degenerate. -/
lemma not_nondegenerate_zero [nontrivial M] : ¬(0 : bilin_form R M).nondegenerate :=
let ⟨m, hm⟩ := exists_ne (0 : M) in λ h, hm (h m $ λ n, rfl)
end
variables {M₂' : Type*}
variables [add_comm_monoid M₂'] [module R₂ M₂']
lemma nondegenerate.ne_zero [nontrivial M] {B : bilin_form R M} (h : B.nondegenerate) : B ≠ 0 :=
λ h0, not_nondegenerate_zero R M $ h0 ▸ h
lemma nondegenerate.congr {B : bilin_form R₂ M₂} (e : M₂ ≃ₗ[R₂] M₂') (h : B.nondegenerate) :
(congr e B).nondegenerate :=
λ m hm, (e.symm).map_eq_zero_iff.1 $ h (e.symm m) $
λ n, (congr_arg _ (e.symm_apply_apply n).symm).trans (hm (e n))
@[simp] lemma nondegenerate_congr_iff {B : bilin_form R₂ M₂} (e : M₂ ≃ₗ[R₂] M₂') :
(congr e B).nondegenerate ↔ B.nondegenerate :=
⟨λ h, begin
convert h.congr e.symm,
rw [congr_congr, e.self_trans_symm, congr_refl, linear_equiv.refl_apply],
end, nondegenerate.congr e⟩
/-- A bilinear form is nondegenerate if and only if it has a trivial kernel. -/
theorem nondegenerate_iff_ker_eq_bot {B : bilin_form R₂ M₂} :
B.nondegenerate ↔ B.to_lin.ker = ⊥ :=
begin
rw linear_map.ker_eq_bot',
split; intro h,
{ refine λ m hm, h _ (λ x, _),
rw [← to_lin_apply, hm], refl },
{ intros m hm, apply h,
ext x, exact hm x }
end
lemma nondegenerate.ker_eq_bot {B : bilin_form R₂ M₂} (h : B.nondegenerate) :
B.to_lin.ker = ⊥ := nondegenerate_iff_ker_eq_bot.mp h
/-- The restriction of a reflexive bilinear form `B` onto a submodule `W` is
nondegenerate if `disjoint W (B.orthogonal W)`. -/
lemma nondegenerate_restrict_of_disjoint_orthogonal
(B : bilin_form R₁ M₁) (b : B.is_refl)
{W : submodule R₁ M₁} (hW : disjoint W (B.orthogonal W)) :
(B.restrict W).nondegenerate :=
begin
rintro ⟨x, hx⟩ b₁,
rw [submodule.mk_eq_zero, ← submodule.mem_bot R₁],
refine hW.le_bot ⟨hx, λ y hy, _⟩,
specialize b₁ ⟨y, hy⟩,
rw [restrict_apply, submodule.coe_mk, submodule.coe_mk] at b₁,
exact is_ortho_def.mpr (b x y b₁),
end
/-- An orthogonal basis with respect to a nondegenerate bilinear form has no self-orthogonal
elements. -/
lemma is_Ortho.not_is_ortho_basis_self_of_nondegenerate
{n : Type w} [nontrivial R] {B : bilin_form R M} {v : basis n R M}
(h : B.is_Ortho v) (hB : B.nondegenerate) (i : n) :
¬B.is_ortho (v i) (v i) :=
begin
intro ho,
refine v.ne_zero i (hB (v i) $ λ m, _),
obtain ⟨vi, rfl⟩ := v.repr.symm.surjective m,
rw [basis.repr_symm_apply, finsupp.total_apply, finsupp.sum, sum_right],
apply finset.sum_eq_zero,
rintros j -,
rw smul_right,
convert mul_zero _ using 2,
obtain rfl | hij := eq_or_ne i j,
{ exact ho },
{ exact h hij },
end
/-- Given an orthogonal basis with respect to a bilinear form, the bilinear form is nondegenerate
iff the basis has no elements which are self-orthogonal. -/
lemma is_Ortho.nondegenerate_iff_not_is_ortho_basis_self {n : Type w} [nontrivial R]
[no_zero_divisors R] (B : bilin_form R M) (v : basis n R M) (hO : B.is_Ortho v) :
B.nondegenerate ↔ ∀ i, ¬B.is_ortho (v i) (v i) :=
begin
refine ⟨hO.not_is_ortho_basis_self_of_nondegenerate, λ ho m hB, _⟩,
obtain ⟨vi, rfl⟩ := v.repr.symm.surjective m,
rw linear_equiv.map_eq_zero_iff,
ext i,
rw [finsupp.zero_apply],
specialize hB (v i),
simp_rw [basis.repr_symm_apply, finsupp.total_apply, finsupp.sum, sum_left, smul_left] at hB,
rw finset.sum_eq_single i at hB,
{ exact eq_zero_of_ne_zero_of_mul_right_eq_zero (ho i) hB, },
{ intros j hj hij, convert mul_zero _ using 2, exact hO hij, },
{ intros hi, convert zero_mul _ using 2, exact finsupp.not_mem_support_iff.mp hi }
end
section
lemma to_lin_restrict_ker_eq_inf_orthogonal
(B : bilin_form K V) (W : subspace K V) (b : B.is_refl) :
(B.to_lin.dom_restrict W).ker.map W.subtype = (W ⊓ B.orthogonal ⊤ : subspace K V) :=
begin
ext x, split; intro hx,
{ rcases hx with ⟨⟨x, hx⟩, hker, rfl⟩,
erw linear_map.mem_ker at hker,
split,
{ simp [hx] },
{ intros y _,
rw [is_ortho, b],
change (B.to_lin.dom_restrict W) ⟨x, hx⟩ y = 0,
rw hker, refl } },
{ simp_rw [submodule.mem_map, linear_map.mem_ker],
refine ⟨⟨x, hx.1⟩, _, rfl⟩,
ext y, change B x y = 0,
rw b,
exact hx.2 _ submodule.mem_top }
end
lemma to_lin_restrict_range_dual_coannihilator_eq_orthogonal
(B : bilin_form K V) (W : subspace K V) :
(B.to_lin.dom_restrict W).range.dual_coannihilator = B.orthogonal W :=
begin
ext x, split; rw [mem_orthogonal_iff]; intro hx,
{ intros y hy,
rw submodule.mem_dual_coannihilator at hx,
refine hx (B.to_lin.dom_restrict W ⟨y, hy⟩) ⟨⟨y, hy⟩, rfl⟩ },
{ rw submodule.mem_dual_coannihilator,
rintro _ ⟨⟨w, hw⟩, rfl⟩,
exact hx w hw }
end
variable [finite_dimensional K V]
open finite_dimensional
lemma finrank_add_finrank_orthogonal
{B : bilin_form K V} {W : subspace K V} (b₁ : B.is_refl) :
finrank K W + finrank K (B.orthogonal W) =
finrank K V + finrank K (W ⊓ B.orthogonal ⊤ : subspace K V) :=
begin
rw [← to_lin_restrict_ker_eq_inf_orthogonal _ _ b₁,
← to_lin_restrict_range_dual_coannihilator_eq_orthogonal _ _,
submodule.finrank_map_subtype_eq],
conv_rhs { rw [← @subspace.finrank_add_finrank_dual_coannihilator_eq K V _ _ _ _
(B.to_lin.dom_restrict W).range,
add_comm, ← add_assoc, add_comm (finrank K ↥((B.to_lin.dom_restrict W).ker)),
linear_map.finrank_range_add_finrank_ker] },
end
/-- A subspace is complement to its orthogonal complement with respect to some
reflexive bilinear form if that bilinear form restricted on to the subspace is nondegenerate. -/
lemma restrict_nondegenerate_of_is_compl_orthogonal
{B : bilin_form K V} {W : subspace K V}
(b₁ : B.is_refl) (b₂ : (B.restrict W).nondegenerate) :
is_compl W (B.orthogonal W) :=
begin
have : W ⊓ B.orthogonal W = ⊥,
{ rw eq_bot_iff,
intros x hx,
obtain ⟨hx₁, hx₂⟩ := submodule.mem_inf.1 hx,
refine subtype.mk_eq_mk.1 (b₂ ⟨x, hx₁⟩ _),
rintro ⟨n, hn⟩,
rw [restrict_apply, submodule.coe_mk, submodule.coe_mk, b₁],
exact hx₂ n hn },
refine is_compl.of_eq this (eq_top_of_finrank_eq $ (submodule.finrank_le _).antisymm _),
conv_rhs { rw ← add_zero (finrank K _) },
rw [← finrank_bot K V, ← this, submodule.finrank_sup_add_finrank_inf_eq,
finrank_add_finrank_orthogonal b₁],
exact le_self_add,
end
/-- A subspace is complement to its orthogonal complement with respect to some reflexive bilinear
form if and only if that bilinear form restricted on to the subspace is nondegenerate. -/
theorem restrict_nondegenerate_iff_is_compl_orthogonal
{B : bilin_form K V} {W : subspace K V} (b₁ : B.is_refl) :
(B.restrict W).nondegenerate ↔ is_compl W (B.orthogonal W) :=
⟨λ b₂, restrict_nondegenerate_of_is_compl_orthogonal b₁ b₂,
λ h, B.nondegenerate_restrict_of_disjoint_orthogonal b₁ h.1⟩
/-- Given a nondegenerate bilinear form `B` on a finite-dimensional vector space, `B.to_dual` is
the linear equivalence between a vector space and its dual with the underlying linear map
`B.to_lin`. -/
noncomputable def to_dual (B : bilin_form K V) (b : B.nondegenerate) :
V ≃ₗ[K] module.dual K V :=
B.to_lin.linear_equiv_of_injective
(linear_map.ker_eq_bot.mp $ b.ker_eq_bot) subspace.dual_finrank_eq.symm
lemma to_dual_def {B : bilin_form K V} (b : B.nondegenerate) {m n : V} :
B.to_dual b m n = B m n := rfl
section dual_basis
variables {ι : Type*} [decidable_eq ι] [fintype ι]
/-- The `B`-dual basis `B.dual_basis hB b` to a finite basis `b` satisfies
`B (B.dual_basis hB b i) (b j) = B (b i) (B.dual_basis hB b j) = if i = j then 1 else 0`,
where `B` is a nondegenerate (symmetric) bilinear form and `b` is a finite basis. -/
noncomputable def dual_basis (B : bilin_form K V) (hB : B.nondegenerate) (b : basis ι K V) :
basis ι K V :=
b.dual_basis.map (B.to_dual hB).symm
@[simp] lemma dual_basis_repr_apply (B : bilin_form K V) (hB : B.nondegenerate) (b : basis ι K V)
(x i) : (B.dual_basis hB b).repr x i = B x (b i) :=
by rw [dual_basis, basis.map_repr, linear_equiv.symm_symm, linear_equiv.trans_apply,
basis.dual_basis_repr, to_dual_def]
lemma apply_dual_basis_left (B : bilin_form K V) (hB : B.nondegenerate) (b : basis ι K V)
(i j) : B (B.dual_basis hB b i) (b j) = if j = i then 1 else 0 :=
by rw [dual_basis, basis.map_apply, basis.coe_dual_basis, ← to_dual_def hB,
linear_equiv.apply_symm_apply, basis.coord_apply, basis.repr_self,
finsupp.single_apply]
lemma apply_dual_basis_right (B : bilin_form K V) (hB : B.nondegenerate)
(sym : B.is_symm) (b : basis ι K V)
(i j) : B (b i) (B.dual_basis hB b j) = if i = j then 1 else 0 :=
by rw [sym, apply_dual_basis_left]
end dual_basis
end
/-! We note that we cannot use `bilin_form.restrict_nondegenerate_iff_is_compl_orthogonal` for the
lemma below since the below lemma does not require `V` to be finite dimensional. However,
`bilin_form.restrict_nondegenerate_iff_is_compl_orthogonal` does not require `B` to be nondegenerate
on the whole space. -/
/-- The restriction of a reflexive, non-degenerate bilinear form on the orthogonal complement of
the span of a singleton is also non-degenerate. -/
lemma restrict_orthogonal_span_singleton_nondegenerate (B : bilin_form K V)
(b₁ : B.nondegenerate) (b₂ : B.is_refl) {x : V} (hx : ¬ B.is_ortho x x) :
nondegenerate $ B.restrict $ B.orthogonal (K ∙ x) :=
begin
refine λ m hm, submodule.coe_eq_zero.1 (b₁ m.1 (λ n, _)),
have : n ∈ (K ∙ x) ⊔ B.orthogonal (K ∙ x) :=
(span_singleton_sup_orthogonal_eq_top hx).symm ▸ submodule.mem_top,
rcases submodule.mem_sup.1 this with ⟨y, hy, z, hz, rfl⟩,
specialize hm ⟨z, hz⟩,
rw restrict at hm,
erw [add_right, show B m.1 y = 0, by rw b₂; exact m.2 y hy, hm, add_zero]
end
section linear_adjoints
lemma comp_left_injective (B : bilin_form R₁ M₁) (b : B.nondegenerate) :
function.injective B.comp_left :=
λ φ ψ h, begin
ext w,
refine eq_of_sub_eq_zero (b _ _),
intro v,
rw [sub_left, ← comp_left_apply, ← comp_left_apply, ← h, sub_self]
end
lemma is_adjoint_pair_unique_of_nondegenerate (B : bilin_form R₁ M₁) (b : B.nondegenerate)
(φ ψ₁ ψ₂ : M₁ →ₗ[R₁] M₁) (hψ₁ : is_adjoint_pair B B ψ₁ φ) (hψ₂ : is_adjoint_pair B B ψ₂ φ) :
ψ₁ = ψ₂ :=
B.comp_left_injective b $ ext $ λ v w, by rw [comp_left_apply, comp_left_apply, hψ₁, hψ₂]
variable [finite_dimensional K V]
/-- Given bilinear forms `B₁, B₂` where `B₂` is nondegenerate, `symm_comp_of_nondegenerate`
is the linear map `B₂.to_lin⁻¹ ∘ B₁.to_lin`. -/
noncomputable def symm_comp_of_nondegenerate
(B₁ B₂ : bilin_form K V) (b₂ : B₂.nondegenerate) : V →ₗ[K] V :=
(B₂.to_dual b₂).symm.to_linear_map.comp B₁.to_lin
lemma comp_symm_comp_of_nondegenerate_apply (B₁ : bilin_form K V)
{B₂ : bilin_form K V} (b₂ : B₂.nondegenerate) (v : V) :
to_lin B₂ (B₁.symm_comp_of_nondegenerate B₂ b₂ v) = to_lin B₁ v :=
by erw [symm_comp_of_nondegenerate, linear_equiv.apply_symm_apply (B₂.to_dual b₂) _]
@[simp]
lemma symm_comp_of_nondegenerate_left_apply (B₁ : bilin_form K V)
{B₂ : bilin_form K V} (b₂ : B₂.nondegenerate) (v w : V) :
B₂ (symm_comp_of_nondegenerate B₁ B₂ b₂ w) v = B₁ w v :=
begin
conv_lhs { rw [← bilin_form.to_lin_apply, comp_symm_comp_of_nondegenerate_apply] },
refl,
end
/-- Given the nondegenerate bilinear form `B` and the linear map `φ`,
`left_adjoint_of_nondegenerate` provides the left adjoint of `φ` with respect to `B`.
The lemma proving this property is `bilin_form.is_adjoint_pair_left_adjoint_of_nondegenerate`. -/
noncomputable def left_adjoint_of_nondegenerate
(B : bilin_form K V) (b : B.nondegenerate) (φ : V →ₗ[K] V) : V →ₗ[K] V :=
symm_comp_of_nondegenerate (B.comp_right φ) B b
lemma is_adjoint_pair_left_adjoint_of_nondegenerate
(B : bilin_form K V) (b : B.nondegenerate) (φ : V →ₗ[K] V) :
is_adjoint_pair B B (B.left_adjoint_of_nondegenerate b φ) φ :=
λ x y, (B.comp_right φ).symm_comp_of_nondegenerate_left_apply b y x
/-- Given the nondegenerate bilinear form `B`, the linear map `φ` has a unique left adjoint given by
`bilin_form.left_adjoint_of_nondegenerate`. -/
theorem is_adjoint_pair_iff_eq_of_nondegenerate
(B : bilin_form K V) (b : B.nondegenerate) (ψ φ : V →ₗ[K] V) :
is_adjoint_pair B B ψ φ ↔ ψ = B.left_adjoint_of_nondegenerate b φ :=
⟨λ h, B.is_adjoint_pair_unique_of_nondegenerate b φ ψ _ h
(is_adjoint_pair_left_adjoint_of_nondegenerate _ _ _),
λ h, h.symm ▸ is_adjoint_pair_left_adjoint_of_nondegenerate _ _ _⟩
end linear_adjoints
end bilin_form
|
9583c93ce8ce8bdfb41924cd5e4a6722e715d6cb | 6094e25ea0b7699e642463b48e51b2ead6ddc23f | /library/algebra/ring.lean | d3f58e69a4474e3d35f2ac3b46687f67f74d9752 | [
"Apache-2.0"
] | permissive | gbaz/lean | a7835c4e3006fbbb079e8f8ffe18aacc45adebfb | a501c308be3acaa50a2c0610ce2e0d71becf8032 | refs/heads/master | 1,611,198,791,433 | 1,451,339,111,000 | 1,451,339,111,000 | 48,713,797 | 0 | 0 | null | 1,451,338,939,000 | 1,451,338,939,000 | null | UTF-8 | Lean | false | false | 18,288 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
Structures with multiplicative and additive components, including semirings, rings, and fields.
The development is modeled after Isabelle's library.
-/
import logic.eq logic.connectives data.unit data.sigma data.prod
import algebra.binary algebra.group
open eq eq.ops
variable {A : Type}
/- auxiliary classes -/
structure distrib [class] (A : Type) extends has_mul A, has_add A :=
(left_distrib : ∀a b c, mul a (add b c) = add (mul a b) (mul a c))
(right_distrib : ∀a b c, mul (add a b) c = add (mul a c) (mul b c))
theorem left_distrib [distrib A] (a b c : A) : a * (b + c) = a * b + a * c :=
!distrib.left_distrib
theorem right_distrib [distrib A] (a b c : A) : (a + b) * c = a * c + b * c :=
!distrib.right_distrib
structure mul_zero_class [class] (A : Type) extends has_mul A, has_zero A :=
(zero_mul : ∀a, mul zero a = zero)
(mul_zero : ∀a, mul a zero = zero)
theorem zero_mul [mul_zero_class A] (a : A) : 0 * a = 0 := !mul_zero_class.zero_mul
theorem mul_zero [mul_zero_class A] (a : A) : a * 0 = 0 := !mul_zero_class.mul_zero
structure zero_ne_one_class [class] (A : Type) extends has_zero A, has_one A :=
(zero_ne_one : zero ≠ one)
theorem zero_ne_one [s: zero_ne_one_class A] : 0 ≠ (1:A) := @zero_ne_one_class.zero_ne_one A s
/- semiring -/
structure semiring [class] (A : Type) extends add_comm_monoid A, monoid A, distrib A,
mul_zero_class A
section semiring
variables [s : semiring A] (a b c : A)
include s
theorem one_add_one_eq_two : 1 + 1 = (2:A) :=
by unfold bit0
theorem ne_zero_of_mul_ne_zero_right {a b : A} (H : a * b ≠ 0) : a ≠ 0 :=
suppose a = 0,
have a * b = 0, from this⁻¹ ▸ zero_mul b,
H this
theorem ne_zero_of_mul_ne_zero_left {a b : A} (H : a * b ≠ 0) : b ≠ 0 :=
suppose b = 0,
have a * b = 0, from this⁻¹ ▸ mul_zero a,
H this
theorem distrib_three_right (a b c d : A) : (a + b + c) * d = a * d + b * d + c * d :=
by rewrite *right_distrib
end semiring
/- comm semiring -/
structure comm_semiring [class] (A : Type) extends semiring A, comm_monoid A
-- TODO: we could also define a cancelative comm_semiring, i.e. satisfying
-- c ≠ 0 → c * a = c * b → a = b.
section comm_semiring
variables [s : comm_semiring A] (a b c : A)
include s
protected definition algebra.dvd (a b : A) : Prop := ∃c, b = a * c
definition comm_semiring_has_dvd [reducible] [instance] [priority algebra.prio] : has_dvd A :=
has_dvd.mk algebra.dvd
theorem dvd.intro {a b c : A} (H : a * c = b) : a ∣ b :=
exists.intro _ H⁻¹
theorem dvd_of_mul_right_eq {a b c : A} (H : a * c = b) : a ∣ b := dvd.intro H
theorem dvd.intro_left {a b c : A} (H : c * a = b) : a ∣ b :=
dvd.intro (!mul.comm ▸ H)
theorem dvd_of_mul_left_eq {a b c : A} (H : c * a = b) : a ∣ b := dvd.intro_left H
theorem exists_eq_mul_right_of_dvd {a b : A} (H : a ∣ b) : ∃c, b = a * c := H
theorem dvd.elim {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀c, b = a * c → P) : P :=
exists.elim H₁ H₂
theorem exists_eq_mul_left_of_dvd {a b : A} (H : a ∣ b) : ∃c, b = c * a :=
dvd.elim H (take c, assume H1 : b = a * c, exists.intro c (H1 ⬝ !mul.comm))
theorem dvd.elim_left {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀c, b = c * a → P) : P :=
exists.elim (exists_eq_mul_left_of_dvd H₁) (take c, assume H₃ : b = c * a, H₂ c H₃)
theorem dvd.refl : a ∣ a := dvd.intro !mul_one
theorem dvd.trans {a b c : A} (H₁ : a ∣ b) (H₂ : b ∣ c) : a ∣ c :=
dvd.elim H₁
(take d, assume H₃ : b = a * d,
dvd.elim H₂
(take e, assume H₄ : c = b * e,
dvd.intro
(show a * (d * e) = c, by rewrite [-mul.assoc, -H₃, H₄])))
theorem eq_zero_of_zero_dvd {a : A} (H : 0 ∣ a) : a = 0 :=
dvd.elim H (take c, assume H' : a = 0 * c, H' ⬝ !zero_mul)
theorem dvd_zero : a ∣ 0 := dvd.intro !mul_zero
theorem one_dvd : 1 ∣ a := dvd.intro !one_mul
theorem dvd_mul_right : a ∣ a * b := dvd.intro rfl
theorem dvd_mul_left : a ∣ b * a := mul.comm a b ▸ dvd_mul_right a b
theorem dvd_mul_of_dvd_left {a b : A} (H : a ∣ b) (c : A) : a ∣ b * c :=
dvd.elim H
(take d,
suppose b = a * d,
dvd.intro
(show a * (d * c) = b * c, from by rewrite [-mul.assoc]; substvars))
theorem dvd_mul_of_dvd_right {a b : A} (H : a ∣ b) (c : A) : a ∣ c * b :=
!mul.comm ▸ (dvd_mul_of_dvd_left H _)
theorem mul_dvd_mul {a b c d : A} (dvd_ab : a ∣ b) (dvd_cd : c ∣ d) : a * c ∣ b * d :=
dvd.elim dvd_ab
(take e, suppose b = a * e,
dvd.elim dvd_cd
(take f, suppose d = c * f,
dvd.intro
(show a * c * (e * f) = b * d,
by rewrite [mul.assoc, {c*_}mul.left_comm, -mul.assoc]; substvars)))
theorem dvd_of_mul_right_dvd {a b c : A} (H : a * b ∣ c) : a ∣ c :=
dvd.elim H (take d, assume Habdc : c = a * b * d, dvd.intro (!mul.assoc⁻¹ ⬝ Habdc⁻¹))
theorem dvd_of_mul_left_dvd {a b c : A} (H : a * b ∣ c) : b ∣ c :=
dvd_of_mul_right_dvd (mul.comm a b ▸ H)
theorem dvd_add {a b c : A} (Hab : a ∣ b) (Hac : a ∣ c) : a ∣ b + c :=
dvd.elim Hab
(take d, suppose b = a * d,
dvd.elim Hac
(take e, suppose c = a * e,
dvd.intro (show a * (d + e) = b + c,
by rewrite [left_distrib]; substvars)))
end comm_semiring
/- ring -/
structure ring [class] (A : Type) extends add_comm_group A, monoid A, distrib A
theorem ring.mul_zero [ring A] (a : A) : a * 0 = 0 :=
have a * 0 + 0 = a * 0 + a * 0, from calc
a * 0 + 0 = a * 0 : by rewrite add_zero
... = a * (0 + 0) : by rewrite add_zero
... = a * 0 + a * 0 : by rewrite {a*_}ring.left_distrib,
show a * 0 = 0, from (add.left_cancel this)⁻¹
theorem ring.zero_mul [ring A] (a : A) : 0 * a = 0 :=
have 0 * a + 0 = 0 * a + 0 * a, from calc
0 * a + 0 = 0 * a : by rewrite add_zero
... = (0 + 0) * a : by rewrite add_zero
... = 0 * a + 0 * a : by rewrite {_*a}ring.right_distrib,
show 0 * a = 0, from (add.left_cancel this)⁻¹
definition ring.to_semiring [trans_instance] [reducible] [s : ring A] : semiring A :=
⦃ semiring, s,
mul_zero := ring.mul_zero,
zero_mul := ring.zero_mul ⦄
section
variables [s : ring A] (a b c d e : A)
include s
theorem neg_mul_eq_neg_mul : -(a * b) = -a * b :=
neg_eq_of_add_eq_zero
begin
rewrite [-right_distrib, add.right_inv, zero_mul]
end
theorem neg_mul_eq_mul_neg : -(a * b) = a * -b :=
neg_eq_of_add_eq_zero
begin
rewrite [-left_distrib, add.right_inv, mul_zero]
end
theorem neg_mul_eq_neg_mul_symm : - a * b = - (a * b) := eq.symm !neg_mul_eq_neg_mul
theorem mul_neg_eq_neg_mul_symm : a * - b = - (a * b) := eq.symm !neg_mul_eq_mul_neg
theorem neg_mul_neg : -a * -b = a * b :=
calc
-a * -b = -(a * -b) : by rewrite -neg_mul_eq_neg_mul
... = - -(a * b) : by rewrite -neg_mul_eq_mul_neg
... = a * b : by rewrite neg_neg
theorem neg_mul_comm : -a * b = a * -b := !neg_mul_eq_neg_mul⁻¹ ⬝ !neg_mul_eq_mul_neg
theorem neg_eq_neg_one_mul : -a = -1 * a :=
calc
-a = -(1 * a) : by rewrite one_mul
... = -1 * a : by rewrite neg_mul_eq_neg_mul
theorem mul_sub_left_distrib : a * (b - c) = a * b - a * c :=
calc
a * (b - c) = a * b + a * -c : left_distrib
... = a * b + - (a * c) : by rewrite -neg_mul_eq_mul_neg
... = a * b - a * c : rfl
theorem mul_sub_right_distrib : (a - b) * c = a * c - b * c :=
calc
(a - b) * c = a * c + -b * c : right_distrib
... = a * c + - (b * c) : by rewrite neg_mul_eq_neg_mul
... = a * c - b * c : rfl
-- TODO: can calc mode be improved to make this easier?
-- TODO: there is also the other direction. It will be easier when we
-- have the simplifier.
theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d :=
calc
a * e + c = b * e + d ↔ a * e + c = d + b * e : by rewrite {b*e+_}add.comm
... ↔ a * e + c - b * e = d : iff.symm !sub_eq_iff_eq_add
... ↔ a * e - b * e + c = d : by rewrite sub_add_eq_add_sub
... ↔ (a - b) * e + c = d : by rewrite mul_sub_right_distrib
theorem mul_add_eq_mul_add_of_sub_mul_add_eq : (a - b) * e + c = d → a * e + c = b * e + d :=
iff.mpr !mul_add_eq_mul_add_iff_sub_mul_add_eq
theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d :=
iff.mp !mul_add_eq_mul_add_iff_sub_mul_add_eq
theorem mul_neg_one_eq_neg : a * (-1) = -a :=
have a + a * -1 = 0, from calc
a + a * -1 = a * 1 + a * -1 : mul_one
... = a * (1 + -1) : left_distrib
... = a * 0 : add.right_inv
... = 0 : mul_zero,
symm (neg_eq_of_add_eq_zero this)
theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : A} (H : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 :=
have a ≠ 0, from
(suppose a = 0,
have a * b = 0, by rewrite [this, zero_mul],
absurd this H),
have b ≠ 0, from
(suppose b = 0,
have a * b = 0, by rewrite [this, mul_zero],
absurd this H),
and.intro `a ≠ 0` `b ≠ 0`
end
structure comm_ring [class] (A : Type) extends ring A, comm_semigroup A
definition comm_ring.to_comm_semiring [trans_instance] [reducible] [s : comm_ring A] : comm_semiring A :=
⦃ comm_semiring, s,
mul_zero := mul_zero,
zero_mul := zero_mul ⦄
section
variables [s : comm_ring A] (a b c d e : A)
include s
theorem mul_self_sub_mul_self_eq : a * a - b * b = (a + b) * (a - b) :=
begin
krewrite [left_distrib, *right_distrib, add.assoc],
rewrite [-{b*a + _}add.assoc,
-*neg_mul_eq_mul_neg, {a*b}mul.comm, add.right_inv, zero_add]
end
theorem mul_self_sub_one_eq : a * a - 1 = (a + 1) * (a - 1) :=
by rewrite [-mul_self_sub_mul_self_eq, mul_one]
theorem dvd_neg_iff_dvd : (a ∣ -b) ↔ (a ∣ b) :=
iff.intro
(suppose a ∣ -b,
dvd.elim this
(take c, suppose -b = a * c,
dvd.intro
(show a * -c = b,
by rewrite [-neg_mul_eq_mul_neg, -this, neg_neg])))
(suppose a ∣ b,
dvd.elim this
(take c, suppose b = a * c,
dvd.intro
(show a * -c = -b,
by rewrite [-neg_mul_eq_mul_neg, -this])))
theorem dvd_neg_of_dvd : (a ∣ b) → (a ∣ -b) :=
iff.mpr !dvd_neg_iff_dvd
theorem dvd_of_dvd_neg : (a ∣ -b) → (a ∣ b) :=
iff.mp !dvd_neg_iff_dvd
theorem neg_dvd_iff_dvd : (-a ∣ b) ↔ (a ∣ b) :=
iff.intro
(suppose -a ∣ b,
dvd.elim this
(take c, suppose b = -a * c,
dvd.intro
(show a * -c = b, by rewrite [-neg_mul_comm, this])))
(suppose a ∣ b,
dvd.elim this
(take c, suppose b = a * c,
dvd.intro
(show -a * -c = b, by rewrite [neg_mul_neg, this])))
theorem neg_dvd_of_dvd : (a ∣ b) → (-a ∣ b) :=
iff.mpr !neg_dvd_iff_dvd
theorem dvd_of_neg_dvd : (-a ∣ b) → (a ∣ b) :=
iff.mp !neg_dvd_iff_dvd
theorem dvd_sub (H₁ : (a ∣ b)) (H₂ : (a ∣ c)) : (a ∣ b - c) :=
dvd_add H₁ (!dvd_neg_of_dvd H₂)
end
/- integral domains -/
structure no_zero_divisors [class] (A : Type) extends has_mul A, has_zero A :=
(eq_zero_or_eq_zero_of_mul_eq_zero : ∀a b, mul a b = zero → a = zero ∨ b = zero)
theorem eq_zero_or_eq_zero_of_mul_eq_zero {A : Type} [no_zero_divisors A] {a b : A}
(H : a * b = 0) :
a = 0 ∨ b = 0 := !no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero H
structure integral_domain [class] (A : Type) extends comm_ring A, no_zero_divisors A,
zero_ne_one_class A
section
variables [s : integral_domain A] (a b c d e : A)
include s
theorem mul_ne_zero {a b : A} (H1 : a ≠ 0) (H2 : b ≠ 0) : a * b ≠ 0 :=
suppose a * b = 0,
or.elim (eq_zero_or_eq_zero_of_mul_eq_zero this) (assume H3, H1 H3) (assume H4, H2 H4)
theorem eq_of_mul_eq_mul_right {a b c : A} (Ha : a ≠ 0) (H : b * a = c * a) : b = c :=
have b * a - c * a = 0, from iff.mp !eq_iff_sub_eq_zero H,
have (b - c) * a = 0, using this, by rewrite [mul_sub_right_distrib, this],
have b - c = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero this) Ha,
iff.elim_right !eq_iff_sub_eq_zero this
theorem eq_of_mul_eq_mul_left {a b c : A} (Ha : a ≠ 0) (H : a * b = a * c) : b = c :=
have a * b - a * c = 0, from iff.mp !eq_iff_sub_eq_zero H,
have a * (b - c) = 0, using this, by rewrite [mul_sub_left_distrib, this],
have b - c = 0, from or_resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero this) Ha,
iff.elim_right !eq_iff_sub_eq_zero this
-- TODO: do we want the iff versions?
theorem eq_zero_of_mul_eq_self_right {a b : A} (H₁ : b ≠ 1) (H₂ : a * b = a) : a = 0 :=
have b - 1 ≠ 0, from
suppose b - 1 = 0, H₁ (!zero_add ▸ eq_add_of_sub_eq this),
have a * b - a = 0, by rewrite H₂; apply sub_self,
have a * (b - 1) = 0, by+ rewrite [mul_sub_left_distrib, mul_one]; apply this,
show a = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero this) `b - 1 ≠ 0`
theorem eq_zero_of_mul_eq_self_left {a b : A} (H₁ : b ≠ 1) (H₂ : b * a = a) : a = 0 :=
eq_zero_of_mul_eq_self_right H₁ (!mul.comm ▸ H₂)
theorem mul_self_eq_mul_self_iff (a b : A) : a * a = b * b ↔ a = b ∨ a = -b :=
iff.intro
(suppose a * a = b * b,
have (a - b) * (a + b) = 0,
by rewrite [mul.comm, -mul_self_sub_mul_self_eq, this, sub_self],
assert a - b = 0 ∨ a + b = 0, from !eq_zero_or_eq_zero_of_mul_eq_zero this,
or.elim this
(suppose a - b = 0, or.inl (eq_of_sub_eq_zero this))
(suppose a + b = 0, or.inr (eq_neg_of_add_eq_zero this)))
(suppose a = b ∨ a = -b, or.elim this
(suppose a = b, by rewrite this)
(suppose a = -b, by rewrite [this, neg_mul_neg]))
theorem mul_self_eq_one_iff (a : A) : a * a = 1 ↔ a = 1 ∨ a = -1 :=
assert a * a = 1 * 1 ↔ a = 1 ∨ a = -1, from mul_self_eq_mul_self_iff a 1,
by rewrite mul_one at this; exact this
-- TODO: c - b * c → c = 0 ∨ b = 1 and variants
theorem dvd_of_mul_dvd_mul_left {a b c : A} (Ha : a ≠ 0) (Hdvd : (a * b ∣ a * c)) : (b ∣ c) :=
dvd.elim Hdvd
(take d,
suppose a * c = a * b * d,
have b * d = c, from eq_of_mul_eq_mul_left Ha (mul.assoc a b d ▸ this⁻¹),
dvd.intro this)
theorem dvd_of_mul_dvd_mul_right {a b c : A} (Ha : a ≠ 0) (Hdvd : (b * a ∣ c * a)) : (b ∣ c) :=
dvd.elim Hdvd
(take d,
suppose c * a = b * a * d,
have b * d * a = c * a, from by rewrite [mul.right_comm, -this],
have b * d = c, from eq_of_mul_eq_mul_right Ha this,
dvd.intro this)
end
namespace norm_num
theorem mul_zero [mul_zero_class A] (a : A) : a * zero = zero :=
by rewrite [↑zero, mul_zero]
theorem zero_mul [mul_zero_class A] (a : A) : zero * a = zero :=
by rewrite [↑zero, zero_mul]
theorem mul_one [monoid A] (a : A) : a * one = a :=
by rewrite [↑one, mul_one]
theorem mul_bit0 [distrib A] (a b : A) : a * (bit0 b) = bit0 (a * b) :=
by rewrite [↑bit0, left_distrib]
theorem mul_bit0_helper [distrib A] (a b t : A) (H : a * b = t) : a * (bit0 b) = bit0 t :=
by rewrite -H; apply mul_bit0
theorem mul_bit1 [semiring A] (a b : A) : a * (bit1 b) = bit0 (a * b) + a :=
by rewrite [↑bit1, ↑bit0, +left_distrib, ↑one, mul_one]
theorem mul_bit1_helper [semiring A] (a b s t : A) (Hs : a * b = s) (Ht : bit0 s + a = t) :
a * (bit1 b) = t :=
begin rewrite [-Ht, -Hs, mul_bit1] end
theorem subst_into_prod [has_mul A] (l r tl tr t : A) (prl : l = tl) (prr : r = tr)
(prt : tl * tr = t) :
l * r = t :=
by rewrite [prl, prr, prt]
theorem mk_cong (op : A → A) (a b : A) (H : a = b) : op a = op b :=
by congruence; exact H
theorem neg_add_neg_eq_of_add_add_eq_zero [add_comm_group A] (a b c : A) (H : c + a + b = 0) :
-a + -b = c :=
begin
apply add_neg_eq_of_eq_add,
apply neg_eq_of_add_eq_zero,
rewrite [add.comm, add.assoc, add.comm b, -add.assoc, H]
end
theorem neg_add_neg_helper [add_comm_group A] (a b c : A) (H : a + b = c) : -a + -b = -c :=
begin apply iff.mp !neg_eq_neg_iff_eq, rewrite [neg_add, *neg_neg, H] end
theorem neg_add_pos_eq_of_eq_add [add_comm_group A] (a b c : A) (H : b = c + a) : -a + b = c :=
begin apply neg_add_eq_of_eq_add, rewrite add.comm, exact H end
theorem neg_add_pos_helper1 [add_comm_group A] (a b c : A) (H : b + c = a) : -a + b = -c :=
begin apply neg_add_eq_of_eq_add, apply eq_add_neg_of_add_eq H end
theorem neg_add_pos_helper2 [add_comm_group A] (a b c : A) (H : a + c = b) : -a + b = c :=
begin apply neg_add_eq_of_eq_add, rewrite H end
theorem pos_add_neg_helper [add_comm_group A] (a b c : A) (H : b + a = c) : a + b = c :=
by rewrite [add.comm, H]
theorem sub_eq_add_neg_helper [add_comm_group A] (t₁ t₂ e w₁ w₂: A) (H₁ : t₁ = w₁)
(H₂ : t₂ = w₂) (H : w₁ + -w₂ = e) : t₁ - t₂ = e :=
by rewrite [sub_eq_add_neg, H₁, H₂, H]
theorem pos_add_pos_helper [add_comm_group A] (a b c h₁ h₂ : A) (H₁ : a = h₁) (H₂ : b = h₂)
(H : h₁ + h₂ = c) : a + b = c :=
by rewrite [H₁, H₂, H]
theorem subst_into_subtr [add_group A] (l r t : A) (prt : l + -r = t) : l - r = t :=
by rewrite [sub_eq_add_neg, prt]
theorem neg_neg_helper [add_group A] (a b : A) (H : a = -b) : -a = b :=
by rewrite [H, neg_neg]
theorem neg_mul_neg_helper [ring A] (a b c : A) (H : a * b = c) : (-a) * (-b) = c :=
begin rewrite [neg_mul_neg, H] end
theorem neg_mul_pos_helper [ring A] (a b c : A) (H : a * b = c) : (-a) * b = -c :=
begin rewrite [-neg_mul_eq_neg_mul, H] end
theorem pos_mul_neg_helper [ring A] (a b c : A) (H : a * b = c) : a * (-b) = -c :=
begin rewrite [-neg_mul_comm, -neg_mul_eq_neg_mul, H] end
end norm_num
attribute [simp]
zero_mul mul_zero
at simplifier.unit
attribute [simp]
neg_mul_eq_neg_mul_symm mul_neg_eq_neg_mul_symm
at simplifier.neg
attribute [simp]
left_distrib right_distrib
at simplifier.distrib
|
9b883df2c7264ab62ce5459b39e66b634ef683e7 | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/computability/partrec.lean | 9a1792def8cfafbc1c1929e4755554d9f394e248 | [
"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 | 28,982 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import computability.primrec
import data.nat.psub
import data.pfun
/-!
# The partial recursive functions
The partial recursive functions are defined similarly to the primitive
recursive functions, but now all functions are partial, implemented
using the `roption` monad, and there is an additional operation, called
μ-recursion, which performs unbounded minimization.
## References
* [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019]
-/
open encodable denumerable roption
namespace nat
section rfind
parameter (p : ℕ →. bool)
private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ff ∈ p k
parameter (H : ∃ n, tt ∈ p n ∧ ∀ k < n, (p k).dom)
private def wf_lbp : well_founded lbp :=
⟨let ⟨n, pn⟩ := H in begin
suffices : ∀m k, n ≤ k + m → acc (lbp p) k,
{ from λa, this _ _ (nat.le_add_left _ _) },
intros m k kn,
induction m with m IH generalizing k;
refine ⟨_, λ y r, _⟩; rcases r with ⟨rfl, a⟩,
{ injection mem_unique pn.1 (a _ kn) },
{ exact IH _ (by rw nat.add_right_comm; exact kn) }
end⟩
def rfind_x : {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m} :=
suffices ∀ k, (∀n < k, ff ∈ p n) → {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m},
from this 0 (λ n, (nat.not_lt_zero _).elim),
@well_founded.fix _ _ lbp wf_lbp begin
intros m IH al,
have pm : (p m).dom,
{ rcases H with ⟨n, h₁, h₂⟩,
rcases decidable.lt_trichotomy m n with h₃|h₃|h₃,
{ exact h₂ _ h₃ },
{ rw h₃, exact h₁.fst },
{ injection mem_unique h₁ (al _ h₃) } },
cases e : (p m).get pm,
{ suffices,
exact IH _ ⟨rfl, this⟩ (λ n h, this _ (le_of_lt_succ h)),
intros n h, cases decidable.lt_or_eq_of_le h with h h,
{ exact al _ h },
{ rw h, exact ⟨_, e⟩ } },
{ exact ⟨m, ⟨_, e⟩, al⟩ }
end
end rfind
def rfind (p : ℕ →. bool) : roption ℕ :=
⟨_, λ h, (rfind_x p h).1⟩
theorem rfind_spec {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : tt ∈ p n :=
h.snd ▸ (rfind_x p h.fst).2.1
theorem rfind_min {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) :
∀ {m : ℕ}, m < n → ff ∈ p m :=
h.snd ▸ (rfind_x p h.fst).2.2
@[simp] theorem rfind_dom {p : ℕ →. bool} :
(rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m < n → (p m).dom :=
iff.rfl
theorem rfind_dom' {p : ℕ →. bool} :
(rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m ≤ n → (p m).dom :=
exists_congr $ λ n, and_congr_right $ λ pn,
⟨λ H m h, (eq_or_lt_of_le h).elim (λ e, e.symm ▸ pn.fst) (H _),
λ H m h, H (le_of_lt h)⟩
@[simp] theorem mem_rfind {p : ℕ →. bool} {n : ℕ} :
n ∈ rfind p ↔ tt ∈ p n ∧ ∀ {m : ℕ}, m < n → ff ∈ p m :=
⟨λ h, ⟨rfind_spec h, @rfind_min _ _ h⟩,
λ ⟨h₁, h₂⟩, let ⟨m, hm⟩ := dom_iff_mem.1 $
(@rfind_dom p).2 ⟨_, h₁, λ m mn, (h₂ mn).fst⟩ in
begin
rcases lt_trichotomy m n with h|h|h,
{ injection mem_unique (h₂ h) (rfind_spec hm) },
{ rwa ← h },
{ injection mem_unique h₁ (rfind_min hm h) },
end⟩
theorem rfind_min' {p : ℕ → bool} {m : ℕ} (pm : p m) :
∃ n ∈ rfind p, n ≤ m :=
have tt ∈ (p : ℕ →. bool) m, from ⟨trivial, pm⟩,
let ⟨n, hn⟩ := dom_iff_mem.1 $
(@rfind_dom p).2 ⟨m, this, λ k h, ⟨⟩⟩ in
⟨n, hn, not_lt.1 $ λ h,
by injection mem_unique this (rfind_min hn h)⟩
theorem rfind_zero_none
(p : ℕ →. bool) (p0 : p 0 = none) : rfind p = none :=
eq_none_iff.2 $ λ a h,
let ⟨n, h₁, h₂⟩ := rfind_dom'.1 h.fst in
(p0 ▸ h₂ (zero_le _) : (@roption.none bool).dom)
def rfind_opt {α} (f : ℕ → option α) : roption α :=
(rfind (λ n, (f n).is_some)).bind (λ n, f n)
theorem rfind_opt_spec {α} {f : ℕ → option α} {a}
(h : a ∈ rfind_opt f) : ∃ n, a ∈ f n :=
let ⟨n, h₁, h₂⟩ := mem_bind_iff.1 h in ⟨n, mem_coe.1 h₂⟩
theorem rfind_opt_dom {α} {f : ℕ → option α} :
(rfind_opt f).dom ↔ ∃ n a, a ∈ f n :=
⟨λ h, (rfind_opt_spec ⟨h, rfl⟩).imp (λ n h, ⟨_, h⟩),
λ h, begin
have h' : ∃ n, (f n).is_some :=
h.imp (λ n, option.is_some_iff_exists.2),
have s := nat.find_spec h',
have fd : (rfind (λ n, (f n).is_some)).dom :=
⟨nat.find h', by simpa using s.symm, λ _ _, trivial⟩,
refine ⟨fd, _⟩,
have := rfind_spec (get_mem fd),
simp at this ⊢,
cases option.is_some_iff_exists.1 this.symm with a e,
rw e, trivial
end⟩
theorem rfind_opt_mono {α} {f : ℕ → option α}
(H : ∀ {a m n}, m ≤ n → a ∈ f m → a ∈ f n)
{a} : a ∈ rfind_opt f ↔ ∃ n, a ∈ f n :=
⟨rfind_opt_spec, λ ⟨n, h⟩, begin
have h' := rfind_opt_dom.2 ⟨_, _, h⟩,
cases rfind_opt_spec ⟨h', rfl⟩ with k hk,
have := (H (le_max_left _ _) h).symm.trans
(H (le_max_right _ _) hk),
simp at this, simp [this, get_mem]
end⟩
inductive partrec : (ℕ →. ℕ) → Prop
| zero : partrec (pure 0)
| succ : partrec succ
| left : partrec ↑(λ n : ℕ, n.unpair.1)
| right : partrec ↑(λ n : ℕ, n.unpair.2)
| pair {f g} : partrec f → partrec g → partrec (λ n, mkpair <$> f n <*> g n)
| comp {f g} : partrec f → partrec g → partrec (λ n, g n >>= f)
| prec {f g} : partrec f → partrec g → partrec (unpaired (λ a n,
n.elim (f a) (λ y IH, do i ← IH, g (mkpair a (mkpair y i)))))
| rfind {f} : partrec f → partrec (λ a,
rfind (λ n, (λ m, m = 0) <$> f (mkpair a n)))
namespace partrec
theorem of_eq {f g : ℕ →. ℕ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g :=
(funext H : f = g) ▸ hf
theorem of_eq_tot {f : ℕ →. ℕ} {g : ℕ → ℕ}
(hf : partrec f) (H : ∀ n, g n ∈ f n) : partrec g :=
hf.of_eq (λ n, eq_some_iff.2 (H n))
theorem of_primrec {f : ℕ → ℕ} (hf : primrec f) : partrec f :=
begin
induction hf,
case nat.primrec.zero { exact zero },
case nat.primrec.succ { exact succ },
case nat.primrec.left { exact left },
case nat.primrec.right { exact right },
case nat.primrec.pair : f g hf hg pf pg {
refine (pf.pair pg).of_eq_tot (λ n, _),
simp [has_seq.seq] },
case nat.primrec.comp : f g hf hg pf pg {
refine (pf.comp pg).of_eq_tot (λ n, _),
simp },
case nat.primrec.prec : f g hf hg pf pg {
refine (pf.prec pg).of_eq_tot (λ n, _),
simp,
induction n.unpair.2 with m IH, {simp},
simp, exact ⟨_, IH, rfl⟩ },
end
protected theorem some : partrec some := of_primrec primrec.id
theorem none : partrec (λ n, none) :=
(of_primrec (nat.primrec.const 1)).rfind.of_eq $
λ n, eq_none_iff.2 $ λ a ⟨h, e⟩, by simpa using h
theorem prec' {f g h}
(hf : partrec f) (hg : partrec g) (hh : partrec h) :
partrec (λ a, (f a).bind (λ n, n.elim (g a)
(λ y IH, do i ← IH, h (mkpair a (mkpair y i))))) :=
((prec hg hh).comp (pair partrec.some hf)).of_eq $
λ a, ext $ λ s, by simp [(<*>)]; exact
⟨λ ⟨n, h₁, h₂⟩, ⟨_, ⟨_, h₁, rfl⟩, by simpa using h₂⟩,
λ ⟨_, ⟨n, h₁, rfl⟩, h₂⟩, ⟨_, h₁, by simpa using h₂⟩⟩
theorem ppred : partrec (λ n, ppred n) :=
have primrec₂ (λ n m, if n = nat.succ m then 0 else 1),
from (primrec.ite
(@@primrec_rel.comp _ _ _ _ _ _ _ primrec.eq
primrec.fst
(_root_.primrec.succ.comp primrec.snd))
(_root_.primrec.const 0) (_root_.primrec.const 1)).to₂,
(of_primrec (primrec₂.unpaired'.2 this)).rfind.of_eq $
λ n, begin
cases n; simp,
{ exact eq_none_iff.2 (λ a ⟨⟨m, h, _⟩, _⟩,
by simpa [show 0 ≠ m.succ, by intro h; injection h] using h) },
{ refine eq_some_iff.2 _,
simp, intros m h, simp [ne_of_gt h] }
end
end partrec
end nat
def partrec {α σ} [primcodable α] [primcodable σ]
(f : α →. σ) := nat.partrec (λ n,
roption.bind (decode α n) (λ a, (f a).map encode))
def partrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ]
(f : α → β →. σ) := partrec (λ p : α × β, f p.1 p.2)
def computable {α σ} [primcodable α] [primcodable σ] (f : α → σ) := partrec (f : α →. σ)
def computable₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ]
(f : α → β → σ) := computable (λ p : α × β, f p.1 p.2)
theorem primrec.to_comp {α σ} [primcodable α] [primcodable σ]
{f : α → σ} (hf : primrec f) : computable f :=
(nat.partrec.ppred.comp (nat.partrec.of_primrec hf)).of_eq $
λ n, by simp; cases decode α n; simp
theorem primrec₂.to_comp {α β σ} [primcodable α] [primcodable β] [primcodable σ]
{f : α → β → σ} (hf : primrec₂ f) : computable₂ f := hf.to_comp
theorem computable.part {α σ} [primcodable α] [primcodable σ]
{f : α → σ} (hf : computable f) : partrec (f : α →. σ) := hf
theorem computable₂.part {α β σ} [primcodable α] [primcodable β] [primcodable σ]
{f : α → β → σ} (hf : computable₂ f) : partrec₂ (λ a, (f a : β →. σ)) := hf
namespace computable
variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ]
theorem of_eq {f g : α → σ} (hf : computable f) (H : ∀ n, f n = g n) : computable g :=
(funext H : f = g) ▸ hf
theorem const (s : σ) : computable (λ a : α, s) :=
(primrec.const _).to_comp
theorem of_option {f : α → option β}
(hf : computable f) : partrec (λ a, (f a : roption β)) :=
(nat.partrec.ppred.comp hf).of_eq $ λ n, begin
cases decode α n with a; simp,
cases f a with b; simp
end
theorem to₂ {f : α × β → σ} (hf : computable f) : computable₂ (λ a b, f (a, b)) :=
hf.of_eq $ λ ⟨a, b⟩, rfl
protected theorem id : computable (@id α) := primrec.id.to_comp
theorem fst : computable (@prod.fst α β) := primrec.fst.to_comp
theorem snd : computable (@prod.snd α β) := primrec.snd.to_comp
theorem pair {f : α → β} {g : α → γ}
(hf : computable f) (hg : computable g) : computable (λ a, (f a, g a)) :=
(hf.pair hg).of_eq $
λ n, by cases decode α n; simp [(<*>)]
theorem unpair : computable nat.unpair := primrec.unpair.to_comp
theorem succ : computable nat.succ := primrec.succ.to_comp
theorem pred : computable nat.pred := primrec.pred.to_comp
theorem nat_bodd : computable nat.bodd := primrec.nat_bodd.to_comp
theorem nat_div2 : computable nat.div2 := primrec.nat_div2.to_comp
theorem sum_inl : computable (@sum.inl α β) := primrec.sum_inl.to_comp
theorem sum_inr : computable (@sum.inr α β) := primrec.sum_inr.to_comp
theorem list_cons : computable₂ (@list.cons α) := primrec.list_cons.to_comp
theorem list_reverse : computable (@list.reverse α) := primrec.list_reverse.to_comp
theorem list_nth : computable₂ (@list.nth α) := primrec.list_nth.to_comp
theorem list_append : computable₂ ((++) : list α → list α → list α) := primrec.list_append.to_comp
theorem list_concat : computable₂ (λ l (a:α), l ++ [a]) := primrec.list_concat.to_comp
theorem list_length : computable (@list.length α) := primrec.list_length.to_comp
theorem vector_cons {n} : computable₂ (@vector.cons α n) := primrec.vector_cons.to_comp
theorem vector_to_list {n} : computable (@vector.to_list α n) := primrec.vector_to_list.to_comp
theorem vector_length {n} : computable (@vector.length α n) := primrec.vector_length.to_comp
theorem vector_head {n} : computable (@vector.head α n) := primrec.vector_head.to_comp
theorem vector_tail {n} : computable (@vector.tail α n) := primrec.vector_tail.to_comp
theorem vector_nth {n} : computable₂ (@vector.nth α n) := primrec.vector_nth.to_comp
theorem vector_nth' {n} : computable (@vector.nth α n) := primrec.vector_nth'.to_comp
theorem vector_of_fn' {n} : computable (@vector.of_fn α n) := primrec.vector_of_fn'.to_comp
theorem fin_app {n} : computable₂ (@id (fin n → σ)) := primrec.fin_app.to_comp
protected theorem encode : computable (@encode α _) :=
primrec.encode.to_comp
protected theorem decode : computable (decode α) :=
primrec.decode.to_comp
protected theorem of_nat (α) [denumerable α] : computable (of_nat α) :=
(primrec.of_nat _).to_comp
theorem encode_iff {f : α → σ} : computable (λ a, encode (f a)) ↔ computable f :=
iff.rfl
theorem option_some : computable (@option.some α) :=
primrec.option_some.to_comp
end computable
namespace partrec
variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ]
open computable
theorem of_eq {f g : α →. σ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g :=
(funext H : f = g) ▸ hf
theorem of_eq_tot {f : α →. σ} {g : α → σ}
(hf : partrec f) (H : ∀ n, g n ∈ f n) : computable g :=
hf.of_eq (λ a, eq_some_iff.2 (H a))
theorem none : partrec (λ a : α, @roption.none σ) :=
nat.partrec.none.of_eq $ λ n, by cases decode α n; simp
protected theorem some : partrec (@roption.some α) := computable.id
theorem const' (s : roption σ) : partrec (λ a : α, s) :=
by haveI := classical.dec s.dom; exact
(of_option (const (to_option s))).of_eq (λ a, of_to_option s)
protected theorem bind {f : α →. β} {g : α → β →. σ}
(hf : partrec f) (hg : partrec₂ g) : partrec (λ a, (f a).bind (g a)) :=
(hg.comp (nat.partrec.some.pair hf)).of_eq $
λ n, by simp [(<*>)]; cases e : decode α n with a;
simp [e, encodek]
theorem map {f : α →. β} {g : α → β → σ}
(hf : partrec f) (hg : computable₂ g) : partrec (λ a, (f a).map (g a)) :=
by simpa [bind_some_eq_map] using
@@partrec.bind _ _ _ (λ a b, roption.some (g a b)) hf hg
theorem to₂ {f : α × β →. σ} (hf : partrec f) : partrec₂ (λ a b, f (a, b)) :=
hf.of_eq $ λ ⟨a, b⟩, rfl
theorem nat_elim
{f : α → ℕ} {g : α →. σ} {h : α → ℕ × σ →. σ}
(hf : computable f) (hg : partrec g) (hh : partrec₂ h) :
partrec (λ a, (f a).elim (g a) (λ y IH, IH.bind (λ i, h a (y, i)))) :=
(nat.partrec.prec' hf hg hh).of_eq $ λ n, begin
cases e : decode α n with a; simp [e],
induction f a with m IH; simp,
rw [IH, bind_map],
congr, funext s,
simp [encodek]
end
theorem comp {f : β →. σ} {g : α → β}
(hf : partrec f) (hg : computable g) : partrec (λ a, f (g a)) :=
(hf.comp hg).of_eq $
λ n, by simp; cases e : decode α n with a;
simp [e, encodek]
theorem nat_iff {f : ℕ →. ℕ} : partrec f ↔ nat.partrec f :=
by simp [partrec, map_id']
theorem map_encode_iff {f : α →. σ} : partrec (λ a, (f a).map encode) ↔ partrec f :=
iff.rfl
end partrec
namespace partrec₂
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ]
theorem unpaired {f : ℕ → ℕ →. α} : partrec (nat.unpaired f) ↔ partrec₂ f :=
⟨λ h, by simpa using h.comp primrec₂.mkpair.to_comp,
λ h, h.comp primrec.unpair.to_comp⟩
theorem unpaired' {f : ℕ → ℕ →. ℕ} : nat.partrec (nat.unpaired f) ↔ partrec₂ f :=
partrec.nat_iff.symm.trans unpaired
theorem comp
{f : β → γ →. σ} {g : α → β} {h : α → γ}
(hf : partrec₂ f) (hg : computable g) (hh : computable h) :
partrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh)
theorem comp₂
{f : γ → δ →. σ} {g : α → β → γ} {h : α → β → δ}
(hf : partrec₂ f) (hg : computable₂ g) (hh : computable₂ h) :
partrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh
end partrec₂
namespace computable
variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ]
theorem comp {f : β → σ} {g : α → β}
(hf : computable f) (hg : computable g) :
computable (λ a, f (g a)) := hf.comp hg
theorem comp₂ {f : γ → σ} {g : α → β → γ}
(hf : computable f) (hg : computable₂ g) :
computable₂ (λ a b, f (g a b)) := hf.comp hg
end computable
namespace computable₂
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ]
theorem comp
{f : β → γ → σ} {g : α → β} {h : α → γ}
(hf : computable₂ f) (hg : computable g) (hh : computable h) :
computable (λ a, f (g a) (h a)) := hf.comp (hg.pair hh)
theorem comp₂
{f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ}
(hf : computable₂ f) (hg : computable₂ g) (hh : computable₂ h) :
computable₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh
end computable₂
namespace partrec
variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ]
open computable
theorem rfind {p : α → ℕ →. bool} (hp : partrec₂ p) :
partrec (λ a, nat.rfind (p a)) :=
(nat.partrec.rfind $ hp.map
((primrec.dom_bool (λ b, cond b 0 1))
.comp primrec.snd).to₂.to_comp).of_eq $
λ n, begin
cases e : decode α n with a;
simp [e, nat.rfind_zero_none, map_id'],
congr, funext n,
simp [roption.map_map, (∘)],
apply map_id' (λ b, _),
cases b; refl
end
theorem rfind_opt {f : α → ℕ → option σ} (hf : computable₂ f) :
partrec (λ a, nat.rfind_opt (f a)) :=
(rfind (primrec.option_is_some.to_comp.comp hf).part.to₂).bind
(of_option hf)
theorem nat_cases_right
{f : α → ℕ} {g : α → σ} {h : α → ℕ →. σ}
(hf : computable f) (hg : computable g) (hh : partrec₂ h) :
partrec (λ a, (f a).cases (some (g a)) (h a)) :=
(nat_elim hf hg (hh.comp fst (pred.comp $ hf.comp fst)).to₂).of_eq $
λ a, begin
simp, cases f a; simp,
refine ext (λ b, ⟨λ H, _, λ H, _⟩),
{ rcases mem_bind_iff.1 H with ⟨c, h₁, h₂⟩, exact h₂ },
{ have : ∀ m, (nat.elim (roption.some (g a))
(λ y IH, IH.bind (λ _, h a n)) m).dom,
{ intro, induction m; simp [*, H.fst] },
exact ⟨⟨this n, H.fst⟩, H.snd⟩ }
end
theorem bind_decode2_iff {f : α →. σ} : partrec f ↔
nat.partrec (λ n, roption.bind (decode2 α n) (λ a, (f a).map encode)) :=
⟨λ hf, nat_iff.1 $ (of_option primrec.decode2.to_comp).bind $
(map hf (computable.encode.comp snd).to₂).comp snd,
λ h, map_encode_iff.1 $ by simpa [encodek2]
using (nat_iff.2 h).comp (@computable.encode α _)⟩
theorem vector_m_of_fn : ∀ {n} {f : fin n → α →. σ}, (∀ i, partrec (f i)) →
partrec (λ (a : α), vector.m_of_fn (λ i, f i a))
| 0 f hf := const _
| (n+1) f hf := by simp [vector.m_of_fn]; exact
(hf 0).bind (partrec.bind ((vector_m_of_fn (λ i, hf i.succ)).comp fst)
(primrec.vector_cons.to_comp.comp (snd.comp fst) snd))
end partrec
@[simp] theorem vector.m_of_fn_roption_some {α n} : ∀ (f : fin n → α),
vector.m_of_fn (λ i, roption.some (f i)) = roption.some (vector.of_fn f) :=
vector.m_of_fn_pure
namespace computable
variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ]
theorem option_some_iff {f : α → σ} : computable (λ a, some (f a)) ↔ computable f :=
⟨λ h, encode_iff.1 $ primrec.pred.to_comp.comp $ encode_iff.2 h,
option_some.comp⟩
theorem bind_decode_iff {f : α → β → option σ} : computable₂ (λ a n,
(decode β n).bind (f a)) ↔ computable₂ f :=
⟨λ hf, nat.partrec.of_eq
(((partrec.nat_iff.2 (nat.partrec.ppred.comp $
nat.partrec.of_primrec $ primcodable.prim β)).comp snd).bind
(computable.comp hf fst).to₂.part) $
λ n, by simp;
cases decode α n.unpair.1; simp;
cases decode β n.unpair.2; simp,
λ hf, begin
have : partrec (λ a : α × ℕ, (encode (decode β a.2)).cases
(some option.none) (λ n, roption.map (f a.1) (decode β n))) :=
partrec.nat_cases_right (primrec.encdec.to_comp.comp snd)
(const none) ((of_option (computable.decode.comp snd)).map
(hf.comp (fst.comp $ fst.comp fst) snd).to₂),
refine this.of_eq (λ a, _),
simp, cases decode β a.2; simp [encodek]
end⟩
theorem map_decode_iff {f : α → β → σ} : computable₂ (λ a n,
(decode β n).map (f a)) ↔ computable₂ f :=
bind_decode_iff.trans option_some_iff
theorem nat_elim
{f : α → ℕ} {g : α → σ} {h : α → ℕ × σ → σ}
(hf : computable f) (hg : computable g) (hh : computable₂ h) :
computable (λ a, (f a).elim (g a) (λ y IH, h a (y, IH))) :=
(partrec.nat_elim hf hg hh.part).of_eq $
λ a, by simp; induction f a; simp *
theorem nat_cases {f : α → ℕ} {g : α → σ} {h : α → ℕ → σ}
(hf : computable f) (hg : computable g) (hh : computable₂ h) :
computable (λ a, (f a).cases (g a) (h a)) :=
nat_elim hf hg (hh.comp fst $ fst.comp snd).to₂
theorem cond {c : α → bool} {f : α → σ} {g : α → σ}
(hc : computable c) (hf : computable f) (hg : computable g) :
computable (λ a, cond (c a) (f a) (g a)) :=
(nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $
λ a, by cases c a; refl
theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ}
(ho : computable o) (hf : computable f) (hg : computable₂ g) :
@computable _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) :=
option_some_iff.1 $
(nat_cases (encode_iff.2 ho) (option_some_iff.2 hf)
(map_decode_iff.2 hg)).of_eq $
λ a, by cases o a; simp [encodek]; refl
theorem option_bind {f : α → option β} {g : α → β → option σ}
(hf : computable f) (hg : computable₂ g) :
computable (λ a, (f a).bind (g a)) :=
(option_cases hf (const option.none) hg).of_eq $
λ a, by cases f a; refl
theorem option_map {f : α → option β} {g : α → β → σ}
(hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).map (g a)) :=
option_bind hf (option_some.comp₂ hg)
theorem option_get_or_else {f : α → option β} {g : α → β}
(hf : computable f) (hg : computable g) :
computable (λ a, (f a).get_or_else (g a)) :=
(computable.option_cases hf hg (show computable₂ (λ a b, b), from computable.snd)).of_eq $
λ a, by cases f a; refl
theorem subtype_mk {f : α → β} {p : β → Prop} [decidable_pred p] {h : ∀ a, p (f a)}
(hp : primrec_pred p) (hf : computable f) :
@computable _ _ _ (primcodable.subtype hp) (λ a, (⟨f a, h a⟩ : subtype p)) :=
nat.partrec.of_eq hf $ λ n, by cases decode α n; simp [subtype.encode_eq]
theorem sum_cases
{f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ}
(hf : computable f) (hg : computable₂ g) (hh : computable₂ h) :
@computable _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) :=
option_some_iff.1 $
(cond (nat_bodd.comp $ encode_iff.2 hf)
(option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh)
(option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $
λ a, by cases f a with b c;
simp [nat.div2_bit, nat.bodd_bit, encodek]; refl
theorem nat_strong_rec
(f : α → ℕ → σ) {g : α → list σ → option σ} (hg : computable₂ g)
(H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : computable₂ f :=
suffices computable₂ (λ a n, (list.range n).map (f a)), from
option_some_iff.1 $
(list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $
λ a, by simp [list.nth_range (nat.lt_succ_self a.2)]; refl,
option_some_iff.1 $
(nat_elim snd (const (option.some [])) (to₂ $
option_bind (snd.comp snd) $ to₂ $
option_map
(hg.comp (fst.comp $ fst.comp fst) snd)
(to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $
λ a, begin
simp, induction a.2 with n IH, {refl},
simp [IH, H, list.range_succ]
end
theorem list_of_fn : ∀ {n} {f : fin n → α → σ},
(∀ i, computable (f i)) → computable (λ a, list.of_fn (λ i, f i a))
| 0 f hf := const []
| (n+1) f hf := by simp [list.of_fn_succ]; exact
list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ))
theorem vector_of_fn {n} {f : fin n → α → σ}
(hf : ∀ i, computable (f i)) : computable (λ a, vector.of_fn (λ i, f i a)) :=
(partrec.vector_m_of_fn hf).of_eq $ λ a, by simp
end computable
namespace partrec
variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ]
open computable
theorem option_some_iff {f : α →. σ} :
partrec (λ a, (f a).map option.some) ↔ partrec f :=
⟨λ h, (nat.partrec.ppred.comp h).of_eq $
λ n, by simp [roption.bind_assoc, bind_some_eq_map],
λ hf, hf.map (option_some.comp snd).to₂⟩
theorem option_cases_right {o : α → option β} {f : α → σ} {g : α → β →. σ}
(ho : computable o) (hf : computable f) (hg : partrec₂ g) :
@partrec _ σ _ _ (λ a, option.cases_on (o a) (some (f a)) (g a)) :=
have partrec (λ (a : α), nat.cases (roption.some (f a))
(λ n, roption.bind (decode β n) (g a)) (encode (o a))) :=
nat_cases_right (encode_iff.2 ho) hf.part $
((@computable.decode β _).comp snd).of_option.bind
(hg.comp (fst.comp fst) snd).to₂,
this.of_eq $ λ a, by cases o a with b; simp [encodek]
theorem sum_cases_right
{f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ →. σ}
(hf : computable f) (hg : computable₂ g) (hh : partrec₂ h) :
@partrec _ σ _ _ (λ a, sum.cases_on (f a) (λ b, some (g a b)) (h a)) :=
have partrec (λ a, (option.cases_on
(sum.cases_on (f a) (λ b, option.none) option.some : option γ)
(some (sum.cases_on (f a) (λ b, some (g a b))
(λ c, option.none)))
(λ c, (h a c).map option.some) : roption (option σ))) :=
option_cases_right
(sum_cases hf (const option.none).to₂ (option_some.comp snd).to₂)
(sum_cases hf (option_some.comp hg) (const option.none).to₂)
(option_some_iff.2 hh),
option_some_iff.1 $ this.of_eq $ λ a, by cases f a; simp
theorem sum_cases_left
{f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ → σ}
(hf : computable f) (hg : partrec₂ g) (hh : computable₂ h) :
@partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (λ c, some (h a c))) :=
(sum_cases_right (sum_cases hf
(sum_inr.comp snd).to₂ (sum_inl.comp snd).to₂) hh hg).of_eq $
λ a, by cases f a; simp
private lemma fix_aux
{f : α →. σ ⊕ α} (hf : partrec f)
(a : α) (b : σ) :
let F : α → ℕ →. σ ⊕ α := λ a n,
n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s,
sum.cases_on s (λ _, roption.some s) f in
(∃ (n : ℕ), ((∃ (b' : σ), sum.inl b' ∈ F a n) ∧
∀ {m : ℕ}, m < n → (∃ (b : α), sum.inr b ∈ F a m)) ∧
sum.inl b ∈ F a n) ↔ b ∈ pfun.fix f a :=
begin
intro, refine ⟨λ h, _, λ h, _⟩,
{ rcases h with ⟨n, ⟨_x, h₁⟩, h₂⟩,
have : ∀ m a' (_: sum.inr a' ∈ F a m)
(_: b ∈ pfun.fix f a'), b ∈ pfun.fix f a,
{ intros m a' am ba,
induction m with m IH generalizing a'; simp [F] at am,
{ rwa ← am },
rcases am with ⟨a₂, am₂, fa₂⟩,
exact IH _ am₂ (pfun.mem_fix_iff.2 (or.inr ⟨_, fa₂, ba⟩)) },
cases n; simp [F] at h₂, {cases h₂},
rcases h₂ with h₂ | ⟨a', am', fa'⟩,
{ cases h₁ (nat.lt_succ_self _) with a' h,
injection mem_unique h h₂ },
{ exact this _ _ am' (pfun.mem_fix_iff.2 (or.inl fa')) } },
{ suffices : ∀ a' (_: b ∈ pfun.fix f a') k (_: sum.inr a' ∈ F a k),
∃ n, sum.inl b ∈ F a n ∧
∀ (m < n) (_ : k ≤ m), ∃ a₂, sum.inr a₂ ∈ F a m,
{ rcases this _ h 0 (by simp [F]) with ⟨n, hn₁, hn₂⟩,
exact ⟨_, ⟨⟨_, hn₁⟩, λ m mn, hn₂ m mn (nat.zero_le _)⟩, hn₁⟩ },
intros a₁ h₁,
apply pfun.fix_induction h₁, intros a₂ h₂ IH k hk,
rcases pfun.mem_fix_iff.1 h₂ with h₂ | ⟨a₃, am₃, fa₃⟩,
{ refine ⟨k.succ, _, λ m mk km, ⟨a₂, _⟩⟩,
{ simp [F], exact or.inr ⟨_, hk, h₂⟩ },
{ rwa le_antisymm (nat.le_of_lt_succ mk) km } },
{ rcases IH _ fa₃ am₃ k.succ _ with ⟨n, hn₁, hn₂⟩,
{ refine ⟨n, hn₁, λ m mn km, _⟩,
cases lt_or_eq_of_le km with km km,
{ exact hn₂ _ mn km },
{ exact km ▸ ⟨_, hk⟩ } },
{ simp [F], exact ⟨_, hk, am₃⟩ } } }
end
theorem fix
{f : α →. σ ⊕ α} (hf : partrec f) : partrec (pfun.fix f) :=
let F : α → ℕ →. σ ⊕ α := λ a n,
n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s,
sum.cases_on s (λ _, roption.some s) f in
have hF : partrec₂ F :=
partrec.nat_elim snd (sum_inr.comp fst).part
(sum_cases_right (snd.comp snd)
(snd.comp $ snd.comp fst).to₂
(hf.comp snd).to₂).to₂,
let p := λ a n, @roption.map _ bool
(λ s, sum.cases_on s (λ_, tt) (λ _, ff)) (F a n) in
have hp : partrec₂ p := hF.map ((sum_cases computable.id
(const tt).to₂ (const ff).to₂).comp snd).to₂,
(hp.rfind.bind (hF.bind
(sum_cases_right snd snd.to₂ none.to₂).to₂).to₂).of_eq $
λ a, ext $ λ b, by simp; apply fix_aux hf
end partrec
|
edda35325c746238ea5f9ba2d1635b30a8d37f69 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/andthen_focus_error_message.lean | 8a519c2bc533d947db2819a685c3babe5f32b406 | [
"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 | 816 | lean | lemma ex3 (a b c : nat) : a + 0 = 0 + a ∧ b = b :=
begin
constructor ; [skip, skip, skip]
--^ The "insufficient number of goals" error message should be reported here.
end
lemma ex4 (a b c : nat) : a + 0 = 0 + a ∧ b = b :=
begin
constructor; [skip, skip, skip]
--^ Flycheck reports the error here if the `;` occurs immediately after the first tactic.
-- This is not ideal, but this is a flycheck issue. Ther error is reported in the right place by Lean.
end
lemma ex5 (a : nat) : a = a ∧ a = a :=
begin
constructor ; [refl]
--^ "insufficient number of tactics" error
end
lemma ex6 (a : nat) : a = a ∧ a = a :=
begin
constructor ; []
--^ "insufficient number of tactics" error
end
lemma ex7 (a : nat) : a = a ∧ a = a :=
begin
constructor ; [refl, refl]
end
|
59bb314a508fcb000399523634445d6637ba2e42 | ff5230333a701471f46c57e8c115a073ebaaa448 | /library/init/meta/type_context.lean | 1d07989a1669bf80a44466b3323581d1cbd6b38e | [
"Apache-2.0"
] | permissive | stanford-cs242/lean | f81721d2b5d00bc175f2e58c57b710d465e6c858 | 7bd861261f4a37326dcf8d7a17f1f1f330e4548c | refs/heads/master | 1,600,957,431,849 | 1,576,465,093,000 | 1,576,465,093,000 | 225,779,423 | 0 | 3 | Apache-2.0 | 1,575,433,936,000 | 1,575,433,935,000 | null | UTF-8 | Lean | false | false | 6,299 | lean | prelude
import init.category init.meta.local_context init.meta.tactic init.meta.fun_info
namespace tactic.unsafe
/-- A monad that exposes the functionality of the C++ class `type_context`.
The idea is that the methods in `tco` are more powerful but _unsafe_ in the
sense that you can create terms that do not typecheck or that are infinitely descending.
Under the hood, `tco` is implemented as a reader monad, with a mutable `type_context` object.
-/
meta constant type_context : Type → Type
namespace type_context
variables {α β : Type}
protected meta constant bind : type_context α → (α → type_context β) → type_context β
protected meta constant pure : α → type_context α
protected meta constant fail : format → type_context α
protected meta def failure : type_context α := type_context.fail ""
meta instance : monad type_context := {bind := @type_context.bind, pure := @type_context.pure}
meta instance : monad_fail type_context := {fail := λ α, type_context.fail ∘ to_fmt}
meta constant get_env : type_context environment
meta constant whnf : expr → type_context expr
meta constant is_def_eq (e₁ e₂ : expr) (approx := ff) : type_context bool
meta constant unify (e₁ e₂ : expr) (approx := ff) : type_context bool
/-- Infer the type of the given expr. Inferring the type does not mean that it typechecks.
Will fail if type can't be inferred. -/
meta constant infer : expr → type_context expr
/-- A stuck expression `e` is an expression that _would_ reduce,
except that a metavariable is present that prevents the reduction.
Returns the metavariable which is causing the stuckage.
For example, `@has_add.add nat ?m a b` can't project because `?m` is not given. -/
meta constant is_stuck : expr → type_context (option expr)
/-- Add a local to the tc local context. -/
meta constant push_local (pp_name : name) (type : expr) (bi := binder_info.default) : type_context expr
meta constant pop_local : type_context unit
/-- Get the local context of the type_context. -/
meta constant get_local_context : type_context local_context
/-- Create and declare a new metavariable. If the local context is not given then it will use the current local context. -/
meta constant mk_mvar (pp_name : name) (type : expr) (context : option local_context := none) : type_context expr
/-- Iterate over all mvars in the mvar context. -/
meta constant fold_mvars {α : Type} (f : α → expr → type_context α) : α → type_context α
meta def list_mvars : type_context (list expr) := fold_mvars (λ l x, pure $ x :: l) []
/-- Set the mvar to the following assignments.
Works for temporary metas too.
[WARNING] `assign` does not perform certain checks:
- No typecheck is done before assignment.
- If the metavariable is already assigned this will clobber the assignment.
- It will not stop you from assigning an metavariable to itself or creating cycles of metavariable assignments.
These will manifest as 'deep recursion' exceptions when `instantiate_mvars` is used.
- It is not checked whether the assignment uses local constants outside the declaration's context.
You can avoid the unsafety by using `unify` instead.
-/
meta constant assign (mvar : expr) (assignment : expr) : type_context unit
meta constant level.assign (mvar : level) (assignment : level) : type_context unit
/-- Returns true if the given expression is a declared local constant or a declared metavariable. -/
meta constant is_declared (e : expr) : type_context bool
meta constant is_assigned (mvar : expr) : type_context bool
meta constant get_context (mvar : expr) : type_context local_context
/-- Get the expression that is assigned to the given mvar expression. Fails if given a -/
meta constant get_assignment (mvar : expr) : type_context expr
meta constant instantiate_mvars : expr → type_context expr
meta constant level.instantiate_mvars : level → type_context level
meta constant is_tmp_mvar (mvar : expr) : type_context bool
meta constant is_regular_mvar (mvar : expr) : type_context bool
/-- Run the given `type_context` monad in a temporary mvar scope.
Doing this twice will push the old tmp_mvar assignments to a stack.
So it is safe to do this whether or not you are already in tmp mode. -/
meta constant tmp_mode (n_uvars n_mvars : nat) : type_context α → type_context α
/-- Returns true when in temp mode. -/
meta constant in_tmp_mode : type_context bool
meta constant tmp_is_assigned : nat → type_context bool
meta constant tmp_get_assignment : nat → type_context expr
meta constant level.tmp_is_assigned : nat → type_context bool
meta constant level.tmp_get_assignment : nat → type_context level
/-- Replace each metavariable in the given expression with a temporary metavariable. -/
meta constant to_tmp_mvars : expr → type_context (expr × list level × list expr)
meta constant mk_tmp_mvar (index : nat) (type : expr): expr
meta constant level.mk_tmp_mvar (index : nat) : level
/-- Run the provided type_context within a backtracking scope.
This means that any changes to the metavariable context will not be committed if the
inner monad fails.
[warning]: the local context modified by `push_local` and `pop_local`
is not affected by `try`. Any unpopped locals will be present after the `try` even if the inner `type_context` failed.
-/
meta constant try {α : Type} : type_context α → type_context (option α)
meta def orelse {α : Type} : type_context α → type_context α → type_context α
| x y := try x >>= λ x, option.rec y pure x
meta instance type_context_alternative : alternative type_context := {
failure := λ α, type_context.fail "failed",
orelse := λ α x y, type_context.orelse x y
}
meta constant run (inner : type_context α) (tr := tactic.transparency.semireducible) : tactic α
meta def trace {α} [has_to_format α] : α → type_context unit | a :=
pure $ _root_.trace_fmt (to_fmt a) (λ u, ())
meta def print_mvars : type_context unit := do
mvs ← list_mvars,
mvs ← pure $ mvs.map (λ x, match x with (expr.mvar _ pp _) := to_fmt pp | _ := "" end),
trace mvs
/-- Same as tactic.get_fun_info -/
meta constant get_fun_info (f : expr) (nargs : option nat := none) : type_context fun_info
end type_context
end tactic.unsafe |
1834afbfa3cb132e6e8d711d19350dbdbc5d4f5e | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/extra/bag.lean | 72a7dec3a316c562227b2e8f191dc7073eb5d6c3 | [
"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 | 34,469 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
Finite bags.
-/
import data.nat data.list.perm algebra.binary
open nat quot list subtype binary function eq.ops algebra
open [decl] perm
variable {A : Type}
definition bag.setoid [instance] (A : Type) : setoid (list A) :=
setoid.mk (@perm A) (mk_equivalence (@perm A) (@perm.refl A) (@perm.symm A) (@perm.trans A))
definition bag (A : Type) : Type :=
quot (bag.setoid A)
namespace bag
definition of_list (l : list A) : bag A :=
⟦l⟧
definition empty : bag A :=
of_list nil
definition singleton (a : A) : bag A :=
of_list [a]
definition insert (a : A) (b : bag A) : bag A :=
quot.lift_on b (λ l, ⟦a::l⟧)
(λ l₁ l₂ h, quot.sound (perm.skip a h))
lemma insert_empty_eq_singleton (a : A) : insert a empty = singleton a :=
rfl
definition insert.comm (a₁ a₂ : A) (b : bag A) : insert a₁ (insert a₂ b) = insert a₂ (insert a₁ b) :=
quot.induction_on b (λ l, quot.sound !perm.swap)
definition append (b₁ b₂ : bag A) : bag A :=
quot.lift_on₂ b₁ b₂ (λ l₁ l₂, ⟦l₁++l₂⟧)
(λ l₁ l₂ l₃ l₄ h₁ h₂, quot.sound (perm_app h₁ h₂))
infix ++ := append
lemma append.comm (b₁ b₂ : bag A) : b₁ ++ b₂ = b₂ ++ b₁ :=
quot.induction_on₂ b₁ b₂ (λ l₁ l₂, quot.sound !perm_app_comm)
lemma append.assoc (b₁ b₂ b₃ : bag A) : (b₁ ++ b₂) ++ b₃ = b₁ ++ (b₂ ++ b₃) :=
quot.induction_on₃ b₁ b₂ b₃ (λ l₁ l₂ l₃, quot.sound (by rewrite list.append.assoc; apply perm.refl))
lemma append_empty_left (b : bag A) : empty ++ b = b :=
quot.induction_on b (λ l, quot.sound (by rewrite append_nil_left; apply perm.refl))
lemma append_empty_right (b : bag A) : b ++ empty = b :=
quot.induction_on b (λ l, quot.sound (by rewrite append_nil_right; apply perm.refl))
lemma append_insert_left (a : A) (b₁ b₂ : bag A) : insert a b₁ ++ b₂ = insert a (b₁ ++ b₂) :=
quot.induction_on₂ b₁ b₂ (λ l₁ l₂, quot.sound (by rewrite append_cons; apply perm.refl))
lemma append_insert_right (a : A) (b₁ b₂ : bag A) : b₁ ++ insert a b₂ = insert a (b₁ ++ b₂) :=
calc b₁ ++ insert a b₂ = insert a b₂ ++ b₁ : append.comm
... = insert a (b₂ ++ b₁) : append_insert_left
... = insert a (b₁ ++ b₂) : append.comm
protected lemma induction_on [recursor 3] {C : bag A → Prop} (b : bag A) (h₁ : C empty) (h₂ : ∀ a b, C b → C (insert a b)) : C b :=
quot.induction_on b (λ l, list.induction_on l h₁ (λ h t ih, h₂ h ⟦t⟧ ih))
section decidable_eq
variable [decA : decidable_eq A]
include decA
open decidable
definition has_decidable_eq [instance] (b₁ b₂ : bag A) : decidable (b₁ = b₂) :=
quot.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂,
match decidable_perm l₁ l₂ with
| inl h := inl (quot.sound h)
| inr h := inr (λ n, absurd (quot.exact n) h)
end)
end decidable_eq
section count
variable [decA : decidable_eq A]
include decA
definition count (a : A) (b : bag A) : nat :=
quot.lift_on b (λ l, count a l)
(λ l₁ l₂ h, count_eq_of_perm h a)
lemma count_empty (a : A) : count a empty = 0 :=
rfl
lemma count_insert (a : A) (b : bag A) : count a (insert a b) = succ (count a b) :=
quot.induction_on b (λ l, begin unfold [insert, count], rewrite count_cons_eq end)
lemma count_insert_of_ne {a₁ a₂ : A} (h : a₁ ≠ a₂) (b : bag A) : count a₁ (insert a₂ b) = count a₁ b :=
quot.induction_on b (λ l, begin unfold [insert, count], rewrite (count_cons_of_ne h) end)
lemma count_singleton (a : A) : count a (singleton a) = 1 :=
begin rewrite [-insert_empty_eq_singleton, count_insert] end
lemma count_append (a : A) (b₁ b₂ : bag A) : count a (append b₁ b₂) = count a b₁ + count a b₂ :=
quot.induction_on₂ b₁ b₂ (λ l₁ l₂, begin unfold [append, count], rewrite list.count_append end)
open perm decidable
protected lemma ext {b₁ b₂ : bag A} : (∀ a, count a b₁ = count a b₂) → b₁ = b₂ :=
quot.induction_on₂ b₁ b₂ (λ l₁ l₂ (h : ∀ a, count a ⟦l₁⟧ = count a ⟦l₂⟧),
have gen : ∀ (l₁ l₂ : list A), (∀ a, list.count a l₁ = list.count a l₂) → l₁ ~ l₂
| [] [] h₁ := !perm.refl
| [] (a₂::s₂) h₁ := assert list.count a₂ [] = list.count a₂ (a₂::s₂), from h₁ a₂, by rewrite [count_nil at this, count_cons_eq at this]; contradiction
| (a::s₁) s₂ h₁ :=
assert g₁ : list.count a (a::s₁) > 0, from count_gt_zero_of_mem !mem_cons,
assert list.count a (a::s₁) = list.count a s₂, from h₁ a,
assert list.count a s₂ > 0, by rewrite [-this]; exact g₁,
have a ∈ s₂, from mem_of_count_gt_zero this,
have ∃ l r, s₂ = l++(a::r), from mem_split this,
obtain l r (e₁ : s₂ = l++(a::r)), from this,
have ∀ a, list.count a s₁ = list.count a (l++r), from
take a₁,
assert e₂ : list.count a₁ (a::s₁) = list.count a₁ (l++(a::r)), by rewrite -e₁; exact h₁ a₁,
by_cases
(suppose a₁ = a, begin
rewrite [-this at e₂, list.count_append at e₂, *count_cons_eq at e₂, add_succ at e₂],
injection e₂ with e₃, rewrite e₃,
rewrite list.count_append
end)
(suppose a₁ ≠ a,
by rewrite [list.count_append at e₂, *count_cons_of_ne this at e₂, e₂, list.count_append]),
have ih : s₁ ~ l++r, from gen s₁ (l++r) this,
calc a::s₁ ~ a::(l++r) : perm.skip a ih
... ~ l++(a::r) : perm_middle
... = s₂ : e₁,
quot.sound (gen l₁ l₂ h))
definition insert.inj {a : A} {b₁ b₂ : bag A} : insert a b₁ = insert a b₂ → b₁ = b₂ :=
assume h, bag.ext (take x,
assert e : count x (insert a b₁) = count x (insert a b₂), by rewrite h,
by_cases
(suppose x = a, begin subst x, rewrite [*count_insert at e], injection e, assumption end)
(suppose x ≠ a, begin rewrite [*count_insert_of_ne this at e], assumption end))
end count
section extract
open decidable
variable [decA : decidable_eq A]
include decA
definition extract (a : A) (b : bag A) : bag A :=
quot.lift_on b (λ l, ⟦filter (λ c, c ≠ a) l⟧)
(λ l₁ l₂ h, quot.sound (perm_filter h))
lemma extract_singleton (a : A) : extract a (singleton a) = empty :=
begin unfold [extract, singleton, of_list, filter], rewrite [if_neg (λ h : a ≠ a, absurd rfl h)] end
lemma extract_insert (a : A) (b : bag A) : extract a (insert a b) = extract a b :=
quot.induction_on b (λ l, begin
unfold [insert, extract],
rewrite [@filter_cons_of_neg _ (λ c, c ≠ a) _ _ l (not_not_intro (eq.refl a))]
end)
lemma extract_insert_of_ne {a₁ a₂ : A} (h : a₁ ≠ a₂) (b : bag A) : extract a₁ (insert a₂ b) = insert a₂ (extract a₁ b) :=
quot.induction_on b (λ l, begin
unfold [insert, extract],
rewrite [@filter_cons_of_pos _ (λ c, c ≠ a₁) _ _ l (ne.symm h)]
end)
lemma count_extract (a : A) (b : bag A) : count a (extract a b) = 0 :=
bag.induction_on b rfl
(λ c b ih, by_cases
(suppose a = c, begin subst c, rewrite [extract_insert, ih] end)
(suppose a ≠ c, begin rewrite [extract_insert_of_ne this, count_insert_of_ne this, ih] end))
lemma count_extract_of_ne {a₁ a₂ : A} (h : a₁ ≠ a₂) (b : bag A) : count a₁ (extract a₂ b) = count a₁ b :=
bag.induction_on b rfl
(take x b ih, by_cases
(suppose x = a₁, begin subst x, rewrite [extract_insert_of_ne (ne.symm h), *count_insert, ih] end)
(suppose x ≠ a₁, by_cases
(suppose x = a₂, begin subst x, rewrite [extract_insert, ih, count_insert_of_ne h] end)
(suppose x ≠ a₂, begin
rewrite [count_insert_of_ne (ne.symm `x ≠ a₁`), extract_insert_of_ne (ne.symm this)],
rewrite [count_insert_of_ne (ne.symm `x ≠ a₁`), ih]
end)))
end extract
section erase
variable [decA : decidable_eq A]
include decA
definition erase (a : A) (b : bag A) : bag A :=
quot.lift_on b (λ l, ⟦erase a l⟧)
(λ l₁ l₂ h, quot.sound (erase_perm_erase_of_perm _ h))
lemma erase_empty (a : A) : erase a empty = empty :=
rfl
lemma erase_insert (a : A) (b : bag A) : erase a (insert a b) = b :=
quot.induction_on b (λ l, quot.sound (by rewrite erase_cons_head; apply perm.refl))
lemma erase_insert_of_ne {a₁ a₂ : A} (h : a₁ ≠ a₂) (b : bag A) : erase a₁ (insert a₂ b) = insert a₂ (erase a₁ b) :=
quot.induction_on b (λ l, quot.sound (by rewrite (erase_cons_tail _ h); apply perm.refl))
end erase
section member
variable [decA : decidable_eq A]
include decA
definition mem (a : A) (b : bag A) := count a b > 0
infix ∈ := mem
lemma mem_def (a : A) (b : bag A) : (a ∈ b) = (count a b > 0) :=
rfl
lemma mem_insert (a : A) (b : bag A) : a ∈ insert a b :=
begin unfold mem, rewrite count_insert, exact dec_trivial end
lemma mem_of_list_iff_mem (a : A) (l : list A) : a ∈ of_list l ↔ a ∈ l :=
iff.intro !mem_of_count_gt_zero !count_gt_zero_of_mem
lemma count_of_list_eq_count (a : A) (l : list A) : count a (of_list l) = list.count a l :=
rfl
end member
section union_inter
variable [decA : decidable_eq A]
include decA
open perm decidable
private definition union_list (l₁ l₂ : list A) :=
erase_dup (l₁ ++ l₂)
private lemma perm_union_list {l₁ l₂ l₃ l₄ : list A} (h₁ : l₁ ~ l₃) (h₂ : l₂ ~ l₄) : union_list l₁ l₂ ~ union_list l₃ l₄ :=
perm_erase_dup_of_perm (perm_app h₁ h₂)
private lemma nodup_union_list (l₁ l₂ : list A) : nodup (union_list l₁ l₂) :=
!nodup_erase_dup
private definition not_mem_of_not_mem_union_list_left {a : A} {l₁ l₂ : list A} (h : a ∉ union_list l₁ l₂) : a ∉ l₁ :=
suppose a ∈ l₁,
have a ∈ l₁ ++ l₂, from mem_append_left _ this,
have a ∈ erase_dup (l₁ ++ l₂), from mem_erase_dup this,
absurd this h
private definition not_mem_of_not_mem_union_list_right {a : A} {l₁ l₂ : list A} (h : a ∉ union_list l₁ l₂) : a ∉ l₂ :=
suppose a ∈ l₂,
have a ∈ l₁ ++ l₂, from mem_append_right _ this,
have a ∈ erase_dup (l₁ ++ l₂), from mem_erase_dup this,
absurd this h
private definition gen : nat → A → list A
| 0 a := nil
| (n+1) a := a :: gen n a
private lemma not_mem_gen_of_ne {a b : A} (h : a ≠ b) : ∀ n, a ∉ gen n b
| 0 := !not_mem_nil
| (n+1) := not_mem_cons_of_ne_of_not_mem h (not_mem_gen_of_ne n)
private lemma count_gen : ∀ (a : A) (n : nat), list.count a (gen n a) = n
| a 0 := rfl
| a (n+1) := begin unfold gen, rewrite [count_cons_eq, count_gen] end
private lemma count_gen_eq_zero_of_ne {a b : A} (h : a ≠ b) : ∀ n, list.count a (gen n b) = 0
| 0 := rfl
| (n+1) := begin unfold gen, rewrite [count_cons_of_ne h, count_gen_eq_zero_of_ne] end
private definition max_count (l₁ l₂ : list A) : list A → list A
| [] := []
| (a::l) := if list.count a l₁ ≥ list.count a l₂ then gen (list.count a l₁) a ++ max_count l else gen (list.count a l₂) a ++ max_count l
private definition min_count (l₁ l₂ : list A) : list A → list A
| [] := []
| (a::l) := if list.count a l₁ ≤ list.count a l₂ then gen (list.count a l₁) a ++ min_count l else gen (list.count a l₂) a ++ min_count l
private lemma not_mem_max_count_of_not_mem (l₁ l₂ : list A) : ∀ {a l}, a ∉ l → a ∉ max_count l₁ l₂ l
| a [] h := !not_mem_nil
| a (b::l) h :=
assert ih : a ∉ max_count l₁ l₂ l, from not_mem_max_count_of_not_mem (not_mem_of_not_mem_cons h),
assert a ≠ b, from ne_of_not_mem_cons h,
by_cases
(suppose list.count b l₁ ≥ list.count b l₂, begin
unfold max_count, rewrite [if_pos this],
exact not_mem_append (not_mem_gen_of_ne `a ≠ b` _) ih
end)
(suppose ¬ list.count b l₁ ≥ list.count b l₂, begin
unfold max_count, rewrite [if_neg this],
exact not_mem_append (not_mem_gen_of_ne `a ≠ b` _) ih
end)
private lemma max_count_eq (l₁ l₂ : list A) : ∀ {a : A} {l : list A}, a ∈ l → nodup l → list.count a (max_count l₁ l₂ l) = max (list.count a l₁) (list.count a l₂)
| a [] h₁ h₂ := absurd h₁ !not_mem_nil
| a (b::l) h₁ h₂ :=
assert nodup l, from nodup_of_nodup_cons h₂,
assert b ∉ l, from not_mem_of_nodup_cons h₂,
or.elim (eq_or_mem_of_mem_cons h₁)
(suppose a = b,
have a ∉ l, by rewrite this; assumption,
assert a ∉ max_count l₁ l₂ l, from not_mem_max_count_of_not_mem l₁ l₂ this,
by_cases
(suppose i : list.count a l₁ ≥ list.count a l₂, begin
unfold max_count, subst b,
rewrite [if_pos i, list.count_append, count_gen, max_eq_left i, count_eq_zero_of_not_mem `a ∉ max_count l₁ l₂ l`]
end)
(suppose i : ¬ list.count a l₁ ≥ list.count a l₂, begin
unfold max_count, subst b,
rewrite [if_neg i, list.count_append, count_gen, max_eq_right_of_lt (lt_of_not_ge i), count_eq_zero_of_not_mem `a ∉ max_count l₁ l₂ l`]
end))
(suppose a ∈ l,
assert a ≠ b, from suppose a = b, by subst b; contradiction,
assert ih : list.count a (max_count l₁ l₂ l) = max (list.count a l₁) (list.count a l₂), from max_count_eq `a ∈ l` `nodup l`,
by_cases
(suppose i : list.count b l₁ ≥ list.count b l₂, begin
unfold max_count,
rewrite [if_pos i, -ih, list.count_append, count_gen_eq_zero_of_ne `a ≠ b`, zero_add]
end)
(suppose i : ¬ list.count b l₁ ≥ list.count b l₂, begin
unfold max_count,
rewrite [if_neg i, -ih, list.count_append, count_gen_eq_zero_of_ne `a ≠ b`, zero_add]
end))
private lemma not_mem_min_count_of_not_mem (l₁ l₂ : list A) : ∀ {a l}, a ∉ l → a ∉ min_count l₁ l₂ l
| a [] h := !not_mem_nil
| a (b::l) h :=
assert ih : a ∉ min_count l₁ l₂ l, from not_mem_min_count_of_not_mem (not_mem_of_not_mem_cons h),
assert a ≠ b, from ne_of_not_mem_cons h,
by_cases
(suppose list.count b l₁ ≤ list.count b l₂, begin
unfold min_count, rewrite [if_pos this],
exact not_mem_append (not_mem_gen_of_ne `a ≠ b` _) ih
end)
(suppose ¬ list.count b l₁ ≤ list.count b l₂, begin
unfold min_count, rewrite [if_neg this],
exact not_mem_append (not_mem_gen_of_ne `a ≠ b` _) ih
end)
private lemma min_count_eq (l₁ l₂ : list A) : ∀ {a : A} {l : list A}, a ∈ l → nodup l → list.count a (min_count l₁ l₂ l) = min (list.count a l₁) (list.count a l₂)
| a [] h₁ h₂ := absurd h₁ !not_mem_nil
| a (b::l) h₁ h₂ :=
assert nodup l, from nodup_of_nodup_cons h₂,
assert b ∉ l, from not_mem_of_nodup_cons h₂,
or.elim (eq_or_mem_of_mem_cons h₁)
(suppose a = b,
have a ∉ l, by rewrite this; assumption,
assert a ∉ min_count l₁ l₂ l, from not_mem_min_count_of_not_mem l₁ l₂ this,
by_cases
(suppose i : list.count a l₁ ≤ list.count a l₂, begin
unfold min_count, subst b,
rewrite [if_pos i, list.count_append, count_gen, min_eq_left i, count_eq_zero_of_not_mem `a ∉ min_count l₁ l₂ l`]
end)
(suppose i : ¬ list.count a l₁ ≤ list.count a l₂, begin
unfold min_count, subst b,
rewrite [if_neg i, list.count_append, count_gen, min_eq_right (le_of_lt (lt_of_not_ge i)), count_eq_zero_of_not_mem `a ∉ min_count l₁ l₂ l`]
end))
(suppose a ∈ l,
assert a ≠ b, from suppose a = b, by subst b; contradiction,
assert ih : list.count a (min_count l₁ l₂ l) = min (list.count a l₁) (list.count a l₂), from min_count_eq `a ∈ l` `nodup l`,
by_cases
(suppose i : list.count b l₁ ≤ list.count b l₂, begin
unfold min_count,
rewrite [if_pos i, -ih, list.count_append, count_gen_eq_zero_of_ne `a ≠ b`, zero_add]
end)
(suppose i : ¬ list.count b l₁ ≤ list.count b l₂, begin
unfold min_count,
rewrite [if_neg i, -ih, list.count_append, count_gen_eq_zero_of_ne `a ≠ b`, zero_add]
end))
private lemma perm_max_count_left {l₁ l₂ l₃ l₄ : list A} (h₁ : l₁ ~ l₃) (h₂ : l₂ ~ l₄) : ∀ l, max_count l₁ l₂ l ~ max_count l₃ l₄ l
| [] := by esimp
| (a::l) :=
assert e₁ : list.count a l₁ = list.count a l₃, from count_eq_of_perm h₁ a,
assert e₂ : list.count a l₂ = list.count a l₄, from count_eq_of_perm h₂ a,
by_cases
(suppose list.count a l₁ ≥ list.count a l₂,
begin unfold max_count, rewrite [-e₁, -e₂, *if_pos this], exact perm_app !perm.refl !perm_max_count_left end)
(suppose ¬ list.count a l₁ ≥ list.count a l₂,
begin unfold max_count, rewrite [-e₁, -e₂, *if_neg this], exact perm_app !perm.refl !perm_max_count_left end)
private lemma perm_app_left_comm (l₁ l₂ l₃ : list A) : l₁ ++ (l₂ ++ l₃) ~ l₂ ++ (l₁ ++ l₃) :=
calc l₁ ++ (l₂ ++ l₃) = (l₁ ++ l₂) ++ l₃ : list.append.assoc
... ~ (l₂ ++ l₁) ++ l₃ : perm_app !perm_app_comm !perm.refl
... = l₂ ++ (l₁ ++ l₃) : list.append.assoc
private lemma perm_max_count_right {l r : list A} (h : l ~ r) : ∀ l₁ l₂, max_count l₁ l₂ l ~ max_count l₁ l₂ r :=
perm.induction_on h
(λ l₁ l₂, !perm.refl)
(λ x s₁ s₂ p ih l₁ l₂, by_cases
(suppose i : list.count x l₁ ≥ list.count x l₂,
begin unfold max_count, rewrite [*if_pos i], exact perm_app !perm.refl !ih end)
(suppose i : ¬ list.count x l₁ ≥ list.count x l₂,
begin unfold max_count, rewrite [*if_neg i], exact perm_app !perm.refl !ih end))
(λ x y l l₁ l₂, by_cases
(suppose i₁ : list.count x l₁ ≥ list.count x l₂, by_cases
(suppose i₂ : list.count y l₁ ≥ list.count y l₂,
begin unfold max_count, unfold max_count, rewrite [*if_pos i₁, *if_pos i₂], apply perm_app_left_comm end)
(suppose i₂ : ¬ list.count y l₁ ≥ list.count y l₂,
begin unfold max_count, unfold max_count, rewrite [*if_pos i₁, *if_neg i₂], apply perm_app_left_comm end))
(suppose i₁ : ¬ list.count x l₁ ≥ list.count x l₂, by_cases
(suppose i₂ : list.count y l₁ ≥ list.count y l₂,
begin unfold max_count, unfold max_count, rewrite [*if_neg i₁, *if_pos i₂], apply perm_app_left_comm end)
(suppose i₂ : ¬ list.count y l₁ ≥ list.count y l₂,
begin unfold max_count, unfold max_count, rewrite [*if_neg i₁, *if_neg i₂], apply perm_app_left_comm end)))
(λ s₁ s₂ s₃ p₁ p₂ ih₁ ih₂ l₁ l₂, perm.trans (ih₁ l₁ l₂) (ih₂ l₁ l₂))
private lemma perm_max_count {l₁ l₂ l₃ r₁ r₂ r₃ : list A} (p₁ : l₁ ~ r₁) (p₂ : l₂ ~ r₂) (p₃ : l₃ ~ r₃) : max_count l₁ l₂ l₃ ~ max_count r₁ r₂ r₃ :=
calc max_count l₁ l₂ l₃ ~ max_count r₁ r₂ l₃ : perm_max_count_left p₁ p₂
... ~ max_count r₁ r₂ r₃ : perm_max_count_right p₃
private lemma perm_min_count_left {l₁ l₂ l₃ l₄ : list A} (h₁ : l₁ ~ l₃) (h₂ : l₂ ~ l₄) : ∀ l, min_count l₁ l₂ l ~ min_count l₃ l₄ l
| [] := by esimp
| (a::l) :=
assert e₁ : list.count a l₁ = list.count a l₃, from count_eq_of_perm h₁ a,
assert e₂ : list.count a l₂ = list.count a l₄, from count_eq_of_perm h₂ a,
by_cases
(suppose list.count a l₁ ≤ list.count a l₂,
begin unfold min_count, rewrite [-e₁, -e₂, *if_pos this], exact perm_app !perm.refl !perm_min_count_left end)
(suppose ¬ list.count a l₁ ≤ list.count a l₂,
begin unfold min_count, rewrite [-e₁, -e₂, *if_neg this], exact perm_app !perm.refl !perm_min_count_left end)
private lemma perm_min_count_right {l r : list A} (h : l ~ r) : ∀ l₁ l₂, min_count l₁ l₂ l ~ min_count l₁ l₂ r :=
perm.induction_on h
(λ l₁ l₂, !perm.refl)
(λ x s₁ s₂ p ih l₁ l₂, by_cases
(suppose i : list.count x l₁ ≤ list.count x l₂,
begin unfold min_count, rewrite [*if_pos i], exact perm_app !perm.refl !ih end)
(suppose i : ¬ list.count x l₁ ≤ list.count x l₂,
begin unfold min_count, rewrite [*if_neg i], exact perm_app !perm.refl !ih end))
(λ x y l l₁ l₂, by_cases
(suppose i₁ : list.count x l₁ ≤ list.count x l₂, by_cases
(suppose i₂ : list.count y l₁ ≤ list.count y l₂,
begin unfold min_count, unfold min_count, rewrite [*if_pos i₁, *if_pos i₂], apply perm_app_left_comm end)
(suppose i₂ : ¬ list.count y l₁ ≤ list.count y l₂,
begin unfold min_count, unfold min_count, rewrite [*if_pos i₁, *if_neg i₂], apply perm_app_left_comm end))
(suppose i₁ : ¬ list.count x l₁ ≤ list.count x l₂, by_cases
(suppose i₂ : list.count y l₁ ≤ list.count y l₂,
begin unfold min_count, unfold min_count, rewrite [*if_neg i₁, *if_pos i₂], apply perm_app_left_comm end)
(suppose i₂ : ¬ list.count y l₁ ≤ list.count y l₂,
begin unfold min_count, unfold min_count, rewrite [*if_neg i₁, *if_neg i₂], apply perm_app_left_comm end)))
(λ s₁ s₂ s₃ p₁ p₂ ih₁ ih₂ l₁ l₂, perm.trans (ih₁ l₁ l₂) (ih₂ l₁ l₂))
private lemma perm_min_count {l₁ l₂ l₃ r₁ r₂ r₃ : list A} (p₁ : l₁ ~ r₁) (p₂ : l₂ ~ r₂) (p₃ : l₃ ~ r₃) : min_count l₁ l₂ l₃ ~ min_count r₁ r₂ r₃ :=
calc min_count l₁ l₂ l₃ ~ min_count r₁ r₂ l₃ : perm_min_count_left p₁ p₂
... ~ min_count r₁ r₂ r₃ : perm_min_count_right p₃
definition union (b₁ b₂ : bag A) : bag A :=
quot.lift_on₂ b₁ b₂ (λ l₁ l₂, ⟦max_count l₁ l₂ (union_list l₁ l₂)⟧)
(λ l₁ l₂ l₃ l₄ p₁ p₂, quot.sound (perm_max_count p₁ p₂ (perm_union_list p₁ p₂)))
infix ∪ := union
definition inter (b₁ b₂ : bag A) : bag A :=
quot.lift_on₂ b₁ b₂ (λ l₁ l₂, ⟦min_count l₁ l₂ (union_list l₁ l₂)⟧)
(λ l₁ l₂ l₃ l₄ p₁ p₂, quot.sound (perm_min_count p₁ p₂ (perm_union_list p₁ p₂)))
infix ∩ := inter
lemma count_union (a : A) (b₁ b₂ : bag A) : count a (b₁ ∪ b₂) = max (count a b₁) (count a b₂) :=
quot.induction_on₂ b₁ b₂ (λ l₁ l₂, by_cases
(suppose a ∈ union_list l₁ l₂, !max_count_eq this !nodup_union_list)
(suppose ¬ a ∈ union_list l₁ l₂,
assert ¬ a ∈ l₁, from not_mem_of_not_mem_union_list_left `¬ a ∈ union_list l₁ l₂`,
assert ¬ a ∈ l₂, from not_mem_of_not_mem_union_list_right `¬ a ∈ union_list l₁ l₂`,
assert n : ¬ a ∈ max_count l₁ l₂ (union_list l₁ l₂), from not_mem_max_count_of_not_mem l₁ l₂ `¬ a ∈ union_list l₁ l₂`,
begin
unfold [union, count],
rewrite [count_eq_zero_of_not_mem `¬ a ∈ l₁`, count_eq_zero_of_not_mem `¬ a ∈ l₂`, max_self],
rewrite [count_eq_zero_of_not_mem n]
end))
lemma count_inter (a : A) (b₁ b₂ : bag A) : count a (b₁ ∩ b₂) = min (count a b₁) (count a b₂) :=
quot.induction_on₂ b₁ b₂ (λ l₁ l₂, by_cases
(suppose a ∈ union_list l₁ l₂, !min_count_eq this !nodup_union_list)
(suppose ¬ a ∈ union_list l₁ l₂,
assert ¬ a ∈ l₁, from not_mem_of_not_mem_union_list_left `¬ a ∈ union_list l₁ l₂`,
assert ¬ a ∈ l₂, from not_mem_of_not_mem_union_list_right `¬ a ∈ union_list l₁ l₂`,
assert n : ¬ a ∈ min_count l₁ l₂ (union_list l₁ l₂), from not_mem_min_count_of_not_mem l₁ l₂ `¬ a ∈ union_list l₁ l₂`,
begin
unfold [inter, count],
rewrite [count_eq_zero_of_not_mem `¬ a ∈ l₁`, count_eq_zero_of_not_mem `¬ a ∈ l₂`, min_self],
rewrite [count_eq_zero_of_not_mem n]
end))
lemma union.comm (b₁ b₂ : bag A) : b₁ ∪ b₂ = b₂ ∪ b₁ :=
bag.ext (λ a, by rewrite [*count_union, max.comm])
lemma union.assoc (b₁ b₂ b₃ : bag A) : (b₁ ∪ b₂) ∪ b₃ = b₁ ∪ (b₂ ∪ b₃) :=
bag.ext (λ a, by rewrite [*count_union, max.assoc])
theorem union.left_comm (s₁ s₂ s₃ : bag A) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
!left_comm union.comm union.assoc s₁ s₂ s₃
lemma union_self (b : bag A) : b ∪ b = b :=
bag.ext (λ a, by rewrite [*count_union, max_self])
lemma union_empty (b : bag A) : b ∪ empty = b :=
bag.ext (λ a, by rewrite [*count_union, count_empty, max_zero])
lemma empty_union (b : bag A) : empty ∪ b = b :=
calc empty ∪ b = b ∪ empty : union.comm
... = b : union_empty
lemma inter.comm (b₁ b₂ : bag A) : b₁ ∩ b₂ = b₂ ∩ b₁ :=
bag.ext (λ a, by rewrite [*count_inter, min.comm])
lemma inter.assoc (b₁ b₂ b₃ : bag A) : (b₁ ∩ b₂) ∩ b₃ = b₁ ∩ (b₂ ∩ b₃) :=
bag.ext (λ a, by rewrite [*count_inter, min.assoc])
theorem inter.left_comm (s₁ s₂ s₃ : bag A) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
!left_comm inter.comm inter.assoc s₁ s₂ s₃
lemma inter_self (b : bag A) : b ∩ b = b :=
bag.ext (λ a, by rewrite [*count_inter, min_self])
lemma inter_empty (b : bag A) : b ∩ empty = empty :=
bag.ext (λ a, by rewrite [*count_inter, count_empty, min_zero])
lemma empty_inter (b : bag A) : empty ∩ b = empty :=
calc empty ∩ b = b ∩ empty : inter.comm
... = empty : inter_empty
lemma append_union_inter (b₁ b₂ : bag A) : (b₁ ∪ b₂) ++ (b₁ ∩ b₂) = b₁ ++ b₂ :=
bag.ext (λ a, begin
rewrite [*count_append, count_inter, count_union],
apply (or.elim (lt_or_ge (count a b₁) (count a b₂))),
{ intro H, rewrite [min_eq_left_of_lt H, max_eq_right_of_lt H, add.comm] },
{ intro H, rewrite [min_eq_right H, max_eq_left H, add.comm] }
end)
lemma inter.left_distrib (b₁ b₂ b₃ : bag A) : b₁ ∩ (b₂ ∪ b₃) = (b₁ ∩ b₂) ∪ (b₁ ∩ b₃) :=
bag.ext (λ a, begin
rewrite [*count_inter, *count_union, *count_inter],
apply (@by_cases (count a b₁ ≤ count a b₂)),
{ intro H₁₂, apply (@by_cases (count a b₂ ≤ count a b₃)),
{ intro H₂₃,
have H₁₃ : count a b₁ ≤ count a b₃, from le.trans H₁₂ H₂₃,
rewrite [max_eq_right H₂₃, min_eq_left H₁₂, min_eq_left H₁₃, max_self]},
{ intro H₂₃,
rewrite [min_eq_left H₁₂, max.comm, max_eq_right_of_lt (lt_of_not_ge H₂₃) ],
apply (@by_cases (count a b₁ ≤ count a b₃)),
{ intro H₁₃, rewrite [min_eq_left H₁₃, max_self, min_eq_left H₁₂] },
{ intro H₁₃,
rewrite [min.comm (count a b₁) (count a b₃), min_eq_left_of_lt (lt_of_not_ge H₁₃),
min_eq_left H₁₂, max.comm, max_eq_right_of_lt (lt_of_not_ge H₁₃)]}}},
{ intro H₁₂, apply (@by_cases (count a b₂ ≤ count a b₃)),
{ intro H₂₃,
rewrite [max_eq_right H₂₃],
apply (@by_cases (count a b₁ ≤ count a b₃)),
{ intro H₁₃, rewrite [min_eq_left H₁₃, min.comm, min_eq_left_of_lt (lt_of_not_ge H₁₂), max_eq_right_of_lt (lt_of_not_ge H₁₂)] },
{ intro H₁₃, rewrite [min.comm, min_eq_left_of_lt (lt_of_not_ge H₁₃), min.comm, min_eq_left_of_lt (lt_of_not_ge H₁₂), max_eq_right H₂₃] } },
{ intro H₂₃,
have H₁₃ : count a b₁ > count a b₃, from lt.trans (lt_of_not_ge H₂₃) (lt_of_not_ge H₁₂),
rewrite [max.comm, max_eq_right_of_lt (lt_of_not_ge H₂₃), min.comm, min_eq_left_of_lt (lt_of_not_ge H₁₂)],
rewrite [min.comm, min_eq_left_of_lt H₁₃, max.comm, max_eq_right_of_lt (lt_of_not_ge H₂₃)] } }
end)
lemma inter.right_distrib (b₁ b₂ b₃ : bag A) : (b₁ ∪ b₂) ∩ b₃ = (b₁ ∩ b₃) ∪ (b₂ ∩ b₃) :=
calc (b₁ ∪ b₂) ∩ b₃ = b₃ ∩ (b₁ ∪ b₂) : inter.comm
... = (b₃ ∩ b₁) ∪ (b₃ ∩ b₂) : inter.left_distrib
... = (b₁ ∩ b₃) ∪ (b₃ ∩ b₂) : inter.comm
... = (b₁ ∩ b₃) ∪ (b₂ ∩ b₃) : inter.comm
end union_inter
section subbag
variable [decA : decidable_eq A]
include decA
definition subbag (b₁ b₂ : bag A) := ∀ a, count a b₁ ≤ count a b₂
infix ⊆ := subbag
lemma subbag.refl (b : bag A) : b ⊆ b :=
take a, !le.refl
lemma subbag.trans {b₁ b₂ b₃ : bag A} : b₁ ⊆ b₂ → b₂ ⊆ b₃ → b₁ ⊆ b₃ :=
assume h₁ h₂, take a, le.trans (h₁ a) (h₂ a)
lemma subbag.antisymm {b₁ b₂ : bag A} : b₁ ⊆ b₂ → b₂ ⊆ b₁ → b₁ = b₂ :=
assume h₁ h₂, bag.ext (take a, le.antisymm (h₁ a) (h₂ a))
lemma count_le_of_subbag {b₁ b₂ : bag A} : b₁ ⊆ b₂ → ∀ a, count a b₁ ≤ count a b₂ :=
assume h, h
lemma subbag.intro {b₁ b₂ : bag A} : (∀ a, count a b₁ ≤ count a b₂) → b₁ ⊆ b₂ :=
assume h, h
lemma empty_subbag (b : bag A) : empty ⊆ b :=
subbag.intro (take a, !zero_le)
lemma eq_empty_of_subbag_empty {b : bag A} : b ⊆ empty → b = empty :=
assume h, subbag.antisymm h (empty_subbag b)
lemma union_subbag_of_subbag_of_subbag {b₁ b₂ b₃ : bag A} : b₁ ⊆ b₃ → b₂ ⊆ b₃ → b₁ ∪ b₂ ⊆ b₃ :=
assume h₁ h₂, subbag.intro (λ a, calc
count a (b₁ ∪ b₂) = max (count a b₁) (count a b₂) : by rewrite count_union
... ≤ count a b₃ : max_le (h₁ a) (h₂ a))
lemma subbag_inter_of_subbag_of_subbag {b₁ b₂ b₃ : bag A} : b₁ ⊆ b₂ → b₁ ⊆ b₃ → b₁ ⊆ b₂ ∩ b₃ :=
assume h₁ h₂, subbag.intro (λ a, calc
count a b₁ ≤ min (count a b₂) (count a b₃) : le_min (h₁ a) (h₂ a)
... = count a (b₂ ∩ b₃) : by rewrite count_inter)
lemma subbag_union_left (b₁ b₂ : bag A) : b₁ ⊆ b₁ ∪ b₂ :=
subbag.intro (take a, by rewrite [count_union]; apply le_max_left)
lemma subbag_union_right (b₁ b₂ : bag A) : b₂ ⊆ b₁ ∪ b₂ :=
subbag.intro (take a, by rewrite [count_union]; apply le_max_right)
lemma inter_subbag_left (b₁ b₂ : bag A) : b₁ ∩ b₂ ⊆ b₁ :=
subbag.intro (take a, by rewrite [count_inter]; apply min_le_left)
lemma inter_subbag_right (b₁ b₂ : bag A) : b₁ ∩ b₂ ⊆ b₂ :=
subbag.intro (take a, by rewrite [count_inter]; apply min_le_right)
lemma subbag_append_left (b₁ b₂ : bag A) : b₁ ⊆ b₁ ++ b₂ :=
subbag.intro (take a, by rewrite [count_append]; apply le_add_right)
lemma subbag_append_right (b₁ b₂ : bag A) : b₂ ⊆ b₁ ++ b₂ :=
subbag.intro (take a, by rewrite [count_append]; apply le_add_left)
lemma inter_subbag_union (b₁ b₂ : bag A) : b₁ ∩ b₂ ⊆ b₁ ∪ b₂ :=
subbag.trans (inter_subbag_left b₁ b₂) (subbag_union_left b₁ b₂)
open decidable
lemma union_subbag_append (b₁ b₂ : bag A) : b₁ ∪ b₂ ⊆ b₁ ++ b₂ :=
subbag.intro (take a, begin
rewrite [count_append, count_union],
exact (or.elim !lt_or_ge)
(suppose count a b₁ < count a b₂, by rewrite [max_eq_right_of_lt this]; apply le_add_left)
(suppose count a b₁ ≥ count a b₂, by rewrite [max_eq_left this]; apply le_add_right)
end)
lemma subbag_insert (a : A) (b : bag A) : b ⊆ insert a b :=
subbag.intro (take x, by_cases
(suppose x = a, by rewrite [this, count_insert]; apply le_succ)
(suppose x ≠ a, by rewrite [count_insert_of_ne this]))
lemma mem_of_subbag_of_mem {a : A} {b₁ b₂ : bag A} : b₁ ⊆ b₂ → a ∈ b₁ → a ∈ b₂ :=
assume h₁ h₂,
have count a b₁ ≤ count a b₂, from count_le_of_subbag h₁ a,
have count a b₁ > 0, from h₂,
show count a b₂ > 0, from lt_of_lt_of_le `0 < count a b₁` `count a b₁ ≤ count a b₂`
lemma extract_subbag (a : A) (b : bag A) : extract a b ⊆ b :=
subbag.intro (take x, by_cases
(suppose x = a, by rewrite [this, count_extract]; apply zero_le)
(suppose x ≠ a, by rewrite [count_extract_of_ne this]))
open bool
private definition subcount : list A → list A → bool
| [] l₂ := tt
| (a::l₁) l₂ := if list.count a (a::l₁) ≤ list.count a l₂ then subcount l₁ l₂ else ff
private lemma all_of_subcount_eq_tt : ∀ {l₁ l₂ : list A}, subcount l₁ l₂ = tt → ∀ a, list.count a l₁ ≤ list.count a l₂
| [] l₂ h := take x, !zero_le
| (a::l₁) l₂ h := take x,
have subcount l₁ l₂ = tt, from by_contradiction (suppose subcount l₁ l₂ ≠ tt,
assert subcount l₁ l₂ = ff, from eq_ff_of_ne_tt this,
begin unfold subcount at h, rewrite [this at h, if_t_t at h], contradiction end),
assert ih : ∀ a, list.count a l₁ ≤ list.count a l₂, from all_of_subcount_eq_tt this,
assert i : list.count a (a::l₁) ≤ list.count a l₂, from by_contradiction (suppose ¬ list.count a (a::l₁) ≤ list.count a l₂,
begin unfold subcount at h, rewrite [if_neg this at h], contradiction end),
by_cases
(suppose x = a, by rewrite this; apply i)
(suppose x ≠ a, by rewrite [list.count_cons_of_ne this]; apply ih)
private lemma ex_of_subcount_eq_ff : ∀ {l₁ l₂ : list A}, subcount l₁ l₂ = ff → ∃ a, ¬ list.count a l₁ ≤ list.count a l₂
| [] l₂ h := by contradiction
| (a::l₁) l₂ h := by_cases
(suppose i : list.count a (a::l₁) ≤ list.count a l₂,
have subcount l₁ l₂ = ff, from by_contradiction (suppose subcount l₁ l₂ ≠ ff,
assert subcount l₁ l₂ = tt, from eq_tt_of_ne_ff this,
begin
unfold subcount at h,
rewrite [if_pos i at h, this at h],
contradiction
end),
have ih : ∃ a, ¬ list.count a l₁ ≤ list.count a l₂, from ex_of_subcount_eq_ff this,
obtain w hw, from ih, by_cases
(suppose w = a, begin subst w, existsi a, rewrite list.count_cons_eq, apply not_lt_of_ge, apply le_of_lt (lt_of_not_ge hw) end)
(suppose w ≠ a, exists.intro w (by rewrite (list.count_cons_of_ne `w ≠ a`); exact hw)))
(suppose ¬ list.count a (a::l₁) ≤ list.count a l₂, exists.intro a this)
definition decidable_subbag [instance] (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) :=
quot.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂,
match subcount l₁ l₂ with
| tt := suppose subcount l₁ l₂ = tt, inl (all_of_subcount_eq_tt this)
| ff := suppose subcount l₁ l₂ = ff, inr (suppose h : (∀ a, list.count a l₁ ≤ list.count a l₂),
obtain w hw, from ex_of_subcount_eq_ff `subcount l₁ l₂ = ff`,
absurd (h w) hw)
end rfl)
end subbag
end bag
|
cd7cb612af124b15217f85059c7e794df0d70fe2 | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch5/ex0213.lean | 3a9955012ebc82982b7f393f6869a5c89cdf8368 | [] | 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 | 76 | lean | example (x : ℕ) : x = x :=
begin
revert x,
intro y,
reflexivity
end
|
a9b9fc7a916d1dcaf95b4670c551fdd41e78b29a | ecdf4e083eb363cd3a0d6880399f86e2cd7f5adb | /src/group_theory/basic.lean | 6d7fd937aa1cc2a98df6f099840b37de5f478fb4 | [] | no_license | fpvandoorn/formalabstracts | 29aa71772da418f18994c38379e2192a6ef361f7 | cea2f9f96d89ee1187d1b01e33f22305cdfe4d59 | refs/heads/master | 1,609,476,761,601 | 1,558,130,287,000 | 1,558,130,287,000 | 97,261,457 | 0 | 2 | null | 1,550,879,230,000 | 1,500,056,313,000 | Lean | UTF-8 | Lean | false | false | 7,834 | lean | import tactic.omitted
group_theory.sylow group_theory.perm.cycles group_theory.free_group
data.nat.enat data.set.finite
category_theory.concrete_category category_theory.isomorphism
universes u v
open equiv
open category_theory
noncomputable theory
/-- The type of groups. -/
@[reducible] def Group : Type (u+1) := bundled group
/-- Group + group homomorphisms form a concrete category -/
instance concrete_is_group_hom : concrete_category @is_group_hom :=
⟨by introsI α ia; apply_instance, by introsI α β γ ia ib ic f g hf hg; apply_instance⟩
namespace Group
/-- The order of a finite group is defined as its cardinality -/
noncomputable def order (G : Group) (h : is_finite G) : ℕ :=
@fintype.card G (classical.choice h)
@[priority 2000] instance (G : Group) : group G := G.str
end Group
/-- Transferring the structure of a group along an equivalence of types -/
def group.equiv {α β} (e : α ≃ β) [group α] : group β :=
begin
refine {mul := λ x y, e (e.symm x * e.symm y), one := e 1, inv := λ x, e (e.symm x)⁻¹, ..},
omit_proofs
end
/-- The group structure on the universe lift of a type -/
instance ulift.group {α} [group α] : group (ulift α) :=
group.equiv (by tidy : ulift α ≃ α).symm
/-- The universe lift of a group -/
def glift (G : Group.{u}) : Group.{max u v} :=
⟨ulift G, by apply_instance⟩
/-- This is the notion of isomorphic groups which might live in arbitrary universe levels -/
def isomorphic (G : Group.{u}) (H : Group.{v}) : Prop :=
nonempty (glift.{u v} G ≅ glift.{v u} H)
/-- The cyclic of order n -/
def cyclic_group (n : ℕ+) : Group := mk_ob $ multiplicative $ zmod n
/- The alternating groups -/
section
variables {α : Type u} [decidable_eq α] [fintype α]
instance : is_subgroup {g : perm α | g.sign = 1 } := omitted
def alternating_group (n : ℕ) : Group := mk_ob {g : perm (fin n) | g.sign = 1}
end
/- Given N ⊆ G normal, return the canonical surjection G → G/N -/
def canonical_surjection {G : Type*} [group G] (N : set G) [normal_subgroup N] :
G → quotient_group.quotient N :=
quotient_group.mk
instance {G : Type*} [group G] (N : set G) [normal_subgroup N] :
is_group_hom $ canonical_surjection N :=
omitted
/-- the "extended" group power, where g^∞ is defined as 1 -/
noncomputable def egpow {α : Type*} [group α] (x : α) (n : enat) : α :=
match n.classical_to_option with
| some n := x ^ n
| none := 1
end
noncomputable instance {α : Type*} [group α] : has_pow α enat := ⟨egpow⟩
variables {α : Type u} [group α] {s : set α} {x y : α}
/-- The centralizer of a set s consists of all elements commuting with all elements of s -/
def centralizer (s : set α) : set α := { g | ∀x ∈ s, g * x = x * g }
instance (s : set α) : is_subgroup (centralizer s) := omitted
-- the normalizer is already defined in mathlib
export is_subgroup (normalizer)
/-- the induced_subgroup t s is the set t viewed as a subgroup s.
in applications we will have t ⊆ s, but otherwise this definition gives t ∩ s -/
def induced_subgroup (t s : set α) : set s :=
subtype.val ⁻¹' t
instance (t s : set α) [is_subgroup s] [is_subgroup t] : is_subgroup (induced_subgroup t s) :=
is_group_hom.preimage _ _
/-- the subgroup spanned by x is normal in its centralizer -/
instance closure_normal_in_centralizer (x : α) :
normal_subgroup $ induced_subgroup (group.closure {x}) (centralizer {x} : set α) :=
omitted
/-- A subgroup is normal in its normalizer -/
instance (s : set α) [is_subgroup s] : normal_subgroup (induced_subgroup s (normalizer s)) :=
by { dsimp [induced_subgroup], apply_instance }
/- Primary groups or p-groups -/
def is_primary (p : nat) (α : Type*) [group α] [decidable_eq α] [fintype α] : Prop :=
∀(x : α), ∃(n : ℕ), order_of x = p ^ n
def is_Sylow_subgroup [fintype α] (p : nat) (s : set α) : Prop :=
by { haveI := classical.prop_decidable, exact
∃(hs : is_subgroup s), is_primary p s ∧
(∀ t (ht : is_subgroup t), by { exact is_primary p t } → s ⊆ t → s = t) }
/-- the multiplication is commutative on a subset -/
def commutative_on (s : set α) : Prop := ∀(x y ∈ s), x * y = y * x
/- Conjugacy Classes -/
variable (α)
def right_conjugation {α : Type*} [group α] (x y : α) := y⁻¹ * x * y
/-- A conjugacy class is a set of the form { h * g * h⁻¹ | h : α} for some element g : α -/
def is_conjugacy_class : set (set α) := {s | ∃g, s = set.range (λh, h * g * h⁻¹) }
variable {α}
/-- Elements in the same conjugacy class have equal order -/
def order_irrel_in_conjugacy_class [fintype α] [decidable_eq α] (s : is_conjugacy_class α)
(h₁ : x ∈ s.1) (h₂ : y ∈ s.1) : order_of x = order_of y :=
omitted
/-- The order of any element in the conjugacy class -/
noncomputable def order_in [fintype α] [decidable_eq α] (s : is_conjugacy_class α) : ℕ :=
order_of (classical.some s.2)
/-- A conjugacy class of a finite group is finite -/
noncomputable instance [fintype α] [decidable_eq α] : fintype (is_conjugacy_class α) :=
@subtype.fintype _ _ _ (classical.dec_pred _)
variable (α)
/-- The set of conjugacy classes where the elements have a given order -/
def is_conjugacy_class_of_order [fintype α] [decidable_eq α] (N : ℕ) : set (is_conjugacy_class α) :=
{ s | order_in s = N }
/-- The set of all conjugacy classes with a given order is finite -/
noncomputable instance [fintype α] [decidable_eq α] (N : ℕ) :
fintype (is_conjugacy_class_of_order α N) :=
@subtype.fintype _ _ _ (classical.dec_pred _)
/- A list of conjugacy classes with elements of the given order, sorted by ascending cardinality -/
def list_conjugacy_class_of_order [fintype α] [decidable_eq α] (N : ℕ)
(h : function.injective (λ s : is_conjugacy_class_of_order α N, s.1.1.cardinality)) :
list (is_conjugacy_class_of_order α N) :=
let f : is_conjugacy_class_of_order α N → ℕ := λ s, s.1.1.cardinality in
let r := pullback_rel f (≤) in
by { haveI : is_antisymm _ r := pullback_rel.is_antisymm f (≤) h,
exact finset.sort r (@finset.univ (is_conjugacy_class_of_order α N) _) }
def number_of_conjugacy_classes_of_order [fintype α] [decidable_eq α] (N : ℕ) : ℕ :=
fintype.card (is_conjugacy_class_of_order α N)
lemma number_of_conjugacy_classes_of_order_eq [fintype α] [decidable_eq α] (N : ℕ)
(h : function.injective (λ s : is_conjugacy_class_of_order α N, s.1.1.cardinality)) :
number_of_conjugacy_classes_of_order α N = (list_conjugacy_class_of_order α N h).length :=
let f : is_conjugacy_class_of_order α N → ℕ := λ s, s.1.1.cardinality in
let r := pullback_rel f (≤) in
begin
haveI : is_antisymm _ r := pullback_rel.is_antisymm f (≤) h,
dsimp [number_of_conjugacy_classes_of_order, list_conjugacy_class_of_order],
omitted --rw [finset.sort_length]
end
/- The m-th conjugacy class of order N -/
def conjugacy_class_classification (G : Group) [fintype G] [decidable_eq G] (N : ℕ) (m : ℕ)
(h1 : function.injective (λ s : is_conjugacy_class_of_order G N, s.1.1.cardinality))
(h2 : m < number_of_conjugacy_classes_of_order G N) :
is_conjugacy_class_of_order G N :=
(list_conjugacy_class_of_order G N h1).nth_le m (by rwa ←number_of_conjugacy_classes_of_order_eq)
namespace char
protected def to_nat_m65 (c : char) : ℕ := c.val - 65
end char
/- The notation for conjugacy classes. The conjugacy class 7C in group G can be written as
conj_class G 7 'C'.
Beware: when using this notation we assume that the group is finite, there are no two conjugacy
classes of the same cardinality with the given order and that there are sufficiently many conjugacy
classes of that order -/
notation `conj_class` := (λ β N X, @conjugacy_class_classification β (classical.choice omitted)
(classical.dec_rel _) N (char.to_nat_m65 X) omitted omitted)
|
d08f0008c69333feabbe0bea5d940c81b1cec373 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/ring_theory/multiplicity.lean | 7e0b62804d76bc9c88aaaf395b893f871cbe40c4 | [
"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 | 17,340 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Chris Hughes
-/
import algebra.associated
import data.int.gcd
import algebra.big_operators.basic
import data.nat.enat
variables {α : Type*}
open nat roption
open_locale big_operators
theorem nat.find_le {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q]
(h : ∀ n, q n → p n) (hp : ∃ n, p n) (hq : ∃ n, q n) :
nat.find hp ≤ nat.find hq :=
nat.find_min' _ ((h _) (nat.find_spec hq))
/-- `multiplicity a b` returns the largest natural number `n` such that
`a ^ n ∣ b`, as an `enat` or natural with infinity. If `∀ n, a ^ n ∣ b`,
then it returns `⊤`-/
def multiplicity [comm_semiring α] [decidable_rel ((∣) : α → α → Prop)] (a b : α) : enat :=
⟨∃ n : ℕ, ¬a ^ (n + 1) ∣ b, λ h, nat.find h⟩
namespace multiplicity
section comm_semiring
variables [comm_semiring α]
@[reducible] def finite (a b : α) : Prop := ∃ n : ℕ, ¬a ^ (n + 1) ∣ b
lemma finite_iff_dom [decidable_rel ((∣) : α → α → Prop)] {a b : α} :
finite a b ↔ (multiplicity a b).dom := iff.rfl
lemma finite_def {a b : α} : finite a b ↔ ∃ n : ℕ, ¬a ^ (n + 1) ∣ b := iff.rfl
@[norm_cast]
theorem int.coe_nat_multiplicity (a b : ℕ) :
multiplicity (a : ℤ) (b : ℤ) = multiplicity a b :=
begin
apply roption.ext',
{ repeat {rw [← finite_iff_dom, finite_def]},
norm_cast, simp },
{ intros h1 h2,
apply _root_.le_antisymm; { apply nat.find_le, norm_cast, simp }}
end
lemma not_finite_iff_forall {a b : α} : (¬ finite a b) ↔ ∀ n : ℕ, a ^ n ∣ b :=
⟨λ h n, nat.cases_on n (one_dvd _) (by simpa [finite, classical.not_not] using h),
by simp [finite, multiplicity, classical.not_not]; tauto⟩
lemma not_unit_of_finite {a b : α} (h : finite a b) : ¬is_unit a :=
let ⟨n, hn⟩ := h in mt (is_unit_iff_forall_dvd.1 ∘ is_unit_pow (n + 1)) $
λ h, hn (h b)
lemma ne_zero_of_finite {a b : α} (h : finite a b) : b ≠ 0 :=
let ⟨n, hn⟩ := h in λ hb, by simpa [hb] using hn
lemma finite_of_finite_mul_left {a b c : α} : finite a (b * c) → finite a c :=
λ ⟨n, hn⟩, ⟨n, λ h, hn (dvd.trans h (by simp [_root_.mul_pow]))⟩
lemma finite_of_finite_mul_right {a b c : α} : finite a (b * c) → finite a b :=
by rw mul_comm; exact finite_of_finite_mul_left
variable [decidable_rel ((∣) : α → α → Prop)]
lemma pow_dvd_of_le_multiplicity {a b : α} {k : ℕ} : (k : enat) ≤ multiplicity a b → a ^ k ∣ b :=
nat.cases_on k (λ _, one_dvd _)
(λ k ⟨h₁, h₂⟩, by_contradiction (λ hk, (nat.find_min _ (lt_of_succ_le (h₂ ⟨k, hk⟩)) hk)))
lemma pow_multiplicity_dvd {a b : α} (h : finite a b) : a ^ get (multiplicity a b) h ∣ b :=
pow_dvd_of_le_multiplicity (by rw enat.coe_get)
lemma is_greatest {a b : α} {m : ℕ} (hm : multiplicity a b < m) : ¬a ^ m ∣ b :=
λ h, have finite a b, from enat.dom_of_le_some (le_of_lt hm),
by rw [← enat.coe_get (finite_iff_dom.1 this), enat.coe_lt_coe] at hm;
exact nat.find_spec this (dvd.trans (pow_dvd_pow _ hm) h)
lemma is_greatest' {a b : α} {m : ℕ} (h : finite a b) (hm : get (multiplicity a b) h < m) :
¬a ^ m ∣ b :=
is_greatest (by rwa [← enat.coe_lt_coe, enat.coe_get] at hm)
lemma unique {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬a ^ (k + 1) ∣ b) :
(k : enat) = multiplicity a b :=
le_antisymm (le_of_not_gt (λ hk', is_greatest hk' hk)) $
have finite a b, from ⟨k, hsucc⟩,
by rw [← enat.coe_get (finite_iff_dom.1 this), enat.coe_le_coe];
exact nat.find_min' _ hsucc
lemma unique' {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬ a ^ (k + 1) ∣ b) :
k = get (multiplicity a b) ⟨k, hsucc⟩ :=
by rw [← enat.coe_inj, enat.coe_get, unique hk hsucc]
lemma le_multiplicity_of_pow_dvd {a b : α}
{k : ℕ} (hk : a ^ k ∣ b) : (k : enat) ≤ multiplicity a b :=
le_of_not_gt $ λ hk', is_greatest hk' hk
lemma pow_dvd_iff_le_multiplicity {a b : α}
{k : ℕ} : a ^ k ∣ b ↔ (k : enat) ≤ multiplicity a b :=
⟨le_multiplicity_of_pow_dvd, pow_dvd_of_le_multiplicity⟩
lemma multiplicity_lt_iff_neg_dvd {a b : α} {k : ℕ} :
multiplicity a b < (k : enat) ↔ ¬ a ^ k ∣ b :=
by { rw [pow_dvd_iff_le_multiplicity, not_le] }
lemma eq_some_iff {a b : α} {n : ℕ} :
multiplicity a b = (n : enat) ↔ a ^ n ∣ b ∧ ¬a ^ (n + 1) ∣ b :=
⟨λ h, let ⟨h₁, h₂⟩ := eq_some_iff.1 h in
h₂ ▸ ⟨pow_multiplicity_dvd _, is_greatest
(by conv_lhs {rw ← enat.coe_get h₁ }; rw [enat.coe_lt_coe]; exact lt_succ_self _)⟩,
λ h, eq_some_iff.2 ⟨⟨n, h.2⟩, eq.symm $ unique' h.1 h.2⟩⟩
lemma eq_top_iff {a b : α} :
multiplicity a b = ⊤ ↔ ∀ n : ℕ, a ^ n ∣ b :=
⟨λ h n, nat.cases_on n (one_dvd _)
(λ n, by_contradiction (not_exists.1 (eq_none_iff'.1 h) n : _)),
λ h, eq_none_iff.2 (λ n ⟨⟨_, h₁⟩, _⟩, h₁ (h _))⟩
@[simp] protected lemma zero (a : α) : multiplicity a 0 = ⊤ :=
roption.eq_none_iff.2 (λ n ⟨⟨k, hk⟩, _⟩, hk (dvd_zero _))
lemma one_right {a : α} (ha : ¬is_unit a) : multiplicity a 1 = 0 :=
eq_some_iff.2 ⟨dvd_refl _, mt is_unit_iff_dvd_one.2 $ by simpa⟩
@[simp] lemma get_one_right {a : α} (ha : finite a 1) : get (multiplicity a 1) ha = 0 :=
get_eq_iff_eq_some.2 (eq_some_iff.2 ⟨dvd_refl _,
by simpa [is_unit_iff_dvd_one.symm] using not_unit_of_finite ha⟩)
@[simp] lemma multiplicity_unit {a : α} (b : α) (ha : is_unit a) : multiplicity a b = ⊤ :=
eq_top_iff.2 (λ _, is_unit_iff_forall_dvd.1 (is_unit_pow _ ha) _)
@[simp] lemma one_left (b : α) : multiplicity 1 b = ⊤ := by simp [eq_top_iff]
lemma multiplicity_eq_zero_of_not_dvd {a b : α} (ha : ¬a ∣ b) : multiplicity a b = 0 :=
eq_some_iff.2 (by simpa)
lemma eq_top_iff_not_finite {a b : α} : multiplicity a b = ⊤ ↔ ¬ finite a b :=
roption.eq_none_iff'
open_locale classical
lemma multiplicity_le_multiplicity_iff {a b c d : α} : multiplicity a b ≤ multiplicity c d ↔
(∀ n : ℕ, a ^ n ∣ b → c ^ n ∣ d) :=
⟨λ h n hab, (pow_dvd_of_le_multiplicity (le_trans (le_multiplicity_of_pow_dvd hab) h)),
λ h, if hab : finite a b
then by rw [← enat.coe_get (finite_iff_dom.1 hab)]; exact le_multiplicity_of_pow_dvd (h _ (pow_multiplicity_dvd _))
else
have ∀ n : ℕ, c ^ n ∣ d, from λ n, h n (not_finite_iff_forall.1 hab _),
by rw [eq_top_iff_not_finite.2 hab, eq_top_iff_not_finite.2
(not_finite_iff_forall.2 this)]⟩
lemma min_le_multiplicity_add {p a b : α} :
min (multiplicity p a) (multiplicity p b) ≤ multiplicity p (a + b) :=
(le_total (multiplicity p a) (multiplicity p b)).elim
(λ h, by rw [min_eq_left h, multiplicity_le_multiplicity_iff];
exact λ n hn, dvd_add hn (multiplicity_le_multiplicity_iff.1 h n hn))
(λ h, by rw [min_eq_right h, multiplicity_le_multiplicity_iff];
exact λ n hn, dvd_add (multiplicity_le_multiplicity_iff.1 h n hn) hn)
lemma dvd_of_multiplicity_pos {a b : α} (h : (0 : enat) < multiplicity a b) : a ∣ b :=
by rw [← _root_.pow_one a]; exact pow_dvd_of_le_multiplicity (enat.pos_iff_one_le.1 h)
lemma finite_nat_iff {a b : ℕ} : finite a b ↔ (a ≠ 1 ∧ 0 < b) :=
begin
rw [← not_iff_not, not_finite_iff_forall, not_and_distrib, ne.def,
not_not, not_lt, nat.le_zero_iff],
exact ⟨λ h, or_iff_not_imp_right.2 (λ hb,
have ha : a ≠ 0, from λ ha, by simpa [ha] using h 1,
by_contradiction (λ ha1 : a ≠ 1,
have ha_gt_one : 1 < a, from
have ∀ a : ℕ, a ≤ 1 → a ≠ 0 → a ≠ 1 → false, from dec_trivial,
lt_of_not_ge (λ ha', this a ha' ha ha1),
not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero hb) (h b))
(by simp only [nat.pow_eq_pow]; exact lt_pow_self ha_gt_one b))),
λ h, by cases h; simp *⟩
end
lemma finite_int_iff_nat_abs_finite {a b : ℤ} : finite a b ↔ finite a.nat_abs b.nat_abs :=
begin
rw [finite_def, finite_def],
conv in (a ^ _ ∣ b)
{ rw [← int.nat_abs_dvd_abs_iff, int.nat_abs_pow, ← pow_eq_pow] }
end
lemma finite_int_iff {a b : ℤ} : finite a b ↔ (a.nat_abs ≠ 1 ∧ b ≠ 0) :=
begin
have := int.nat_abs_eq a,
have := @int.nat_abs_ne_zero_of_ne_zero b,
rw [finite_int_iff_nat_abs_finite, finite_nat_iff, nat.pos_iff_ne_zero],
split; finish
end
instance decidable_nat : decidable_rel (λ a b : ℕ, (multiplicity a b).dom) :=
λ a b, decidable_of_iff _ finite_nat_iff.symm
instance decidable_int : decidable_rel (λ a b : ℤ, (multiplicity a b).dom) :=
λ a b, decidable_of_iff _ finite_int_iff.symm
end comm_semiring
section comm_ring
variables [comm_ring α] [decidable_rel ((∣) : α → α → Prop)]
open_locale classical
@[simp] protected lemma neg (a b : α) : multiplicity a (-b) = multiplicity a b :=
roption.ext' (by simp only [multiplicity]; conv in (_ ∣ - _) {rw dvd_neg})
(λ h₁ h₂, enat.coe_inj.1 (by rw [enat.coe_get]; exact
eq.symm (unique ((dvd_neg _ _).2 (pow_multiplicity_dvd _))
(mt (dvd_neg _ _).1 (is_greatest' _ (lt_succ_self _))))))
lemma multiplicity_add_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) :
multiplicity p (a + b) = multiplicity p b :=
begin
apply le_antisymm,
{ apply enat.le_of_lt_add_one,
cases enat.ne_top_iff.mp (enat.ne_top_of_lt h) with k hk,
rw [hk], rw_mod_cast [multiplicity_lt_iff_neg_dvd], intro h_dvd,
rw [← dvd_add_iff_right] at h_dvd,
apply multiplicity.is_greatest _ h_dvd, rw [hk], apply_mod_cast nat.lt_succ_self,
rw [pow_dvd_iff_le_multiplicity, enat.coe_add, ← hk], exact enat.add_one_le_of_lt h },
{ convert min_le_multiplicity_add, rw [min_eq_right (le_of_lt h)] }
end
lemma multiplicity_sub_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) :
multiplicity p (a - b) = multiplicity p b :=
by { rw [sub_eq_add_neg, multiplicity_add_of_gt]; rwa [multiplicity.neg] }
lemma multiplicity_add_eq_min {p a b : α} (h : multiplicity p a ≠ multiplicity p b) :
multiplicity p (a + b) = min (multiplicity p a) (multiplicity p b) :=
begin
rcases lt_trichotomy (multiplicity p a) (multiplicity p b) with hab|hab|hab,
{ rw [add_comm, multiplicity_add_of_gt hab, min_eq_left], exact le_of_lt hab },
{ contradiction },
{ rw [multiplicity_add_of_gt hab, min_eq_right], exact le_of_lt hab},
end
end comm_ring
section integral_domain
variables [integral_domain α]
lemma finite_mul_aux {p : α} (hp : prime p) : ∀ {n m : ℕ} {a b : α},
¬p ^ (n + 1) ∣ a → ¬p ^ (m + 1) ∣ b → ¬p ^ (n + m + 1) ∣ a * b
| n m := λ a b ha hb ⟨s, hs⟩,
have p ∣ a * b, from ⟨p ^ (n + m) * s,
by simp [hs, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩,
(hp.2.2 a b this).elim
(λ ⟨x, hx⟩, have hn0 : 0 < n,
from nat.pos_of_ne_zero (λ hn0, by clear _fun_match _fun_match; simpa [hx, hn0] using ha),
have wf : (n - 1) < n, from nat.sub_lt_self hn0 dec_trivial,
have hpx : ¬ p ^ (n - 1 + 1) ∣ x,
from λ ⟨y, hy⟩, ha (hx.symm ▸ ⟨y, mul_right_cancel' hp.1
$ by rw [nat.sub_add_cancel hn0] at hy;
simp [hy, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩),
have 1 ≤ n + m, from le_trans hn0 (le_add_right n m),
finite_mul_aux hpx hb ⟨s, mul_right_cancel' hp.1 begin
rw [← nat.sub_add_comm hn0, nat.sub_add_cancel this],
clear _fun_match _fun_match finite_mul_aux,
simp [*, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add] at *
end⟩)
(λ ⟨x, hx⟩, have hm0 : 0 < m,
from nat.pos_of_ne_zero (λ hm0, by clear _fun_match _fun_match; simpa [hx, hm0] using hb),
have wf : (m - 1) < m, from nat.sub_lt_self hm0 dec_trivial,
have hpx : ¬ p ^ (m - 1 + 1) ∣ x,
from λ ⟨y, hy⟩, hb (hx.symm ▸ ⟨y, mul_right_cancel' hp.1
$ by rw [nat.sub_add_cancel hm0] at hy;
simp [hy, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩),
finite_mul_aux ha hpx ⟨s, mul_right_cancel' hp.1 begin
rw [add_assoc, nat.sub_add_cancel hm0],
clear _fun_match _fun_match finite_mul_aux,
simp [*, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add] at *
end⟩)
lemma finite_mul {p a b : α} (hp : prime p) : finite p a → finite p b → finite p (a * b) :=
λ ⟨n, hn⟩ ⟨m, hm⟩, ⟨n + m, finite_mul_aux hp hn hm⟩
lemma finite_mul_iff {p a b : α} (hp : prime p) : finite p (a * b) ↔ finite p a ∧ finite p b :=
⟨λ h, ⟨finite_of_finite_mul_right h, finite_of_finite_mul_left h⟩,
λ h, finite_mul hp h.1 h.2⟩
lemma finite_pow {p a : α} (hp : prime p) : Π {k : ℕ} (ha : finite p a), finite p (a ^ k)
| 0 ha := ⟨0, by simp [mt is_unit_iff_dvd_one.2 hp.2.1]⟩
| (k+1) ha := by rw [pow_succ]; exact finite_mul hp ha (finite_pow ha)
variable [decidable_rel ((∣) : α → α → Prop)]
@[simp] lemma multiplicity_self {a : α} (ha : ¬is_unit a) (ha0 : a ≠ 0) :
multiplicity a a = 1 :=
eq_some_iff.2 ⟨by simp, λ ⟨b, hb⟩, ha (is_unit_iff_dvd_one.2
⟨b, mul_left_cancel' ha0 $ by clear _fun_match;
simpa [pow_succ, mul_assoc] using hb⟩)⟩
@[simp] lemma get_multiplicity_self {a : α} (ha : finite a a) :
get (multiplicity a a) ha = 1 :=
roption.get_eq_iff_eq_some.2 (eq_some_iff.2
⟨by simp, λ ⟨b, hb⟩,
by rw [← mul_one a, _root_.pow_add, _root_.pow_one, mul_assoc, mul_assoc,
mul_right_inj' (ne_zero_of_finite ha)] at hb;
exact mt is_unit_iff_dvd_one.2 (not_unit_of_finite ha)
⟨b, by clear _fun_match; simp * at *⟩⟩)
protected lemma mul' {p a b : α} (hp : prime p)
(h : (multiplicity p (a * b)).dom) :
get (multiplicity p (a * b)) h =
get (multiplicity p a) ((finite_mul_iff hp).1 h).1 +
get (multiplicity p b) ((finite_mul_iff hp).1 h).2 :=
have hdiva : p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 ∣ a, from pow_multiplicity_dvd _,
have hdivb : p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2 ∣ b, from pow_multiplicity_dvd _,
have hpoweq : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 +
get (multiplicity p b) ((finite_mul_iff hp).1 h).2) =
p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 *
p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2,
by simp [_root_.pow_add],
have hdiv : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 +
get (multiplicity p b) ((finite_mul_iff hp).1 h).2) ∣ a * b,
by rw [hpoweq]; apply mul_dvd_mul; assumption,
have hsucc : ¬p ^ ((get (multiplicity p a) ((finite_mul_iff hp).1 h).1 +
get (multiplicity p b) ((finite_mul_iff hp).1 h).2) + 1) ∣ a * b,
from λ h, not_or (is_greatest' _ (lt_succ_self _)) (is_greatest' _ (lt_succ_self _))
(succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul hp (by convert hdiva)
(by convert hdivb) h),
by rw [← enat.coe_inj, enat.coe_get, eq_some_iff];
exact ⟨hdiv, hsucc⟩
open_locale classical
protected lemma mul {p a b : α} (hp : prime p) :
multiplicity p (a * b) = multiplicity p a + multiplicity p b :=
if h : finite p a ∧ finite p b then
by rw [← enat.coe_get (finite_iff_dom.1 h.1), ← enat.coe_get (finite_iff_dom.1 h.2),
← enat.coe_get (finite_iff_dom.1 (finite_mul hp h.1 h.2)),
← enat.coe_add, enat.coe_inj, multiplicity.mul' hp]; refl
else begin
rw [eq_top_iff_not_finite.2 (mt (finite_mul_iff hp).1 h)],
cases not_and_distrib.1 h with h h;
simp [eq_top_iff_not_finite.2 h]
end
lemma finset.prod {β : Type*} {p : α} (hp : prime p) (s : finset β) (f : β → α) :
multiplicity p (∏ x in s, f x) = ∑ x in s, multiplicity p (f x) :=
begin
classical,
induction s using finset.induction with a s has ih h,
{ simp only [finset.sum_empty, finset.prod_empty],
convert one_right hp.not_unit },
{ simp [has, ← ih],
convert multiplicity.mul hp }
end
protected lemma pow' {p a : α} (hp : prime p) (ha : finite p a) : ∀ {k : ℕ},
get (multiplicity p (a ^ k)) (finite_pow hp ha) = k * get (multiplicity p a) ha
| 0 := by dsimp [_root_.pow_zero]; simp [one_right hp.not_unit]; refl
| (k+1) := by dsimp only [pow_succ];
erw [multiplicity.mul' hp, pow', add_mul, one_mul, add_comm]
lemma pow {p a : α} (hp : prime p) : ∀ {k : ℕ},
multiplicity p (a ^ k) = k •ℕ (multiplicity p a)
| 0 := by simp [one_right hp.not_unit]
| (succ k) := by simp [pow_succ, succ_nsmul, pow, multiplicity.mul hp]
lemma multiplicity_pow_self {p : α} (h0 : p ≠ 0) (hu : ¬ is_unit p) (n : ℕ) :
multiplicity p (p ^ n) = n :=
by { rw [eq_some_iff], use dvd_refl _, rw [pow_dvd_pow_iff h0 hu], apply nat.not_succ_le_self }
lemma multiplicity_pow_self_of_prime {p : α} (hp : prime p) (n : ℕ) :
multiplicity p (p ^ n) = n :=
multiplicity_pow_self hp.ne_zero hp.not_unit n
end integral_domain
end multiplicity
section nat
open multiplicity
lemma multiplicity_eq_zero_of_coprime {p a b : ℕ} (hp : p ≠ 1)
(hle : multiplicity p a ≤ multiplicity p b)
(hab : nat.coprime a b) : multiplicity p a = 0 :=
begin
rw [multiplicity_le_multiplicity_iff] at hle,
rw [← le_zero_iff_eq, ← not_lt, enat.pos_iff_one_le, ← enat.coe_one,
← pow_dvd_iff_le_multiplicity],
assume h,
have := nat.dvd_gcd h (hle _ h),
rw [coprime.gcd_eq_one hab, nat.dvd_one, _root_.pow_one] at this,
exact hp this
end
end nat
|
8355f0784ce1381af8d631bd48bfb9af297d395e | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/algebra/multilinear.lean | 19dcd60db964d773bc7e87a36f1ac8fa2897ecc2 | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,214 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.algebra.module
import linear_algebra.multilinear.basic
/-!
# Continuous multilinear maps
We define continuous multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are multilinear
and continuous, by extending the space of multilinear maps with a continuity assumption.
Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type, and all these
spaces are also topological spaces.
## Main definitions
* `continuous_multilinear_map R M₁ M₂` is the space of continuous multilinear maps from
`Π(i : ι), M₁ i` to `M₂`. We show that it is an `R`-module.
## Implementation notes
We mostly follow the API of multilinear maps.
## Notation
We introduce the notation `M [×n]→L[R] M'` for the space of continuous `n`-multilinear maps from
`M^n` to `M'`. This is a particular case of the general notion (where we allow varying dependent
types as the arguments of our continuous multilinear maps), but arguably the most important one,
especially when defining iterated derivatives.
-/
open function fin set
open_locale big_operators
universes u v w w₁ w₁' w₂ w₃ w₄
variables {R : Type u} {ι : Type v} {n : ℕ} {M : fin n.succ → Type w} {M₁ : ι → Type w₁}
{M₁' : ι → Type w₁'} {M₂ : Type w₂} {M₃ : Type w₃} {M₄ : Type w₄} [decidable_eq ι]
/-- Continuous multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂`
are modules over `R` with a topological structure. In applications, there will be compatibility
conditions between the algebraic and the topological structures, but this is not needed for the
definition. -/
structure continuous_multilinear_map (R : Type u) {ι : Type v} (M₁ : ι → Type w₁) (M₂ : Type w₂)
[decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂]
[∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂]
extends multilinear_map R M₁ M₂ :=
(cont : continuous to_fun)
notation M `[×`:25 n `]→L[`:25 R `] ` M' := continuous_multilinear_map R (λ (i : fin n), M) M'
namespace continuous_multilinear_map
section semiring
variables [semiring R]
[Πi, add_comm_monoid (M i)] [Πi, add_comm_monoid (M₁ i)] [Πi, add_comm_monoid (M₁' i)]
[add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [Π i, module R (M i)]
[Π i, module R (M₁ i)] [Π i, module R (M₁' i)] [module R M₂]
[module R M₃] [module R M₄]
[Π i, topological_space (M i)] [Π i, topological_space (M₁ i)] [Π i, topological_space (M₁' i)]
[topological_space M₂] [topological_space M₃] [topological_space M₄]
(f f' : continuous_multilinear_map R M₁ M₂)
instance : has_coe_to_fun (continuous_multilinear_map R M₁ M₂) (λ _, (Π i, M₁ i) → M₂) :=
⟨λ f, f.to_fun⟩
@[continuity] lemma coe_continuous : continuous (f : (Π i, M₁ i) → M₂) := f.cont
@[simp] lemma coe_coe : (f.to_multilinear_map : (Π i, M₁ i) → M₂) = f := rfl
theorem to_multilinear_map_inj :
function.injective (continuous_multilinear_map.to_multilinear_map :
continuous_multilinear_map R M₁ M₂ → multilinear_map R M₁ M₂)
| ⟨f, hf⟩ ⟨g, hg⟩ rfl := rfl
@[ext] theorem ext {f f' : continuous_multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' :=
to_multilinear_map_inj $ multilinear_map.ext H
@[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) :
f (update m i (x + y)) = f (update m i x) + f (update m i y) :=
f.map_add' m i x y
@[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) :
f (update m i (c • x)) = c • f (update m i x) :=
f.map_smul' m i c x
lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 :=
f.to_multilinear_map.map_coord_zero i h
@[simp] lemma map_zero [nonempty ι] : f 0 = 0 :=
f.to_multilinear_map.map_zero
instance : has_zero (continuous_multilinear_map R M₁ M₂) :=
⟨{ cont := continuous_const, ..(0 : multilinear_map R M₁ M₂) }⟩
instance : inhabited (continuous_multilinear_map R M₁ M₂) := ⟨0⟩
@[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : continuous_multilinear_map R M₁ M₂) m = 0 := rfl
section has_continuous_add
variable [has_continuous_add M₂]
instance : has_add (continuous_multilinear_map R M₁ M₂) :=
⟨λ f f', ⟨f.to_multilinear_map + f'.to_multilinear_map, f.cont.add f'.cont⟩⟩
@[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl
@[simp] lemma to_multilinear_map_add (f g : continuous_multilinear_map R M₁ M₂) :
(f + g).to_multilinear_map = f.to_multilinear_map + g.to_multilinear_map :=
rfl
instance add_comm_monoid : add_comm_monoid (continuous_multilinear_map R M₁ M₂) :=
to_multilinear_map_inj.add_comm_monoid _ rfl (λ _ _, rfl)
/-- Evaluation of a `continuous_multilinear_map` at a vector as an `add_monoid_hom`. -/
def apply_add_hom (m : Π i, M₁ i) : continuous_multilinear_map R M₁ M₂ →+ M₂ :=
⟨λ f, f m, rfl, λ _ _, rfl⟩
@[simp] lemma sum_apply {α : Type*} (f : α → continuous_multilinear_map R M₁ M₂)
(m : Πi, M₁ i) {s : finset α} : (∑ a in s, f a) m = ∑ a in s, f a m :=
(apply_add_hom m).map_sum f s
end has_continuous_add
/-- If `f` is a continuous multilinear map, then `f.to_continuous_linear_map m i` is the continuous
linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the
`i`-th coordinate. -/
def to_continuous_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →L[R] M₂ :=
{ cont := f.cont.comp (continuous_const.update i continuous_id),
.. f.to_multilinear_map.to_linear_map m i }
/-- The cartesian product of two continuous multilinear maps, as a continuous multilinear map. -/
def prod (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) :
continuous_multilinear_map R M₁ (M₂ × M₃) :=
{ cont := f.cont.prod_mk g.cont,
.. f.to_multilinear_map.prod g.to_multilinear_map }
@[simp] lemma prod_apply
(f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) (m : Πi, M₁ i) :
(f.prod g) m = (f m, g m) := rfl
/-- Combine a family of continuous multilinear maps with the same domain and codomains `M' i` into a
continuous multilinear map taking values in the space of functions `Π i, M' i`. -/
def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)]
[Π i, module R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) :
continuous_multilinear_map R M₁ (Π i, M' i) :=
{ cont := continuous_pi $ λ i, (f i).coe_continuous,
to_multilinear_map := multilinear_map.pi (λ i, (f i).to_multilinear_map) }
@[simp] lemma coe_pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)]
[Π i, topological_space (M' i)] [Π i, module R (M' i)]
(f : Π i, continuous_multilinear_map R M₁ (M' i)) :
⇑(pi f) = λ m j, f j m :=
rfl
lemma pi_apply {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)]
[Π i, topological_space (M' i)] [Π i, module R (M' i)]
(f : Π i, continuous_multilinear_map R M₁ (M' i)) (m : Π i, M₁ i) (j : ι') :
pi f m j = f j m :=
rfl
/-- If `g` is continuous multilinear and `f` is a collection of continuous linear maps,
then `g (f₁ m₁, ..., fₙ mₙ)` is again a continuous multilinear map, that we call
`g.comp_continuous_linear_map f`. -/
def comp_continuous_linear_map
(g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) :
continuous_multilinear_map R M₁ M₄ :=
{ cont := g.cont.comp $ continuous_pi $ λj, (f j).cont.comp $ continuous_apply _,
.. g.to_multilinear_map.comp_linear_map (λ i, (f i).to_linear_map) }
@[simp] lemma comp_continuous_linear_map_apply (g : continuous_multilinear_map R M₁' M₄)
(f : Π i : ι, M₁ i →L[R] M₁' i) (m : Π i, M₁ i) :
g.comp_continuous_linear_map f m = g (λ i, f i $ m i) :=
rfl
/-- Composing a continuous multilinear map with a continuous linear map gives again a
continuous multilinear map. -/
def _root_.continuous_linear_map.comp_continuous_multilinear_map
(g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) :
continuous_multilinear_map R M₁ M₃ :=
{ cont := g.cont.comp f.cont,
.. g.to_linear_map.comp_multilinear_map f.to_multilinear_map }
@[simp] lemma _root_.continuous_linear_map.comp_continuous_multilinear_map_coe (g : M₂ →L[R] M₃)
(f : continuous_multilinear_map R M₁ M₂) :
((g.comp_continuous_multilinear_map f) : (Πi, M₁ i) → M₃) =
(g : M₂ → M₃) ∘ (f : (Πi, M₁ i) → M₂) :=
by { ext m, refl }
/-- `continuous_multilinear_map.pi` as an `equiv`. -/
@[simps]
def pi_equiv {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)]
[Π i, topological_space (M' i)] [Π i, module R (M' i)] :
(Π i, continuous_multilinear_map R M₁ (M' i)) ≃
continuous_multilinear_map R M₁ (Π i, M' i) :=
{ to_fun := continuous_multilinear_map.pi,
inv_fun := λ f i, (continuous_linear_map.proj i : _ →L[R] M' i).comp_continuous_multilinear_map f,
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl } }
/-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one
can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the
additivity of a multilinear map along the first variable. -/
lemma cons_add (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) :
f (cons (x+y) m) = f (cons x m) + f (cons y m) :=
f.to_multilinear_map.cons_add m x y
/-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one
can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the
multiplicativity of a multilinear map along the first variable. -/
lemma cons_smul
(f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) :
f (cons (c • x) m) = c • f (cons x m) :=
f.to_multilinear_map.cons_smul m c x
lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) :
f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') :=
f.to_multilinear_map.map_piecewise_add _ _ _
/-- Additivity of a continuous multilinear map along all coordinates at the same time,
writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/
lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) :
f (m + m') = ∑ s : finset ι, f (s.piecewise m m') :=
f.to_multilinear_map.map_add_univ _ _
section apply_sum
open fintype finset
variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i))
/-- If `f` is continuous multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the
sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ...,
`r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each
coordinate. -/
lemma map_sum_finset :
f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) :=
f.to_multilinear_map.map_sum_finset _ _
/-- If `f` is continuous multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of
`f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from
multilinearity by expanding successively with respect to each coordinate. -/
lemma map_sum [∀ i, fintype (α i)] :
f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) :=
f.to_multilinear_map.map_sum _
end apply_sum
section restrict_scalar
variables (R) {A : Type*} [semiring A] [has_scalar R A] [Π (i : ι), module A (M₁ i)]
[module A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂]
/-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R`
and their actions on all involved modules agree with the action of `R` on `A`. -/
def restrict_scalars (f : continuous_multilinear_map A M₁ M₂) :
continuous_multilinear_map R M₁ M₂ :=
{ to_multilinear_map := f.to_multilinear_map.restrict_scalars R,
cont := f.cont }
@[simp] lemma coe_restrict_scalars (f : continuous_multilinear_map A M₁ M₂) :
⇑(f.restrict_scalars R) = f := rfl
end restrict_scalar
end semiring
section ring
variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂]
[∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂]
(f f' : continuous_multilinear_map R M₁ M₂)
@[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) :
f (update m i (x - y)) = f (update m i x) - f (update m i y) :=
f.to_multilinear_map.map_sub _ _ _ _
section topological_add_group
variable [topological_add_group M₂]
instance : has_neg (continuous_multilinear_map R M₁ M₂) :=
⟨λ f, {cont := f.cont.neg, ..(-f.to_multilinear_map)}⟩
@[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl
instance : has_sub (continuous_multilinear_map R M₁ M₂) :=
⟨λ f g, { cont := f.cont.sub g.cont, .. (f.to_multilinear_map - g.to_multilinear_map) }⟩
@[simp] lemma sub_apply (m : Πi, M₁ i) : (f - f') m = f m - f' m := rfl
instance : add_comm_group (continuous_multilinear_map R M₁ M₂) :=
to_multilinear_map_inj.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
end topological_add_group
end ring
section comm_semiring
variables [comm_semiring R]
[∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂]
[∀i, module R (M₁ i)] [module R M₂]
[∀i, topological_space (M₁ i)] [topological_space M₂]
(f : continuous_multilinear_map R M₁ M₂)
lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) :
f (s.piecewise (λ i, c i • m i) m) = (∏ i in s, c i) • f m :=
f.to_multilinear_map.map_piecewise_smul _ _ _
/-- Multiplicativity of a continuous multilinear map along all coordinates at the same time,
writing `f (λ i, c i • m i)` as `(∏ i, c i) • f m`. -/
lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) :
f (λ i, c i • m i) = (∏ i, c i) • f m :=
f.to_multilinear_map.map_smul_univ _ _
variables {R' A : Type*} [comm_semiring R'] [semiring A] [algebra R' A]
[Π i, module A (M₁ i)] [module R' M₂] [module A M₂] [is_scalar_tower R' A M₂]
[topological_space R'] [has_continuous_smul R' M₂]
instance : has_scalar R' (continuous_multilinear_map A M₁ M₂) :=
⟨λ c f, { cont := continuous_const.smul f.cont, .. c • f.to_multilinear_map }⟩
@[simp] lemma smul_apply (f : continuous_multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) :
(c • f) m = c • f m := rfl
@[simp] lemma to_multilinear_map_smul (c : R') (f : continuous_multilinear_map A M₁ M₂) :
(c • f).to_multilinear_map = c • f.to_multilinear_map :=
rfl
instance {R''} [comm_semiring R''] [has_scalar R' R''] [algebra R'' A]
[module R'' M₂] [is_scalar_tower R'' A M₂] [is_scalar_tower R' R'' M₂]
[topological_space R''] [has_continuous_smul R'' M₂]:
is_scalar_tower R' R'' (continuous_multilinear_map A M₁ M₂) :=
⟨λ c₁ c₂ f, ext $ λ x, smul_assoc _ _ _⟩
variable [has_continuous_add M₂]
/-- The space of continuous multilinear maps over an algebra over `R` is a module over `R`, for the
pointwise addition and scalar multiplication. -/
instance : module R' (continuous_multilinear_map A M₁ M₂) :=
{ one_smul := λ f, ext $ λ x, one_smul _ _,
mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _,
smul_zero := λ r, ext $ λ x, smul_zero _,
smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _,
add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _,
zero_smul := λ f, ext $ λ x, zero_smul _ _ }
/-- Linear map version of the map `to_multilinear_map` associating to a continuous multilinear map
the corresponding multilinear map. -/
@[simps] def to_multilinear_map_linear :
(continuous_multilinear_map A M₁ M₂) →ₗ[R'] (multilinear_map A M₁ M₂) :=
{ to_fun := λ f, f.to_multilinear_map,
map_add' := λ f g, rfl,
map_smul' := λ c f, rfl }
/-- `continuous_multilinear_map.pi` as a `linear_equiv`. -/
@[simps {simp_rhs := tt}]
def pi_linear_equiv {ι' : Type*} {M' : ι' → Type*}
[Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [∀ i, has_continuous_add (M' i)]
[Π i, module R' (M' i)] [Π i, module A (M' i)] [∀ i, is_scalar_tower R' A (M' i)]
[Π i, has_continuous_smul R' (M' i)] :
-- typeclass search doesn't find this instance, presumably due to struggles converting
-- `Π i, module R (M' i)` to `Π i, has_scalar R (M' i)` in dependent arguments.
let inst : has_continuous_smul R' (Π i, M' i) := pi.has_continuous_smul in
(Π i, continuous_multilinear_map A M₁ (M' i)) ≃ₗ[R']
continuous_multilinear_map A M₁ (Π i, M' i) :=
{ map_add' := λ x y, rfl,
map_smul' := λ c x, rfl,
.. pi_equiv }
end comm_semiring
end continuous_multilinear_map
|
03a658f9ed8589de8267347c166d358776daf397 | b561a44b48979a98df50ade0789a21c79ee31288 | /stage0/src/Lean/Data/Lsp/Extra.lean | 045536e3c6766527736c307444bdd7ba556bbe85 | [
"Apache-2.0"
] | permissive | 3401ijk/lean4 | 97659c475ebd33a034fed515cb83a85f75ccfb06 | a5b1b8de4f4b038ff752b9e607b721f15a9a4351 | refs/heads/master | 1,693,933,007,651 | 1,636,424,845,000 | 1,636,424,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,183 | lean | /-
Copyright (c) 2020 Marc Huisinga. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Marc Huisinga, Wojciech Nawrocki
-/
import Lean.Data.Json
import Lean.Data.JsonRpc
import Lean.Data.Lsp.Basic
/-! This file contains Lean-specific extensions to LSP. See the structures below for which
additional requests and notifications are supported. -/
namespace Lean.Lsp
open Json
/-- `textDocument/waitForDiagnostics` client->server request.
Yields a response when all the diagnostics for a version of the document greater or equal to the
specified one have been emitted. If the request specifies a version above the most recently
processed one, the server will delay the response until it does receive the specified version.
Exists for synchronization purposes, e.g. during testing or when external tools might want to use
our LSP server. -/
structure WaitForDiagnosticsParams where
uri : DocumentUri
version : Nat
deriving FromJson, ToJson
/-- `textDocument/waitForDiagnostics` client<-server reply. -/
structure WaitForDiagnostics
instance : FromJson WaitForDiagnostics :=
⟨fun j => WaitForDiagnostics.mk⟩
instance : ToJson WaitForDiagnostics :=
⟨fun o => mkObj []⟩
structure LeanFileProgressProcessingInfo where
range : Range
deriving FromJson, ToJson
/-- `$/lean/fileProgress` client<-server notification.
Contains the ranges of the document that are currently being processed by the server. -/
structure LeanFileProgressParams where
textDocument : VersionedTextDocumentIdentifier
processing : Array LeanFileProgressProcessingInfo
deriving FromJson, ToJson
/-- `$/lean/plainGoal` client->server request.
If there is a tactic proof at the specified position, returns the current goals.
Otherwise returns `null`. -/
structure PlainGoalParams extends TextDocumentPositionParams
deriving FromJson, ToJson
/-- `$/lean/plainGoal` client<-server reply. -/
structure PlainGoal where
/-- The goals as pretty-printed Markdown, or something like "no goals" if accomplished. -/
rendered : String
/-- The pretty-printed goals, empty if all accomplished. -/
goals : Array String
deriving FromJson, ToJson
/-- `$/lean/plainTermGoal` client->server request.
Returns the expected type at the specified position, pretty-printed as a string. -/
structure PlainTermGoalParams extends TextDocumentPositionParams
deriving FromJson, ToJson
/-- `$/lean/plainTermGoal` client<-server reply. -/
structure PlainTermGoal where
goal : String
range : Range
deriving FromJson, ToJson
/-- An object which RPC clients can refer to without marshalling. -/
structure RpcRef where
/- NOTE(WN): It is important for this to be a single-field structure
in order to deserialize as an `Object` on the JS side. -/
p : USize
deriving BEq, Hashable, FromJson, ToJson
instance : ToString RpcRef where
toString r := toString r.p
/-- `$/lean/rpc/connect` client->server request.
Starts an RPC session at the given file's worker, replying with the new session ID.
Multiple sessions may be started and operating concurrently.
A session may be destroyed by the server at any time (e.g. due to a crash), in which case further
RPC requests for that session will reply with `RpcNeedsReconnect` errors. The client should discard
references held from that session and `connect` again. -/
structure RpcConnectParams where
uri : DocumentUri
deriving FromJson, ToJson
/-- `$/lean/rpc/connect` client<-server reply.
Indicates that an RPC connection had been made and a session started for it. -/
structure RpcConnected where
sessionId : UInt64
deriving FromJson, ToJson
/-- `$/lean/rpc/call` client->server request.
A request to execute a procedure bound for RPC. If an incorrect session ID is present, the server
errors with `RpcNeedsReconnect`.
Extending TDPP is weird. But in Lean, symbols exist in the context of a position within a source
file. So we need this to refer to code in the environment at that position. -/
structure RpcCallParams extends TextDocumentPositionParams where
sessionId : UInt64
/-- Procedure to invoke. Must be fully qualified. -/
method : Name
params : Json
deriving FromJson, ToJson
/-- `$/lean/rpc/release` client->server notification.
A notification to release remote references. Should be sent by the client when it no longer needs
`RpcRef`s it has previously received from the server. Not doing so is safe but will leak memory. -/
structure RpcReleaseParams where
uri : DocumentUri
sessionId : UInt64
refs : Array RpcRef
deriving FromJson, ToJson
/-- `$/lean/rpc/keepAlive` client->server notification.
The client must send an RPC notification every 10s in order to keep the RPC session alive.
This is the simplest one. On not seeing any notifications for three 10s periods, the server
will drop the RPC session and its associated references. -/
structure RpcKeepAliveParams where
uri : DocumentUri
sessionId : UInt64
deriving FromJson, ToJson
/--
Range of lines in a document, including `start` but excluding `end`.
-/
structure LineRange where
start : Nat
«end» : Nat
deriving Inhabited, Repr, FromJson, ToJson
end Lean.Lsp
|
2f6713b645fee56244efc59d90f10578acfb4865 | 9c1ad797ec8a5eddb37d34806c543602d9a6bf70 | /products/associator.lean | d5deb8c228db657eb458dbe4fd6791c82cbe5636 | [] | no_license | timjb/lean-category-theory | 816eefc3a0582c22c05f4ee1c57ed04e57c0982f | 12916cce261d08bb8740bc85e0175b75fb2a60f4 | refs/heads/master | 1,611,078,926,765 | 1,492,080,000,000 | 1,492,080,000,000 | 88,348,246 | 0 | 0 | null | 1,492,262,499,000 | 1,492,262,498,000 | null | UTF-8 | Lean | false | false | 874 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison
import .products
open tqft.categories
open tqft.categories.functor
open tqft.categories.natural_transformation
namespace tqft.categories.products
definition ProductCategoryAssociator
( C D E: Category )
: Functor ((C × D) × E) (C × (D × E)) :=
{
onObjects := λ X, (X.1.1, (X.1.2, X.2)),
onMorphisms := λ _ _ f, (f.1.1, (f.1.2, f.2)),
identities := ♮,
functoriality := ♮
}
definition ProductCategoryInverseAssociator
( C D E: Category )
: Functor (C × (D × E)) ((C × D) × E) :=
{
onObjects := λ X, ((X.1, X.2.1), X.2.2),
onMorphisms := λ _ _ f, ((f.1, f.2.1), f.2.2),
identities := ♮,
functoriality := ♮
}
end tqft.categories.products
|
d1d4e7431b6712d77c1ddcc9c6d341133e006864 | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/ring_theory/int/basic.lean | 016f335103e832140db52387664b1d0749bcc69e | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,194 | 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 data.int.basic
import data.int.gcd
import ring_theory.multiplicity
import ring_theory.principal_ideal_domain
/-!
# Divisibility over ℕ and ℤ
This file collects results for the integers and natural numbers that use abstract algebra in
their proofs or cases of ℕ and ℤ being examples of structures in abstract algebra.
## Main statements
* `nat.prime_iff`: `nat.prime` coincides with the general definition of `prime`
* `nat.irreducible_iff_prime`: a non-unit natural number is only divisible by `1` iff it is prime
* `nat.factors_eq`: the multiset of elements of `nat.factors` is equal to the factors
given by the `unique_factorization_monoid` instance
* ℤ is a `normalization_monoid`
* ℤ is a `gcd_monoid`
## Tags
prime, irreducible, natural numbers, integers, normalization monoid, gcd monoid,
greatest common divisor, prime factorization, prime factors, unique factorization,
unique factors
-/
theorem nat.prime_iff {p : ℕ} : p.prime ↔ prime p :=
begin
split; intro h,
{ refine ⟨h.ne_zero, ⟨_, λ a b, _⟩⟩,
{ rw nat.is_unit_iff, apply h.ne_one },
{ apply h.dvd_mul.1 } },
{ refine ⟨_, λ m hm, _⟩,
{ cases p, { exfalso, apply h.ne_zero rfl },
cases p, { exfalso, apply h.ne_one rfl },
exact (add_le_add_right (zero_le p) 2 : _ ) },
{ cases hm with n hn,
cases h.2.2 m n (hn ▸ dvd_refl _) with hpm hpn,
{ right, apply nat.dvd_antisymm (dvd.intro _ hn.symm) hpm },
{ left,
cases n, { exfalso, rw [hn, mul_zero] at h, apply h.ne_zero rfl },
apply nat.eq_of_mul_eq_mul_right (nat.succ_pos _),
rw [← hn, one_mul],
apply nat.dvd_antisymm hpn (dvd.intro m _),
rw [mul_comm, hn], }, } }
end
theorem nat.irreducible_iff_prime {p : ℕ} : irreducible p ↔ prime p :=
begin
refine ⟨λ h, _, irreducible_of_prime⟩,
rw ← nat.prime_iff,
refine ⟨_, λ m hm, _⟩,
{ cases p, { exfalso, apply h.ne_zero rfl },
cases p, { exfalso, apply h.not_unit is_unit_one, },
exact (add_le_add_right (zero_le p) 2 : _ ) },
{ cases hm with n hn,
cases h.is_unit_or_is_unit hn with um un,
{ left, rw nat.is_unit_iff.1 um, },
{ right, rw [hn, nat.is_unit_iff.1 un, mul_one], } }
end
namespace nat
instance : wf_dvd_monoid ℕ :=
⟨begin
apply rel_hom.well_founded _ (with_top.well_founded_lt nat.lt_wf),
refine ⟨λ x, if x = 0 then ⊤ else x, _⟩,
intros a b h,
cases a,
{ exfalso, revert h, simp [dvd_not_unit] },
cases b,
{simp [succ_ne_zero, with_top.coe_lt_top]},
cases dvd_and_not_dvd_iff.2 h with h1 h2,
simp only [succ_ne_zero, with_top.coe_lt_coe, if_false],
apply lt_of_le_of_ne (nat.le_of_dvd (nat.succ_pos _) h1) (λ con, h2 _),
rw con,
end⟩
instance : unique_factorization_monoid ℕ :=
⟨λ _, nat.irreducible_iff_prime⟩
end nat
namespace int
section normalization_monoid
instance : normalization_monoid ℤ :=
{ norm_unit := λa:ℤ, if 0 ≤ a then 1 else -1,
norm_unit_zero := if_pos (le_refl _),
norm_unit_mul := assume a b hna hnb,
begin
cases hna.lt_or_lt with ha ha; cases hnb.lt_or_lt with hb hb;
simp [mul_nonneg_iff, ha.le, ha.not_le, hb.le, hb.not_le]
end,
norm_unit_coe_units := assume u, (units_eq_one_or u).elim
(assume eq, eq.symm ▸ if_pos zero_le_one)
(assume eq, eq.symm ▸ if_neg (not_le_of_gt $ show (-1:ℤ) < 0, by dec_trivial)), }
lemma normalize_of_nonneg {z : ℤ} (h : 0 ≤ z) : normalize z = z :=
show z * ↑(ite _ _ _) = z, by rw [if_pos h, units.coe_one, mul_one]
lemma normalize_of_neg {z : ℤ} (h : z < 0) : normalize z = -z :=
show z * ↑(ite _ _ _) = -z,
by rw [if_neg (not_le_of_gt h), units.coe_neg, units.coe_one, mul_neg_one]
lemma normalize_coe_nat (n : ℕ) : normalize (n : ℤ) = n :=
normalize_of_nonneg (coe_nat_le_coe_nat_of_le $ nat.zero_le n)
theorem coe_nat_abs_eq_normalize (z : ℤ) : (z.nat_abs : ℤ) = normalize z :=
begin
by_cases 0 ≤ z,
{ simp [nat_abs_of_nonneg h, normalize_of_nonneg h] },
{ simp [of_nat_nat_abs_of_nonpos (le_of_not_ge h), normalize_of_neg (lt_of_not_ge h)] }
end
end normalization_monoid
section gcd_monoid
instance : gcd_monoid ℤ :=
{ gcd := λa b, int.gcd a b,
lcm := λa b, int.lcm a b,
gcd_dvd_left := assume a b, int.gcd_dvd_left _ _,
gcd_dvd_right := assume a b, int.gcd_dvd_right _ _,
dvd_gcd := assume a b c, dvd_gcd,
normalize_gcd := assume a b, normalize_coe_nat _,
gcd_mul_lcm := by intros; rw [← int.coe_nat_mul, gcd_mul_lcm, coe_nat_abs_eq_normalize],
lcm_zero_left := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_left _,
lcm_zero_right := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_right _,
.. int.normalization_monoid }
lemma coe_gcd (i j : ℤ) : ↑(int.gcd i j) = gcd_monoid.gcd i j := rfl
lemma coe_lcm (i j : ℤ) : ↑(int.lcm i j) = gcd_monoid.lcm i j := rfl
lemma nat_abs_gcd (i j : ℤ) : nat_abs (gcd_monoid.gcd i j) = int.gcd i j := rfl
lemma nat_abs_lcm (i j : ℤ) : nat_abs (gcd_monoid.lcm i j) = int.lcm i j := rfl
end gcd_monoid
lemma exists_unit_of_abs (a : ℤ) : ∃ (u : ℤ) (h : is_unit u), (int.nat_abs a : ℤ) = u * a :=
begin
cases (nat_abs_eq a) with h,
{ use [1, is_unit_one], rw [← h, one_mul], },
{ use [-1, is_unit_one.neg], rw [ ← neg_eq_iff_neg_eq.mp (eq.symm h)],
simp only [neg_mul_eq_neg_mul_symm, one_mul] }
end
lemma gcd_eq_nat_abs {a b : ℤ} : int.gcd a b = nat.gcd a.nat_abs b.nat_abs := rfl
lemma gcd_eq_one_iff_coprime {a b : ℤ} : int.gcd a b = 1 ↔ is_coprime a b :=
begin
split,
{ intro hg,
obtain ⟨ua, hua, ha⟩ := exists_unit_of_abs a,
obtain ⟨ub, hub, hb⟩ := exists_unit_of_abs b,
use [(nat.gcd_a (int.nat_abs a) (int.nat_abs b)) * ua,
(nat.gcd_b (int.nat_abs a) (int.nat_abs b)) * ub],
rw [mul_assoc, ← ha, mul_assoc, ← hb, mul_comm, mul_comm _ (int.nat_abs b : ℤ),
← nat.gcd_eq_gcd_ab, ←gcd_eq_nat_abs, hg, int.coe_nat_one] },
{ rintro ⟨r, s, h⟩,
by_contradiction hg,
obtain ⟨p, ⟨hp, ha, hb⟩⟩ := nat.prime.not_coprime_iff_dvd.mp hg,
apply nat.prime.not_dvd_one hp,
rw [←coe_nat_dvd, int.coe_nat_one, ← h],
exact dvd_add (dvd_mul_of_dvd_right (coe_nat_dvd_left.mpr ha) _)
(dvd_mul_of_dvd_right (coe_nat_dvd_left.mpr hb) _) }
end
lemma coprime_iff_nat_coprime {a b : ℤ} : is_coprime a b ↔ nat.coprime a.nat_abs b.nat_abs :=
by rw [←gcd_eq_one_iff_coprime, nat.coprime_iff_gcd_eq_one, gcd_eq_nat_abs]
lemma sq_of_gcd_eq_one {a b c : ℤ} (h : int.gcd a b = 1) (heq : a * b = c ^ 2) :
∃ (a0 : ℤ), a = a0 ^ 2 ∨ a = - (a0 ^ 2) :=
begin
have h' : gcd_monoid.gcd a b = 1, { rw [← coe_gcd, h], dec_trivial },
obtain ⟨d, ⟨u, hu⟩⟩ := exists_associated_pow_of_mul_eq_pow h' heq,
use d,
rw ← hu,
cases int.units_eq_one_or u with hu' hu'; { rw hu', simp }
end
lemma sq_of_coprime {a b c : ℤ} (h : is_coprime a b) (heq : a * b = c ^ 2) :
∃ (a0 : ℤ), a = a0 ^ 2 ∨ a = - (a0 ^ 2) := sq_of_gcd_eq_one (gcd_eq_one_iff_coprime.mpr h) heq
lemma nat_abs_euclidean_domain_gcd (a b : ℤ) :
int.nat_abs (euclidean_domain.gcd a b) = int.gcd a b :=
begin
apply nat.dvd_antisymm; rw ← int.coe_nat_dvd,
{ rw int.nat_abs_dvd,
exact int.dvd_gcd (euclidean_domain.gcd_dvd_left _ _) (euclidean_domain.gcd_dvd_right _ _) },
{ rw int.dvd_nat_abs,
exact euclidean_domain.dvd_gcd (int.gcd_dvd_left _ _) (int.gcd_dvd_right _ _) }
end
end int
theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a
| 0 := by simp [nat.not_prime_zero]
| 1 := by simp [nat.prime, one_lt_two]
| (n + 2) :=
have h₁ : ¬n + 2 = 1, from dec_trivial,
begin
simp [h₁, nat.prime, irreducible_iff, (≥), nat.le_add_left 2 n, (∣)],
refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _),
by_cases a = 1; simp [h],
split,
{ assume hb, simpa [hb] using hab.symm },
{ assume ha, subst ha,
have : n + 2 > 0, from dec_trivial,
refine nat.eq_of_mul_eq_mul_left this _,
rw [← hab, mul_one] }
end
lemma nat.prime_iff_prime {p : ℕ} : p.prime ↔ _root_.prime (p : ℕ) :=
⟨λ hp, ⟨pos_iff_ne_zero.1 hp.pos, mt is_unit_iff_dvd_one.1 hp.not_dvd_one,
λ a b, hp.dvd_mul.1⟩,
λ hp, ⟨nat.one_lt_iff_ne_zero_and_ne_one.2 ⟨hp.1, λ h1, hp.2.1 $ h1.symm ▸ is_unit_one⟩,
λ a h, let ⟨b, hab⟩ := h in
(hp.2.2 a b (hab ▸ dvd_refl _)).elim
(λ ha, or.inr (nat.dvd_antisymm h ha))
(λ hb, or.inl (have hpb : p = b, from nat.dvd_antisymm hb
(hab.symm ▸ dvd_mul_left _ _),
(nat.mul_right_inj (show 0 < p, from
nat.pos_of_ne_zero hp.1)).1 $
by rw [hpb, mul_comm, ← hab, hpb, mul_one]))⟩⟩
lemma nat.prime_iff_prime_int {p : ℕ} : p.prime ↔ _root_.prime (p : ℤ) :=
⟨λ hp, ⟨int.coe_nat_ne_zero_iff_pos.2 hp.pos, mt int.is_unit_iff_nat_abs_eq.1 hp.ne_one,
λ a b h, by rw [← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul, hp.dvd_mul] at h;
rwa [← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd]⟩,
λ hp, nat.prime_iff_prime.2 ⟨int.coe_nat_ne_zero.1 hp.1,
mt nat.is_unit_iff.1 $ λ h, by simpa [h, not_prime_one] using hp,
λ a b, by simpa only [int.coe_nat_dvd, (int.coe_nat_mul _ _).symm] using hp.2.2 a b⟩⟩
/-- Maps an associate class of integers consisting of `-n, n` to `n : ℕ` -/
def associates_int_equiv_nat : associates ℤ ≃ ℕ :=
begin
refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩,
{ refine (assume a, quotient.induction_on' a $ assume a,
associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩),
show normalize a = int.nat_abs (normalize a),
rw [int.coe_nat_abs_eq_normalize, normalize_idem] },
{ intro n, dsimp, rw [associates.out_mk ↑n,
← int.coe_nat_abs_eq_normalize, int.nat_abs_of_nat, int.nat_abs_of_nat] }
end
lemma int.prime.dvd_mul {m n : ℤ} {p : ℕ}
(hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : p ∣ m.nat_abs ∨ p ∣ n.nat_abs :=
begin
apply (nat.prime.dvd_mul hp).mp,
rw ← int.nat_abs_mul,
exact int.coe_nat_dvd_left.mp h
end
lemma int.prime.dvd_mul' {m n : ℤ} {p : ℕ}
(hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : (p : ℤ) ∣ m ∨ (p : ℤ) ∣ n :=
begin
rw [int.coe_nat_dvd_left, int.coe_nat_dvd_left],
exact int.prime.dvd_mul hp h
end
lemma int.prime.dvd_pow {n : ℤ} {k p : ℕ}
(hp : nat.prime p) (h : (p : ℤ) ∣ n ^ k) : p ∣ n.nat_abs :=
begin
apply @nat.prime.dvd_of_dvd_pow _ _ k hp,
rw ← int.nat_abs_pow,
exact int.coe_nat_dvd_left.mp h
end
lemma int.prime.dvd_pow' {n : ℤ} {k p : ℕ}
(hp : nat.prime p) (h : (p : ℤ) ∣ n ^ k) : (p : ℤ) ∣ n :=
begin
rw int.coe_nat_dvd_left,
exact int.prime.dvd_pow hp h
end
lemma prime_two_or_dvd_of_dvd_two_mul_pow_self_two {m : ℤ} {p : ℕ}
(hp : nat.prime p) (h : (p : ℤ) ∣ 2 * m ^ 2) : p = 2 ∨ p ∣ int.nat_abs m :=
begin
cases int.prime.dvd_mul hp h with hp2 hpp,
{ apply or.intro_left,
exact le_antisymm (nat.le_of_dvd zero_lt_two hp2) (nat.prime.two_le hp) },
{ apply or.intro_right,
rw [sq, int.nat_abs_mul] at hpp,
exact (or_self _).mp ((nat.prime.dvd_mul hp).mp hpp)}
end
instance nat.unique_units : unique (units ℕ) :=
{ default := 1, uniq := nat.units_eq_one }
open unique_factorization_monoid
theorem nat.factors_eq {n : ℕ} : factors n = n.factors :=
begin
cases n, { simp },
rw [← multiset.rel_eq, ← associated_eq_eq],
apply factors_unique (irreducible_of_factor) _,
{ rw [multiset.coe_prod, nat.prod_factors (nat.succ_pos _)],
apply factors_prod (nat.succ_ne_zero _) },
{ apply_instance },
{ intros x hx,
rw [nat.irreducible_iff_prime, ← nat.prime_iff],
exact nat.prime_of_mem_factors hx }
end
lemma nat.factors_multiset_prod_of_irreducible
{s : multiset ℕ} (h : ∀ (x : ℕ), x ∈ s → irreducible x) :
unique_factorization_monoid.factors (s.prod) = s :=
begin
rw [← multiset.rel_eq, ← associated_eq_eq],
apply (unique_factorization_monoid.factors_unique irreducible_of_factor h (factors_prod _)),
rw [ne.def, multiset.prod_eq_zero_iff],
intro con,
exact not_irreducible_zero (h 0 con),
end
namespace multiplicity
lemma finite_int_iff_nat_abs_finite {a b : ℤ} : finite a b ↔ finite a.nat_abs b.nat_abs :=
by simp only [finite_def, ← int.nat_abs_dvd_abs_iff, int.nat_abs_pow]
lemma finite_int_iff {a b : ℤ} : finite a b ↔ (a.nat_abs ≠ 1 ∧ b ≠ 0) :=
by rw [finite_int_iff_nat_abs_finite, finite_nat_iff, pos_iff_ne_zero, int.nat_abs_ne_zero]
instance decidable_nat : decidable_rel (λ a b : ℕ, (multiplicity a b).dom) :=
λ a b, decidable_of_iff _ finite_nat_iff.symm
instance decidable_int : decidable_rel (λ a b : ℤ, (multiplicity a b).dom) :=
λ a b, decidable_of_iff _ finite_int_iff.symm
end multiplicity
lemma induction_on_primes {P : ℕ → Prop} (h₀ : P 0) (h₁ : P 1)
(h : ∀ p a : ℕ, p.prime → P a → P (p * a)) (n : ℕ) : P n :=
begin
apply unique_factorization_monoid.induction_on_prime,
exact h₀,
{ intros n h,
rw nat.is_unit_iff.1 h,
exact h₁, },
{ intros a p _ hp ha,
exact h p a (nat.prime_iff_prime.2 hp) ha, },
end
lemma int.associated_nat_abs (k : ℤ) : associated k k.nat_abs :=
associated_of_dvd_dvd (int.coe_nat_dvd_right.mpr (dvd_refl _)) (int.nat_abs_dvd.mpr (dvd_refl _))
lemma int.prime_iff_nat_abs_prime {k : ℤ} : prime k ↔ nat.prime k.nat_abs :=
begin
rw nat.prime_iff_prime_int,
rw prime_iff_of_associated (int.associated_nat_abs k),
end
theorem int.associated_iff_nat_abs {a b : ℤ} : associated a b ↔ a.nat_abs = b.nat_abs :=
begin
rw [←dvd_dvd_iff_associated, ←int.nat_abs_dvd_abs_iff, ←int.nat_abs_dvd_abs_iff,
dvd_dvd_iff_associated],
exact associated_iff_eq,
end
lemma int.associated_iff {a b : ℤ} : associated a b ↔ (a = b ∨ a = -b) :=
begin
rw int.associated_iff_nat_abs,
exact int.nat_abs_eq_nat_abs_iff,
end
|
13f3ae43a21e730b95d7a5bf8ec3075a253f5779 | 618003631150032a5676f229d13a079ac875ff77 | /src/tactic/alias.lean | 5b53cd48b7ca7a33f76c8015c46b7af1b955bb8d | [
"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 | 5,504 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.buffer.parser
import tactic.core
/-!
# The `alias` command
This file defines an `alias` command, which can be used to create copies
of a theorem or definition with different names.
Syntax:
```lean
/-- doc string -/
alias my_theorem ← alias1 alias2 ...
```
This produces defs or theorems of the form:
```lean
/-- doc string -/
@[alias] theorem alias1 : <type of my_theorem> := my_theorem
/-- doc string -/
@[alias] theorem alias2 : <type of my_theorem> := my_theorem
```
Iff alias syntax:
```lean
alias A_iff_B ↔ B_of_A A_of_B
alias A_iff_B ↔ ..
```
This gets an existing biconditional theorem `A_iff_B` and produces
the one-way implications `B_of_A` and `A_of_B` (with no change in
implicit arguments). A blank `_` can be used to avoid generating one direction.
The `..` notation attempts to generate the 'of'-names automatically when the
input theorem has the form `A_iff_B` or `A_iff_B_left` etc.
-/
open lean.parser tactic interactive parser
namespace tactic.alias
@[user_attribute] meta def alias_attr : user_attribute :=
{ name := `alias, descr := "This definition is an alias of another." }
meta def alias_direct (d : declaration) (doc : string) (al : name) : tactic unit :=
do updateex_env $ λ env,
env.add (match d.to_definition with
| declaration.defn n ls t _ _ _ :=
declaration.defn al ls t (expr.const n (level.param <$> ls))
reducibility_hints.abbrev tt
| declaration.thm n ls t _ :=
declaration.thm al ls t $ task.pure $ expr.const n (level.param <$> ls)
| _ := undefined
end),
alias_attr.set al () tt,
add_doc_string al doc
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → tactic expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))
| `(%%a ↔ %%b) f := pure $ @expr.const tt iffmp [] a b (f 0)
| _ f := fail "Target theorem must have the form `Π x y z, a ↔ b`"
meta def alias_iff (d : declaration) (doc : string) (al : name) (iffmp : name) : tactic unit :=
(if al = `_ then skip else get_decl al >> skip) <|> do
let ls := d.univ_params,
let t := d.type,
v ← mk_iff_mp_app iffmp t (λ_, expr.const d.to_name (level.param <$> ls)),
t' ← infer_type v,
updateex_env $ λ env, env.add (declaration.thm al ls t' $ task.pure v),
alias_attr.set al () tt,
add_doc_string al doc
meta def make_left_right : name → tactic (name × name)
| (name.mk_string s p) := do
let buf : char_buffer := s.to_char_buffer,
sum.inr parts ← pure $ run (sep_by1 (ch '_') (many_char (sat (≠ '_')))) s.to_char_buffer,
(left, _::right) ← pure $ parts.span (≠ "iff"),
let pfx (a b : string) := a.to_list.is_prefix_of b.to_list,
(suffix', right') ← pure $ right.reverse.span (λ s, pfx "left" s ∨ pfx "right" s),
let right := right'.reverse,
let suffix := suffix'.reverse,
pure (p <.> "_".intercalate (right ++ "of" :: left ++ suffix),
p <.> "_".intercalate (left ++ "of" :: right ++ suffix))
| _ := failed
/--
The `alias` command can be used to create copies
of a theorem or definition with different names.
Syntax:
```lean
/-- doc string -/
alias my_theorem ← alias1 alias2 ...
```
This produces defs or theorems of the form:
```lean
/-- doc string -/
@[alias] theorem alias1 : <type of my_theorem> := my_theorem
/-- doc string -/
@[alias] theorem alias2 : <type of my_theorem> := my_theorem
```
Iff alias syntax:
```lean
alias A_iff_B ↔ B_of_A A_of_B
alias A_iff_B ↔ ..
```
This gets an existing biconditional theorem `A_iff_B` and produces
the one-way implications `B_of_A` and `A_of_B` (with no change in
implicit arguments). A blank `_` can be used to avoid generating one direction.
The `..` notation attempts to generate the 'of'-names automatically when the
input theorem has the form `A_iff_B` or `A_iff_B_left` etc.
-/
@[user_command] meta def alias_cmd (meta_info : decl_meta_info)
(_ : parse $ tk "alias") : lean.parser unit :=
do old ← ident,
d ← (do old ← resolve_constant old, get_decl old) <|>
fail ("declaration " ++ to_string old ++ " not found"),
let doc := λ al : name, meta_info.doc_string.get_or_else $
"**Alias** of `" ++ to_string old ++ "`.",
do {
tk "←" <|> tk "<-",
aliases ← many ident,
↑(aliases.mmap' $ λ al, alias_direct d (doc al) al) } <|>
do {
tk "↔" <|> tk "<->",
(left, right) ←
mcond ((tk "." *> tk "." >> pure tt) <|> pure ff)
(make_left_right old <|> fail "invalid name for automatic name generation")
(prod.mk <$> types.ident_ <*> types.ident_),
alias_iff d (doc left) left `iff.mp,
alias_iff d (doc right) right `iff.mpr }
add_tactic_doc
{ name := "alias",
category := doc_category.cmd,
decl_names := [`tactic.alias.alias_cmd],
tags := ["renaming"] }
meta def get_lambda_body : expr → expr
| (expr.lam _ _ _ b) := get_lambda_body b
| a := a
meta def get_alias_target (n : name) : tactic (option name) :=
do tt ← has_attribute' `alias n | pure none,
d ← get_decl n,
let (head, args) := (get_lambda_body d.value).get_app_fn_args,
let head := if head.is_constant_of `iff.mp ∨ head.is_constant_of `iff.mpr then
expr.get_app_fn (head.ith_arg 2)
else head,
guardb $ head.is_constant,
pure $ head.const_name
end tactic.alias
|
116c0e56487976d838ed42a1da2d6488503fc00f | 6094e25ea0b7699e642463b48e51b2ead6ddc23f | /tests/lean/run/vector_subterm_pred.lean | 869047e7a376feaeaeab788657adb4486b393db7 | [
"Apache-2.0"
] | permissive | gbaz/lean | a7835c4e3006fbbb079e8f8ffe18aacc45adebfb | a501c308be3acaa50a2c0610ce2e0d71becf8032 | refs/heads/master | 1,611,198,791,433 | 1,451,339,111,000 | 1,451,339,111,000 | 48,713,797 | 0 | 0 | null | 1,451,338,939,000 | 1,451,338,939,000 | null | UTF-8 | Lean | false | false | 2,973 | lean | import logic data.nat.basic data.sigma
open nat eq.ops sigma
inductive vector (A : Type) : nat → Type :=
| nil : vector A zero
| cons : A → (Π{n}, vector A n → vector A (succ n))
namespace vector
definition vec (A : Type) : Type := Σ n : nat, vector A n
definition to_vec {A : Type} {n : nat} (v : vector A n) : vec A := ⟨n, v⟩
inductive direct_subterm (A : Type) : vec A → vec A → Prop :=
cons : Π (n : nat) (a : A) (v : vector A n), direct_subterm A (to_vec v) (to_vec (cons a v))
definition direct_subterm.wf (A : Type) : well_founded (direct_subterm A) :=
well_founded.intro (λ (bv : vec A),
sigma.rec_on bv (λ (n : nat) (v : vector A n),
vector.rec_on v
(show acc (direct_subterm A) (to_vec (nil A)), from
acc.intro (to_vec (nil A)) (λ (v₂ : vec A) (H : direct_subterm A v₂ (to_vec (nil A))),
have gen : ∀ (bv : vec A) (H : direct_subterm A v₂ bv) (Heq : bv = (to_vec (nil A))), acc (direct_subterm A) v₂, from
λ bv H, direct_subterm.induction_on H (λ n₁ a₁ v₁ e,
have e₁ : succ n₁ = zero, from sigma.no_confusion e (λ e₁ e₂, e₁),
nat.no_confusion e₁),
gen (to_vec (nil A)) H rfl))
(λ (a₁ : A) (n₁ : nat) (v₁ : vector A n₁) (ih : acc (direct_subterm A) (to_vec v₁)),
acc.intro (to_vec (cons a₁ v₁)) (λ (w₁ : vec A) (lt₁ : direct_subterm A w₁ (to_vec (cons a₁ v₁))),
have gen : ∀ (bv : vec A) (H : direct_subterm A w₁ bv) (Heq : bv = (to_vec (cons a₁ v₁))), acc (direct_subterm A) w₁, from
λ bv H, direct_subterm.induction_on H (λ n₂ a₂ v₂ e,
sigma.no_confusion e (λ (e₁ : succ n₂ = succ n₁) (e₂ : @cons A a₂ n₂ v₂ == @cons A a₁ n₁ v₁),
nat.no_confusion e₁ (λ (e₃ : n₂ = n₁),
have gen₂ : ∀ (m : nat) (Heq₁ : n₂ = m) (v : vector A m) (ih : acc (direct_subterm A) (to_vec v))
(Heq₂ : @cons A a₂ n₂ v₂ == @cons A a₁ m v), acc (direct_subterm A) (to_vec v₂), from
λ m Heq₁, eq.rec_on Heq₁ (λ (v : vector A n₂) (ih : acc (direct_subterm A) (to_vec v)) (Heq₂ : @cons A a₂ n₂ v₂ == @cons A a₁ n₂ v),
vector.no_confusion (heq.to_eq Heq₂) (λ (e₄ : a₂ = a₁) (e₅ : n₂ = n₂) (e₆ : v₂ == v),
eq.rec_on (heq.to_eq (heq.symm e₆)) ih)),
gen₂ n₁ e₃ v₁ ih e₂))),
gen (to_vec (cons a₁ v₁)) lt₁ rfl))))
definition direct_subterm.wf₂ (A : Type) : well_founded (direct_subterm A) :=
begin
constructor, intro V, cases V with n v, induction v,
repeat (constructor; intro y hlt; cases hlt; repeat assumption)
end
definition subterm (A : Type) := tc (direct_subterm A)
definition subterm.wf (A : Type) : well_founded (subterm A) :=
tc.wf (direct_subterm.wf A)
end vector
|
82f22d8904fdde2e3a32c18bcaa6ddb6a9d17936 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/data/nat/parity.lean | 036e9c38827bf90eec907d3aeb9e3aba50ebc630 | [
"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 | 7,469 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Benjamin Davidson
The `even` and `odd` predicates on the natural numbers.
-/
import data.nat.modeq
namespace nat
variables {m n : ℕ}
@[simp] theorem mod_two_ne_one : ¬ n % 2 = 1 ↔ n % 2 = 0 :=
by cases mod_two_eq_zero_or_one n with h h; simp [h]
@[simp] theorem mod_two_ne_zero : ¬ n % 2 = 0 ↔ n % 2 = 1 :=
by cases mod_two_eq_zero_or_one n with h h; simp [h]
theorem even_iff : even n ↔ n % 2 = 0 :=
⟨λ ⟨m, hm⟩, by simp [hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [h])⟩⟩
theorem odd_iff : odd n ↔ n % 2 = 1 :=
⟨λ ⟨m, hm⟩, by norm_num [hm, add_mod],
λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by rw [h, add_comm])⟩⟩
lemma not_even_iff : ¬ even n ↔ n % 2 = 1 :=
by rw [even_iff, mod_two_ne_zero]
lemma not_odd_iff : ¬ odd n ↔ n % 2 = 0 :=
by rw [odd_iff, mod_two_ne_one]
lemma even_iff_not_odd : even n ↔ ¬ odd n :=
by rw [not_odd_iff, even_iff]
@[simp] lemma odd_iff_not_even : odd n ↔ ¬ even n :=
by rw [not_even_iff, odd_iff]
lemma even_or_odd (n : ℕ) : even n ∨ odd n :=
or.imp_right (odd_iff_not_even.2) (em (even n))
lemma even_or_odd' (n : ℕ) : ∃ k, n = 2 * k ∨ n = 2 * k + 1 :=
by simpa only [exists_or_distrib, ← odd, ← even] using even_or_odd n
lemma even_xor_odd (n : ℕ) : xor (even n) (odd n) :=
begin
cases (even_or_odd n) with h,
{ exact or.inl ⟨h, (even_iff_not_odd.mp h)⟩ },
{ exact or.inr ⟨h, (odd_iff_not_even.mp h)⟩ },
end
lemma even_xor_odd' (n : ℕ) : ∃ k, xor (n = 2 * k) (n = 2 * k + 1) :=
begin
rcases (even_or_odd n) with ⟨k, h⟩ | ⟨k, h⟩;
use k,
{ simpa only [xor, h, true_and, eq_self_iff_true, not_true, or_false, and_false]
using (succ_ne_self (2*k)).symm },
{ simp only [xor, h, add_right_eq_self, false_or, eq_self_iff_true, not_true, not_false_iff,
one_ne_zero, and_self] },
end
lemma odd_gt_zero (h : odd n) : 0 < n :=
by { obtain ⟨k, hk⟩ := h, rw hk, exact succ_pos', }
instance : decidable_pred (even : ℕ → Prop) :=
λ n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm
instance decidable_pred_odd : decidable_pred (odd : ℕ → Prop) :=
λ n, decidable_of_decidable_of_iff (by apply_instance) odd_iff_not_even.symm
mk_simp_attribute parity_simps "Simp attribute for lemmas about `even`"
@[simp] theorem even_zero : even 0 := ⟨0, dec_trivial⟩
@[simp] theorem not_even_one : ¬ even 1 :=
by rw even_iff; apply one_ne_zero
@[simp] theorem even_bit0 (n : ℕ) : even (bit0 n) :=
⟨n, by rw [bit0, two_mul]⟩
@[parity_simps] theorem even_add : even (m + n) ↔ (even m ↔ even n) :=
begin
cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂;
simp [even_iff, h₁, h₂],
{ exact @modeq.modeq_add _ _ 0 _ 0 h₁ h₂ },
{ exact @modeq.modeq_add _ _ 0 _ 1 h₁ h₂ },
{ exact @modeq.modeq_add _ _ 1 _ 0 h₁ h₂ },
exact @modeq.modeq_add _ _ 1 _ 1 h₁ h₂
end
theorem even.add_even (hm : even m) (hn : even n) : even (m + n) :=
even_add.2 $ by simp only [*]
theorem even_add' : even (m + n) ↔ (odd m ↔ odd n) :=
by rw [even_add, even_iff_not_odd, even_iff_not_odd, not_iff_not]
theorem odd.add_odd (hm : odd m) (hn : odd n) : even (m + n) :=
even_add'.2 $ by simp only [*]
@[simp] theorem not_even_bit1 (n : ℕ) : ¬ even (bit1 n) :=
by simp [bit1] with parity_simps
lemma two_not_dvd_two_mul_add_one (n : ℕ) : ¬(2 ∣ 2 * n + 1) :=
by convert not_even_bit1 n; exact two_mul n
lemma two_not_dvd_two_mul_sub_one : Π {n} (w : 0 < n), ¬(2 ∣ 2 * n - 1) | (n + 1) _ :=
two_not_dvd_two_mul_add_one n
@[parity_simps] theorem even_sub (h : n ≤ m) : even (m - n) ↔ (even m ↔ even n) :=
begin
conv { to_rhs, rw [←nat.sub_add_cancel h, even_add] },
by_cases h : even n; simp [h]
end
theorem even.sub_even (hm : even m) (hn : even n) : even (m - n) :=
(le_total n m).elim
(λ h, by simp only [even_sub h, *])
(λ h, by simp only [sub_eq_zero_of_le h, even_zero])
theorem even_sub' (h : n ≤ m) : even (m - n) ↔ (odd m ↔ odd n) :=
by rw [even_sub h, even_iff_not_odd, even_iff_not_odd, not_iff_not]
theorem odd.sub_odd (hm : odd m) (hn : odd n) : even (m - n) :=
(le_total n m).elim
(λ h, by simp only [even_sub' h, *])
(λ h, by simp only [sub_eq_zero_of_le h, even_zero])
@[parity_simps] theorem even_succ : even (succ n) ↔ ¬ even n :=
by rw [succ_eq_add_one, even_add]; simp [not_even_one]
@[parity_simps] theorem even_mul : even (m * n) ↔ even m ∨ even n :=
begin
cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂;
simp [even_iff, h₁, h₂],
{ exact @modeq.modeq_mul _ _ 0 _ 0 h₁ h₂ },
{ exact @modeq.modeq_mul _ _ 0 _ 1 h₁ h₂ },
{ exact @modeq.modeq_mul _ _ 1 _ 0 h₁ h₂ },
exact @modeq.modeq_mul _ _ 1 _ 1 h₁ h₂
end
/-- If `m` and `n` are natural numbers, then the natural number `m^n` is even
if and only if `m` is even and `n` is positive. -/
@[parity_simps] theorem even_pow : even (m^n) ↔ even m ∧ n ≠ 0 :=
by { induction n with n ih; simp [*, pow_succ', even_mul], tauto }
lemma even_div : even (m / n) ↔ m % (2 * n) / n = 0 :=
by rw [even_iff_two_dvd, dvd_iff_mod_eq_zero, nat.div_mod_eq_mod_mul_div, mul_comm]
@[parity_simps] theorem odd_add : odd (m + n) ↔ (odd m ↔ even n) :=
begin
by_contra hnot,
rw [not_iff, ← even_iff_not_odd, even_add, odd_iff_not_even, ← not_iff] at hnot,
exact (iff_not_self _).mp hnot,
end
theorem odd.add_even (hm : odd m) (hn : even n) : odd (m + n) :=
odd_add.2 $ by simp only [*]
theorem odd_add' : odd (m + n) ↔ (odd n ↔ even m) :=
by rw [add_comm, odd_add]
theorem even.add_odd (hm : even m) (hn : odd n) : odd (m + n) :=
odd_add'.2 $ by simp only [*]
@[parity_simps] theorem odd_sub (h : n ≤ m) : odd (m - n) ↔ (odd m ↔ even n) :=
begin
by_contra hnot,
rw [not_iff, ← even_iff_not_odd, even_sub h, odd_iff_not_even, ← not_iff] at hnot,
exact (iff_not_self _).mp hnot,
end
theorem odd.sub_even (h : n ≤ m) (hm : odd m) (hn : even n) : odd (m - n) :=
(odd_sub h).mpr (iff_of_true hm hn)
theorem odd_sub' (h : n ≤ m) : odd (m - n) ↔ (odd n ↔ even m) :=
begin
by_contra hnot,
rw [not_iff, ← even_iff_not_odd, even_sub h, odd_iff_not_even, ← not_iff,
@iff.comm _ (even n)] at hnot,
exact (iff_not_self _).mp hnot,
end
theorem even.sub_odd (h : n ≤ m) (hm : even m) (hn : odd n) : odd (m - n) :=
(odd_sub' h).mpr (iff_of_true hn hm)
variables {R : Type*} [ring R]
theorem neg_one_pow_eq_one_iff_even (h1 : (-1 : R) ≠ 1) : (-1 : R) ^ n = 1 ↔ even n :=
⟨λ h, n.mod_two_eq_zero_or_one.elim (dvd_iff_mod_eq_zero _ _).2
(λ hn, by rw [neg_one_pow_eq_pow_mod_two, hn, pow_one] at h; exact (h1 h).elim),
λ ⟨m, hm⟩, by rw [neg_one_pow_eq_pow_mod_two, hm]; simp⟩
@[simp] theorem neg_one_pow_two : (-1 : R) ^ 2 = 1 := by simp
theorem neg_one_pow_of_even : even n → (-1 : R) ^ n = 1 :=
by { rintro ⟨c, rfl⟩, simp [pow_mul] }
theorem neg_one_pow_of_odd : odd n → (-1 : R) ^ n = -1 :=
by { rintro ⟨c, rfl⟩, simp [pow_add, pow_mul] }
-- Here are examples of how `parity_simps` can be used with `nat`.
example (m n : ℕ) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) :=
by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps
example : ¬ even 25394535 :=
by simp
end nat
|
e828ba011e0828a500f055440a1abc801400b6a7 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/continuous_function/algebra.lean | c1c2fb79db23a0575cd30944c79475e3436bc4df | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,295 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Nicolò Cavalleri
-/
import topology.algebra.module
import topology.continuous_function.basic
import algebra.algebra.subalgebra
import tactic.field_simp
/-!
# Algebraic structures over continuous functions
In this file we define instances of algebraic structures over the type `continuous_map α β`
(denoted `C(α, β)`) of **bundled** continuous maps from `α` to `β`. For example, `C(α, β)`
is a group when `β` is a group, a ring when `β` is a ring, etc.
For each type of algebraic structure, we also define an appropriate subobject of `α → β`
with carrier `{ f : α → β | continuous f }`. For example, when `β` is a group, a subgroup
`continuous_subgroup α β` of `α → β` is constructed with carrier `{ f : α → β | continuous f }`.
Note that, rather than using the derived algebraic structures on these subobjects
(for example, when `β` is a group, the derived group structure on `continuous_subgroup α β`),
one should use `C(α, β)` with the appropriate instance of the structure.
-/
local attribute [elab_simple] continuous.comp
namespace continuous_functions
variables {α : Type*} {β : Type*} [topological_space α] [topological_space β]
variables {f g : {f : α → β | continuous f }}
instance : has_coe_to_fun {f : α → β | continuous f} (λ _, α → β) := ⟨subtype.val⟩
end continuous_functions
namespace continuous_map
variables {α : Type*} {β : Type*} [topological_space α] [topological_space β]
@[to_additive]
instance has_mul [has_mul β] [has_continuous_mul β] : has_mul C(α, β) :=
⟨λ f g, ⟨f * g, continuous_mul.comp (f.continuous.prod_mk g.continuous : _)⟩⟩
@[simp, norm_cast, to_additive]
lemma coe_mul [has_mul β] [has_continuous_mul β] (f g : C(α, β)) :
((f * g : C(α, β)) : α → β) = (f : α → β) * (g : α → β) := rfl
@[to_additive]
instance [has_one β] : has_one C(α, β) := ⟨const (1 : β)⟩
@[simp, norm_cast, to_additive]
lemma coe_one [has_one β] :
((1 : C(α, β)) : α → β) = (1 : α → β) := rfl
@[simp, to_additive] lemma mul_comp {α : Type*} {β : Type*} {γ : Type*}
[topological_space α] [topological_space β] [topological_space γ]
[semigroup γ] [has_continuous_mul γ] (f₁ f₂ : C(β, γ)) (g : C(α, β)) :
(f₁ * f₂).comp g = f₁.comp g * f₂.comp g :=
by { ext, simp, }
@[simp, to_additive] lemma one_comp {α : Type*} {β : Type*} {γ : Type*}
[topological_space α] [topological_space β] [topological_space γ] [has_one γ] (g : C(α, β)) :
(1 : C(β, γ)).comp g = 1 :=
by { ext, simp, }
end continuous_map
section group_structure
/-!
### Group stucture
In this section we show that continuous functions valued in a topological group inherit
the structure of a group.
-/
section subtype
/-- The `submonoid` of continuous maps `α → β`. -/
@[to_additive "The `add_submonoid` of continuous maps `α → β`. "]
def continuous_submonoid (α : Type*) (β : Type*) [topological_space α] [topological_space β]
[monoid β] [has_continuous_mul β] : submonoid (α → β) :=
{ carrier := { f : α → β | continuous f },
one_mem' := @continuous_const _ _ _ _ 1,
mul_mem' := λ f g fc gc, continuous.comp
has_continuous_mul.continuous_mul (continuous.prod_mk fc gc : _) }
/-- The subgroup of continuous maps `α → β`. -/
@[to_additive "The `add_subgroup` of continuous maps `α → β`. "]
def continuous_subgroup (α : Type*) (β : Type*) [topological_space α] [topological_space β]
[group β] [topological_group β] : subgroup (α → β) :=
{ inv_mem' := λ f fc, continuous.comp (@topological_group.continuous_inv β _ _ _) fc,
..continuous_submonoid α β, }.
end subtype
namespace continuous_map
@[to_additive]
instance {α : Type*} {β : Type*} [topological_space α]
[topological_space β] [semigroup β] [has_continuous_mul β] : semigroup C(α, β) :=
{ mul_assoc := λ a b c, by ext; exact mul_assoc _ _ _,
..continuous_map.has_mul}
@[to_additive]
instance {α : Type*} {β : Type*} [topological_space α] [topological_space β]
[monoid β] [has_continuous_mul β] : monoid C(α, β) :=
{ one_mul := λ a, by ext; exact one_mul _,
mul_one := λ a, by ext; exact mul_one _,
..continuous_map.semigroup,
..continuous_map.has_one }
/-- Coercion to a function as an `monoid_hom`. Similar to `monoid_hom.coe_fn`. -/
@[to_additive "Coercion to a function as an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn`.",
simps]
def coe_fn_monoid_hom {α : Type*} {β : Type*} [topological_space α] [topological_space β]
[monoid β] [has_continuous_mul β] : C(α, β) →* (α → β) :=
{ to_fun := coe_fn, map_one' := coe_one, map_mul' := coe_mul }
/-- Composition on the left by a (continuous) homomorphism of topological monoids, as a
`monoid_hom`. Similar to `monoid_hom.comp_left`. -/
@[to_additive "Composition on the left by a (continuous) homomorphism of topological `add_monoid`s,
as an `add_monoid_hom`. Similar to `add_monoid_hom.comp_left`.", simps]
protected def _root_.monoid_hom.comp_left_continuous (α : Type*) {β : Type*} {γ : Type*}
[topological_space α] [topological_space β] [monoid β] [has_continuous_mul β]
[topological_space γ] [monoid γ] [has_continuous_mul γ] (g : β →* γ) (hg : continuous g) :
C(α, β) →* C(α, γ) :=
{ to_fun := λ f, (⟨g, hg⟩ : C(β, γ)).comp f,
map_one' := ext $ λ x, g.map_one,
map_mul' := λ f₁ f₂, ext $ λ x, g.map_mul _ _ }
/-- Composition on the right as a `monoid_hom`. Similar to `monoid_hom.comp_hom'`. -/
@[to_additive "Composition on the right as an `add_monoid_hom`. Similar to
`add_monoid_hom.comp_hom'`.", simps]
def comp_monoid_hom' {α : Type*} {β : Type*} {γ : Type*}
[topological_space α] [topological_space β] [topological_space γ]
[monoid γ] [has_continuous_mul γ] (g : C(α, β)) : C(β, γ) →* C(α, γ) :=
{ to_fun := λ f, f.comp g, map_one' := one_comp g, map_mul' := λ f₁ f₂, mul_comp f₁ f₂ g }
@[simp, norm_cast]
lemma coe_pow {α : Type*} {β : Type*} [topological_space α] [topological_space β]
[monoid β] [has_continuous_mul β] (f : C(α, β)) (n : ℕ) :
((f^n : C(α, β)) : α → β) = (f : α → β)^n :=
(coe_fn_monoid_hom : C(α, β) →* _).map_pow f n
@[simp] lemma pow_comp {α : Type*} {β : Type*} {γ : Type*}
[topological_space α] [topological_space β] [topological_space γ]
[monoid γ] [has_continuous_mul γ] (f : C(β, γ)) (n : ℕ) (g : C(α, β)) :
(f^n).comp g = (f.comp g)^n :=
(comp_monoid_hom' g).map_pow f n
@[to_additive]
instance {α : Type*} {β : Type*} [topological_space α]
[topological_space β] [comm_monoid β] [has_continuous_mul β] : comm_monoid C(α, β) :=
{ one_mul := λ a, by ext; exact one_mul _,
mul_one := λ a, by ext; exact mul_one _,
mul_comm := λ a b, by ext; exact mul_comm _ _,
..continuous_map.semigroup,
..continuous_map.has_one }
open_locale big_operators
@[simp, to_additive] lemma coe_prod {α : Type*} {β : Type*} [comm_monoid β]
[topological_space α] [topological_space β] [has_continuous_mul β]
{ι : Type*} (s : finset ι) (f : ι → C(α, β)) :
⇑(∏ i in s, f i) = (∏ i in s, (f i : α → β)) :=
(coe_fn_monoid_hom : C(α, β) →* _).map_prod f s
@[to_additive]
lemma prod_apply {α : Type*} {β : Type*} [comm_monoid β]
[topological_space α] [topological_space β] [has_continuous_mul β]
{ι : Type*} (s : finset ι) (f : ι → C(α, β)) (a : α) :
(∏ i in s, f i) a = (∏ i in s, f i a) :=
by simp
@[to_additive]
instance {α : Type*} {β : Type*} [topological_space α] [topological_space β]
[group β] [topological_group β] : group C(α, β) :=
{ inv := λ f, ⟨λ x, (f x)⁻¹, continuous_inv.comp f.continuous⟩,
mul_left_inv := λ a, by ext; exact mul_left_inv _,
..continuous_map.monoid }
@[simp, norm_cast, to_additive]
lemma coe_inv {α : Type*} {β : Type*} [topological_space α] [topological_space β]
[group β] [topological_group β] (f : C(α, β)) :
((f⁻¹ : C(α, β)) : α → β) = (f⁻¹ : α → β) :=
rfl
@[simp, norm_cast, to_additive]
lemma coe_div {α : Type*} {β : Type*} [topological_space α] [topological_space β]
[group β] [topological_group β] (f g : C(α, β)) :
((f / g : C(α, β)) : α → β) = (f : α → β) / (g : α → β) :=
by { simp only [div_eq_mul_inv], refl, }
@[simp, to_additive] lemma inv_comp {α : Type*} {β : Type*} {γ : Type*}
[topological_space α] [topological_space β] [topological_space γ]
[group γ] [topological_group γ] (f : C(β, γ)) (g : C(α, β)) :
(f⁻¹).comp g = (f.comp g)⁻¹ :=
by { ext, simp, }
@[simp, to_additive] lemma div_comp {α : Type*} {β : Type*} {γ : Type*}
[topological_space α] [topological_space β] [topological_space γ]
[group γ] [topological_group γ] (f g : C(β, γ)) (h : C(α, β)) :
(f / g).comp h = (f.comp h) / (g.comp h) :=
by { ext, simp, }
@[to_additive]
instance {α : Type*} {β : Type*} [topological_space α]
[topological_space β] [comm_group β] [topological_group β] : comm_group C(α, β) :=
{ ..continuous_map.group,
..continuous_map.comm_monoid }
end continuous_map
end group_structure
section ring_structure
/-!
### Ring stucture
In this section we show that continuous functions valued in a topological ring `R` inherit
the structure of a ring.
-/
section subtype
/-- The subsemiring of continuous maps `α → β`. -/
def continuous_subsemiring (α : Type*) (R : Type*) [topological_space α] [topological_space R]
[semiring R] [topological_ring R] : subsemiring (α → R) :=
{ ..continuous_add_submonoid α R,
..continuous_submonoid α R }.
/-- The subring of continuous maps `α → β`. -/
def continuous_subring (α : Type*) (R : Type*) [topological_space α] [topological_space R]
[ring R] [topological_ring R] : subring (α → R) :=
{ ..continuous_subsemiring α R,
..continuous_add_subgroup α R }.
end subtype
namespace continuous_map
instance {α : Type*} {β : Type*} [topological_space α] [topological_space β]
[semiring β] [topological_ring β] : semiring C(α, β) :=
{ left_distrib := λ a b c, by ext; exact left_distrib _ _ _,
right_distrib := λ a b c, by ext; exact right_distrib _ _ _,
zero_mul := λ a, by ext; exact zero_mul _,
mul_zero := λ a, by ext; exact mul_zero _,
..continuous_map.add_comm_monoid,
..continuous_map.monoid }
instance {α : Type*} {β : Type*} [topological_space α] [topological_space β]
[ring β] [topological_ring β] : ring C(α, β) :=
{ ..continuous_map.semiring,
..continuous_map.add_comm_group, }
instance {α : Type*} {β : Type*} [topological_space α]
[topological_space β] [comm_ring β] [topological_ring β] : comm_ring C(α, β) :=
{ ..continuous_map.semiring,
..continuous_map.add_comm_group,
..continuous_map.comm_monoid,}
/-- Composition on the left by a (continuous) homomorphism of topological rings, as a `ring_hom`.
Similar to `ring_hom.comp_left`. -/
@[simps] protected def _root_.ring_hom.comp_left_continuous (α : Type*) {β : Type*} {γ : Type*}
[topological_space α] [topological_space β] [semiring β] [topological_ring β]
[topological_space γ] [semiring γ] [topological_ring γ] (g : β →+* γ) (hg : continuous g) :
C(α, β) →+* C(α, γ) :=
{ .. g.to_monoid_hom.comp_left_continuous α hg,
.. g.to_add_monoid_hom.comp_left_continuous α hg }
/-- Coercion to a function as a `ring_hom`. -/
@[simps]
def coe_fn_ring_hom {α : Type*} {β : Type*} [topological_space α] [topological_space β]
[ring β] [topological_ring β] : C(α, β) →+* (α → β) :=
{ to_fun := coe_fn,
..(coe_fn_monoid_hom : C(α, β) →* _),
..(coe_fn_add_monoid_hom : C(α, β) →+ _) }
end continuous_map
end ring_structure
local attribute [ext] subtype.eq
section module_structure
/-!
### Semiodule stucture
In this section we show that continuous functions valued in a topological module `M` over a
topological semiring `R` inherit the structure of a module.
-/
section subtype
variables (α : Type*) [topological_space α]
variables (R : Type*) [semiring R] [topological_space R]
variables (M : Type*) [topological_space M] [add_comm_group M]
variables [module R M] [has_continuous_smul R M] [topological_add_group M]
/-- The `R`-submodule of continuous maps `α → M`. -/
def continuous_submodule : submodule R (α → M) :=
{ carrier := { f : α → M | continuous f },
smul_mem' := λ c f hf, continuous_smul.comp
(continuous.prod_mk (continuous_const : continuous (λ x, c)) hf),
..continuous_add_subgroup α M }
end subtype
namespace continuous_map
variables {α : Type*} [topological_space α]
{R : Type*} [semiring R] [topological_space R]
{M : Type*} [topological_space M] [add_comm_monoid M]
{M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂]
instance
[module R M] [has_continuous_smul R M] :
has_scalar R C(α, M) :=
⟨λ r f, ⟨r • f, f.continuous.const_smul r⟩⟩
@[simp, norm_cast]
lemma coe_smul [module R M] [has_continuous_smul R M]
(c : R) (f : C(α, M)) : ⇑(c • f) = c • f := rfl
lemma smul_apply [module R M] [has_continuous_smul R M]
(c : R) (f : C(α, M)) (a : α) : (c • f) a = c • (f a) :=
by simp
@[simp] lemma smul_comp {α : Type*} {β : Type*}
[topological_space α] [topological_space β]
[module R M] [has_continuous_smul R M] (r : R) (f : C(β, M)) (g : C(α, β)) :
(r • f).comp g = r • (f.comp g) :=
by { ext, simp, }
variables [has_continuous_add M] [module R M] [has_continuous_smul R M]
variables [has_continuous_add M₂] [module R M₂] [has_continuous_smul R M₂]
instance module : module R C(α, M) :=
{ smul := (•),
smul_add := λ c f g, by { ext, exact smul_add c (f x) (g x) },
add_smul := λ c₁ c₂ f, by { ext, exact add_smul c₁ c₂ (f x) },
mul_smul := λ c₁ c₂ f, by { ext, exact mul_smul c₁ c₂ (f x) },
one_smul := λ f, by { ext, exact one_smul R (f x) },
zero_smul := λ f, by { ext, exact zero_smul _ _ },
smul_zero := λ r, by { ext, exact smul_zero _ } }
variables (R)
/-- Composition on the left by a continuous linear map, as a `linear_map`.
Similar to `linear_map.comp_left`. -/
@[simps] protected def _root_.continuous_linear_map.comp_left_continuous (α : Type*)
[topological_space α] (g : M →L[R] M₂) :
C(α, M) →ₗ[R] C(α, M₂) :=
{ map_smul' := λ c f, ext $ λ x, g.map_smul' c _,
.. g.to_linear_map.to_add_monoid_hom.comp_left_continuous α g.continuous }
/-- Coercion to a function as a `linear_map`. -/
@[simps]
def coe_fn_linear_map : C(α, M) →ₗ[R] (α → M) :=
{ to_fun := coe_fn,
map_smul' := coe_smul,
..(coe_fn_add_monoid_hom : C(α, M) →+ _) }
end continuous_map
end module_structure
section algebra_structure
/-!
### Algebra structure
In this section we show that continuous functions valued in a topological algebra `A` over a ring
`R` inherit the structure of an algebra. Note that the hypothesis that `A` is a topological algebra
is obtained by requiring that `A` be both a `has_continuous_smul` and a `topological_ring`.-/
section subtype
variables {α : Type*} [topological_space α]
{R : Type*} [comm_semiring R]
{A : Type*} [topological_space A] [semiring A]
[algebra R A] [topological_ring A]
/-- The `R`-subalgebra of continuous maps `α → A`. -/
def continuous_subalgebra : subalgebra R (α → A) :=
{ carrier := { f : α → A | continuous f },
algebra_map_mem' := λ r, (continuous_const : continuous $ λ (x : α), algebra_map R A r),
..continuous_subsemiring α A }
end subtype
section continuous_map
variables {α : Type*} [topological_space α]
{R : Type*} [comm_semiring R]
{A : Type*} [topological_space A] [semiring A]
[algebra R A] [topological_ring A]
{A₂ : Type*} [topological_space A₂] [semiring A₂]
[algebra R A₂] [topological_ring A₂]
/-- Continuous constant functions as a `ring_hom`. -/
def continuous_map.C : R →+* C(α, A) :=
{ to_fun := λ c : R, ⟨λ x: α, ((algebra_map R A) c), continuous_const⟩,
map_one' := by ext x; exact (algebra_map R A).map_one,
map_mul' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_mul _ _,
map_zero' := by ext x; exact (algebra_map R A).map_zero,
map_add' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_add _ _ }
@[simp] lemma continuous_map.C_apply (r : R) (a : α) : continuous_map.C r a = algebra_map R A r :=
rfl
variables [topological_space R] [has_continuous_smul R A] [has_continuous_smul R A₂]
instance continuous_map.algebra : algebra R C(α, A) :=
{ to_ring_hom := continuous_map.C,
commutes' := λ c f, by ext x; exact algebra.commutes' _ _,
smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _, }
variables (R)
/-- Composition on the left by a (continuous) homomorphism of topological `R`-algebras, as an
`alg_hom`. Similar to `alg_hom.comp_left`. -/
@[simps] protected def alg_hom.comp_left_continuous {α : Type*} [topological_space α]
(g : A →ₐ[R] A₂) (hg : continuous g) :
C(α, A) →ₐ[R] C(α, A₂) :=
{ commutes' := λ c, continuous_map.ext $ λ _, g.commutes' _,
.. g.to_ring_hom.comp_left_continuous α hg }
/-- Coercion to a function as an `alg_hom`. -/
@[simps]
def continuous_map.coe_fn_alg_hom : C(α, A) →ₐ[R] (α → A) :=
{ to_fun := coe_fn,
commutes' := λ r, rfl,
-- `..(continuous_map.coe_fn_ring_hom : C(α, A) →+* _)` times out for some reason
map_zero' := continuous_map.coe_zero,
map_one' := continuous_map.coe_one,
map_add' := continuous_map.coe_add,
map_mul' := continuous_map.coe_mul }
instance: is_scalar_tower R A C(α, A) :=
{ smul_assoc := λ _ _ _, by { ext, simp } }
variables {R}
/--
A version of `separates_points` for subalgebras of the continuous functions,
used for stating the Stone-Weierstrass theorem.
-/
abbreviation subalgebra.separates_points (s : subalgebra R C(α, A)) : Prop :=
set.separates_points ((λ f : C(α, A), (f : α → A)) '' (s : set C(α, A)))
lemma subalgebra.separates_points_monotone :
monotone (λ s : subalgebra R C(α, A), s.separates_points) :=
λ s s' r h x y n,
begin
obtain ⟨f, m, w⟩ := h n,
rcases m with ⟨f, ⟨m, rfl⟩⟩,
exact ⟨_, ⟨f, ⟨r m, rfl⟩⟩, w⟩,
end
@[simp] lemma algebra_map_apply (k : R) (a : α) :
algebra_map R C(α, A) k a = k • 1 :=
by { rw algebra.algebra_map_eq_smul_one, refl, }
variables {𝕜 : Type*} [topological_space 𝕜]
/--
A set of continuous maps "separates points strongly"
if for each pair of distinct points there is a function with specified values on them.
We give a slightly unusual formulation, where the specified values are given by some
function `v`, and we ask `f x = v x ∧ f y = v y`. This avoids needing a hypothesis `x ≠ y`.
In fact, this definition would work perfectly well for a set of non-continuous functions,
but as the only current use case is in the Stone-Weierstrass theorem,
writing it this way avoids having to deal with casts inside the set.
(This may need to change if we do Stone-Weierstrass on non-compact spaces,
where the functions would be continuous functions vanishing at infinity.)
-/
def set.separates_points_strongly (s : set C(α, 𝕜)) : Prop :=
∀ (v : α → 𝕜) (x y : α), ∃ f : s, (f x : 𝕜) = v x ∧ f y = v y
variables [field 𝕜] [topological_ring 𝕜]
/--
Working in continuous functions into a topological field,
a subalgebra of functions that separates points also separates points strongly.
By the hypothesis, we can find a function `f` so `f x ≠ f y`.
By an affine transformation in the field we can arrange so that `f x = a` and `f x = b`.
-/
lemma subalgebra.separates_points.strongly {s : subalgebra 𝕜 C(α, 𝕜)} (h : s.separates_points) :
(s : set C(α, 𝕜)).separates_points_strongly :=
λ v x y,
begin
by_cases n : x = y,
{ subst n,
use ((v x) • 1 : C(α, 𝕜)),
{ apply s.smul_mem,
apply s.one_mem, },
{ simp [coe_fn_coe_base'] }, },
obtain ⟨f, ⟨f, ⟨m, rfl⟩⟩, w⟩ := h n,
replace w : f x - f y ≠ 0 := sub_ne_zero_of_ne w,
let a := v x,
let b := v y,
let f' := ((b - a) * (f x - f y)⁻¹) • (continuous_map.C (f x) - f) + continuous_map.C a,
refine ⟨⟨f', _⟩, _, _⟩,
{ simp only [f', set_like.mem_coe, subalgebra.mem_to_submodule],
-- TODO should there be a tactic for this?
-- We could add an attribute `@[subobject_mem]`, and a tactic
-- ``def subobject_mem := `[solve_by_elim with subobject_mem { max_depth := 10 }]``
solve_by_elim
[subalgebra.add_mem, subalgebra.smul_mem, subalgebra.sub_mem, subalgebra.algebra_map_mem]
{ max_depth := 6 }, },
{ simp [f', coe_fn_coe_base'], },
{ simp [f', coe_fn_coe_base', inv_mul_cancel_right₀ w], },
end
end continuous_map
-- TODO[gh-6025]: make this an instance once safe to do so
lemma continuous_map.subsingleton_subalgebra (α : Type*) [topological_space α]
(R : Type*) [comm_semiring R] [topological_space R] [topological_ring R]
[subsingleton α] : subsingleton (subalgebra R C(α, R)) :=
begin
fsplit,
intros s₁ s₂,
by_cases n : nonempty α,
{ obtain ⟨x⟩ := n,
ext f,
have h : f = algebra_map R C(α, R) (f x),
{ ext x', simp only [mul_one, algebra.id.smul_eq_mul, algebra_map_apply], congr, },
rw h,
simp only [subalgebra.algebra_map_mem], },
{ ext f,
have h : f = 0,
{ ext x', exact false.elim (n ⟨x'⟩), },
subst h,
simp only [subalgebra.zero_mem], },
end
end algebra_structure
section module_over_continuous_functions
/-!
### Structure as module over scalar functions
If `M` is a module over `R`, then we show that the space of continuous functions from `α` to `M`
is naturally a module over the ring of continuous functions from `α` to `R`. -/
namespace continuous_map
instance has_scalar' {α : Type*} [topological_space α]
{R : Type*} [semiring R] [topological_space R]
{M : Type*} [topological_space M] [add_comm_monoid M]
[module R M] [has_continuous_smul R M] :
has_scalar C(α, R) C(α, M) :=
⟨λ f g, ⟨λ x, (f x) • (g x), (continuous.smul f.2 g.2)⟩⟩
instance module' {α : Type*} [topological_space α]
(R : Type*) [ring R] [topological_space R] [topological_ring R]
(M : Type*) [topological_space M] [add_comm_monoid M] [has_continuous_add M]
[module R M] [has_continuous_smul R M] :
module C(α, R) C(α, M) :=
{ smul := (•),
smul_add := λ c f g, by ext x; exact smul_add (c x) (f x) (g x),
add_smul := λ c₁ c₂ f, by ext x; exact add_smul (c₁ x) (c₂ x) (f x),
mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul (c₁ x) (c₂ x) (f x),
one_smul := λ f, by ext x; exact one_smul R (f x),
zero_smul := λ f, by ext x; exact zero_smul _ _,
smul_zero := λ r, by ext x; exact smul_zero _, }
end continuous_map
end module_over_continuous_functions
/-!
We now provide formulas for `f ⊓ g` and `f ⊔ g`, where `f g : C(α, β)`,
in terms of `continuous_map.abs`.
-/
section
variables {R : Type*} [linear_ordered_field R]
-- TODO:
-- This lemma (and the next) could go all the way back in `algebra.order.field`,
-- except that it is tedious to prove without tactics.
-- Rather than stranding it at some intermediate location,
-- it's here, immediately prior to the point of use.
lemma min_eq_half_add_sub_abs_sub {x y : R} : min x y = 2⁻¹ * (x + y - |x - y|) :=
by cases le_total x y with h h; field_simp [h, abs_of_nonneg, abs_of_nonpos, mul_two]; abel
lemma max_eq_half_add_add_abs_sub {x y : R} : max x y = 2⁻¹ * (x + y + |x - y|) :=
by cases le_total x y with h h; field_simp [h, abs_of_nonneg, abs_of_nonpos, mul_two]; abel
end
namespace continuous_map
section lattice
variables {α : Type*} [topological_space α]
variables {β : Type*} [linear_ordered_field β] [topological_space β]
[order_topology β] [topological_ring β]
lemma inf_eq (f g : C(α, β)) : f ⊓ g = (2⁻¹ : β) • (f + g - |f - g|) :=
ext (λ x, by simpa using min_eq_half_add_sub_abs_sub)
-- Not sure why this is grosser than `inf_eq`:
lemma sup_eq (f g : C(α, β)) : f ⊔ g = (2⁻¹ : β) • (f + g + |f - g|) :=
ext (λ x, by simpa [mul_add] using @max_eq_half_add_add_abs_sub _ _ (f x) (g x))
end lattice
end continuous_map
|
422ee5232d7533ed10e249957dd9b044f9d501bf | 6fbf10071e62af7238f2de8f9aa83d55d8763907 | /answers/hw2.lean | 7134386fad4953f515edafec069f89a055169f6e | [] | no_license | HasanMukati/uva-cs-dm-s19 | ee5aad4568a3ca330c2738ed579c30e1308b03b0 | 3e7177682acdb56a2d16914e0344c10335583dcf | refs/heads/master | 1,596,946,213,130 | 1,568,221,949,000 | 1,568,221,949,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,850 | lean | /-
This is the second homework assignment for UVa CS2101, Spring 2019.
If you are in Professor Sullivan's class, you are to complete problems 1 - 8.
If you are in Prof. Hocking's class, you are to complete problems 9 - 13.
The first eight problems require that you carefully read the updated class
notes on relations vs. functions and on properties of functions: from the
start of 2.4 through 2.4.4. For all of the remaining problems, you must
have read the rest of the chapter, on higher-order functions.
The collaboration policy for this assignment has two parts. First, you must
complete this work on your own. Second, please do not discuss your results
with anyone in the other professor's class, even after the deadline for the
homework has passed, as your assignment this week will be part of their
assignment next week.
To complete this homework, first make a copy of this file in the "work"
directory of your class repository. Do not edit this file directly in the
hw directory. Make a copy first. Then fill in answers as required, save
your changes, and submit your work by uploading the completed file on Collab.
Make a copy of this file in your work directory; complete the work using
that copy; then upload the resulting file, after saving it, through Collab
before the due date.
-/
/- [10 points]
1. Is the function, G, as defined in the reading, total? Explain.
Answer here: G = ({1, 2, 3}, { (1, 10), (2, 20), (3, 30) }, ℕ)
Yes, it's defined for every value in its domain of definition.
-/
/- [10 points]
2. Give an example of a value in the domain of definition of the function, F,
as defined in the reading, that proves that F is strictly partial, i.e.,
for which F is not defined.
Answer here: F = (ℕ, { (1, 10), (2, 20), (3, 30) }, ℕ ). F is partial. It's
not defined for 0 or any other value that's not 1, 2, 3.
-/
/- [10 points]
3. Give an example of a value in the codomain of F that proves that F is
not surjective.
Answer here: Any natural number other than 10, 20, 30.
-/
/- [10 points]
4. Is our example function, G, strictly partial? Explain.
Answer here: No, we already said it's total.
-/
/- [15 points]
5. Identify a value in the codomain of F that is not the image of any
value in its domain of definition.
Answer here: Any number that's not 10, 20, 30
-/
/- [15 points]
6. Translate our logical definition of injective into mathematically
precise English following the examples for other properties of functions
given in the reading.
Answer here: A function, f, is injective if the whenever two values map
to the same image they are the same value. We will accept any reasonable
version of this statement.
-/
/- [15 points]
7. Is the function, f(x) = log(x) over the real numbers, injective?
Is it surjective? Is it bijective? Explain each of your answers briefly.
Answer here: Yes it's injective (it passes the horizontal line test.) We
will take any reasonable explanation. Yes it's surjective, in that it covers
the whole co-domain.
-/
/- [15 points]
8. Is the relation, 3x^2 + 4y^2 = 4, single-valued? Explain your answers.
Answer here: No, it's an ellipse. Doesn't pass vertical line test.
-/
/-
Complete each of the following partial definitions in Lean by replacing
the underscore characters with code to define functions of the specified
types using lambda notation. We only care that you define some function
of each required type, not what particular function you define.
In preparation, note that if you hover your mouse over an underscore,
Lean will tell you what type of term you is needed to fill that hole.
The type that Lean requires appears after the "turnstile" symbol, |-,
in the message Lean will give you. Even more interestingly, if you
fill in a hole with a term of the right type that itself has one or
more remaining holes, Lean will tell you what types of terms are needed
to fill in those holes! You can thus fill a hole in an incremental manner,
refining a partial solution at each step until all holes are filled,
guided by the types that Lean tells you are needed for any given hole.
We recommend that you try developing your answers in this "top-down
structured" style of programming. That said, we will grade you only on
your answers and not on how you developed them.
-/
-- Rubric: We will accept your answer as long as Lean does. We give
-- examples of answers in this key. Other anwers are possible.
-- 9.
def hw2_1: ℕ → ℕ :=
λ(x: ℕ),
0
-- 10.
def hw2_2: ℕ → ℕ → ℕ :=
λ n m, 0
-- 11.
def hw2_3: (ℕ → ℕ) → (ℕ → ℕ) :=
λ f, f
-- 12.
def hw2_4: (ℕ → ℕ) → ((ℕ → ℕ) → ℕ) :=
λ f,
λ g, 0
-- 13.
def hw2_5: (ℕ → ℕ) → ((ℕ → ℕ) → (ℕ → ℕ)) :=
λ f,
λ g,
f
|
0b015cde4d202be6057dfd5f300b5a4fe27637fe | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Meta/Tactic/Cases.lean | 418a77e2eb5ce57e410c87943ec0ce9b5e9fa4b3 | [
"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 | 14,348 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.AppBuilder
import Lean.Meta.Tactic.Induction
import Lean.Meta.Tactic.Injection
import Lean.Meta.Tactic.Assert
import Lean.Meta.Tactic.Subst
import Lean.Meta.Tactic.Acyclic
import Lean.Meta.Tactic.UnifyEq
namespace Lean.Meta
private def throwInductiveTypeExpected (type : Expr) : MetaM α := do
throwError "failed to compile pattern matching, inductive type expected{indentExpr type}"
def getInductiveUniverseAndParams (type : Expr) : MetaM (List Level × Array Expr) := do
let type ← whnfD type
matchConstInduct type.getAppFn (fun _ => throwInductiveTypeExpected type) fun val us =>
let Iargs := type.getAppArgs
let params := Iargs.extract 0 val.numParams
pure (us, params)
private def mkEqAndProof (lhs rhs : Expr) : MetaM (Expr × Expr) := do
let lhsType ← inferType lhs
let rhsType ← inferType rhs
let u ← getLevel lhsType
if (← isDefEq lhsType rhsType) then
pure (mkApp3 (mkConst ``Eq [u]) lhsType lhs rhs, mkApp2 (mkConst ``Eq.refl [u]) lhsType lhs)
else
pure (mkApp4 (mkConst ``HEq [u]) lhsType lhs rhsType rhs, mkApp2 (mkConst ``HEq.refl [u]) lhsType lhs)
private partial def withNewEqs (targets targetsNew : Array Expr) (k : Array Expr → Array Expr → MetaM α) : MetaM α :=
let rec loop (i : Nat) (newEqs : Array Expr) (newRefls : Array Expr) := do
if i < targets.size then
let (newEqType, newRefl) ← mkEqAndProof targets[i]! targetsNew[i]!
withLocalDeclD `h newEqType fun newEq => do
loop (i+1) (newEqs.push newEq) (newRefls.push newRefl)
else
k newEqs newRefls
loop 0 #[] #[]
def generalizeTargetsEq (mvarId : MVarId) (motiveType : Expr) (targets : Array Expr) : MetaM MVarId :=
mvarId.withContext do
mvarId.checkNotAssigned `generalizeTargets
let (typeNew, eqRefls) ←
forallTelescopeReducing motiveType fun targetsNew _ => do
unless targetsNew.size == targets.size do
throwError "invalid number of targets #{targets.size}, motive expects #{targetsNew.size}"
withNewEqs targets targetsNew fun eqs eqRefls => do
let type ← mvarId.getType
let typeNew ← mkForallFVars eqs type
let typeNew ← mkForallFVars targetsNew typeNew
pure (typeNew, eqRefls)
let mvarNew ← mkFreshExprSyntheticOpaqueMVar typeNew (← mvarId.getTag)
mvarId.assign (mkAppN (mkAppN mvarNew targets) eqRefls)
pure mvarNew.mvarId!
structure GeneralizeIndicesSubgoal where
mvarId : MVarId
indicesFVarIds : Array FVarId
fvarId : FVarId
numEqs : Nat
/--
Similar to `generalizeTargets` but customized for the `casesOn` motive.
Given a metavariable `mvarId` representing the
```
Ctx, h : I A j, D |- T
```
where `fvarId` is `h`s id, and the type `I A j` is an inductive datatype where `A` are parameters,
and `j` the indices. Generate the goal
```
Ctx, h : I A j, D, j' : J, h' : I A j' |- j == j' -> h == h' -> T
```
Remark: `(j == j' -> h == h')` is a "telescopic" equality.
Remark: `j` is sequence of terms, and `j'` a sequence of free variables.
The result contains the fields
- `mvarId`: the new goal
- `indicesFVarIds`: `j'` ids
- `fvarId`: `h'` id
- `numEqs`: number of equations in the target -/
def generalizeIndices (mvarId : MVarId) (fvarId : FVarId) : MetaM GeneralizeIndicesSubgoal :=
mvarId.withContext do
let lctx ← getLCtx
let localInsts ← getLocalInstances
mvarId.checkNotAssigned `generalizeIndices
let fvarDecl ← fvarId.getDecl
let type ← whnf fvarDecl.type
type.withApp fun f args => matchConstInduct f (fun _ => throwTacticEx `generalizeIndices mvarId "inductive type expected") fun val _ => do
unless val.numIndices > 0 do throwTacticEx `generalizeIndices mvarId "indexed inductive type expected"
unless args.size == val.numIndices + val.numParams do throwTacticEx `generalizeIndices mvarId "ill-formed inductive datatype"
let indices := args.extract (args.size - val.numIndices) args.size
let IA := mkAppN f (args.extract 0 val.numParams) -- `I A`
let IAType ← inferType IA
forallTelescopeReducing IAType fun newIndices _ => do
let newType := mkAppN IA newIndices
withLocalDeclD fvarDecl.userName newType fun h' =>
withNewEqs indices newIndices fun newEqs newRefls => do
let (newEqType, newRefl) ← mkEqAndProof fvarDecl.toExpr h'
let newRefls := newRefls.push newRefl
withLocalDeclD `h newEqType fun newEq => do
let newEqs := newEqs.push newEq
/- auxType `forall (j' : J) (h' : I A j'), j == j' -> h == h' -> target -/
let target ← mvarId.getType
let tag ← mvarId.getTag
let auxType ← mkForallFVars newEqs target
let auxType ← mkForallFVars #[h'] auxType
let auxType ← mkForallFVars newIndices auxType
let newMVar ← mkFreshExprMVarAt lctx localInsts auxType MetavarKind.syntheticOpaque tag
/- assign mvarId := newMVar indices h refls -/
mvarId.assign (mkAppN (mkApp (mkAppN newMVar indices) fvarDecl.toExpr) newRefls)
let (indicesFVarIds, newMVarId) ← newMVar.mvarId!.introNP newIndices.size
let (fvarId, newMVarId) ← newMVarId.intro1P
return {
mvarId := newMVarId,
indicesFVarIds := indicesFVarIds,
fvarId := fvarId,
numEqs := newEqs.size
}
structure CasesSubgoal extends InductionSubgoal where
ctorName : Name
namespace Cases
structure Context where
inductiveVal : InductiveVal
casesOnVal : DefinitionVal
nminors : Nat := inductiveVal.ctors.length
majorDecl : LocalDecl
majorTypeFn : Expr
majorTypeArgs : Array Expr
majorTypeIndices : Array Expr := majorTypeArgs.extract (majorTypeArgs.size - inductiveVal.numIndices) majorTypeArgs.size
private def mkCasesContext? (majorFVarId : FVarId) : MetaM (Option Context) := do
let env ← getEnv
if !env.contains `Eq || !env.contains `HEq then
pure none
else
let majorDecl ← majorFVarId.getDecl
let majorType ← whnf majorDecl.type
majorType.withApp fun f args => matchConstInduct f (fun _ => pure none) fun ival _ =>
if args.size != ival.numIndices + ival.numParams then pure none
else match env.find? (Name.mkStr ival.name "casesOn") with
| ConstantInfo.defnInfo cval =>
return some {
inductiveVal := ival,
casesOnVal := cval,
majorDecl := majorDecl,
majorTypeFn := f,
majorTypeArgs := args
}
| _ => pure none
/--
We say the major premise has independent indices IF
1- its type is *not* an indexed inductive family, OR
2- its type is an indexed inductive family, but all indices are distinct free variables, and
all local declarations different from the major and its indices do not depend on the indices.
-/
private def hasIndepIndices (ctx : Context) : MetaM Bool := do
if ctx.majorTypeIndices.isEmpty then
return true
else if ctx.majorTypeIndices.any fun idx => !idx.isFVar then
/- One of the indices is not a free variable. -/
return false
else if ctx.majorTypeIndices.size.any fun i => i.any fun j => ctx.majorTypeIndices[i]! == ctx.majorTypeIndices[j]! then
/- An index ocurrs more than once -/
return false
else
(← getLCtx).allM fun decl =>
pure (decl.fvarId == ctx.majorDecl.fvarId) <||> -- decl is the major
pure (ctx.majorTypeIndices.any (fun index => decl.fvarId == index.fvarId!)) <||> -- decl is one of the indices
findLocalDeclDependsOn decl (fun fvarId => ctx.majorTypeIndices.all fun idx => idx.fvarId! != fvarId) -- or does not depend on any index
private def elimAuxIndices (s₁ : GeneralizeIndicesSubgoal) (s₂ : Array CasesSubgoal) : MetaM (Array CasesSubgoal) :=
let indicesFVarIds := s₁.indicesFVarIds
s₂.mapM fun s => do
indicesFVarIds.foldlM (init := s) fun s indexFVarId =>
match s.subst.get indexFVarId with
| Expr.fvar indexFVarId' =>
(do let mvarId ← s.mvarId.clear indexFVarId'; pure { s with mvarId := mvarId, subst := s.subst.erase indexFVarId })
<|>
(pure s)
| _ => pure s
/--
Convert `s` into an array of `CasesSubgoal`, by attaching the corresponding constructor name,
and adding the substitution `majorFVarId -> ctor_i us params fields` into each subgoal. -/
private def toCasesSubgoals (s : Array InductionSubgoal) (ctorNames : Array Name) (majorFVarId : FVarId) (us : List Level) (params : Array Expr)
: Array CasesSubgoal :=
s.mapIdx fun i s =>
let ctorName := ctorNames[i]!
let ctorApp := mkAppN (mkAppN (mkConst ctorName us) params) s.fields
let s := { s with subst := s.subst.insert majorFVarId ctorApp }
{ ctorName := ctorName,
toInductionSubgoal := s }
partial def unifyEqs? (numEqs : Nat) (mvarId : MVarId) (subst : FVarSubst) (caseName? : Option Name := none): MetaM (Option (MVarId × FVarSubst)) := do
if numEqs == 0 then
return some (mvarId, subst)
else
let (eqFVarId, mvarId) ← mvarId.intro1
if let some { mvarId, subst, numNewEqs } ← unifyEq? mvarId eqFVarId subst MVarId.acyclic caseName? then
unifyEqs? (numEqs - 1 + numNewEqs) mvarId subst caseName?
else
return none
private def unifyCasesEqs (numEqs : Nat) (subgoals : Array CasesSubgoal) : MetaM (Array CasesSubgoal) :=
subgoals.foldlM (init := #[]) fun subgoals s => do
match (← unifyEqs? numEqs s.mvarId s.subst s.ctorName) with
| none => pure subgoals
| some (mvarId, subst) =>
return subgoals.push { s with
mvarId := mvarId,
subst := subst,
fields := s.fields.map (subst.apply ·)
}
private def inductionCasesOn (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames) (ctx : Context)
: MetaM (Array CasesSubgoal) := mvarId.withContext do
let majorType ← inferType (mkFVar majorFVarId)
let (us, params) ← getInductiveUniverseAndParams majorType
let casesOn := mkCasesOnName ctx.inductiveVal.name
let ctors := ctx.inductiveVal.ctors.toArray
let s ← mvarId.induction majorFVarId casesOn givenNames
return toCasesSubgoals s ctors majorFVarId us params
def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames := #[]) : MetaM (Array CasesSubgoal) := do
try
mvarId.withContext do
mvarId.checkNotAssigned `cases
let context? ← mkCasesContext? majorFVarId
match context? with
| none => throwTacticEx `cases mvarId "not applicable to the given hypothesis"
| some ctx =>
/- Remark: if caller does not need a `FVarSubst` (variable substitution), and `hasIndepIndices ctx` is true,
then we can also use the simple case. This is a minor optimization, and we currently do not even
allow callers to specify whether they want the `FVarSubst` or not. -/
if ctx.inductiveVal.numIndices == 0 then
-- Simple case
inductionCasesOn mvarId majorFVarId givenNames ctx
else
let s₁ ← generalizeIndices mvarId majorFVarId
trace[Meta.Tactic.cases] "after generalizeIndices\n{MessageData.ofGoal s₁.mvarId}"
let s₂ ← inductionCasesOn s₁.mvarId s₁.fvarId givenNames ctx
let s₂ ← elimAuxIndices s₁ s₂
unifyCasesEqs s₁.numEqs s₂
catch ex =>
throwNestedTacticEx `cases ex
end Cases
/--
Apply `casesOn` using the free variable `majorFVarId` as the major premise (aka discriminant).
`givenNames` contains user-facing names for each alternative.
-/
def _root_.Lean.MVarId.cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames := #[]) : MetaM (Array CasesSubgoal) :=
Cases.cases mvarId majorFVarId givenNames
@[deprecated MVarId.cases]
def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames := #[]) : MetaM (Array CasesSubgoal) :=
Cases.cases mvarId majorFVarId givenNames
/--
Keep applying `cases` on any hypothesis that satisfies `p`.
-/
def _root_.Lean.MVarId.casesRec (mvarId : MVarId) (p : LocalDecl → MetaM Bool) : MetaM (List MVarId) :=
saturate mvarId fun mvarId =>
mvarId.withContext do
for localDecl in (← getLCtx) do
if (← p localDecl) then
let r? ← observing? do
let r ← mvarId.cases localDecl.fvarId
return r.toList.map (·.mvarId)
if r?.isSome then
return r?
return none
/--
Applies `cases` (recursively) to any hypothesis of the form `h : p ∧ q`.
-/
def _root_.Lean.MVarId.casesAnd (mvarId : MVarId) : MetaM MVarId := do
let mvarIds ← mvarId.casesRec fun localDecl => return (← instantiateMVars localDecl.type).isAppOfArity ``And 2
exactlyOne mvarIds
/--
Applies `cases` to any hypothesis of the form `h : r = s`.
-/
def _root_.Lean.MVarId.substEqs (mvarId : MVarId) : MetaM (Option MVarId) := do
let mvarIds ← mvarId.casesRec fun localDecl => do
let type ← instantiateMVars localDecl.type
return type.isEq || type.isHEq
ensureAtMostOne mvarIds
/-- Auxiliary structure for storing `byCases` tactic result. -/
structure ByCasesSubgoal where
mvarId : MVarId
fvarId : FVarId
private def toByCasesSubgoal (s : CasesSubgoal) : MetaM ByCasesSubgoal := do
let #[Expr.fvar fvarId ..] ← pure s.fields | throwError "'byCases' tactic failed, unexpected new hypothesis"
return { mvarId := s.mvarId, fvarId }
/--
Split the goal in two subgoals: one containing the hypothesis `h : p` and another containing `h : ¬ p`.
-/
def _root_.Lean.MVarId.byCases (mvarId : MVarId) (p : Expr) (hName : Name := `h) : MetaM (ByCasesSubgoal × ByCasesSubgoal) := do
let mvarId ← mvarId.assert `hByCases (mkOr p (mkNot p)) (mkEM p)
let (fvarId, mvarId) ← mvarId.intro1
let #[s₁, s₂] ← mvarId.cases fvarId #[{ varNames := [hName] }, { varNames := [hName] }] |
throwError "'byCases' tactic failed, unexpected number of subgoals"
return ((← toByCasesSubgoal s₁), (← toByCasesSubgoal s₂))
builtin_initialize registerTraceClass `Meta.Tactic.cases
end Lean.Meta
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.