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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a9e068cdd44ad0328c6038c1a245cbfbab9543e | 022547453607c6244552158ff25ab3bf17361760 | /src/measure_theory/measure_space.lean | 30ab9d854036b9f6e9fa00d9455d9e84839411cb | [
"Apache-2.0"
] | permissive | 1293045656/mathlib | 5f81741a7c1ff1873440ec680b3680bfb6b7b048 | 4709e61525a60189733e72a50e564c58d534bed8 | refs/heads/master | 1,687,010,200,553 | 1,626,245,646,000 | 1,626,245,646,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 112,503 | 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_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:
* `probability_measure μ`: `μ univ = 1`;
* `finite_measure μ`: `μ univ < ∞`;
* `sigma_finite μ`: there exists a countable collection of measurable sets that cover `univ`
where `μ` is finite;
* `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 [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 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
/-- 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, 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 (μ : 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
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, 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⟩,
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)
(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 (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 {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 {s : ℕ → set α}
(hs : ∀ n, measurable_set (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 (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
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, measurable_set.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
lemma measure_if {x : β} {t : set β} {s : set α} {μ : measure α} :
μ (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
end outer_measure
variables [measurable_space α] [measurable_space β] [measurable_space γ]
variables {μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : measure α} {s s' t : set α}
namespace measure
protected lemma caratheodory (μ : 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 : 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 : set α) : (μ₁ + μ₂) 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 ℝ≥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 (c : ℝ≥0∞) (μ : measure α) :
(c • μ).to_outer_measure = c • μ.to_outer_measure :=
rfl
@[simp, norm_cast] theorem coe_smul (c : ℝ≥0∞) (μ : measure α) : ⇑(c • μ) = c • μ :=
rfl
theorem smul_apply (c : ℝ≥0∞) (μ : measure α) (s : set α) : (c • μ) s = c * μ s :=
rfl
instance : 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 (c : ℝ≥0) (μ : measure α) : ⇑(c • μ) = c • μ :=
rfl
/-! ### The complete lattice of measures -/
instance : 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]
-- TODO: add typeclasses for `∀ c, monotone ((*) c)` and `∀ c, monotone ((+) c)`
protected lemma add_le_add_left (ν : measure α) (hμ : μ₁ ≤ μ₂) : ν + μ₁ ≤ ν + μ₂ :=
λ s hs, add_le_add_left (hμ s hs) _
protected lemma add_le_add_right (hμ : μ₁ ≤ μ₂) (ν : measure α) : μ₁ + ν ≤ μ₂ + ν :=
λ s hs, add_le_add_right (hμ s hs) _
protected lemma add_le_add (hμ : μ₁ ≤ μ₂) (hν : ν₁ ≤ ν₂) :
μ₁ + ν₁ ≤ μ₂ + ν₂ :=
λ s hs, add_le_add (hμ s hs) (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 : 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 : 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 : 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 (μ : 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 (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 (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]
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 (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 (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ₗ (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 (μ : measure α) (s : set α) : measure α := restrictₗ s μ
@[simp] lemma restrictₗ_apply (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 (μ: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 (μ ν : 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 : ℝ≥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 (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' ⦃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 ⦃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 {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 (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, (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
/-- 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]
/-- 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]
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
@[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]
/-- 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
/-! ### 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 (μ ν : 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 (μ : 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 (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 (μ : 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 (μ : 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
end measure
open measure
@[simp] lemma ae_eq_bot : μ.ae = ⊥ ↔ μ = 0 :=
by rw [← empty_in_sets_eq_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 : (0 : measure α).ae = ⊥ := ae_eq_bot.2 rfl
@[mono] lemma ae_mono {μ ν : measure α} (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 (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_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 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_sets, mem_inf_sets];
exact ⟨_, univ_mem_sets, s, by rw [univ_inter, and_self]⟩
/-- 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
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]
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 finite_measure
/-- A measure `μ` is called finite if `μ univ < ∞`. -/
class finite_measure (μ : measure α) : Prop := (measure_univ_lt_top : μ univ < ∞)
instance restrict.finite_measure (μ : measure α) [hs : fact (μ s < ∞)] :
finite_measure (μ.restrict s) :=
⟨by simp [hs.elim]⟩
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)
/-- 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 α) [finite_measure μ] :
↑(measure_univ_nnreal μ) = μ univ :=
ennreal.coe_to_nnreal (measure_ne_top μ univ)
instance finite_measure_zero : finite_measure (0 : measure α) := ⟨by simp⟩
instance finite_measure_add [finite_measure μ] [finite_measure ν] : 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 finite_measure_smul_nnreal [finite_measure μ] {r : ℝ≥0} : finite_measure (r • μ) :=
{ measure_univ_lt_top := ennreal.mul_lt_top ennreal.coe_lt_top (measure_lt_top _ _) }
@[simp] lemma measure_univ_nnreal_zero : measure_univ_nnreal (0 : measure α) = 0 := rfl
@[simp] lemma measure_univ_nnreal_eq_zero [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 [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 {μ ν₁ ν₂ : measure α} [finite_measure μ]
(A2 : μ + ν₁ ≤ μ + ν₂) : ν₁ ≤ ν₂ :=
λ S B1, ennreal.le_of_add_le_add_left (measure_theory.measure_lt_top μ S) (A2 S B1)
end finite_measure
section probability_measure
/-- A measure `μ` is called a probability measure if `μ univ = 1`. -/
class probability_measure (μ : measure α) : Prop := (measure_univ : μ univ = 1)
export probability_measure (measure_univ)
instance measure.dirac.probability_measure {x : α} : probability_measure (dirac x) :=
⟨dirac_apply_of_mem $ mem_univ x⟩
@[priority 100]
instance probability_measure.to_finite_measure (μ : measure α) [probability_measure μ] :
finite_measure μ :=
⟨by simp only [measure_univ, ennreal.one_lt_top]⟩
lemma probability_measure.ne_zero (μ : measure α) [probability_measure μ] : μ ≠ 0 :=
mt measure_univ_eq_zero.2 $ by simp [measure_univ]
lemma prob_add_prob_compl [probability_measure μ]
(h : measurable_set s) : μ s + μ sᶜ = 1 :=
(measure_add_measure_compl h).trans measure_univ
lemma prob_le_one [probability_measure μ] : μ s ≤ 1 :=
(measure_mono $ set.subset_univ _).trans_eq measure_univ
end 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 (μ : measure α) : Prop :=
(measure_singleton : ∀ x, μ {x} = 0)
export has_no_atoms (measure_singleton)
attribute [simp] measure_singleton
variables [has_no_atoms μ]
@[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 (h : countable s) : μ 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 (h : s.finite) : μ s = 0 :=
h.countable.measure_zero
lemma _root_.finset.measure_zero (s : finset α) : μ ↑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 (μ : 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 finite_at_filter.exists_mem_basis {μ : measure α} {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 (μ : measure α) : μ.finite_at_filter ⊥ :=
⟨∅, mem_bot_sets, 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 (μ : 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 (μ : measure α) : Prop :=
(out' : nonempty (μ.finite_spanning_sets_in {s | measurable_set s}))
theorem sigma_finite_iff {μ : measure α} : sigma_finite μ ↔
nonempty (μ.finite_spanning_sets_in {s | measurable_set s}) :=
⟨λ h, h.1, λ h, ⟨h⟩⟩
theorem sigma_finite.out {μ : measure α} (h : sigma_finite μ) :
nonempty (μ.finite_spanning_sets_in {s | measurable_set s}) := h.1
/-- 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} :=
classical.choice h.out
/-- 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
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 μ⟩
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 ⊆ 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.set, λ i, hC (h.set_mem i), h.finite, h.spanning⟩
/-- 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) (hC : ∀ s ∈ C, measurable_set s) :
sigma_finite μ :=
⟨⟨h.mono hC⟩⟩
/-- 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 h.finite h_eq
protected lemma is_countably_spanning (h : μ.finite_spanning_sets_in C) : is_countably_spanning C :=
⟨_, h.set_mem, h.spanning⟩
end finite_spanning_sets_in
lemma sigma_finite_of_not_nonempty (μ : measure α) (hα : ¬ nonempty α) : sigma_finite μ :=
⟨⟨⟨λ _, ∅, λ n, measurable_set.empty, λ n, by simp, by simp [eq_empty_of_not_nonempty hα univ]⟩⟩⟩
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⟩,
refine ⟨⟨⟨λ n, to_measurable μ (s n), λ n, measurable_set_to_measurable _ _, by simpa, _⟩⟩⟩,
exact eq_univ_of_subset (Union_subset_Union $ λ n, subset_to_measurable μ (s n)) hs
end
end measure
/-- Every finite measure is σ-finite. -/
@[priority 100]
instance finite_measure.to_sigma_finite (μ : measure α) [finite_measure μ] : sigma_finite μ :=
⟨⟨⟨λ _, univ, λ _, measurable_set.univ, λ _, measure_lt_top μ _, Union_const _⟩⟩⟩
instance restrict.sigma_finite (μ : measure α) [sigma_finite μ] (s : set α) :
sigma_finite (μ.restrict s) :=
begin
refine ⟨⟨⟨spanning_sets μ, measurable_spanning_sets μ, λ 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 ι := (encodable.trunc_encodable_of_fintype ι).out,
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, this, λ 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, hf $ measurable_spanning_sets _ _,
λ 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 locally_finite_measure [topological_space α] (μ : measure α) : Prop :=
(finite_at_nhds : ∀ x, μ.finite_at_filter (𝓝 x))
@[priority 100] -- see Note [lower instance priority]
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
lemma measure.smul_finite {α : Type*} [measurable_space α] (μ : measure α) [finite_measure μ]
{c : ℝ≥0∞} (hc : c < ∞) :
finite_measure (c • μ) :=
begin
refine ⟨_⟩,
rw measure.smul_apply,
exact ennreal.mul_lt_top hc (measure_lt_top μ set.univ),
end
lemma measure.exists_is_open_measure_lt_top [topological_space α] (μ : measure α)
[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)
@[priority 100] -- see Note [lower instance priority]
instance sigma_finite_of_locally_finite [topological_space α]
[topological_space.second_countable_topology α]
{μ : measure α} [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 α} [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 : @finite_measure _ m₀ ν := begin
constructor,
rw ← h_univ,
apply 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_lt_top α m₀ μ _ t),
@measure_compl α m₀ ν t h1t_ (@measure_lt_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 : _inst_1 = generate_from C)
(hC : is_pi_system C) {μ ν : measure α} [finite_measure μ]
(hμν : ∀ s ∈ C, μ s = ν s) (h_univ : μ univ = ν univ) :
μ = ν :=
measure.ext (λ s hs,
ext_on_measurable_space_of_generate_finite _inst_1 C hμν (le_refl _inst_1) hA hC h_univ hs)
namespace measure
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, 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 : μ.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 [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 },
apply measure_theory.measure_lt_top, intro i, apply h₂, apply 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 [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 finite_measure_sub [finite_measure μ] : 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.to_equiv.image_eq_preimage,
simp only [←coe_eq, symm_symm, symm_to_equiv] at this,
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]
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 finite_measure_trim (hm : m ≤ m0) [finite_measure μ] : @finite_measure α m (μ.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 :=
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 _ _ m _ f (μ.trim hm)) :
ae_measurable f μ :=
begin
let f' := @ae_measurable.mk _ _ m _ _ _ hf,
have hf'_meas : @measurable _ _ m _ f', from @ae_measurable.measurable_mk _ _ m _ _ _ hf,
have hff'_m : f' =ᶠ[@measure.ae _ m (μ.trim hm)] f,
from (@ae_measurable.ae_eq_mk _ _ m _ _ _ hf).symm,
have hff' : f' =ᵐ[μ] f, from ae_eq_of_ae_eq_trim hff'_m,
exact ⟨f', measurable.mono hf'_meas hm le_rfl, hff'.symm⟩,
end
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
by_cases h : nonempty β,
{ 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) },
{ exact (measurable_of_not_nonempty (mt (nonempty.map f) h) f).ae_measurable }
end
end
namespace is_compact
variables [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 [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
section piecewise
variables [measurable_space α] {μ : measure α} {s : 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
end piecewise
section indicator_function
variables [measurable_space α] {μ : measure α} {s : set α} {f : α → β}
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
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
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
namespace measurable_set
variables [measurable_space α]
@[measurability]
lemma cond {A B : set α} (hA : measurable_set A) (hB : measurable_set B)
{i : bool} : measurable_set (cond i A B) :=
by { cases i, exacts [hB, hA] }
end measurable_set
|
0dac2b29277627793d4d6cd94b24c852803b0630 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /tests/lean/mutualdef1.lean | fccf316c0fb84d2488d97ce7dece21df2f6b27e4 | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 460 | lean |
mutual
def f (x : Nat) : Nat → Nat
| 0 => 1
| x+1 => g x
theorem g (x : Nat) : Nat → Nat -- cannot mix theorems and definitions
| 0 => 2
| x+1 => f x
end
mutual
def f : Nat → Nat
| 0 => 1
| x+1 => g x
example : Nat := -- cannot mix examples and definitions
g 10
end
mutual
def f (x : Nat) : Nat → Nat
| 0 => 1
| x+1 => g x
unsafe def g (x : Nat) : Nat → Nat -- cannot mix safe and unsafe definitions
| 0 => 2
| x+1 => f x
end
|
11631a5359190084b93944bbb8a172d960983b8d | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /library/data/stream.lean | 77dc52b37d9e605f3f87f35b47e4952bdd4da7dd | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 21,297 | 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
-/
open nat function option
universes u v w
def stream (α : Type u) := nat → α
namespace stream
variables {α : Type u} {β : Type v} {δ : Type w}
def cons (a : α) (s : stream α) : stream α :=
λ i,
match i with
| 0 := a
| succ n := s n
end
notation h :: t := cons h t
@[reducible] def head (s : stream α) : α :=
s 0
def tail (s : stream α) : stream α :=
λ i, s (i+1)
def drop (n : nat) (s : stream α) : stream α :=
λ i, s (i+n)
@[reducible] def nth (n : nat) (s : stream α) : α :=
s n
protected lemma eta (s : stream α) : head s :: tail s = s :=
funext (λ i, begin cases i, repeat {reflexivity} end)
lemma nth_zero_cons (a : α) (s : stream α) : nth 0 (a :: s) = a :=
rfl
lemma head_cons (a : α) (s : stream α) : head (a :: s) = a :=
rfl
lemma tail_cons (a : α) (s : stream α) : tail (a :: s) = s :=
rfl
lemma tail_drop (n : nat) (s : stream α) : tail (drop n s) = drop n (tail s) :=
funext (λ i, begin unfold tail drop, simp end)
lemma nth_drop (n m : nat) (s : stream α) : nth n (drop m s) = nth (n+m) s :=
rfl
lemma tail_eq_drop (s : stream α) : tail s = drop 1 s :=
rfl
lemma drop_drop (n m : nat) (s : stream α) : drop n (drop m s) = drop (n+m) s :=
funext (λ i, begin unfold drop, rw add_assoc end)
lemma nth_succ (n : nat) (s : stream α) : nth (succ n) s = nth n (tail s) :=
rfl
lemma drop_succ (n : nat) (s : stream α) : drop (succ n) s = drop n (tail s) :=
rfl
protected lemma ext {s₁ s₂ : stream α} : (∀ n, nth n s₁ = nth n s₂) → s₁ = s₂ :=
assume h, funext h
def all (p : α → Prop) (s : stream α) := ∀ n, p (nth n s)
def any (p : α → Prop) (s : stream α) := ∃ n, p (nth n s)
lemma all_def (p : α → Prop) (s : stream α) : all p s = ∀ n, p (nth n s) :=
rfl
lemma any_def (p : α → Prop) (s : stream α) : any p s = ∃ n, p (nth n s) :=
rfl
protected def mem (a : α) (s : stream α) := any (λ b, a = b) s
instance : has_mem α (stream α) :=
⟨stream.mem⟩
lemma mem_cons (a : α) (s : stream α) : a ∈ (a::s) :=
exists.intro 0 rfl
lemma mem_cons_of_mem {a : α} {s : stream α} (b : α) : a ∈ s → a ∈ b :: s :=
assume ⟨n, h⟩,
exists.intro (succ n) (by rw [nth_succ, tail_cons, h])
lemma eq_or_mem_of_mem_cons {a b : α} {s : stream α} : a ∈ b::s → a = b ∨ a ∈ s :=
assume ⟨n, h⟩,
begin
cases n with n',
{left, exact h},
{right, rw [nth_succ, tail_cons] at h, exact ⟨n', h⟩}
end
lemma mem_of_nth_eq {n : nat} {s : stream α} {a : α} : a = nth n s → a ∈ s :=
assume h, exists.intro n h
section map
variable (f : α → β)
def map (s : stream α) : stream β :=
λ n, f (nth n s)
lemma drop_map (n : nat) (s : stream α) : drop n (map f s) = map f (drop n s) :=
stream.ext (λ i, rfl)
lemma nth_map (n : nat) (s : stream α) : nth n (map f s) = f (nth n s) :=
rfl
lemma tail_map (s : stream α) : tail (map f s) = map f (tail s) :=
begin rw tail_eq_drop, reflexivity end
lemma head_map (s : stream α) : head (map f s) = f (head s) :=
rfl
lemma map_eq (s : stream α) : map f s = f (head s) :: map f (tail s) :=
by rw [-stream.eta (map f s), tail_map, head_map]
lemma map_cons (a : α) (s : stream α) : map f (a :: s) = f a :: map f s :=
begin rw [-stream.eta (map f (a :: s)), map_eq], reflexivity end
lemma map_id (s : stream α) : map id s = s :=
rfl
lemma map_map (g : β → δ) (f : α → β) (s : stream α) : map g (map f s) = map (g ∘ f) s :=
rfl
lemma mem_map {a : α} {s : stream α} : a ∈ s → f a ∈ map f s :=
assume ⟨n, h⟩,
exists.intro n (by rw [nth_map, h])
end map
section zip
variable (f : α → β → δ)
def zip (s₁ : stream α) (s₂ : stream β) : stream δ :=
λ n, f (nth n s₁) (nth n s₂)
lemma drop_zip (n : nat) (s₁ : stream α) (s₂ : stream β) : drop n (zip f s₁ s₂) = zip f (drop n s₁) (drop n s₂) :=
stream.ext (λ i, rfl)
lemma nth_zip (n : nat) (s₁ : stream α) (s₂ : stream β) : nth n (zip f s₁ s₂) = f (nth n s₁) (nth n s₂) :=
rfl
lemma head_zip (s₁ : stream α) (s₂ : stream β) : head (zip f s₁ s₂) = f (head s₁) (head s₂) :=
rfl
lemma tail_zip (s₁ : stream α) (s₂ : stream β) : tail (zip f s₁ s₂) = zip f (tail s₁) (tail s₂) :=
rfl
lemma zip_eq (s₁ : stream α) (s₂ : stream β) : zip f s₁ s₂ = f (head s₁) (head s₂) :: zip f (tail s₁) (tail s₂) :=
begin rw [-stream.eta (zip f s₁ s₂)], reflexivity end
end zip
def const (a : α) : stream α :=
λ n, a
lemma mem_const (a : α) : a ∈ const a :=
exists.intro 0 rfl
lemma const_eq (a : α) : const a = a :: const a :=
begin
apply stream.ext, intro n,
cases n, repeat {reflexivity}
end
lemma tail_const (a : α) : tail (const a) = const a :=
suffices tail (a :: const a) = const a, by rwa -const_eq at this,
rfl
lemma map_const (f : α → β) (a : α) : map f (const a) = const (f a) :=
rfl
lemma nth_const (n : nat) (a : α) : nth n (const a) = a :=
rfl
lemma drop_const (n : nat) (a : α) : drop n (const a) = const a :=
stream.ext (λ i, rfl)
def iterate (f : α → α) (a : α) : stream α :=
λ n, nat.rec_on n a (λ n r, f r)
lemma head_iterate (f : α → α) (a : α) : head (iterate f a) = a :=
rfl
lemma tail_iterate (f : α → α) (a : α) : tail (iterate f a) = iterate f (f a) :=
begin
apply funext, intro n,
induction n with n' ih,
{reflexivity},
{unfold tail iterate,
unfold tail iterate at ih,
rw add_one_eq_succ at ih, dsimp at ih,
rw add_one_eq_succ, dsimp, rw ih}
end
lemma iterate_eq (f : α → α) (a : α) : iterate f a = a :: iterate f (f a) :=
begin
rw [-stream.eta (iterate f a)],
rw tail_iterate, reflexivity
end
lemma nth_zero_iterate (f : α → α) (a : α) : nth 0 (iterate f a) = a :=
rfl
lemma nth_succ_iterate (n : nat) (f : α → α) (a : α) : nth (succ n) (iterate f a) = nth n (iterate f (f a)) :=
by rw [nth_succ, tail_iterate]
section bisim
variable (R : stream α → stream α → Prop)
local infix ~ := R
def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → head s₁ = head s₂ ∧ tail s₁ ~ tail s₂
lemma nth_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂} n, s₁ ~ s₂ → nth n s₁ = nth n s₂ ∧ drop (n+1) s₁ ~ drop (n+1) s₂
| s₁ s₂ 0 h := bisim h
| s₁ s₂ (n+1) h :=
match bisim h with
| ⟨h₁, trel⟩ := nth_of_bisim n trel
end
-- If two streams are bisimilar, then they are equal
lemma eq_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂}, s₁ ~ s₂ → s₁ = s₂ :=
λ s₁ s₂ r, stream.ext (λ n, and.elim_left (nth_of_bisim R bisim n r))
end bisim
lemma bisim_simple (s₁ s₂ : stream α) : head s₁ = head s₂ → s₁ = tail s₁ → s₂ = tail s₂ → s₁ = s₂ :=
assume hh ht₁ ht₂, eq_of_bisim
(λ s₁ s₂, head s₁ = head s₂ ∧ s₁ = tail s₁ ∧ s₂ = tail s₂)
(λ s₁ s₂ ⟨h₁, h₂, h₃⟩,
begin
constructor, exact h₁, rw [-h₂, -h₃], repeat {constructor, repeat {assumption}}
end)
(and.intro hh (and.intro ht₁ ht₂))
lemma coinduction {s₁ s₂ : stream α} :
head s₁ = head s₂ → (∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ :=
assume hh ht,
eq_of_bisim
(λ s₁ s₂, head s₁ = head s₂ ∧ ∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂))
(λ s₁ s₂ h,
have h₁ : head s₁ = head s₂, from and.elim_left h,
have h₂ : head (tail s₁) = head (tail s₂), from and.elim_right h α (@head α) h₁,
have h₃ : ∀ (β : Type u) (fr : stream α → β), fr (tail s₁) = fr (tail s₂) → fr (tail (tail s₁)) = fr (tail (tail s₂)), from
λ β fr, and.elim_right h β (λ s, fr (tail s)),
and.intro h₁ (and.intro h₂ h₃))
(and.intro hh ht)
lemma iterate_id (a : α) : iterate id a = const a :=
coinduction
rfl
(λ β fr ch, begin rw [tail_iterate, tail_const], exact ch end)
local attribute [reducible] stream
lemma map_iterate (f : α → α) (a : α) : iterate f (f a) = map f (iterate f a) :=
begin
apply funext, intro n,
induction n with n' ih,
{reflexivity},
{ unfold map iterate nth, dsimp,
unfold map iterate nth at ih, dsimp at ih,
rw ih }
end
section corec
def corec (f : α → β) (g : α → α) : α → stream β :=
λ a, map f (iterate g a)
def corec_on (a : α) (f : α → β) (g : α → α) : stream β :=
corec f g a
lemma corec_def (f : α → β) (g : α → α) (a : α) : corec f g a = map f (iterate g a) :=
rfl
lemma corec_eq (f : α → β) (g : α → α) (a : α) : corec f g a = f a :: corec f g (g a) :=
begin rw [corec_def, map_eq, head_iterate, tail_iterate], reflexivity end
lemma corec_id_id_eq_const (a : α) : corec id id a = const a :=
by rw [corec_def, map_id, iterate_id]
lemma corec_id_f_eq_iterate (f : α → α) (a : α) : corec id f a = iterate f a :=
rfl
end corec
-- corec is also known as unfold
def unfolds (g : α → β) (f : α → α) (a : α) : stream β :=
corec g f a
lemma unfolds_eq (g : α → β) (f : α → α) (a : α) : unfolds g f a = g a :: unfolds g f (f a) :=
begin unfold unfolds, rw [corec_eq] end
lemma nth_unfolds_head_tail : ∀ (n : nat) (s : stream α), nth n (unfolds head tail s) = nth n s :=
begin
intro n, induction n with n' ih,
{intro s, reflexivity},
{intro s, rw [nth_succ, nth_succ, unfolds_eq, tail_cons, ih]}
end
lemma unfolds_head_eq : ∀ (s : stream α), unfolds head tail s = s :=
λ s, stream.ext (λ n, nth_unfolds_head_tail n s)
def interleave (s₁ s₂ : stream α) : stream α :=
corec_on (s₁, s₂)
(λ ⟨s₁, s₂⟩, head s₁)
(λ ⟨s₁, s₂⟩, (s₂, tail s₁))
infix `⋈`:65 := interleave
lemma interleave_eq (s₁ s₂ : stream α) : s₁ ⋈ s₂ = head s₁ :: head s₂ :: (tail s₁ ⋈ tail s₂) :=
begin
unfold interleave corec_on, rw corec_eq, dsimp, rw corec_eq, reflexivity
end
lemma tail_interleave (s₁ s₂ : stream α) : tail (s₁ ⋈ s₂) = s₂ ⋈ (tail s₁) :=
begin unfold interleave corec_on, rw corec_eq, reflexivity end
lemma interleave_tail_tail (s₁ s₂ : stream α) : tail s₁ ⋈ tail s₂ = tail (tail (s₁ ⋈ s₂)) :=
begin rw [interleave_eq s₁ s₂], reflexivity end
lemma nth_interleave_left : ∀ (n : nat) (s₁ s₂ : stream α), nth (2*n) (s₁ ⋈ s₂) = nth n s₁
| 0 s₁ s₂ := rfl
| (succ n) s₁ s₂ :=
begin
change nth (succ (succ (2*n))) (s₁ ⋈ s₂) = nth (succ n) s₁,
rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_left],
reflexivity
end
lemma nth_interleave_right : ∀ (n : nat) (s₁ s₂ : stream α), nth (2*n+1) (s₁ ⋈ s₂) = nth n s₂
| 0 s₁ s₂ := rfl
| (succ n) s₁ s₂ :=
begin
change nth (succ (succ (2*n+1))) (s₁ ⋈ s₂) = nth (succ n) s₂,
rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_right],
reflexivity
end
lemma mem_interleave_left {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₁ → a ∈ s₁ ⋈ s₂ :=
assume ⟨n, h⟩,
exists.intro (2*n) (by rw [h, nth_interleave_left])
lemma mem_interleave_right {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₂ → a ∈ s₁ ⋈ s₂ :=
assume ⟨n, h⟩,
exists.intro (2*n+1) (by rw [h, nth_interleave_right])
def even (s : stream α) : stream α :=
corec
(λ s, head s)
(λ s, tail (tail s))
s
def odd (s : stream α) : stream α :=
even (tail s)
lemma odd_eq (s : stream α) : odd s = even (tail s) :=
rfl
lemma head_even (s : stream α) : head (even s) = head s :=
rfl
lemma tail_even (s : stream α) : tail (even s) = even (tail (tail s)) :=
begin unfold even, rw corec_eq, reflexivity end
lemma even_cons_cons (a₁ a₂ : α) (s : stream α) : even (a₁ :: a₂ :: s) = a₁ :: even s :=
begin unfold even, rw corec_eq, reflexivity end
lemma even_tail (s : stream α) : even (tail s) = odd s :=
rfl
lemma even_interleave (s₁ s₂ : stream α) : even (s₁ ⋈ s₂) = s₁ :=
eq_of_bisim
(λ s₁' s₁, ∃ s₂, s₁' = even (s₁ ⋈ s₂))
(λ s₁' s₁ ⟨s₂, h₁⟩,
begin
rw h₁,
constructor,
{refl},
{exact ⟨tail s₂, by rw [interleave_eq, even_cons_cons, tail_cons]⟩}
end)
(exists.intro s₂ rfl)
lemma interleave_even_odd (s₁ : stream α) : even s₁ ⋈ odd s₁ = s₁ :=
eq_of_bisim
(λ s' s, s' = even s ⋈ odd s)
(λ s' s (h : s' = even s ⋈ odd s),
begin
rw h, constructor,
{reflexivity},
{simp [odd_eq, odd_eq, tail_interleave, tail_even]}
end)
rfl
lemma nth_even : ∀ (n : nat) (s : stream α), nth n (even s) = nth (2*n) s
| 0 s := rfl
| (succ n) s :=
begin
change nth (succ n) (even s) = nth (succ (succ (2 * n))) s,
rw [nth_succ, nth_succ, tail_even, nth_even], reflexivity
end
lemma nth_odd : ∀ (n : nat) (s : stream α), nth n (odd s) = nth (2*n + 1) s :=
λ n s, begin rw [odd_eq, nth_even], reflexivity end
lemma mem_of_mem_even (a : α) (s : stream α) : a ∈ even s → a ∈ s :=
assume ⟨n, h⟩,
exists.intro (2*n) (by rw [h, nth_even])
lemma mem_of_mem_odd (a : α) (s : stream α) : a ∈ odd s → a ∈ s :=
assume ⟨n, h⟩,
exists.intro (2*n+1) (by rw [h, nth_odd])
def append_stream : list α → stream α → stream α
| [] s := s
| (list.cons a l) s := a :: append_stream l s
lemma nil_append_stream (s : stream α) : append_stream [] s = s :=
rfl
lemma cons_append_stream (a : α) (l : list α) (s : stream α) : append_stream (a::l) s = a :: append_stream l s :=
rfl
infix `++ₛ`:65 := append_stream
lemma append_append_stream : ∀ (l₁ l₂ : list α) (s : stream α), (l₁ ++ l₂) ++ₛ s = l₁ ++ₛ (l₂ ++ₛ s)
| [] l₂ s := rfl
| (list.cons a l₁) l₂ s := by rw [list.cons_append, cons_append_stream, cons_append_stream, append_append_stream]
lemma map_append_stream (f : α → β) : ∀ (l : list α) (s : stream α), map f (l ++ₛ s) = list.map f l ++ₛ map f s
| [] s := rfl
| (list.cons a l) s := by rw [cons_append_stream, list.map_cons, map_cons, cons_append_stream, map_append_stream]
lemma drop_append_stream : ∀ (l : list α) (s : stream α), drop l.length (l ++ₛ s) = s
| [] s := by reflexivity
| (list.cons a l) s := by rw [list.length_cons, add_one_eq_succ, drop_succ, cons_append_stream, tail_cons, drop_append_stream]
lemma append_stream_head_tail (s : stream α) : [head s] ++ₛ tail s = s :=
by rw [cons_append_stream, nil_append_stream, stream.eta]
lemma mem_append_stream_right : ∀ {a : α} (l : list α) {s : stream α}, a ∈ s → a ∈ l ++ₛ s
| a [] s h := h
| a (list.cons b l) s h :=
have ih : a ∈ l ++ₛ s, from mem_append_stream_right l h,
mem_cons_of_mem _ ih
lemma mem_append_stream_left : ∀ {a : α} {l : list α} (s : stream α), a ∈ l → a ∈ l ++ₛ s
| a [] s h := absurd h (list.not_mem_nil _)
| a (list.cons b l) s h :=
or.elim (list.eq_or_mem_of_mem_cons h)
(λ (aeqb : a = b), exists.intro 0 aeqb)
(λ (ainl : a ∈ l), mem_cons_of_mem b (mem_append_stream_left s ainl))
def approx : nat → stream α → list α
| 0 s := []
| (n+1) s := list.cons (head s) (approx n (tail s))
lemma approx_zero (s : stream α) : approx 0 s = [] :=
rfl
lemma approx_succ (n : nat) (s : stream α) : approx (succ n) s = head s :: approx n (tail s) :=
rfl
lemma nth_approx : ∀ (n : nat) (s : stream α), list.nth (approx (succ n) s) n = some (nth n s)
| 0 s := rfl
| (n+1) s := begin rw [approx_succ, add_one_eq_succ, list.nth_succ, nth_approx], reflexivity end
lemma append_approx_drop : ∀ (n : nat) (s : stream α), append_stream (approx n s) (drop n s) = s :=
begin
intro n,
induction n with n' ih,
{intro s, reflexivity},
{intro s, rw [approx_succ, drop_succ, cons_append_stream, ih (tail s), stream.eta]}
end
-- Take lemma reduces a proof of equality of infinite streams to an
-- induction over all their finite approximations.
lemma take_lemma (s₁ s₂ : stream α) : (∀ (n : nat), approx n s₁ = approx n s₂) → s₁ = s₂ :=
begin
intro h, apply stream.ext, intro n,
induction n with n ih,
{ note aux := h 1, unfold approx at aux, injection aux },
{ assert h₁ : some (nth (succ n) s₁) = some (nth (succ n) s₂),
{ rw [-nth_approx, -nth_approx, h (succ (succ n))] },
injection h₁ }
end
-- auxiliary def for cycle corecursive def
private def cycle_f : α × list α × α × list α → α
| (v, _, _, _) := v
-- auxiliary def for cycle corecursive def
private def cycle_g : α × list α × α × list α → α × list α × α × list α
| (v₁, [], v₀, l₀) := (v₀, l₀, v₀, l₀)
| (v₁, list.cons v₂ l₂, v₀, l₀) := (v₂, l₂, v₀, l₀)
private lemma cycle_g_cons (a : α) (a₁ : α) (l₁ : list α) (a₀ : α) (l₀ : list α) :
cycle_g (a, a₁::l₁, a₀, l₀) = (a₁, l₁, a₀, l₀) :=
rfl
def cycle : Π (l : list α), l ≠ [] → stream α
| [] h := absurd rfl h
| (list.cons a l) h := corec cycle_f cycle_g (a, l, a, l)
lemma cycle_eq : ∀ (l : list α) (h : l ≠ []), cycle l h = l ++ₛ cycle l h
| [] h := absurd rfl h
| (list.cons a l) h :=
have gen : ∀ l' a', corec cycle_f cycle_g (a', l', a, l) = (a' :: l') ++ₛ corec cycle_f cycle_g (a, l, a, l),
begin
intro l',
induction l' with a₁ l₁ ih,
{intros, rw [corec_eq], reflexivity},
{intros, rw [corec_eq, cycle_g_cons, ih a₁], reflexivity}
end,
gen l a
lemma mem_cycle {a : α} {l : list α} : ∀ (h : l ≠ []), a ∈ l → a ∈ cycle l h :=
assume h ainl, begin rw [cycle_eq], exact mem_append_stream_left _ ainl end
lemma cycle_singleton (a : α) (h : [a] ≠ []) : cycle [a] h = const a :=
coinduction
rfl
(λ β fr ch, by rwa [cycle_eq, const_eq])
def tails (s : stream α) : stream (stream α) :=
corec id tail (tail s)
lemma tails_eq (s : stream α) : tails s = tail s :: tails (tail s) :=
by unfold tails; rw [corec_eq]; reflexivity
lemma nth_tails : ∀ (n : nat) (s : stream α), nth n (tails s) = drop n (tail s) :=
begin
intro n, induction n with n' ih,
{intros, reflexivity},
{intro s, rw [nth_succ, drop_succ, tails_eq, tail_cons, ih]}
end
lemma tails_eq_iterate (s : stream α) : tails s = iterate tail (tail s) :=
rfl
def inits_core (l : list α) (s : stream α) : stream (list α) :=
corec_on (l, s)
(λ ⟨a, b⟩, a)
(λ p, match p with (l', s') := (l' ++ [head s'], tail s') end)
def inits (s : stream α) : stream (list α) :=
inits_core [head s] (tail s)
lemma inits_core_eq (l : list α) (s : stream α) : inits_core l s = l :: inits_core (l ++ [head s]) (tail s) :=
begin unfold inits_core corec_on, rw [corec_eq], reflexivity end
lemma tail_inits (s : stream α) : tail (inits s) = inits_core [head s, head (tail s)] (tail (tail s)) :=
begin unfold inits, rw inits_core_eq, reflexivity end
lemma inits_tail (s : stream α) : inits (tail s) = inits_core [head (tail s)] (tail (tail s)) :=
rfl
lemma cons_nth_inits_core : ∀ (a : α) (n : nat) (l : list α) (s : stream α),
a :: nth n (inits_core l s) = nth n (inits_core (a::l) s) :=
begin
intros a n,
induction n with n' ih,
{intros, reflexivity},
{intros l s, rw [nth_succ, inits_core_eq, tail_cons, ih, inits_core_eq (a::l) s], reflexivity }
end
lemma nth_inits : ∀ (n : nat) (s : stream α), nth n (inits s) = approx (succ n) s :=
begin
intro n, induction n with n' ih,
{intros, reflexivity},
{intros, rw [nth_succ, approx_succ, -ih, tail_inits, inits_tail, cons_nth_inits_core]}
end
lemma inits_eq (s : stream α) : inits s = [head s] :: map (list.cons (head s)) (inits (tail s)) :=
begin
apply stream.ext, intro n,
cases n,
{reflexivity},
{rw [nth_inits, nth_succ, tail_cons, nth_map, nth_inits], reflexivity}
end
lemma zip_inits_tails (s : stream α) : zip append_stream (inits s) (tails s) = const s :=
begin
apply stream.ext, intro n,
rw [nth_zip, nth_inits, nth_tails, nth_const, approx_succ,
cons_append_stream, append_approx_drop, stream.eta]
end
def pure (a : α) : stream α :=
const a
def apply (f : stream (α → β)) (s : stream α) : stream β :=
λ n, (nth n f) (nth n s)
infix `⊛`:75 := apply -- input as \o*
lemma identity (s : stream α) : pure id ⊛ s = s :=
rfl
lemma composition (g : stream (β → δ)) (f : stream (α → β)) (s : stream α) : pure comp ⊛ g ⊛ f ⊛ s = g ⊛ (f ⊛ s) :=
rfl
lemma homomorphism (f : α → β) (a : α) : pure f ⊛ pure a = pure (f a) :=
rfl
lemma interchange (fs : stream (α → β)) (a : α) : fs ⊛ pure a = pure (λ f : α → β, f a) ⊛ fs :=
rfl
lemma map_eq_apply (f : α → β) (s : stream α) : map f s = pure f ⊛ s :=
rfl
def nats : stream nat :=
λ n, n
lemma nth_nats (n : nat) : nth n nats = n :=
rfl
lemma nats_eq : nats = 0 :: map succ nats :=
begin
apply stream.ext, intro n,
cases n, reflexivity, rw [nth_succ], reflexivity
end
end stream
|
92a5116cec5845e5f8bcc2d227d16d7a0ddb06b1 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/rw_set1.lean | a4e6a7d60952e05747127c3773c872a103c17c7f | [
"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 | 293 | lean | constant nat.add_assoc (a b c : nat) : (a + b) + c = a + (b + c)
namespace foo
attribute nat.add_assoc [simp]
print nat.add_assoc
end foo
print nat.add_assoc
namespace foo
print nat.add_assoc
attribute nat.add_comm [simp]
open nat
print "---------"
print [simp] simp
end foo
|
d2cc85599cb55318f0b29721d53337cc94bb7b99 | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/data/list/basic.lean | b8c019daf34dd17da211c078d86df3a3925322df | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 202,467 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import control.monad.basic
import data.nat.basic
import order.rel_classes
import algebra.group_power.basic
/-!
# Basic properties of lists
-/
open function nat
namespace list
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
attribute [inline] list.head
instance : is_left_id (list α) has_append.append [] :=
⟨ nil_append ⟩
instance : is_right_id (list α) has_append.append [] :=
⟨ append_nil ⟩
instance : is_associative (list α) has_append.append :=
⟨ append_assoc ⟩
theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ [].
theorem cons_ne_self (a : α) (l : list α) : a::l ≠ l :=
mt (congr_arg length) (nat.succ_ne_self _)
theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → h₁ = h₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq)
theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → t₁ = t₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq)
@[simp] theorem cons_injective {a : α} : injective (cons a) :=
assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe
theorem cons_inj (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' :=
cons_injective.eq_iff
theorem exists_cons_of_ne_nil {l : list α} (h : l ≠ nil) : ∃ b L, l = b :: L :=
by { induction l with c l', contradiction, use [c,l'], }
/-! ### mem -/
theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _
theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b :=
assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, this)
(assume : a ∈ [], absurd this (not_mem_nil a))
@[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b :=
⟨eq_of_mem_singleton, or.inl⟩
theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl)
(assume : a = b, begin subst a, exact binl end)
(assume : a ∈ l, this)
theorem _root_.decidable.list.eq_or_ne_mem_of_mem [decidable_eq α]
{a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) :=
decidable.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩
theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} : a ∈ b :: l → a = b ∨ (a ≠ b ∧ a ∈ l) :=
by classical; exact decidable.list.eq_or_ne_mem_of_mem
theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t :=
mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩
theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] :=
by intro e; rw e at h; cases h
theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t :=
begin
induction l with b l ih, {cases h}, rcases h with rfl | h,
{ exact ⟨[], l, rfl⟩ },
{ rcases ih h with ⟨s, t, rfl⟩,
exact ⟨b::s, t, rfl⟩ }
end
theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l :=
or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r)
theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (or.inl aeqb) nin
theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (or.inr nainl) nin
theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l :=
assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2))
theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l :=
assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p)
theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l :=
begin
induction l with b l' ih,
{cases h},
{rcases h with rfl | h,
{exact or.inl rfl},
{exact or.inr (ih h)}}
end
theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) :
∃ a, a ∈ l ∧ f a = b :=
begin
induction l with c l' ih,
{cases h},
{cases (eq_or_mem_of_mem_cons h) with h h,
{exact ⟨c, mem_cons_self _ _, h.symm⟩},
{rcases ih h with ⟨a, ha₁, ha₂⟩,
exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }}
end
@[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b :=
⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩
theorem mem_map_of_injective {f : α → β} (H : injective f) {a : α} {l : list α} :
f a ∈ map f l ↔ a ∈ l :=
⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩
lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} :
(∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) :=
begin
split,
{ assume H j hj,
exact H (f j) (mem_map_of_mem f hj) },
{ assume H i hi,
rcases mem_map.1 hi with ⟨j, hj, ji⟩,
rw ← ji,
exact H j hj }
end
@[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] :=
⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff],
λ h, h.symm ▸ rfl⟩
@[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l
| [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩
| (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right,
exists_or_distrib, exists_eq_left]
theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l :=
mem_join.1
theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L :=
mem_join.2 ⟨l, lL, al⟩
@[simp]
theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a :=
iff.trans mem_join
⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩,
λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩
theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} :
b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a :=
mem_bind.1
theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) :
b ∈ list.bind l f :=
mem_bind.2 ⟨a, al, h⟩
lemma bind_map {g : α → list β} {f : β → γ} :
∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f)
| [] := rfl
| (a::l) := by simp only [cons_bind, map_append, bind_map l]
lemma map_bind (g : β → list γ) (f : α → β) :
∀ l : list α, (list.map f l).bind g = l.bind (λ a, g (f a))
| [] := rfl
| (a::l) := by simp only [cons_bind, map_cons, map_bind l]
/-! ### length -/
theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] :=
⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩
@[simp] lemma length_singleton (a : α) : length [a] = 1 := rfl
theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l
| (b::l) _ := zero_lt_succ _
theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l
| (b::l) _ := ⟨b, mem_cons_self _ _⟩
theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l :=
⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩
theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] :=
λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1)
theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l :=
λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0
theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] :=
⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩
lemma exists_mem_of_ne_nil (l : list α) (h : l ≠ []) : ∃ x, x ∈ l :=
exists_mem_of_length_pos (length_pos_of_ne_nil h)
theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] :=
⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩
lemma exists_of_length_succ {n} :
∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t
| [] H := absurd H.symm $ succ_ne_zero n
| (h :: t) H := ⟨h, t, rfl⟩
@[simp] lemma length_injective_iff : injective (list.length : list α → ℕ) ↔ subsingleton α :=
begin
split,
{ intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl },
{ intros hα l1 l2 hl, induction l1 generalizing l2; cases l2,
{ refl }, { cases hl }, { cases hl },
congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl }
end
@[simp] lemma length_injective [subsingleton α] : injective (length : list α → ℕ) :=
length_injective_iff.mpr $ by apply_instance
/-! ### set-theoretic notation of lists -/
lemma empty_eq : (∅ : list α) = [] := by refl
lemma singleton_eq (x : α) : ({x} : list α) = [x] := rfl
lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) :
has_insert.insert x l = x :: l :=
if_neg h
lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) :
has_insert.insert x l = l :=
if_pos h
lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [x, y] :=
by { rw [insert_neg, singleton_eq], rwa [singleton_eq, mem_singleton] }
/-! ### bounded quantifiers over lists -/
theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x.
theorem forall_mem_cons : ∀ {p : α → Prop} {a : α} {l : list α},
(∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x :=
ball_cons
theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α}
(h : ∀ x ∈ a :: l, p x) :
∀ x ∈ l, p x :=
(forall_mem_cons.1 h).2
theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a :=
by simp only [mem_singleton, forall_eq]
theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_append, or_imp_distrib, forall_and_distrib]
theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x.
theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) :
∃ x ∈ a :: l, p x :=
bex.intro a (mem_cons_self _ _) h
theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) :
∃ x ∈ a :: l, p x :=
bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px)
theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) :
p a ∨ ∃ x ∈ l, p x :=
bex.elim h (λ x xal px,
or.elim (eq_or_mem_of_mem_cons xal)
(assume : x = a, begin rw ←this, left, exact px end)
(assume : x ∈ l, or.inr (bex.intro x this px)))
theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) :
(∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x :=
iff.intro or_exists_of_exists_mem_cons
(assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists)
/-! ### list subset -/
theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl
theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_left _ _
theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_right _ _
@[simp] theorem cons_subset {a : α} {l m : list α} :
a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m :=
by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq]
theorem cons_subset_of_subset_of_mem {a : α} {l m : list α}
(ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m :=
cons_subset.2 ⟨ainm, lsubm⟩
theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) :
l₁ ++ l₂ ⊆ l :=
λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _)
@[simp] theorem append_subset_iff {l₁ l₂ l : list α} :
l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l :=
begin
split,
{ intro h, simp only [subset_def] at *, split; intros; simp* },
{ rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 }
end
theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = []
| [] s := rfl
| (a::l) s := false.elim $ s $ mem_cons_self a l
theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l :=
show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩
theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ :=
λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩
theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) :
map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ :=
begin
refine ⟨_, map_subset f⟩, intros h2 x hx,
rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩,
cases h hxx', exact hx'
end
/-! ### append -/
lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl
@[simp] lemma singleton_append {x : α} {l : list α} : [x] ++ l = x :: l := rfl
theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
@[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] :=
by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and]
@[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] :=
by rw [eq_comm, append_eq_nil]
lemma append_eq_cons_iff {a b c : list α} {x : α} :
a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true,
true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left']
lemma cons_eq_append_iff {a b c : list α} {x : α} :
(x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by rw [eq_comm, append_eq_cons_iff]
lemma append_eq_append_iff {a b c d : list α} :
a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) :=
begin
induction a generalizing c,
case nil { rw nil_append, split,
{ rintro rfl, left, exact ⟨_, rfl, rfl⟩ },
{ rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } },
case cons : a as ih {
cases c,
{ simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'],
exact eq_comm },
{ simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left,
exists_and_distrib_left] } }
end
@[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l)
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop]
@[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs
-- TODO(Leo): cleanup proof after arith dec proc
theorem append_inj :
∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂
| [] [] t₁ t₂ h hl := ⟨rfl, h⟩
| (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl
| [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm
| (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap,
let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in
by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩
theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length s₁ = length s₂) : t₁ = t₂ :=
(append_inj h hl).right
theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length s₁ = length s₂) : s₁ = s₂ :=
(append_inj h hl).left
theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) :
s₁ = s₂ ∧ t₁ = t₂ :=
append_inj h $ @nat.add_right_cancel _ (length t₁) _ $
let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap
theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length t₁ = length t₂) : t₁ = t₂ :=
(append_inj' h hl).right
theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length t₁ = length t₂) : s₁ = s₂ :=
(append_inj' h hl).left
theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ :=
append_inj_right h rfl
theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ :=
append_inj_left' h rfl
theorem append_right_injective (s : list α) : function.injective (λ t, s ++ t) :=
λ t₁ t₂, append_left_cancel
theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ :=
(append_right_injective s).eq_iff
theorem append_left_injective (t : list α) : function.injective (λ s, s ++ t) :=
λ s₁ s₂, append_right_cancel
theorem append_left_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ :=
(append_left_injective t).eq_iff
theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β}
(h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ :=
begin
have := h, rw [← take_append_drop (length s₁) l] at this ⊢,
rw map_append at this,
refine ⟨_, _, rfl, append_inj this _⟩,
rw [length_map, length_take, min_eq_left],
rw [← length_map f l, h, length_append],
apply nat.le_add_right
end
/-! ### repeat -/
@[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl
theorem mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n ↔ n ≠ 0 ∧ b = a
| 0 := by simp
| (n + 1) := by simp [mem_repeat]
theorem eq_of_mem_repeat {a b : α} {n} (h : b ∈ repeat a n) : b = a :=
(mem_repeat.1 h).2
theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length
| [] H := rfl
| (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂;
unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂]
theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩
theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n :=
by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl
theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] :=
λ b h, mem_singleton.2 (eq_of_mem_repeat h)
@[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) :
b₁ = b₂ :=
by rw map_const at h; exact eq_of_mem_repeat h
@[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n :=
by induction n; [refl, simp only [*, repeat, map]]; split; refl
@[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred :=
by cases n; refl
@[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α :=
by induction n; [refl, simp only [*, repeat, join, append_nil]]
lemma repeat_left_injective {n : ℕ} (hn : n ≠ 0) :
function.injective (λ a : α, repeat a n) :=
λ a b h, (eq_repeat.1 h).2 _ $ mem_repeat.2 ⟨hn, rfl⟩
lemma repeat_left_inj {a b : α} {n : ℕ} (hn : n ≠ 0) :
repeat a n = repeat b n ↔ a = b :=
(repeat_left_injective hn).eq_iff
@[simp] lemma repeat_left_inj' {a b : α} :
∀ {n}, repeat a n = repeat b n ↔ n = 0 ∨ a = b
| 0 := by simp
| (n + 1) := (repeat_left_inj n.succ_ne_zero).trans $ by simp only [n.succ_ne_zero, false_or]
lemma repeat_right_injective (a : α) : function.injective (repeat a) :=
function.left_inverse.injective (length_repeat a)
@[simp] lemma repeat_right_inj {a : α} {n m : ℕ} :
repeat a n = repeat a m ↔ n = m :=
(repeat_right_injective a).eq_iff
/-! ### pure -/
@[simp] theorem mem_pure {α} (x y : α) :
x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret]
/-! ### bind -/
@[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) :
l >>= f = l.bind f := rfl
-- TODO: duplicate of a lemma in core
theorem bind_append (f : α → list β) (l₁ l₂ : list α) :
(l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f :=
append_bind _ _ _
@[simp] theorem bind_singleton (f : α → list β) (x : α) : [x].bind f = f x :=
append_nil (f x)
@[simp] theorem bind_singleton' (l : list α) : l.bind (λ x, [x]) = l := bind_pure l
theorem map_eq_bind {α β} (f : α → β) (l : list α) : map f l = l.bind (λ x, [f x]) :=
by { transitivity, rw [← bind_singleton' l, bind_map], refl }
theorem bind_assoc {α β} (l : list α) (f : α → list β) (g : β → list γ) :
(l.bind f).bind g = l.bind (λ x, (f x).bind g) :=
by induction l; simp *
/-! ### concat -/
theorem concat_nil (a : α) : concat [] a = [a] := rfl
theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl
@[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] :=
by induction l; simp only [*, concat]; split; refl
theorem init_eq_of_concat_eq {a : α} {l₁ l₂ : list α} : concat l₁ a = concat l₂ a → l₁ = l₂ :=
begin
intro h,
rw [concat_eq_append, concat_eq_append] at h,
exact append_right_cancel h
end
theorem last_eq_of_concat_eq {a b : α} {l : list α} : concat l a = concat l b → a = b :=
begin
intro h,
rw [concat_eq_append, concat_eq_append] at h,
exact head_eq_of_cons_eq (append_left_cancel h)
end
theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] :=
by simp
theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ :=
by simp
theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) :=
by simp only [concat_eq_append, length_append, length]
theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a :=
by simp
/-! ### reverse -/
@[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl
local attribute [simp] reverse_core
@[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] :=
have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]),
by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]],
(aux l nil).symm
theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ :=
by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]];
refl
theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a :=
by simp only [reverse_cons, concat_eq_append]
@[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl
@[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) :=
by induction s; [rw [nil_append, reverse_nil, append_nil],
simp only [*, cons_append, reverse_cons, append_assoc]]
theorem reverse_concat (l : list α) (a : α) : reverse (concat l a) = a :: reverse l :=
by rw [concat_eq_append, reverse_append, reverse_singleton, singleton_append]
@[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l :=
by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl
@[simp] theorem reverse_involutive : involutive (@reverse α) :=
λ l, reverse_reverse l
@[simp] theorem reverse_injective : injective (@reverse α) :=
reverse_involutive.injective
@[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ :=
reverse_injective.eq_iff
lemma reverse_eq_iff {l l' : list α} :
l.reverse = l' ↔ l = l'.reverse :=
reverse_involutive.eq_iff
@[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] :=
@reverse_inj _ l []
theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) :=
by simp only [concat_eq_append, reverse_cons, reverse_reverse]
@[simp] theorem length_reverse (l : list α) : length (reverse l) = length l :=
by induction l; [refl, simp only [*, reverse_cons, length_append, length]]
@[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) :=
by induction l; [refl, simp only [*, map, reverse_cons, map_append]]
theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) :
map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) :=
by simp only [reverse_core_eq, map_append, map_reverse]
@[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l :=
by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff,
not_mem_nil, false_or, or_false, or_comm]]
@[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n :=
eq_repeat.2 ⟨by simp only [length_reverse, length_repeat],
λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩
/-! ### empty -/
attribute [simp] list.empty
lemma empty_iff_eq_nil {l : list α} : l.empty ↔ l = [] :=
list.cases_on l (by simp) (by simp)
/-! ### init -/
@[simp] theorem length_init : ∀ (l : list α), length (init l) = length l - 1
| [] := rfl
| [a] := rfl
| (a :: b :: l) :=
begin
rw init,
simp only [add_left_inj, length, succ_add_sub_one],
exact length_init (b :: l)
end
/-! ### last -/
@[simp] theorem last_cons {a : α} {l : list α} :
∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ :=
by {induction l; intros, contradiction, reflexivity}
@[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a :=
by induction l;
[refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]]
theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a :=
by simp only [concat_eq_append, last_append]
@[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl
@[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) :
last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl
theorem init_append_last : ∀ {l : list α} (h : l ≠ []), init l ++ [last l h] = l
| [] h := absurd rfl h
| [a] h := rfl
| (a::b::l) h :=
begin
rw [init, cons_append, last_cons (cons_ne_nil _ _) (cons_ne_nil _ _)],
congr,
exact init_append_last (cons_ne_nil b l)
end
theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) :
last l₁ h₁ = last l₂ h₂ :=
by subst l₁
theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l
| [] h := absurd rfl h
| [a] h := or.inl rfl
| (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) }
lemma last_repeat_succ (a m : ℕ) :
(repeat a m.succ).last (ne_nil_of_length_eq_succ
(show (repeat a m.succ).length = m.succ, by rw length_repeat)) = a :=
begin
induction m with k IH,
{ simp },
{ simpa only [repeat_succ, last] }
end
/-! ### last' -/
@[simp] theorem last'_is_none :
∀ {l : list α}, (last' l).is_none ↔ l = []
| [] := by simp
| [a] := by simp
| (a::b::l) := by simp [@last'_is_none (b::l)]
@[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ []
| [] := by simp
| [a] := by simp
| (a::b::l) := by simp [@last'_is_some (b::l)]
theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h
| [] x hx := false.elim $ by simpa using hx
| [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩
| (a::b::l) x hx :=
begin
rw last' at hx,
rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩,
use cons_ne_nil _ _,
rwa [last_cons]
end
theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l :=
let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _
theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l
| [] a ha := (option.not_mem_none a ha).elim
| [a] _ rfl := rfl
| (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] }
theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget
| [] := by simp [ilast, arbitrary]
| [a] := rfl
| [a, b] := rfl
| [a, b, c] := rfl
| (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)]
@[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α),
last' (l₁ ++ a :: l₂) = last' (a :: l₂)
| [] a l₂ := rfl
| [b] a l₂ := rfl
| (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons]
theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []),
last' (l₁ ++ l₂) = last' l₂
| [] hl₂ := by contradiction
| (b::l₂) _ := last'_append_cons l₁ b l₂
/-! ### head(') and tail -/
theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget :=
by cases l; refl
theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l
| [] h := (option.not_mem_none _ h).elim
| (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl }
@[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl
@[simp] theorem tail_nil : tail (@nil α) = [] := rfl
@[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl
@[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) :
head (s ++ t) = head s :=
by {induction s, contradiction, refl}
theorem tail_append_singleton_of_ne_nil {a : α} {l : list α} (h : l ≠ nil) :
tail (l ++ [a]) = tail l ++ [a] :=
by { induction l, contradiction, rw [tail,cons_append,tail], }
theorem cons_head'_tail : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l
| [] a h := by contradiction
| (b::l) a h := by { simp at h, simp [h] }
theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l
| [] h := by contradiction
| (a::l) h := rfl
theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l :=
cons_head'_tail (head_mem_head' h)
lemma head_mem_self [inhabited α] {l : list α} (h : l ≠ nil) : l.head ∈ l :=
begin
have h' := mem_cons_self l.head l.tail,
rwa cons_head_tail h at h',
end
@[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := by cases l; refl
lemma tail_append_of_ne_nil (l l' : list α) (h : l ≠ []) :
(l ++ l').tail = l.tail ++ l' :=
begin
cases l,
{ contradiction },
{ simp }
end
/-! ### Induction from the right -/
/-- Induction principle from the right for lists: if a property holds for the empty list, and
for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
@[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*}
(l : list α) (H0 : C [])
(H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l :=
begin
rw ← reverse_reverse l,
induction reverse l,
{ exact H0 },
{ rw reverse_cons, exact H1 _ _ ih }
end
/-- Bidirectional induction principle for lists: if a property holds for the empty list, the
singleton list, and `a :: (l ++ [b])` from `l`, then it holds for all lists. This can be used to
prove statements about palindromes. The principle is given for a `Sort`-valued predicate, i.e., it
can also be used to construct data. -/
def bidirectional_rec {C : list α → Sort*}
(H0 : C []) (H1 : ∀ (a : α), C [a])
(Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : ∀ l, C l
| [] := H0
| [a] := H1 a
| (a :: b :: l) :=
let l' := init (b :: l), b' := last (b :: l) (cons_ne_nil _ _) in
have length l' < length (a :: b :: l), by { change _ < length l + 2, simp },
begin
rw ←init_append_last (cons_ne_nil b l),
have : C l', from bidirectional_rec l',
exact Hn a l' b' ‹C l'›
end
using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf list.length⟩] }
/-- Like `bidirectional_rec`, but with the list parameter placed first. -/
@[elab_as_eliminator] def bidirectional_rec_on {C : list α → Sort*}
(l : list α) (H0 : C []) (H1 : ∀ (a : α), C [a])
(Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : C l :=
bidirectional_rec H0 H1 Hn l
/-! ### sublists -/
@[simp] theorem nil_sublist : Π (l : list α), [] <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons _ _ a (nil_sublist l)
@[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons2 _ _ a (sublist.refl l)
@[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ :=
sublist.rec_on h₂ (λ_ s, s)
(λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁))
(λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁
(λ_, nil_sublist _)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ :=
sublist.cons _ _ _ (IH _ h₁) end)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ :=
sublist.cons2 _ _ _ (IH _ h₁) end) rfl)
l₁ h₁
@[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l :=
sublist.cons _ _ _ (sublist.refl l)
theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ :=
sublist.trans (sublist_cons a l₁)
theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ :=
sublist.cons2 _ _ _ s
@[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂
| [] l₂ := nil_sublist _
| (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂)
@[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂
| [] l₂ := sublist.refl _
| (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂)
theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ :=
sublist.cons _ _ _
theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ :=
s.trans $ sublist_append_left _ _
theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ :=
s.trans $ sublist_append_right _ _
theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂
| ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s
| ._ (sublist.cons2 ._ ._ a s) := s
theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ :=
⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩
@[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂
| [] := iff.rfl
| (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l)
theorem sublist.append_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l :=
begin
induction h with _ _ a _ ih _ _ a _ ih,
{ refl },
{ apply sublist_cons_of_sublist a ih },
{ apply cons_sublist_cons a ih }
end
theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) :
l <+ l₁ ++ l₂ ∨ a ∈ l :=
begin
induction l₁ with b l₁ IH generalizing l,
{ cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } },
{ cases h with _ _ _ h _ _ _ h,
{ exact or.imp_left (sublist_cons_of_sublist _) (IH h) },
{ exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } }
end
theorem sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse :=
begin
induction h with _ _ _ _ ih _ _ a _ ih, {refl},
{ rw reverse_cons, exact sublist_append_of_sublist_left ih },
{ rw [reverse_cons, reverse_cons], exact ih.append_right [a] }
end
@[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ :=
⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩
@[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ :=
⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff]
using h.reverse,
λ h, h.append_right l⟩
theorem sublist.append {l₁ l₂ r₁ r₂ : list α}
(hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ :=
(hl.append_right _).trans ((append_sublist_append_left _).2 hr)
theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂
| ._ ._ sublist.slnil b h := h
| ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset s h)
| ._ ._ (sublist.cons2 l₁ l₂ a s) b h :=
match eq_or_mem_of_mem_cons h with
| or.inl h := h ▸ mem_cons_self _ _
| or.inr h := mem_cons_of_mem _ (sublist.subset s h)
end
theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l :=
⟨λ h, h.subset (mem_singleton_self _), λ h,
let ⟨s, t, e⟩ := mem_split h in e.symm ▸
(cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩
theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] :=
eq_nil_of_subset_nil $ s.subset
@[simp] theorem sublist_nil_iff_eq_nil {l : list α} : l <+ [] ↔ l = [] :=
⟨eq_nil_of_sublist_nil, λ H, H ▸ sublist.refl _⟩
theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n :=
⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h,
λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩
theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂
| ._ ._ sublist.slnil h := rfl
| ._ ._ (sublist.cons l₁ l₂ a s) h :=
absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self
| ._ ._ (sublist.cons2 l₁ l₂ a s) h :=
by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h
theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) :
l₁ = l₂ :=
eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h)
theorem sublist.antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂)
instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂)
| [] l₂ := is_true $ nil_sublist _
| (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h
| (a::l₁) (b::l₂) :=
if h : a = b then
decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $
by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩
else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂)
⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with
| a, l₁, sublist.cons ._ ._ ._ s', h := s'
| ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h
end⟩
/-! ### index_of -/
section index_of
variable [decidable_eq α]
@[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl
theorem index_of_cons (a b : α) (l : list α) :
index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl
theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 :=
assume e, if_pos e
@[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 :=
index_of_cons_eq _ rfl
@[simp, priority 990]
theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) :=
assume n, if_neg n
theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l :=
begin
induction l with b l ih,
{ exact iff_of_true rfl (not_mem_nil _) },
simp only [length, mem_cons_iff, index_of_cons], split_ifs,
{ exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) },
{ simp only [h, false_or], rw ← ih, exact succ_inj' }
end
@[simp, priority 980]
theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l :=
index_of_eq_length.2
theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l :=
begin
induction l with b l ih, {refl},
simp only [length, index_of_cons],
by_cases h : a = b, {rw if_pos h, exact nat.zero_le _},
rw if_neg h, exact succ_le_succ ih
end
theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l :=
⟨λh, decidable.by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al,
λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩
end index_of
/-! ### nth element -/
theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a
| a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩
| a (b :: l) (or.inr m) :=
let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩
theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h)
| (a :: l) 0 h := rfl
| (a :: l) (n+1) h := @nth_le_nth l n _
theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none
| [] n h := rfl
| (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h)
theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a :=
⟨λ e,
have h : n < length l, from lt_of_not_ge $ λ hn,
by rw nth_len_le hn at e; contradiction,
⟨h, by rw nth_le_nth h at e;
injection e with e; apply nth_le_mem⟩,
λ ⟨h, e⟩, e ▸ nth_le_nth _⟩
@[simp]
theorem nth_eq_none_iff : ∀ {l : list α} {n}, nth l n = none ↔ length l ≤ n :=
begin
intros, split,
{ intro h, by_contradiction h',
have h₂ : ∃ h, l.nth_le n h = l.nth_le n (lt_of_not_ge h') := ⟨lt_of_not_ge h', rfl⟩,
rw [← nth_eq_some, h] at h₂, cases h₂ },
{ solve_by_elim [nth_len_le] },
end
theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a :=
let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩
theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l
| (a :: l) 0 h := mem_cons_self _ _
| (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _)
theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l :=
let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _
theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a :=
⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩
theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a :=
mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm
lemma nth_zero (l : list α) : l.nth 0 = l.head' := by cases l; refl
lemma nth_injective {α : Type u} {xs : list α} {i j : ℕ}
(h₀ : i < xs.length)
(h₁ : nodup xs)
(h₂ : xs.nth i = xs.nth j) : i = j :=
begin
induction xs with x xs generalizing i j,
{ cases h₀ },
{ cases i; cases j,
case nat.zero nat.zero
{ refl },
case nat.succ nat.succ
{ congr, cases h₁,
apply xs_ih;
solve_by_elim [lt_of_succ_lt_succ] },
iterate 2
{ dsimp at h₂,
cases h₁ with _ _ h h',
cases h x _ rfl,
rw mem_iff_nth,
exact ⟨_, h₂.symm⟩ <|>
exact ⟨_, h₂⟩ } },
end
@[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f
| [] n := rfl
| (a :: l) 0 := rfl
| (a :: l) (n+1) := nth_map l n
theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) :=
option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl
/-- A version of `nth_le_map` that can be used for rewriting. -/
theorem nth_le_map_rev (f : α → β) {l n} (H) :
f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) :=
(nth_le_map f _ _).symm
@[simp] theorem nth_le_map' (f : α → β) {l n} (H) :
nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) :=
nth_le_map f _ _
/-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as
`hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make
such a rewrite, with `rw (nth_le_of_eq h)`. -/
lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) :
nth_le L i hi = nth_le L' i (h ▸ hi) :=
by { congr, exact h}
@[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) :
nth_le [a] n hn = a :=
have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn),
by subst hn0; refl
lemma nth_le_zero [inhabited α] {L : list α} (h : 0 < L.length) :
L.nth_le 0 h = L.head :=
by { cases L, cases h, simp, }
lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂),
(l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂
| [] _ n hn₁ hn₂ := (nat.not_lt_zero _ hn₂).elim
| (a::l) _ 0 hn₁ hn₂ := rfl
| (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append];
exact nth_le_append _ _
lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ}
(h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length :=
begin
rw list.length_append at h₂,
convert (nat.sub_lt_sub_right_iff h₁).mpr h₂,
simp,
end
lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂),
(l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂)
| [] _ n h₁ h₂ := rfl
| (a :: l) _ (n+1) h₁ h₂ :=
begin
dsimp,
conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], },
rw nth_le_append_right (nat.lt_succ_iff.mp h₁),
end
@[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) :
(list.repeat a n).nth_le m h = a :=
eq_of_mem_repeat (nth_le_mem _ _ _)
lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) :
(l₁ ++ l₂).nth n = l₁.nth n :=
have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn
(by rw length_append; exact nat.le_add_right _ _),
by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append]
lemma nth_append_right {l₁ l₂ : list α} {n : ℕ} (hn : l₁.length ≤ n) :
(l₁ ++ l₂).nth n = l₂.nth (n - l₁.length) :=
begin
by_cases hl : n < (l₁ ++ l₂).length,
{ rw [nth_le_nth hl, nth_le_nth, nth_le_append_right hn] },
{ rw [nth_len_le (le_of_not_lt hl), nth_len_le],
rw [not_lt, length_append] at hl,
exact nat.le_sub_left_of_add_le hl }
end
lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []),
last l h = l.nth_le (l.length - 1) (nat.sub_lt (length_pos_of_ne_nil h) one_pos)
| [] h := rfl
| [a] h := by rw [last_singleton, nth_le_singleton]
| (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)],
refl, exact cons_ne_nil b l }
@[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a
| [] a := rfl
| (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length]
lemma nth_le_cons_length (x : α) (xs : list α) (n : ℕ) (h : n = xs.length) :
(x :: xs).nth_le n (by simp [h]) = (x :: xs).last (cons_ne_nil x xs) :=
begin
rw last_eq_nth_le,
congr,
simp [h]
end
@[ext]
theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂
| [] [] h := rfl
| (a::l₁) [] h := by have h0 := h 0; contradiction
| [] (a'::l₂) h := by have h0 := h 0; contradiction
| (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa;
simp only [aa, ext (λn, h (n+1))]; split; refl
theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂)
(h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ :=
ext $ λn, if h₁ : n < length l₁
then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])]
else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], }
@[simp] theorem index_of_nth_le [decidable_eq α] {a : α} :
∀ {l : list α} h, nth_le l (index_of a l) h = a
| (b::l) h := by by_cases h' : a = b;
simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l]
@[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) :
nth l (index_of a l) = some a :=
by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)]
theorem nth_le_reverse_aux1 :
∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2
| [] r i := λh1 h2, rfl
| (a :: l) r i :=
by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1);
exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2)
lemma index_of_inj [decidable_eq α] {l : list α} {x y : α}
(hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y :=
⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) =
nth_le l (index_of y l) (index_of_lt_length.2 hy),
by simp only [h],
by simpa only [index_of_nth_le],
λ h, by subst h⟩
theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2),
nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2
| [] r i h1 h2 := absurd h2 (nat.not_lt_zero _)
| (a :: l) r 0 h1 h2 := begin
have aux := nth_le_reverse_aux1 l (a :: r) 0,
rw zero_add at aux,
exact aux _ (zero_lt_succ _)
end
| (a :: l) r (i+1) h1 h2 := begin
have aux := nth_le_reverse_aux2 l (a :: r) i,
have heq := calc length (a :: l) - 1 - (i + 1)
= length l - (1 + i) : by rw add_comm; refl
... = length l - 1 - i : by rw nat.sub_sub,
rw [← heq] at aux,
apply aux
end
@[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) :
nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 :=
nth_le_reverse_aux2 _ _ _ _ _
lemma nth_le_reverse' (l : list α) (n : ℕ) (hn : n < l.reverse.length) (hn') :
l.reverse.nth_le n hn = l.nth_le (l.length - 1 - n) hn' :=
begin
rw eq_comm,
convert nth_le_reverse l.reverse _ _ _ using 1,
{ simp },
{ simpa }
end
lemma eq_cons_of_length_one {l : list α} (h : l.length = 1) :
l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] :=
begin
refine ext_le (by convert h) (λ n h₁ h₂, _),
simp only [nth_le_singleton],
congr,
exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂)
end
lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) :
∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) =
l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l)
lemma modify_nth_tail_modify_nth_tail_le
{f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) :
(l.modify_nth_tail f n).modify_nth_tail g m =
l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n :=
begin
rcases le_iff_exists_add.1 h with ⟨m, rfl⟩,
rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail]
end
lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) :
(l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n :=
by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl
lemma modify_nth_tail_id :
∀n (l:list α), l.modify_nth_tail id n = l
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l)
theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _)
theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α),
update_nth l n a = modify_nth (λ _, a) n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _)
theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α),
modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := (congr_arg (cons b)
(modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl
theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m,
nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m
| n l 0 := by cases l; cases n; refl
| n [] (m+1) := by cases n; refl
| 0 (a::l) (m+1) := by cases nth l m; refl
| (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $
by cases nth l m with b; by_cases n = m;
simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ.inj,
not_false_iff]
theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) :
∀ n l, length (modify_nth_tail f n l) = length l
| 0 l := H _
| (n+1) [] := rfl
| (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _)
@[simp] theorem modify_nth_length (f : α → α) :
∀ n l, length (modify_nth f n l) = length l :=
modify_nth_tail_length _ (λ l, by cases l; refl)
@[simp] theorem update_nth_length (l : list α) (n) (a : α) :
length (update_nth l n a) = length l :=
by simp only [update_nth_eq_modify_nth, modify_nth_length]
@[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) :
nth (modify_nth f n l) n = f <$> nth l n :=
by simp only [nth_modify_nth, if_pos]
@[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) :
nth (modify_nth f m l) n = nth l n :=
by simp only [nth_modify_nth, if_neg h, id_map']
theorem nth_update_nth_eq (a : α) (n) (l : list α) :
nth (update_nth l n a) n = (λ _, a) <$> nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq]
theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) :
nth (update_nth l n a) n = some a :=
by rw [nth_update_nth_eq, nth_le_nth h]; refl
theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) :
nth (update_nth l m a) n = nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h]
@[simp] lemma update_nth_nil (n : ℕ) (a : α) : [].update_nth n a = [] := rfl
@[simp] lemma update_nth_succ (x : α) (xs : list α) (n : ℕ) (a : α) :
(x :: xs).update_nth n.succ a = x :: xs.update_nth n a := rfl
lemma update_nth_comm (a b : α) : Π {n m : ℕ} (l : list α) (h : n ≠ m),
(l.update_nth n a).update_nth m b = (l.update_nth m b).update_nth n a
| _ _ [] _ := by simp
| 0 0 (x :: t) h := absurd rfl h
| (n + 1) 0 (x :: t) h := by simp [list.update_nth]
| 0 (m + 1) (x :: t) h := by simp [list.update_nth]
| (n + 1) (m + 1) (x :: t) h := by { simp only [update_nth, true_and, eq_self_iff_true],
exact update_nth_comm t (λ h', h $ nat.succ_inj'.mpr h'), }
@[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α)
(h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a :=
by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at *
@[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α)
(hj : j < (l.update_nth i a).length) :
(l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) :=
by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth]
lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α}
(h : a ∈ l.update_nth n b), a ∈ l ∨ a = b
| [] n a b h := false.elim h
| (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim
or.inr (or.inl ∘ mem_cons_of_mem _)
| (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim
(λ h, h ▸ or.inl (mem_cons_self _ _))
(λ h, (mem_or_eq_of_mem_update_nth h).elim
(or.inl ∘ mem_cons_of_mem _) or.inr)
section insert_nth
variable {a : α}
@[simp] lemma insert_nth_zero (s : list α) (x : α) : insert_nth 0 x s = x :: s := rfl
@[simp] lemma insert_nth_succ_nil (n : ℕ) (a : α) : insert_nth (n + 1) a [] = [] := rfl
@[simp] lemma insert_nth_succ_cons (s : list α) (hd x : α) (n : ℕ) :
insert_nth (n + 1) x (hd :: s) = hd :: (insert_nth n x s) := rfl
lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1
| 0 as h := rfl
| (n+1) [] h := (nat.not_succ_le_zero _ h).elim
| (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h)
lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l :=
by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same];
from modify_nth_tail_id _ _
lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → n ≤ m →
insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n
| 0 0 [] has _ := (lt_irrefl _ has).elim
| 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth]
| 0 (m+1) (a::as) has hmn := rfl
| (n+1) (m+1) (a::as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n →
insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1)
| n 0 (a :: as) has hmn := rfl
| (n + 1) (m + 1) (a :: as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_comm (a b : α) :
∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l),
(l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a
| 0 j l := by simp [insert_nth]
| (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim
| (i + 1) (j+1) [] := by simp
| (i + 1) (j+1) (c::l) :=
assume h₀ h₁,
by simp [insert_nth];
exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁)
lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length),
a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l
| 0 as h := iff.rfl
| (n+1) [] h := (nat.not_succ_le_zero _ h).elim
| (n+1) (a'::as) h := begin
dsimp [list.insert_nth],
erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff,
← or.assoc, or_comm (a = a'), or.assoc]
end
lemma inj_on_insert_nth_index_of_not_mem (l : list α) (x : α) (hx : x ∉ l) :
set.inj_on (λ k, insert_nth k x l) {n | n ≤ l.length} :=
begin
induction l with hd tl IH,
{ intros n hn m hm h,
simp only [set.mem_singleton_iff, set.set_of_eq_eq_singleton, length, nonpos_iff_eq_zero]
at hn hm,
simp [hn, hm] },
{ intros n hn m hm h,
simp only [length, set.mem_set_of_eq] at hn hm,
simp only [mem_cons_iff, not_or_distrib] at hx,
cases n;
cases m,
{ refl },
{ simpa [hx.left] using h },
{ simpa [ne.symm hx.left] using h },
{ simp only [true_and, eq_self_iff_true, insert_nth_succ_cons] at h,
rw nat.succ_inj',
refine IH hx.right _ _ h,
{ simpa [nat.succ_le_succ_iff] using hn },
{ simpa [nat.succ_le_succ_iff] using hm } } }
end
lemma insert_nth_of_length_lt (l : list α) (x : α) (n : ℕ) (h : l.length < n) :
insert_nth n x l = l :=
begin
induction l with hd tl IH generalizing n,
{ cases n,
{ simpa using h },
{ simp } },
{ cases n,
{ simpa using h },
{ simp only [nat.succ_lt_succ_iff, length] at h,
simpa using IH _ h } }
end
@[simp] lemma insert_nth_length_self (l : list α) (x : α) :
insert_nth l.length x l = l ++ [x] :=
begin
induction l with hd tl IH,
{ simp },
{ simpa using IH }
end
lemma length_le_length_insert_nth (l : list α) (x : α) (n : ℕ) :
l.length ≤ (insert_nth n x l).length :=
begin
cases le_or_lt n l.length with hn hn,
{ rw length_insert_nth _ _ hn,
exact (nat.lt_succ_self _).le },
{ rw insert_nth_of_length_lt _ _ _ hn }
end
lemma length_insert_nth_le_succ (l : list α) (x : α) (n : ℕ) :
(insert_nth n x l).length ≤ l.length + 1 :=
begin
cases le_or_lt n l.length with hn hn,
{ rw length_insert_nth _ _ hn },
{ rw insert_nth_of_length_lt _ _ _ hn,
exact (nat.lt_succ_self _).le }
end
lemma nth_le_insert_nth_of_lt (l : list α) (x : α) (n k : ℕ) (hn : k < n)
(hk : k < l.length)
(hk' : k < (insert_nth n x l).length := hk.trans_le (length_le_length_insert_nth _ _ _)):
(insert_nth n x l).nth_le k hk' = l.nth_le k hk :=
begin
induction n with n IH generalizing k l,
{ simpa using hn },
{ cases l with hd tl,
{ simp },
{ cases k,
{ simp },
{ rw nat.succ_lt_succ_iff at hn,
simpa using IH _ _ hn _ } } }
end
@[simp] lemma nth_le_insert_nth_self (l : list α) (x : α) (n : ℕ)
(hn : n ≤ l.length) (hn' : n < (insert_nth n x l).length :=
by rwa [length_insert_nth _ _ hn, nat.lt_succ_iff]) :
(insert_nth n x l).nth_le n hn' = x :=
begin
induction l with hd tl IH generalizing n,
{ simp only [length, nonpos_iff_eq_zero] at hn,
simp [hn] },
{ cases n,
{ simp },
{ simp only [nat.succ_le_succ_iff, length] at hn,
simpa using IH _ hn } }
end
lemma nth_le_insert_nth_add_succ (l : list α) (x : α) (n k : ℕ)
(hk' : n + k < l.length)
(hk : n + k + 1 < (insert_nth n x l).length :=
by rwa [length_insert_nth _ _ (le_self_add.trans hk'.le), nat.succ_lt_succ_iff]) :
(insert_nth n x l).nth_le (n + k + 1) hk = nth_le l (n + k) hk' :=
begin
induction l with hd tl IH generalizing n k,
{ simpa using hk' },
{ cases n,
{ simpa },
{ simpa [succ_add] using IH _ _ _ } }
end
lemma insert_nth_injective (n : ℕ) (x : α) : function.injective (insert_nth n x) :=
begin
induction n with n IH,
{ have : insert_nth 0 x = cons x := funext (λ _, rfl),
simp [this] },
{ rintros (_|⟨a, as⟩) (_|⟨b, bs⟩) h;
simpa [IH.eq_iff] using h <|> refl }
end
end insert_nth
/-! ### map -/
@[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl
theorem map_eq_foldr (f : α → β) (l : list α) :
map f l = foldr (λ a bs, f a :: bs) [] l :=
by induction l; simp *
lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l
| [] _ := rfl
| (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in
by rw [map, map, h₁, map_congr h₂]
lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) :=
begin
refine ⟨_, map_congr⟩, intros h x hx,
rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩,
rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h
end
theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) :=
by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl
theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil :=
eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl
@[simp] theorem map_join (f : α → β) (L : list (list α)) :
map f (join L) = join (map (map f) L) :=
by induction L; [refl, simp only [*, join, map, map_append]]
theorem bind_ret_eq_map (f : α → β) (l : list α) :
l.bind (list.ret ∘ f) = map f l :=
by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *];
split; refl
@[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl
@[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) :=
by cases l; refl
@[simp] theorem map_injective_iff {f : α → β} : injective (map f) ↔ injective f :=
begin
split; intros h x y hxy,
{ suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] },
{ induction y generalizing x, simpa using hxy,
cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] }
end
/--
A single `list.map` of a composition of functions is equal to
composing a `list.map` with another `list.map`, fully applied.
This is the reverse direction of `list.map_map`.
-/
lemma comp_map (h : β → γ) (g : α → β) (l : list α) :
map (h ∘ g) l = map h (map g l) := (map_map _ _ _).symm
/--
Composing a `list.map` with another `list.map` is equal to
a single `list.map` of composed functions.
-/
@[simp] lemma map_comp_map (g : β → γ) (f : α → β) :
map g ∘ map f = map (g ∘ f) :=
by { ext l, rw comp_map }
theorem map_filter_eq_foldr (f : α → β) (p : α → Prop) [decidable_pred p] (as : list α) :
map f (filter p as) = foldr (λ a bs, if p a then f a :: bs else bs) [] as :=
by { induction as, { refl }, { simp! [*, apply_ite (map f)] } }
lemma last_map (f : α → β) {l : list α} (hl : l ≠ []) :
(l.map f).last (mt eq_nil_of_map_eq_nil hl) = f (l.last hl) :=
begin
induction l with l_ih l_tl l_ih,
{ apply (hl rfl).elim },
{ cases l_tl,
{ simp },
{ simpa using l_ih } }
end
/-! ### map₂ -/
theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] :=
by cases l; refl
theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] :=
by cases l; refl
@[simp] theorem map₂_flip (f : α → β → γ) :
∀ as bs, map₂ (flip f) bs as = map₂ f as bs
| [] [] := rfl
| [] (b :: bs) := rfl
| (a :: as) [] := rfl
| (a :: as) (b :: bs) := by { simp! [map₂_flip], refl }
/-! ### take, drop -/
@[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl
@[simp] theorem take_nil : ∀ n, take n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl
@[simp] theorem take_length : ∀ (l : list α), take (length l) l = l
| [] := rfl
| (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end
theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l
| 0 [] h := rfl
| 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _))
| (n+1) [] h := rfl
| (n+1) (a::l) h :=
begin
change a :: take n l = a :: l,
rw [take_all_of_le (le_of_succ_le_succ h)]
end
@[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁
| [] l₂ := rfl
| (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂)
theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take_left
theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l
| n 0 l := by rw [nat.min_zero, take_zero, take_nil]
| 0 m l := by rw [nat.zero_min, take_zero, take_zero]
| (succ n) (succ m) nil := by simp only [take_nil]
| (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl
theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m)
| n 0 := by simp
| 0 m := by simp
| (succ n) (succ m) := by simp [min_succ_succ, take_repeat]
lemma map_take {α β : Type*} (f : α → β) :
∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [map_take], }
lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ},
n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n
| l₁ l₂ 0 hn := by simp
| [] l₂ (n+1) hn := absurd hn dec_trivial
| (a::l₁) l₂ (n+1) hn :=
by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)]
/-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first
`i` elements of `l₂` to `l₁`. -/
lemma take_append {l₁ l₂ : list α} (i : ℕ) :
take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) :=
begin
induction l₁, { simp },
have : length l₁_tl + 1 + i = (length l₁_tl + i).succ,
by { rw nat.succ_eq_add_one, exact succ_add _ _ },
simp only [cons_append, length, this, take_cons, l₁_ih, eq_self_iff_true, and_self]
end
/-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of
length `> i`. Version designed to rewrite from the big list to the small list. -/
lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) :
nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) :=
by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ }
/-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of
length `> i`. Version designed to rewrite from the small list to the big list. -/
lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) :
nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) :=
by { simp at hi, rw nth_le_take L _ hi.1 }
lemma nth_take {l : list α} {n m : ℕ} (h : m < n) :
(l.take n).nth m = l.nth m :=
begin
induction n with n hn generalizing l m,
{ simp only [nat.nat_zero_eq_zero] at h,
exact absurd h (not_lt_of_le m.zero_le) },
{ cases l with hd tl,
{ simp only [take_nil] },
{ cases m,
{ simp only [nth, take] },
{ simpa only using hn (nat.lt_of_succ_lt_succ h) } } },
end
@[simp] lemma nth_take_of_succ {l : list α} {n : ℕ} :
(l.take (n + 1)).nth n = l.nth n :=
nth_take (nat.lt_succ_self n)
lemma take_succ {l : list α} {n : ℕ} :
l.take (n + 1) = l.take n ++ (l.nth n).to_list :=
begin
induction l with hd tl hl generalizing n,
{ simp only [option.to_list, nth, take_nil, append_nil]},
{ cases n,
{ simp only [option.to_list, nth, eq_self_iff_true, and_self, take, nil_append] },
{ simp only [hl, cons_append, nth, eq_self_iff_true, and_self, take] } }
end
@[simp] lemma take_eq_nil_iff {l : list α} {k : ℕ} :
l.take k = [] ↔ l = [] ∨ k = 0 :=
by { cases l; cases k; simp [nat.succ_ne_zero] }
lemma init_eq_take (l : list α) : l.init = l.take l.length.pred :=
begin
cases l with x l,
{ simp [init] },
{ induction l with hd tl hl generalizing x,
{ simp [init], },
{ simp [init, hl] } }
end
lemma init_take {n : ℕ} {l : list α} (h : n < l.length) :
(l.take n).init = l.take n.pred :=
by simp [init_eq_take, min_eq_left_of_lt h, take_take, pred_le]
@[simp] lemma drop_eq_nil_of_le {l : list α} {k : ℕ} (h : l.length ≤ k) :
l.drop k = [] :=
by simpa [←length_eq_zero] using nat.sub_eq_zero_of_le h
lemma drop_eq_nil_iff_le {l : list α} {k : ℕ} :
l.drop k = [] ↔ l.length ≤ k :=
begin
refine ⟨λ h, _, drop_eq_nil_of_le⟩,
induction k with k hk generalizing l,
{ simp only [drop] at h,
simp [h] },
{ cases l,
{ simp },
{ simp only [drop] at h,
simpa [nat.succ_le_succ_iff] using hk h } }
end
lemma tail_drop (l : list α) (n : ℕ) : (l.drop n).tail = l.drop (n + 1) :=
begin
induction l with hd tl hl generalizing n,
{ simp },
{ cases n,
{ simp },
{ simp [hl] } }
end
lemma cons_nth_le_drop_succ {l : list α} {n : ℕ} (hn : n < l.length) :
l.nth_le n hn :: l.drop (n + 1) = l.drop n :=
begin
induction l with hd tl hl generalizing n,
{ exact absurd n.zero_le (not_le_of_lt (by simpa using hn)) },
{ cases n,
{ simp },
{ simp only [nat.succ_lt_succ_iff, list.length] at hn,
simpa [list.nth_le, list.drop] using hl hn } }
end
theorem drop_nil : ∀ n, drop n [] = ([] : list α) :=
λ _, drop_eq_nil_of_le (nat.zero_le _)
lemma mem_of_mem_drop {α} {n : ℕ} {l : list α} {x : α}
(h : x ∈ l.drop n) :
x ∈ l :=
begin
induction l generalizing n,
case list.nil : n h
{ simpa using h },
case list.cons : l_hd l_tl l_ih n h
{ cases n; simp only [mem_cons_iff, drop] at h ⊢,
{ exact h },
right, apply l_ih h },
end
@[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l
| [] := rfl
| (a :: l) := rfl
theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l)
| m 0 l := rfl
| m (n+1) [] := (drop_nil _).symm
| m (n+1) (a::l) := drop_add m n _
@[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂
| [] l₂ := rfl
| (a::l₁) l₂ := drop_left l₁ l₂
theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
drop n (l₁ ++ l₂) = l₂ :=
by rw ← h; apply drop_left
theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h,
drop n l = nth_le l n h :: drop (n+1) l
| 0 (a::l) h := rfl
| (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _
@[simp] lemma drop_length (l : list α) : l.drop l.length = [] :=
calc l.drop l.length = (l ++ []).drop l.length : by simp
... = [] : drop_left _ _
lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length →
(l₁ ++ l₂).drop n = l₁.drop n ++ l₂
| l₁ l₂ 0 hn := by simp
| [] l₂ (n+1) hn := absurd hn dec_trivial
| (a::l₁) l₂ (n+1) hn :=
by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)]
/-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements
up to `i` in `l₂`. -/
lemma drop_append {l₁ l₂ : list α} (i : ℕ) :
drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ :=
begin
induction l₁, { simp },
have : length l₁_tl + 1 + i = (length l₁_tl + i).succ,
by { rw nat.succ_eq_add_one, exact succ_add _ _ },
simp only [cons_append, length, this, drop, l₁_ih]
end
/-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by
dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/
lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) :
nth_le L (i + j) h = nth_le (L.drop i) j
begin
have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h,
rw (take_append_drop i L).symm at h,
simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h
end :=
begin
have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)],
rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right];
simp [A]
end
/-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by
dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/
lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) :
nth_le (L.drop i) j h = nth_le L (i + j) (nat.add_lt_of_lt_sub_left ((length_drop i L) ▸ h)) :=
by rw nth_le_drop
lemma nth_drop (L : list α) (i j : ℕ) :
nth (L.drop i) j = nth L (i + j) :=
begin
ext,
simp only [nth_eq_some, nth_le_drop', option.mem_def],
split;
exact λ ⟨h, ha⟩, ⟨by simpa [nat.lt_sub_left_iff_add_lt] using h, ha⟩
end
@[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l
| m [] := by simp
| 0 l := by simp
| (m+1) (a::l) :=
calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl
... = drop (n + m) l : drop_drop m l
... = drop (n + (m + 1)) (a :: l) : rfl
theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α),
drop m (take (m + n) l) = take n (drop m l)
| 0 n _ := by simp
| (m+1) n nil := by simp
| (m+1) n (_::l) :=
have h: m + 1 + n = (m+n) + 1, by ac_refl,
by simpa [take_cons, h] using drop_take m n l
lemma map_drop {α β : Type*} (f : α → β) :
∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [map_drop], }
theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) :
∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l)
| 0 l := rfl
| (n+1) [] := H.symm
| (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l)
theorem modify_nth_eq_take_drop (f : α → α) :
∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) :=
modify_nth_tail_eq_take_drop _ rfl
theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) :
modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l :=
by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl
theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) :
update_nth l n a = take n l ++ a :: drop (n+1) l :=
by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h]
lemma reverse_take {α} {xs : list α} (n : ℕ)
(h : n ≤ xs.length) :
xs.reverse.take n = (xs.drop (xs.length - n)).reverse :=
begin
induction xs generalizing n;
simp only [reverse_cons, drop, reverse_nil, nat.zero_sub, length, take_nil],
cases h.lt_or_eq_dec with h' h',
{ replace h' := le_of_succ_le_succ h',
rwa [take_append_of_le_length, xs_ih _ h'],
rw [show xs_tl.length + 1 - n = succ (xs_tl.length - n), from _, drop],
{ rwa [succ_eq_add_one, nat.sub_add_comm] },
{ rwa length_reverse } },
{ subst h', rw [length, nat.sub_self, drop],
suffices : xs_tl.length + 1 = (xs_tl.reverse ++ [xs_hd]).length,
by rw [this, take_length, reverse_cons],
rw [length_append, length_reverse], refl }
end
@[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] :=
by cases l; cases n; simp only [update_nth]
section take'
variable [inhabited α]
@[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n
| 0 l := rfl
| (n+1) l := congr_arg succ (take'_length _ _)
@[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n
| 0 := rfl
| (n+1) := congr_arg (cons _) (take'_nil _)
theorem take'_eq_take : ∀ {n} {l : list α},
n ≤ length l → take' n l = take n l
| 0 l h := rfl
| (n+1) (a::l) h := congr_arg (cons _) $
take'_eq_take $ le_of_succ_le_succ h
@[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ :=
(take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _)
theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take' n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take'_left
end take'
/-! ### foldl, foldr -/
lemma foldl_ext (f g : α → β → α) (a : α)
{l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) :
foldl f a l = foldl g a l :=
begin
induction l with hd tl ih generalizing a, {refl},
unfold foldl,
rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)]
end
lemma foldr_ext (f g : α → β → β) (b : β)
{l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) :
foldr f b l = foldr g b l :=
begin
induction l with hd tl ih, {refl},
simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H,
simp only [foldr, ih H.2, H.1]
end
@[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl
@[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) :
foldl f a (b::l) = foldl f (f a b) l := rfl
@[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
foldr f b (a::l) = f a (foldr f b l) := rfl
@[simp] theorem foldl_append (f : α → β → α) :
∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂
| a [] l₂ := rfl
| a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂]
@[simp] theorem foldr_append (f : α → β → β) :
∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁
| b [] l₂ := rfl
| b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂]
@[simp] theorem foldl_join (f : α → β → α) :
∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L
| a [] := rfl
| a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L]
@[simp] theorem foldr_join (f : α → β → β) :
∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L
| a [] := rfl
| a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons]
theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) :
foldl f a (reverse l) = foldr (λx y, f y x) a l :=
by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]]
theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) :
foldr f a (reverse l) = foldl (λx y, f y x) a l :=
let t := foldl_reverse (λx y, f y x) a (reverse l) in
by rw reverse_reverse l at t; rwa t
@[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l
| [] := rfl
| (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl
@[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l :=
by rw ←foldr_reverse; simp
@[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) :
foldl f a (map g l) = foldl (λx y, f x (g y)) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldl]]
@[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) :
foldr f a (map g l) = foldr (f ∘ g) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldr]]
theorem foldl_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β)
(a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) :
list.foldl f' (g a) (l.map g) = g (list.foldl f a l) :=
begin
induction l generalizing a,
{ simp }, { simp [l_ih, h] }
end
theorem foldr_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β)
(a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) :
list.foldr f' (g a) (l.map g) = g (list.foldr f a l) :=
begin
induction l generalizing a,
{ simp }, { simp [l_ih, h] }
end
theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α)
(h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) :=
eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] }
theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α)
(h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) :=
by { revert a, induction l; intros; [refl, simp only [*, foldr]] }
lemma injective_foldl_comp {α : Type*} {l : list (α → α)} {f : α → α}
(hl : ∀ f ∈ l, function.injective f) (hf : function.injective f):
function.injective (@list.foldl (α → α) (α → α) function.comp f l) :=
begin
induction l generalizing f,
{ exact hf },
{ apply l_ih (λ _ h, hl _ (list.mem_cons_of_mem _ h)),
apply function.injective.comp hf,
apply hl _ (list.mem_cons_self _ _) }
end
/-- Induction principle for values produced by a `foldr`: if a property holds
for the seed element `b : β` and for all incremental `op : α → β → β`
performed on the elements `(a : α) ∈ l`. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
def foldr_rec_on {C : β → Sort*} (l : list α) (op : α → β → β) (b : β) (hb : C b)
(hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ l), C (op a b)) :
C (foldr op b l) :=
begin
induction l with hd tl IH,
{ exact hb },
{ refine hl _ _ hd (mem_cons_self hd tl),
refine IH _,
intros y hy x hx,
exact hl y hy x (mem_cons_of_mem hd hx) }
end
/-- Induction principle for values produced by a `foldl`: if a property holds
for the seed element `b : β` and for all incremental `op : β → α → β`
performed on the elements `(a : α) ∈ l`. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
def foldl_rec_on {C : β → Sort*} (l : list α) (op : β → α → β) (b : β) (hb : C b)
(hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ l), C (op b a)) :
C (foldl op b l) :=
begin
induction l with hd tl IH generalizing b,
{ exact hb },
{ refine IH _ _ _,
{ intros y hy x hx,
exact hl y hy x (mem_cons_of_mem hd hx) },
{ exact hl b hb hd (mem_cons_self hd tl) } }
end
@[simp] lemma foldr_rec_on_nil {C : β → Sort*} (op : α → β → β) (b) (hb : C b) (hl) :
foldr_rec_on [] op b hb hl = hb := rfl
@[simp] lemma foldr_rec_on_cons {C : β → Sort*} (x : α) (l : list α)
(op : α → β → β) (b) (hb : C b)
(hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ (x :: l)), C (op a b)) :
foldr_rec_on (x :: l) op b hb hl = hl _ (foldr_rec_on l op b hb
(λ b hb a ha, hl b hb a (mem_cons_of_mem _ ha))) x (mem_cons_self _ _) := rfl
@[simp] lemma foldl_rec_on_nil {C : β → Sort*} (op : β → α → β) (b) (hb : C b) (hl) :
foldl_rec_on [] op b hb hl = hb := rfl
/- scanl -/
section scanl
variables {f : β → α → β} {b : β} {a : α} {l : list α}
lemma length_scanl :
∀ a l, length (scanl f a l) = l.length + 1
| a [] := rfl
| a (x :: l) := by erw [length_cons, length_cons, length_scanl]
@[simp] lemma scanl_nil (b : β) : scanl f b nil = [b] := rfl
@[simp] lemma scanl_cons :
scanl f b (a :: l) = [b] ++ scanl f (f b a) l :=
by simp only [scanl, eq_self_iff_true, singleton_append, and_self]
@[simp] lemma nth_zero_scanl : (scanl f b l).nth 0 = some b :=
begin
cases l,
{ simp only [nth, scanl_nil] },
{ simp only [nth, scanl_cons, singleton_append] }
end
@[simp] lemma nth_le_zero_scanl {h : 0 < (scanl f b l).length} :
(scanl f b l).nth_le 0 h = b :=
begin
cases l,
{ simp only [nth_le, scanl_nil] },
{ simp only [nth_le, scanl_cons, singleton_append] }
end
lemma nth_succ_scanl {i : ℕ} :
(scanl f b l).nth (i + 1) = ((scanl f b l).nth i).bind (λ x, (l.nth i).map (λ y, f x y)) :=
begin
induction l with hd tl hl generalizing b i,
{ symmetry,
simp only [option.bind_eq_none', nth, forall_2_true_iff, not_false_iff, option.map_none',
scanl_nil, option.not_mem_none, forall_true_iff] },
{ simp only [nth, scanl_cons, singleton_append],
cases i,
{ simp only [option.map_some', nth_zero_scanl, nth, option.some_bind'] },
{ simp only [hl, nth] } }
end
lemma nth_le_succ_scanl {i : ℕ} {h : i + 1 < (scanl f b l).length} :
(scanl f b l).nth_le (i + 1) h =
f ((scanl f b l).nth_le i (nat.lt_of_succ_lt h))
(l.nth_le i (nat.lt_of_succ_lt_succ (lt_of_lt_of_le h (le_of_eq (length_scanl b l))))) :=
begin
induction i with i hi generalizing b l,
{ cases l,
{ simp only [length, zero_add, scanl_nil] at h,
exact absurd h (lt_irrefl 1) },
{ simp only [scanl_cons, singleton_append, nth_le_zero_scanl, nth_le] } },
{ cases l,
{ simp only [length, add_lt_iff_neg_right, scanl_nil] at h,
exact absurd h (not_lt_of_lt nat.succ_pos') },
{ simp_rw scanl_cons,
rw nth_le_append_right _,
{ simpa only [hi, length, succ_add_sub_one] },
{ simp only [length, nat.zero_le, le_add_iff_nonneg_left] } } }
end
end scanl
/- scanr -/
@[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl
@[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α),
scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l)
| a [] := rfl
| a (x::l) := let t := scanr_aux_cons x l in
by simp only [scanr, scanr_aux, t, foldr_cons]
@[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
scanr f b (a::l) = foldr f b (a::l) :: scanr f b l :=
by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f)
include hassoc
theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l)
| a b nil := rfl
| a b (c :: l) :=
by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc
include hcomm
theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := hcomm a b
| a b (c::l) := by simp only [foldl_cons];
rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl
theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l)
end foldl_eq_foldr
section foldl_eq_foldlr'
variables {f : α → β → α}
variables hf : ∀ a b c, f (f a b) c = f (f a c) b
include hf
theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b
| a b [] := rfl
| a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf]
theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l
| a [] := rfl
| a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl
end foldl_eq_foldlr'
section foldl_eq_foldlr'
variables {f : α → β → β}
variables hf : ∀ a b c, f a (f b c) = f b (f a c)
include hf
theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l
| a b [] := rfl
| a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl
end foldl_eq_foldlr'
section
variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
include ha
lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂)
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ :=
calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc]
... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons]
lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc];
rw [foldl_op_eq_op_foldr_assoc]
include hc
lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) :=
by rw [foldl_cons, hc.comm, foldl_assoc]
end
/-! ### mfoldl, mfoldr, mmap -/
section mfoldl_mfoldr
variables {m : Type v → Type w} [monad m]
@[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl
@[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl
@[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} :
mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl
@[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} :
mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl
theorem mfoldr_eq_foldr (f : α → β → m β) (b l) :
mfoldr f b l = foldr (λ a mb, mb >>= f a) (pure b) l :=
by induction l; simp *
attribute [simp] mmap mmap'
variables [is_lawful_monad m]
theorem mfoldl_eq_foldl (f : β → α → m β) (b l) :
mfoldl f b l = foldl (λ mb a, mb >>= λ b, f b a) (pure b) l :=
begin
suffices h : ∀ (mb : m β),
(mb >>= λ b, mfoldl f b l) = foldl (λ mb a, mb >>= λ b, f b a) mb l,
by simp [←h (pure b)],
induction l; intro,
{ simp },
{ simp only [mfoldl, foldl, ←l_ih] with monad_norm }
end
@[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂},
mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂
| _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind]
| _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, is_lawful_monad.bind_assoc]
@[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂},
mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁
| _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure]
| _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, is_lawful_monad.bind_assoc]
end mfoldl_mfoldr
/-! ### prod and sum -/
-- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet.
attribute [to_additive] list.prod
section monoid
variables [monoid α] {l l₁ l₂ : list α} {a : α}
@[simp, to_additive]
theorem prod_nil : ([] : list α).prod = 1 := rfl
@[to_additive]
theorem prod_singleton : [a].prod = a := one_mul a
@[simp, to_additive]
theorem prod_cons : (a::l).prod = a * l.prod :=
calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one]
... = _ : foldl_assoc
@[simp, priority 500, to_additive]
theorem prod_repeat (a : α) (n : ℕ) : (list.repeat a n).prod = a ^ n :=
begin
induction n with n ih,
{ rw pow_zero, refl },
{ rw [list.repeat_succ, list.prod_cons, ih, pow_succ] }
end
@[simp, to_additive]
theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod :=
calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod]
... = l₁.prod * l₂.prod : foldl_assoc
@[simp, to_additive]
theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod :=
by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]]
/-- If zero is an element of a list `L`, then `list.prod L = 0`. If the domain is a nontrivial
monoid with zero with no divisors, then this implication becomes an `iff`, see
`list.prod_eq_zero_iff`. -/
theorem prod_eq_zero {M₀ : Type*} [monoid_with_zero M₀] {L : list M₀} (h : (0 : M₀) ∈ L) :
L.prod = 0 :=
begin
induction L with a L ihL,
{ exact absurd h (not_mem_nil _) },
{ rw prod_cons,
cases (mem_cons_iff _ _ _).1 h with ha hL,
exacts [mul_eq_zero_of_left ha.symm _, mul_eq_zero_of_right _ (ihL hL)] }
end
/-- Product of elements of a list `L` equals zero if and only if `0 ∈ L`. See also
`list.prod_eq_zero` for an implication that needs weaker typeclass assumptions. -/
@[simp] theorem prod_eq_zero_iff {M₀ : Type*} [monoid_with_zero M₀] [nontrivial M₀]
[no_zero_divisors M₀] {L : list M₀} :
L.prod = 0 ↔ (0 : M₀) ∈ L :=
begin
induction L with a L ihL,
{ simp },
{ rw [prod_cons, mul_eq_zero, ihL, mem_cons_iff, eq_comm] }
end
theorem prod_ne_zero {M₀ : Type*} [monoid_with_zero M₀] [nontrivial M₀] [no_zero_divisors M₀]
{L : list M₀} (hL : (0 : M₀) ∉ L) : L.prod ≠ 0 :=
mt prod_eq_zero_iff.1 hL
@[to_additive]
theorem prod_eq_foldr : l.prod = foldr (*) 1 l :=
list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl]
@[to_additive]
theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop}
{f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) :
r (l.map f).prod (l.map g).prod :=
list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl])
@[to_additive]
theorem prod_hom [monoid β] (l : list α) (f : α →* β) :
(l.map f).prod = f l.prod :=
by { simp only [prod, foldl_map, f.map_one.symm],
exact l.foldl_hom _ _ _ 1 f.map_mul }
@[to_additive]
lemma prod_is_unit [monoid β] : Π {L : list β} (u : ∀ m ∈ L, is_unit m), is_unit L.prod
| [] _ := by simp
| (h :: t) u :=
begin
simp only [list.prod_cons],
exact is_unit.mul (u h (mem_cons_self h t)) (prod_is_unit (λ m mt, u m (mem_cons_of_mem h mt)))
end
-- `to_additive` chokes on the next few lemmas, so we do them by hand below
@[simp]
lemma prod_take_mul_prod_drop :
∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop], }
@[simp]
lemma prod_take_succ :
∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p
| [] i p := by cases p
| (h :: t) 0 _ := by simp
| (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc], }
/-- A list with product not one must have positive length. -/
lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length :=
by { cases L, { simp at h, cases h, }, { simp, }, }
lemma prod_update_nth : ∀ (L : list α) (n : ℕ) (a : α),
(L.update_nth n a).prod =
(L.take n).prod * (if n < L.length then a else 1) * (L.drop (n + 1)).prod
| (x::xs) 0 a := by simp [update_nth]
| (x::xs) (i+1) a := by simp [update_nth, prod_update_nth xs i a, mul_assoc]
| [] _ _ := by simp [update_nth, (nat.zero_le _).not_lt]
end monoid
section group
variables [group α]
/-- This is the `list.prod` version of `mul_inv_rev` -/
@[to_additive "This is the `list.sum` version of `add_neg_rev`"]
lemma prod_inv_reverse : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).reverse.prod
| [] := by simp
| (x :: xs) := by simp [prod_inv_reverse xs]
/-- A non-commutative variant of `list.prod_reverse` -/
@[to_additive "A non-commutative variant of `list.sum_reverse`"]
lemma prod_reverse_noncomm : ∀ (L : list α), L.reverse.prod = (L.map (λ x, x⁻¹)).prod⁻¹ :=
by simp [prod_inv_reverse]
end group
section comm_group
variables [comm_group α]
/-- This is the `list.prod` version of `mul_inv` -/
@[to_additive "This is the `list.sum` version of `add_neg`"]
lemma prod_inv : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).prod
| [] := by simp
| (x :: xs) := by simp [mul_comm, prod_inv xs]
end comm_group
@[simp]
lemma sum_take_add_sum_drop [add_monoid α] :
∀ (L : list α) (i : ℕ), (L.take i).sum + (L.drop i).sum = L.sum
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [sum_cons, sum_cons, add_assoc, sum_take_add_sum_drop], }
@[simp]
lemma sum_take_succ [add_monoid α] :
∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).sum = (L.take i).sum + L.nth_le i p
| [] i p := by cases p
| (h :: t) 0 _ := by simp
| (h :: t) (n+1) _ := by { dsimp, rw [sum_cons, sum_cons, sum_take_succ, add_assoc], }
lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length)
(h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' :=
begin
apply ext_le h (λ i h₁ h₂, _),
have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁),
rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this,
exact add_left_cancel this
end
lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) :
monotone (λ i, (L.take i).sum) :=
begin
apply monotone_nat_of_le_succ (λ n, _),
by_cases h : n < L.length,
{ rw sum_take_succ _ _ h,
exact le_self_add },
{ push_neg at h,
simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] }
end
@[to_additive sum_nonneg]
lemma one_le_prod_of_one_le [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) :
1 ≤ l.prod :=
begin
induction l with hd tl ih,
{ simp },
rw prod_cons,
exact one_le_mul (hl₁ hd (mem_cons_self hd tl)) (ih (λ x h, hl₁ x (mem_cons_of_mem hd h))),
end
@[to_additive]
lemma single_le_prod [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) :
∀ x ∈ l, x ≤ l.prod :=
begin
induction l,
{ simp },
simp_rw [prod_cons, forall_mem_cons] at ⊢ hl₁,
split,
{ exact le_mul_of_one_le_right' (one_le_prod_of_one_le hl₁.2) },
{ exact λ x H, le_mul_of_one_le_of_le hl₁.1 (l_ih hl₁.right x H) },
end
@[to_additive all_zero_of_le_zero_le_of_sum_eq_zero]
lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α]
{l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) (hl₂ : l.prod = 1) :
∀ x ∈ l, x = (1 : α) :=
λ x hx, le_antisymm (hl₂ ▸ single_le_prod hl₁ _ hx) (hl₁ x hx)
lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] (l : list α) :
l.sum = 0 ↔ ∀ x ∈ l, x = (0 : α) :=
⟨all_zero_of_le_zero_le_of_sum_eq_zero (λ _ _, zero_le _),
begin
induction l,
{ simp },
{ intro h,
rw [sum_cons, add_eq_zero_iff],
rw forall_mem_cons at h,
exact ⟨h.1, l_ih h.2⟩ },
end⟩
/-- A list with sum not zero must have positive length. -/
lemma length_pos_of_sum_ne_zero [add_monoid α] (L : list α) (h : L.sum ≠ 0) : 0 < L.length :=
by { cases L, { simp at h, cases h, }, { simp, }, }
/-- If all elements in a list are bounded below by `1`, then the length of the list is bounded
by the sum of the elements. -/
lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum :=
begin
induction L with j L IH h, { simp },
rw [sum_cons, length, add_comm],
exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi)))
end
-- Now we tie those lemmas back to their multiplicative versions.
attribute [to_additive] prod_take_mul_prod_drop prod_take_succ length_pos_of_prod_ne_one
/-- A list with positive sum must have positive length. -/
-- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications.
lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) :
0 < L.length :=
length_pos_of_sum_ne_zero L (ne_of_gt h)
@[simp, to_additive]
theorem prod_erase [decidable_eq α] [comm_monoid α] {a} :
Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod
| (b::l) h :=
begin
rcases decidable.list.eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩,
{ simp only [list.erase, if_pos, prod_cons] },
{ simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] }
end
lemma dvd_prod [comm_monoid α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod :=
let ⟨s, t, h⟩ := mem_split ha in
by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _
@[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n :=
by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]]
theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum :=
begin
induction l with x l ih,
{ exact dvd_zero _ },
{ rw [list.sum_cons],
exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) }
end
@[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) :=
by induction L; [refl, simp only [*, join, map, sum_cons, length_append]]
@[simp] theorem length_bind (l : list α) (f : α → list β) :
length (list.bind l f) = sum (map (length ∘ f) l) :=
by rw [list.bind, length_join, map_map]
lemma exists_lt_of_sum_lt [linear_ordered_cancel_add_comm_monoid β] {l : list α}
(f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x :=
begin
induction l with x l,
{ exfalso, exact lt_irrefl _ h },
{ by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩,
rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h,
exact lt_of_add_lt_add_left (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) }
end
lemma exists_le_of_sum_le [linear_ordered_cancel_add_comm_monoid β] {l : list α}
(hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x :=
begin
cases l with x l,
{ contradiction },
{ by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩,
rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩,
exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h,
exact lt_of_add_lt_add_left (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) }
end
@[to_additive]
lemma prod_le_of_forall_le [ordered_comm_monoid α] (l : list α) (n : α) (h : ∀ (x ∈ l), x ≤ n) :
l.prod ≤ n ^ l.length :=
begin
induction l with y l IH,
{ simp },
{ specialize IH (λ x hx, h x (mem_cons_of_mem _ hx)),
have hy : y ≤ n := h y (mem_cons_self _ _),
simpa [pow_succ] using mul_le_mul' hy IH }
end
-- Several lemmas about sum/head/tail for `list ℕ`.
-- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`.
-- We'd like to state this as `L.head * L.tail.prod = L.prod`,
-- but because `L.head` relies on an inhabited instances and
-- returns a garbage value for the empty list, this is not possible.
-- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`,
-- and below, restate the lemma just for `ℕ`.
@[to_additive]
lemma head_mul_tail_prod' [monoid α] (L : list α) :
(L.nth 0).get_or_else 1 * L.tail.prod = L.prod :=
by cases L; simp
lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum :=
by { cases L, { simp, refl, }, { simp, }, }
lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum :=
nat.le.intro (head_add_tail_sum L)
lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head :=
by rw [← head_add_tail_sum L, add_comm, nat.add_sub_cancel]
section
variables {G : Type*} [comm_group G]
attribute [to_additive] alternating_prod
@[simp, to_additive] lemma alternating_prod_nil :
alternating_prod ([] : list G) = 1 := rfl
@[simp, to_additive] lemma alternating_prod_singleton (g : G) :
alternating_prod [g] = g := rfl
@[simp, to_additive alternating_sum_cons_cons']
lemma alternating_prod_cons_cons (g h : G) (l : list G) :
alternating_prod (g :: h :: l) = g * h⁻¹ * alternating_prod l := rfl
lemma alternating_sum_cons_cons {G : Type*} [add_comm_group G] (g h : G) (l : list G) :
alternating_sum (g :: h :: l) = g - h + alternating_sum l :=
by rw [sub_eq_add_neg, alternating_sum]
end
/-! ### join -/
attribute [simp] join
@[simp] theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = []
| [] := iff_of_true rfl (forall_mem_nil _)
| (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons]
@[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ :=
by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]]
@[simp] theorem join_filter_empty_eq_ff [decidable_pred (λ l : list α, l.empty = ff)] :
∀ {L : list (list α)}, join (L.filter (λ l, l.empty = ff)) = L.join
| [] := rfl
| ([]::L) := by simp [@join_filter_empty_eq_ff L]
| ((a::l)::L) := by simp [@join_filter_empty_eq_ff L]
@[simp] theorem join_filter_ne_nil [decidable_pred (λ l : list α, l ≠ [])] {L : list (list α)} :
join (L.filter (λ l, l ≠ [])) = L.join :=
by simp [join_filter_empty_eq_ff, ← empty_iff_eq_nil]
lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join :=
by { induction l, simp, simp [l_ih] }
/-- In a join, taking the first elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join of the first `i` sublists. -/
lemma take_sum_join (L : list (list α)) (i : ℕ) :
L.join.take ((L.map length).take i).sum = (L.take i).join :=
begin
induction L generalizing i, { simp },
cases i, { simp },
simp [take_append, L_ih]
end
/-- In a join, dropping all the elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/
lemma drop_sum_join (L : list (list α)) (i : ℕ) :
L.join.drop ((L.map length).take i).sum = (L.drop i).join :=
begin
induction L generalizing i, { simp },
cases i, { simp },
simp [drop_append, L_ih],
end
/-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is
left with a list of length `1` made of the `i`-th element of the original list. -/
lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) :
(L.take (i+1)).drop i = [nth_le L i hi] :=
begin
induction L generalizing i,
{ simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim },
cases i, { simp },
have : i < L_tl.length,
{ simp at hi,
exact nat.lt_of_succ_lt_succ hi },
simp [L_ih this],
refl
end
/-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the
original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and
`B` is the sum of the lengths of sublists of index `≤ i`. -/
lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) :
(L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi :=
begin
have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take],
simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi]
end
/-- Auxiliary lemma to control elements in a join. -/
lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum :=
by simp [hi, sum_take_succ, hj]
/-- Auxiliary lemma to control elements in a join. -/
lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
((L.map length).take i).sum + j < L.join.length :=
begin
convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi),
have : L.length = (L.map length).length, by simp,
simp [this, -length_map]
end
/-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist,
where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists
of index `< i`, and adding `j`. -/
lemma nth_le_join (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) =
nth_le (nth_le L i hi) j hj :=
by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj),
nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)]
/-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the
sublists. -/
theorem eq_iff_join_eq (L L' : list (list α)) :
L = L' ↔ L.join = L'.join ∧ map length L = map length L' :=
begin
refine ⟨λ H, by simp [H], _⟩,
rintros ⟨join_eq, length_eq⟩,
apply ext_le,
{ have : length (map length L) = length (map length L'), by rw length_eq,
simpa using this },
{ assume n h₁ h₂,
rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] }
end
/-! ### lexicographic ordering -/
/-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which
`[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`.
The definition is given for any relation `r`, not only strict orders. -/
inductive lex (r : α → α → Prop) : list α → list α → Prop
| nil {a l} : lex [] (a :: l)
| cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂)
| rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂)
namespace lex
theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} :
lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ :=
⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h;
[exact h, exact (irrefl_of r a h).elim], lex.cons⟩
@[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l [].
instance is_order_connected (r : α → α → Prop)
[is_order_connected α r] [is_trichotomous α r] :
is_order_connected (list α) (lex r) :=
⟨λ l₁, match l₁ with
| _, [], c::l₃, nil := or.inr nil
| _, [], c::l₃, rel _ := or.inr nil
| _, [], c::l₃, cons _ := or.inr nil
| _, b::l₂, c::l₃, nil := or.inl nil
| a::l₁, b::l₂, c::l₃, rel h :=
(is_order_connected.conn _ b _ h).imp rel rel
| a::l₁, b::l₂, _::l₃, cons h := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match _ l₂ _ h).imp cons cons },
{ exact or.inr (rel ab) }
end
end⟩
instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] :
is_trichotomous (list α) (lex r) :=
⟨λ l₁, match l₁ with
| [], [] := or.inr (or.inl rfl)
| [], b::l₂ := or.inl nil
| a::l₁, [] := or.inr (or.inr nil)
| a::l₁, b::l₂ := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match l₁ l₂).imp cons
(or.imp (congr_arg _) cons) },
{ exact or.inr (or.inr (rel ab)) }
end
end⟩
instance is_asymm (r : α → α → Prop)
[is_asymm α r] : is_asymm (list α) (lex r) :=
⟨λ l₁, match l₁ with
| a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂
| a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁
| a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂
| a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ :=
by exact _match _ _ h₁ h₂
end⟩
instance is_strict_total_order (r : α → α → Prop)
[is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) :=
{..is_strict_weak_order_of_is_order_connected}
instance decidable_rel [decidable_eq α] (r : α → α → Prop)
[decidable_rel r] : decidable_rel (lex r)
| l₁ [] := is_false $ λ h, by cases h
| [] (b::l₂) := is_true lex.nil
| (a::l₁) (b::l₂) := begin
haveI := decidable_rel l₁ l₂,
refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩,
{ rcases h with h | ⟨rfl, h⟩,
{ exact lex.rel h },
{ exact lex.cons h } },
{ rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩,
{ exact or.inr ⟨rfl, h⟩ },
{ exact or.inl h } }
end
theorem append_right (r : α → α → Prop) :
∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t)
| _ _ t nil := nil
| _ _ t (cons h) := cons (append_right _ h)
| _ _ t (rel r) := rel r
theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) :
∀ s, lex R (s ++ t₁) (s ++ t₂)
| [] := h
| (a::l) := cons (append_left l)
theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) :
∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂
| _ _ nil := nil
| _ _ (cons h) := cons (imp _ _ h)
| _ _ (rel r) := rel (H _ _ r)
theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂
| _ _ (cons h) e := to_ne h (list.cons.inj e).2
| _ _ (rel r) e := r (list.cons.inj e).1
theorem _root_.decidable.list.lex.ne_iff [decidable_eq α]
{l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ :=
⟨to_ne, λ h, begin
induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂,
{ contradiction },
{ apply nil },
{ exact (not_lt_of_ge H).elim (succ_pos _) },
{ by_cases ab : a = b,
{ subst b, apply cons,
exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) },
{ exact rel ab } }
end⟩
theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ :=
by classical; exact decidable.list.lex.ne_iff H
end lex
--Note: this overrides an instance in core lean
instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩
theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l :=
lex.nil
instance [linear_order α] : linear_order (list α) :=
linear_order_of_STO' (lex (<))
--Note: this overrides an instance in core lean
instance has_le' [linear_order α] : has_le (list α) :=
preorder.to_has_le _
/-! ### all & any -/
@[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl
@[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) :
all (a::l) p = (p a && all l p) := rfl
theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
simp only [all_cons, band_coe_iff, ih, forall_mem_cons]
end
theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p]
{l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a :=
by simp only [all_iff_forall, bool.of_to_bool_iff]
@[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl
@[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) :
any (a::l) p = (p a || any l p) := rfl
theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_false bool.not_ff (not_exists_mem_nil _) },
simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff]
end
theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p]
{l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a :=
by simp [any_iff_exists]
theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p :=
any_iff_exists.2 ⟨_, h₁, h₂⟩
@[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∀ x ∈ l, p x) :=
decidable_of_iff _ all_iff_forall_prop
instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∃ x ∈ l, p x) :=
decidable_of_iff _ any_iff_exists_prop
/-! ### map for partial functions -/
/-- Partial map. If `f : Π a, p a → β` is a partial function defined on
`a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`
but is defined only when all members of `l` satisfy `p`, using the proof
to apply `f`. -/
@[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β
| [] H := []
| (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2
/-- "Attach" the proof that the elements of `l` are in `l` to produce a new list
with the same elements but in the type `{x // x ∈ l}`. -/
def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id)
theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {l : list α} (hx : x ∈ l) :
sizeof x < sizeof l :=
begin
induction l with h t ih; cases hx,
{ rw hx, exact lt_add_of_lt_of_nonneg (lt_one_add _) (nat.zero_le _) },
{ exact lt_add_of_pos_of_le (zero_lt_one_add _) (le_of_lt (ih hx)) }
end
theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) :
@pmap _ _ p (λ a _, f a) l H = map f l :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f l H₁ = pmap g l H₂ :=
by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]]
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_map {p : β → Prop} (g : ∀ b, p b → γ) (f : α → β)
(l H) : pmap g (map f l) H = pmap (λ a h, g (f a) h) l (λ a h, H _ (mem_map_of_mem _ h)) :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) :=
by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl)
theorem attach_map_val (l : list α) : l.attach.map subtype.val = l :=
by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l)
@[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ :=
by have := mem_map.1 (by rw [attach_map_val]; exact h);
{ rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m }
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b :=
by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists]
@[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β}
{l H} : length (pmap f l H) = length l :=
by induction l; [refl, simp only [*, pmap, length]]
@[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap
@[simp] lemma pmap_eq_nil {p : α → Prop} {f : Π a, p a → β}
{l H} : pmap f l H = [] ↔ l = [] :=
by rw [← length_eq_zero, length_pmap, length_eq_zero]
@[simp] lemma attach_eq_nil (l : list α) : l.attach = [] ↔ l = [] := pmap_eq_nil
lemma last_pmap {α β : Type*} (p : α → Prop) (f : Π a, p a → β)
(l : list α) (hl₁ : ∀ a ∈ l, p a) (hl₂ : l ≠ []) :
(l.pmap f hl₁).last (mt list.pmap_eq_nil.1 hl₂) = f (l.last hl₂) (hl₁ _ (list.last_mem hl₂)) :=
begin
induction l with l_hd l_tl l_ih,
{ apply (hl₂ rfl).elim },
{ cases l_tl,
{ simp },
{ apply l_ih } }
end
lemma nth_pmap {p : α → Prop} (f : Π a, p a → β) {l : list α} (h : ∀ a ∈ l, p a) (n : ℕ) :
nth (pmap f l h) n = option.pmap f (nth l n) (λ x H, h x (nth_mem H)) :=
begin
induction l with hd tl hl generalizing n,
{ simp },
{ cases n; simp [hl] }
end
lemma nth_le_pmap {p : α → Prop} (f : Π a, p a → β) {l : list α} (h : ∀ a ∈ l, p a) {n : ℕ}
(hn : n < (pmap f l h).length) :
nth_le (pmap f l h) n hn = f (nth_le l n (@length_pmap _ _ p f l h ▸ hn))
(h _ (nth_le_mem l n (@length_pmap _ _ p f l h ▸ hn))) :=
begin
induction l with hd tl hl generalizing n,
{ simp only [length, pmap] at hn,
exact absurd hn (not_lt_of_le n.zero_le) },
{ cases n,
{ simp },
{ simpa [hl] } }
end
/-! ### find -/
section find
variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α}
@[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none :=
rfl
@[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a :=
if_pos h
@[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l :=
if_neg h
@[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x :=
begin
induction l with a l IH,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases h : p a,
{ simp only [find_cons_of_pos _ h, h, not_true, false_and] },
{ rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] }
end
theorem find_some (H : find p l = some a) : p a :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, exact h },
{ rw find_cons_of_neg _ h at H, exact IH H }
end
@[simp] theorem find_mem (H : find p l = some a) : a ∈ l :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self },
{ rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) }
end
end find
/-! ### lookmap -/
section lookmap
variables (f : α → option α)
@[simp] theorem lookmap_nil : [].lookmap f = [] := rfl
@[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) :
(a :: l).lookmap f = a :: l.lookmap f :=
by simp [lookmap, h]
@[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) :
(a :: l).lookmap f = b :: l :=
by simp [lookmap, h]
theorem lookmap_some : ∀ l : list α, l.lookmap some = l
| [] := rfl
| (a::l) := rfl
theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l
| [] := rfl
| (a::l) := congr_arg (cons a) (lookmap_none l)
theorem lookmap_congr {f g : α → option α} :
∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g
| [] H := rfl
| (a::l) H := begin
cases forall_mem_cons.1 H with H₁ H₂,
cases h : g a with b,
{ simp [h, H₁.trans h, lookmap_congr H₂] },
{ simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] }
end
theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l :=
(lookmap_congr H).trans (lookmap_none l)
theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) :
∀ l : list α, map g (l.lookmap f) = map g l
| [] := rfl
| (a::l) := begin
cases h' : f a with b,
{ simp [h', lookmap_map_eq] },
{ simp [lookmap_cons_some _ _ h', h _ _ h'] }
end
theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l :=
by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h
theorem length_lookmap (l : list α) : length (l.lookmap f) = length l :=
by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp
end lookmap
/-! ### filter_map -/
@[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) :
filter_map f (a :: l) = filter_map f l :=
by simp only [filter_map, h]
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (l : list α) {b : β} (h : f a = some b) :
filter_map f (a :: l) = b :: filter_map f l :=
by simp only [filter_map, h]; split; refl
lemma filter_map_append {α β : Type*} (l l' : list α) (f : α → option β) :
filter_map f (l ++ l') = filter_map f l ++ filter_map f l' :=
begin
induction l with hd tl hl generalizing l',
{ simp },
{ rw [cons_append, filter_map, filter_map],
cases f hd;
simp only [filter_map, hl, cons_append, eq_self_iff_true, and_self] }
end
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
begin
funext l,
induction l with a l IH, {refl},
simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl
end
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
begin
funext l,
induction l with a l IH, {refl},
by_cases pa : p a,
{ simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl },
{ simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] }
end
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) :
filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l :=
begin
induction l with a l IH, {refl},
cases h : f a with b,
{ rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH],
simp only [h, option.none_bind'] },
rw filter_map_cons_some _ _ _ h,
cases h' : g b with c;
[ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH],
rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ];
simp only [h, h', option.some_bind']
end
theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) :
map g (filter_map f l) = filter_map (λ x, (f x).map g) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) :
filter_map g (map f l) = filter_map (g ∘ f) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) :
filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l :=
by rw [← filter_map_eq_filter, filter_map_filter_map]; refl
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) :
filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l :=
begin
rw [← filter_map_eq_filter, filter_map_filter_map], congr,
funext x,
show (option.guard p x).bind f = ite (p x) (f x) none,
by_cases h : p x,
{ simp only [option.guard, if_pos h, option.some_bind'] },
{ simp only [option.guard, if_neg h, option.none_bind'] }
end
@[simp] theorem filter_map_some (l : list α) : filter_map some l = l :=
by rw filter_map_eq_map; apply map_id
@[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} :
b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b :=
begin
induction l with a l IH,
{ split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } },
cases h : f a with b',
{ have : f a ≠ some b, {rw h, intro, contradiction},
simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] },
{ have : f a = some b ↔ b = b',
{ split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} },
simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, this, exists_eq_left] }
end
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (l : list α) :
map g (filter_map f l) = l :=
by simp only [map_filter_map, H, filter_map_some]
theorem sublist.filter_map (f : α → option β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ :=
by induction s with l₁ l₂ a s IH l₁ l₂ a s IH;
simp only [filter_map]; cases f a with b;
simp only [filter_map, IH, sublist.cons, sublist.cons2]
theorem sublist.map (f : α → β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : map f l₁ <+ map f l₂ :=
filter_map_eq_map f ▸ s.filter_map _
/-! ### reduce_option -/
@[simp] lemma reduce_option_cons_of_some (x : α) (l : list (option α)) :
reduce_option (some x :: l) = x :: l.reduce_option :=
by simp only [reduce_option, filter_map, id.def, eq_self_iff_true, and_self]
@[simp] lemma reduce_option_cons_of_none (l : list (option α)) :
reduce_option (none :: l) = l.reduce_option :=
by simp only [reduce_option, filter_map, id.def]
@[simp] lemma reduce_option_nil : @reduce_option α [] = [] := rfl
@[simp] lemma reduce_option_map {l : list (option α)} {f : α → β} :
reduce_option (map (option.map f) l) = map f (reduce_option l) :=
begin
induction l with hd tl hl,
{ simp only [reduce_option_nil, map_nil] },
{ cases hd;
simpa only [true_and, option.map_some', map, eq_self_iff_true,
reduce_option_cons_of_some] using hl },
end
lemma reduce_option_append (l l' : list (option α)) :
(l ++ l').reduce_option = l.reduce_option ++ l'.reduce_option :=
filter_map_append l l' id
lemma reduce_option_length_le (l : list (option α)) :
l.reduce_option.length ≤ l.length :=
begin
induction l with hd tl hl,
{ simp only [reduce_option_nil, length] },
{ cases hd,
{ exact nat.le_succ_of_le hl },
{ simpa only [length, add_le_add_iff_right, reduce_option_cons_of_some] using hl} }
end
lemma reduce_option_length_eq_iff {l : list (option α)} :
l.reduce_option.length = l.length ↔ ∀ x ∈ l, option.is_some x :=
begin
induction l with hd tl hl,
{ simp only [forall_const, reduce_option_nil, not_mem_nil,
forall_prop_of_false, eq_self_iff_true, length, not_false_iff] },
{ cases hd,
{ simp only [mem_cons_iff, forall_eq_or_imp, bool.coe_sort_ff, false_and,
reduce_option_cons_of_none, length, option.is_some_none, iff_false],
intro H,
have := reduce_option_length_le tl,
rw H at this,
exact absurd (nat.lt_succ_self _) (not_lt_of_le this) },
{ simp only [hl, true_and, mem_cons_iff, forall_eq_or_imp, add_left_inj,
bool.coe_sort_tt, length, option.is_some_some, reduce_option_cons_of_some] } }
end
lemma reduce_option_length_lt_iff {l : list (option α)} :
l.reduce_option.length < l.length ↔ none ∈ l :=
begin
rw [(reduce_option_length_le l).lt_iff_ne, ne, reduce_option_length_eq_iff],
induction l; simp *,
rw [eq_comm, ← option.not_is_some_iff_eq_none, decidable.imp_iff_not_or]
end
lemma reduce_option_singleton (x : option α) :
[x].reduce_option = x.to_list :=
by cases x; refl
lemma reduce_option_concat (l : list (option α)) (x : option α) :
(l.concat x).reduce_option = l.reduce_option ++ x.to_list :=
begin
induction l with hd tl hl generalizing x,
{ cases x;
simp [option.to_list] },
{ simp only [concat_eq_append, reduce_option_append] at hl,
cases hd;
simp [hl, reduce_option_append] }
end
lemma reduce_option_concat_of_some (l : list (option α)) (x : α) :
(l.concat (some x)).reduce_option = l.reduce_option.concat x :=
by simp only [reduce_option_nil, concat_eq_append, reduce_option_append, reduce_option_cons_of_some]
lemma reduce_option_mem_iff {l : list (option α)} {x : α} :
x ∈ l.reduce_option ↔ (some x) ∈ l :=
by simp only [reduce_option, id.def, mem_filter_map, exists_eq_right]
lemma reduce_option_nth_iff {l : list (option α)} {x : α} :
(∃ i, l.nth i = some (some x)) ↔ ∃ i, l.reduce_option.nth i = some x :=
by rw [←mem_iff_nth, ←mem_iff_nth, reduce_option_mem_iff]
/-! ### filter -/
section filter
variables {p : α → Prop} [decidable_pred p]
theorem filter_eq_foldr (p : α → Prop) [decidable_pred p] (l : list α) :
filter p l = foldr (λ a out, if p a then a :: out else out) [] l :=
by induction l; simp [*, filter]
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
: ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l
| [] _ := rfl
| (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a;
[simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2],
simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]];
split; refl
@[simp] theorem filter_subset (l : list α) : filter p l ⊆ l :=
(filter_sublist l).subset
theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a
| (b::l) ain :=
if pb : p b then
have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain,
or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, begin rw [← this] at pb, exact pb end)
(assume : a ∈ filter p l, of_mem_filter this)
else
begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end
theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l :=
filter_subset l h
theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l
| (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self
| (b::l) (or.inr ain) pa := if pb : p b
then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa
else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa
@[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a :=
⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩
theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases p a,
{ rw [filter_cons_of_pos _ h, cons_inj, ih, and_iff_right h] },
{ rw [filter_cons_of_neg _ h],
refine iff_of_false _ (mt and.left h), intro e,
have := filter_sublist l, rw e at this,
exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) }
end
theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a :=
by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and]
variable (p)
theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ :=
filter_map_eq_filter p ▸ s.filter_map _
theorem map_filter (f : β → α) (l : list β) :
filter p (map f l) = map f (filter (p ∘ f) l) :=
by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl
@[simp] theorem filter_filter (q) [decidable_pred q] : ∀ l,
filter p (filter q l) = filter (λ a, p a ∧ q a) l
| [] := rfl
| (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false,
true_and, false_and, filter_filter l, eq_self_iff_true]
@[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) :
@filter α (λ _, true) h l = l :=
by convert filter_eq_self.2 (λ _ _, trivial)
@[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) :
@filter α (λ _, false) h l = [] :=
by convert filter_eq_nil.2 (λ _ _, id)
@[simp] theorem span_eq_take_drop : ∀ (l : list α), span p l = (take_while p l, drop_while p l)
| [] := rfl
| (a::l) :=
if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while]
else by simp only [span, take_while, drop_while, if_neg pa]
@[simp] theorem take_while_append_drop : ∀ (l : list α), take_while p l ++ drop_while p l = l
| [] := rfl
| (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append,
take_while_append_drop l]
else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append]
@[simp] theorem countp_nil : countp p [] = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 :=
if_pos pa
@[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l :=
if_neg pa
theorem countp_eq_length_filter (l) : countp p l = length (filter p l) :=
by induction l with x l ih; [refl, by_cases (p x)];
[simp only [filter_cons_of_pos _ h, countp, ih, if_pos h],
simp only [countp_cons_of_neg _ _ h, ih, filter_cons_of_neg _ h]]; refl
local attribute [simp] countp_eq_length_filter
@[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ :=
by simp only [countp_eq_length_filter, filter_append, length_append]
theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a :=
by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop]
theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ :=
by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter p s)
@[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) :
countp p (filter q l) = countp (λ a, p a ∧ q a) l :=
by simp only [countp_eq_length_filter, filter_filter]
end filter
/-! ### count -/
section count
variable [decidable_eq α]
@[simp] theorem count_nil (a : α) : count a [] = 0 := rfl
theorem count_cons (a b : α) (l : list α) :
count a (b :: l) = if a = b then succ (count a l) else count a l := rfl
theorem count_cons' (a b : α) (l : list α) :
count a (b :: l) = count a l + (if a = b then 1 else 0) :=
begin rw count_cons, split_ifs; refl end
@[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) :=
if_pos rfl
@[simp, priority 990]
theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l :=
if_neg h
theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length),
l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0
| (_ :: _) a h := by { rw [count_cons], split_ifs; simp }
theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ :=
countp_le_of_sublist _
theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) :=
count_le_of_sublist _ (sublist_cons _ _)
theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl
@[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ :=
countp_append _
theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) :=
by simp [-add_comm]
theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l :=
by simp only [count, countp_pos, exists_prop, exists_eq_right']
@[simp, priority 980]
theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 :=
decidable.by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l :=
λ h', ne_of_gt (count_pos.2 h') h
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat];
exact λ b m, (eq_of_mem_repeat m).symm
theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} :
n ≤ count a l ↔ repeat a n <+ l :=
⟨λ h, ((repeat_sublist_repeat a).2 h).trans $
have filter (eq a) l = repeat a (count a l), from eq_repeat.2
⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩,
by rw ← this; apply filter_sublist,
λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩
theorem repeat_count_eq_of_count_eq_length {a : α} {l : list α} (h : count a l = length l) :
repeat a (count a l) = l :=
eq_of_sublist_of_length_eq (le_count_iff_repeat_sublist.mp (le_refl (count a l)))
(eq.trans (length_repeat a (count a l)) h)
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {l : list α} (h : p a) : count a (filter p l) = count a l :=
by simp only [count, countp_filter]; congr; exact
set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h))
lemma count_bind {α β} [decidable_eq β] (l : list α) (f : α → list β) (x : β) :
count x (l.bind f) = sum (map (count x ∘ f) l) :=
begin
induction l with hd tl IH,
{ simp },
{ simpa }
end
@[simp] lemma count_map_map {α β} [decidable_eq α] [decidable_eq β] (l : list α) (f : α → β)
(hf : function.injective f) (x : α) :
count (f x) (map f l) = count x l :=
begin
induction l with y l IH generalizing x,
{ simp },
{ rw map_cons,
by_cases h : x = y,
{ simpa [h] using IH _ },
{ simpa [h, hf.ne h] using IH _ } }
end
end count
/-! ### prefix, suffix, infix -/
@[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩
@[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩
theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩
@[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) :=
by rw ← list.append_assoc; apply infix_append
theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩
theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩
@[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩
@[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩
@[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a]
theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp
theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨[], t, h⟩
theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩
@[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l
theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l
theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ :=
λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩
@[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃
| l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩
@[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃
| l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩
@[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃
| l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩
theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ :=
λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _)
theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_prefix
theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_suffix
theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ :=
⟨λ ⟨r, e⟩, ⟨reverse r,
by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩,
λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩
theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ :=
by rw ← reverse_suffix; simp only [reverse_reverse]
theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ :=
length_le_of_sublist $ sublist_of_infix s
theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] :=
eq_nil_of_sublist_nil $ sublist_of_infix s
@[simp] theorem eq_nil_iff_infix_nil {l : list α} : l <:+: [] ↔ l = [] :=
⟨eq_nil_of_infix_nil, λ h, h ▸ infix_refl _⟩
theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_prefix s
@[simp] theorem eq_nil_iff_prefix_nil {l : list α} : l <+: [] ↔ l = [] :=
⟨eq_nil_of_prefix_nil, λ h, h ▸ prefix_refl _⟩
theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_suffix s
@[simp] theorem eq_nil_iff_suffix_nil {l : list α} : l <:+ [] ↔ l = [] :=
⟨eq_nil_of_suffix_nil, λ h, h ▸ suffix_refl _⟩
theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ :=
⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩,
λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩
theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_infix s
theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_prefix s
theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_suffix s
theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α},
l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂
| [] l₂ l₃ h₁ h₂ _ := nil_prefix _
| (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin
injection e with _ e', subst b,
rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩
(le_of_succ_le_succ ll) with ⟨r₃, rfl⟩,
exact ⟨r₃, rfl⟩
end
theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ :=
(le_total (length l₁) (length l₂)).imp
(prefix_of_prefix_length_le h₁ h₂)
(prefix_of_prefix_length_le h₂ h₁)
theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ :=
reverse_prefix.1 $ prefix_of_prefix_length_le
(reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll])
theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ :=
(prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp
reverse_prefix.1 reverse_prefix.1
theorem suffix_cons_iff {x : α} {l₁ l₂ : list α} :
l₁ <:+ x :: l₂ ↔ l₁ = x :: l₂ ∨ l₁ <:+ l₂ :=
begin
split,
{ rintro ⟨⟨hd, tl⟩, hl₃⟩,
{ exact or.inl hl₃ },
{ simp only [cons_append] at hl₃,
exact or.inr ⟨_, hl₃.2⟩ } },
{ rintro (rfl | hl₁),
{ exact (x :: l₂).suffix_refl },
{ exact hl₁.trans (l₂.suffix_cons _) } }
end
theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L
| (_ :: L) l (or.inl rfl) := infix_append [] _ _
| (l' :: L) l (or.inr h) :=
is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _
theorem prefix_append_right_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ :=
exists_congr $ λ r, by rw [append_assoc, append_right_inj]
theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ :=
prefix_append_right_inj [a]
theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩
theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩
theorem tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix
lemma tail_sublist (l : list α) : l.tail <+ l := sublist_of_suffix (tail_suffix l)
theorem tail_subset (l : list α) : tail l ⊆ l := (tail_sublist l).subset
theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ :=
⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩
theorem suffix_iff_eq_append {l₁ l₂ : list α} :
l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ :=
⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩
theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ :=
⟨λ h, append_right_cancel $
(prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ take_prefix _ _⟩
theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ :=
⟨λ h, append_left_cancel $
(suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ drop_suffix _ _⟩
instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂)
| [] l₂ := is_true ⟨l₂, rfl⟩
| (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te
| (a::l₁) (b::l₂) :=
if h : a = b then
@decidable_of_iff _ _ (by rw [← h, prefix_cons_inj])
(decidable_prefix l₁ l₂)
else
is_false $ λ ⟨t, te⟩, h $ by injection te
-- Alternatively, use mem_tails
instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂)
| [] l₂ := is_true ⟨l₂, append_nil _⟩
| (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial
| l₁ l₂ := let len1 := length l₁, len2 := length l₂ in
if hl : len1 ≤ len2 then
decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop
else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h
lemma prefix_take_le_iff {L : list (list (option α))} {m n : ℕ} (hm : m < L.length) :
(take m L) <+: (take n L) ↔ m ≤ n :=
begin
simp only [prefix_iff_eq_take, length_take],
induction m with m IH generalizing L n,
{ simp only [min_eq_left, eq_self_iff_true, nat.zero_le, take] },
{ cases n,
{ simp only [nat.nat_zero_eq_zero, nonpos_iff_eq_zero, take, take_nil],
split,
{ cases L,
{ exact absurd hm (not_lt_of_le m.succ.zero_le) },
{ simp only [forall_prop_of_false, not_false_iff, take] } },
{ intro h,
contradiction } },
{ cases L with l ls,
{ exact absurd hm (not_lt_of_le m.succ.zero_le) },
{ simp only [length] at hm,
specialize @IH ls n (nat.lt_of_succ_lt_succ hm),
simp only [le_of_lt (nat.lt_of_succ_lt_succ hm), min_eq_left] at IH,
simp only [le_of_lt hm, IH, true_and, min_eq_left, eq_self_iff_true, length, take],
exact ⟨nat.succ_le_succ, nat.le_of_succ_le_succ⟩ } } },
end
lemma cons_prefix_iff {l l' : list α} {x y : α} :
x :: l <+: y :: l' ↔ x = y ∧ l <+: l' :=
begin
split,
{ rintro ⟨L, hL⟩,
simp only [cons_append] at hL,
exact ⟨hL.left, ⟨L, hL.right⟩⟩ },
{ rintro ⟨rfl, h⟩,
rwa [prefix_cons_inj] },
end
lemma map_prefix {l l' : list α} (f : α → β) (h : l <+: l') :
l.map f <+: l'.map f :=
begin
induction l with hd tl hl generalizing l',
{ simp only [nil_prefix, map_nil] },
{ cases l' with hd' tl',
{ simpa only using eq_nil_of_prefix_nil h },
{ rw cons_prefix_iff at h,
simp only [h, prefix_cons_inj, hl, map] } },
end
lemma is_prefix.filter_map {l l' : list α} (h : l <+: l') (f : α → option β) :
l.filter_map f <+: l'.filter_map f :=
begin
induction l with hd tl hl generalizing l',
{ simp only [nil_prefix, filter_map_nil] },
{ cases l' with hd' tl',
{ simpa only using eq_nil_of_prefix_nil h },
{ rw cons_prefix_iff at h,
rw [←@singleton_append _ hd _, ←@singleton_append _ hd' _, filter_map_append,
filter_map_append, h.left, prefix_append_right_inj],
exact hl h.right } },
end
lemma is_prefix.reduce_option {l l' : list (option α)} (h : l <+: l') :
l.reduce_option <+: l'.reduce_option :=
h.filter_map id
@[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t
| s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton],
⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩
| s (a::t) :=
suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa,
⟨λo, match s, o with
| ._, or.inl rfl := ⟨_, rfl⟩
| s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in
by rw [← hs, ← ht]; exact ⟨s, rfl⟩
end, λmi, match s, mi with
| [], ⟨._, rfl⟩ := or.inl rfl
| (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $
by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩
end⟩
@[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t
| s [] := by simp only [tails, mem_singleton];
exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩
| s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t];
exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from
⟨λo, match s, t, o with
| ._, t, or.inl rfl := suffix_refl _
| s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩
end, λe, match s, t, e with
| ._, t, ⟨[], rfl⟩ := or.inl rfl
| s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩)
end⟩
lemma inits_cons (a : α) (l : list α) : inits (a :: l) = [] :: l.inits.map (λ t, a :: t) :=
by simp
lemma tails_cons (a : α) (l : list α) : tails (a :: l) = (a :: l) :: l.tails :=
by simp
@[simp]
lemma inits_append : ∀ (s t : list α), inits (s ++ t) = s.inits ++ t.inits.tail.map (λ l, s ++ l)
| [] [] := by simp
| [] (a::t) := by simp
| (a::s) t := by simp [inits_append s t]
@[simp]
lemma tails_append : ∀ (s t : list α), tails (s ++ t) = s.tails.map (λ l, l ++ t) ++ t.tails.tail
| [] [] := by simp
| [] (a::t) := by simp
| (a::s) t := by simp [tails_append s t]
-- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'`
lemma inits_eq_tails :
∀ (l : list α), l.inits = (reverse $ map reverse $ tails $ reverse l)
| [] := by simp
| (a :: l) := by simp [inits_eq_tails l, map_eq_map_iff]
lemma tails_eq_inits :
∀ (l : list α), l.tails = (reverse $ map reverse $ inits $ reverse l)
| [] := by simp
| (a :: l) := by simp [tails_eq_inits l, append_left_inj]
lemma inits_reverse (l : list α) : inits (reverse l) = reverse (map reverse l.tails) :=
by { rw tails_eq_inits l, simp [reverse_involutive.comp_self], }
lemma tails_reverse (l : list α) : tails (reverse l) = reverse (map reverse l.inits) :=
by { rw inits_eq_tails l, simp [reverse_involutive.comp_self], }
lemma map_reverse_inits (l : list α) : map reverse l.inits = (reverse $ tails $ reverse l) :=
by { rw inits_eq_tails l, simp [reverse_involutive.comp_self], }
lemma map_reverse_tails (l : list α) : map reverse l.tails = (reverse $ inits $ reverse l) :=
by { rw tails_eq_inits l, simp [reverse_involutive.comp_self], }
@[simp] lemma length_tails (l : list α) : length (tails l) = length l + 1 :=
begin
induction l with x l IH,
{ simp },
{ simpa using IH }
end
@[simp] lemma length_inits (l : list α) : length (inits l) = length l + 1 :=
by simp [inits_eq_tails]
@[simp] lemma nth_le_tails (l : list α) (n : ℕ) (hn : n < length (tails l)) :
nth_le (tails l) n hn = l.drop n :=
begin
induction l with x l IH generalizing n,
{ simp },
{ cases n,
{ simp },
{ simpa using IH n _ } },
end
@[simp] lemma nth_le_inits (l : list α) (n : ℕ) (hn : n < length (inits l)) :
nth_le (inits l) n hn = l.take n :=
begin
induction l with x l IH generalizing n,
{ simp },
{ cases n,
{ simp },
{ simpa using IH n _ } }
end
instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂)
| [] l₂ := is_true ⟨[], l₂, rfl⟩
| (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $
append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h
| l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $
by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm;
exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩
/-! ### permutations -/
section permutations
theorem permutations_aux2_fst (t : α) (ts : list α) (r : list β) : ∀ (ys : list α) (f : list α → β),
(permutations_aux2 t ts r ys f).1 = ys ++ ts
| [] f := rfl
| (y::ys) f := match _, permutations_aux2_fst ys _ : ∀ o : list α × list β, o.1 = ys ++ ts →
(permutations_aux2._match_1 t y f o).1 = y :: ys ++ ts with
| ⟨_, zs⟩, rfl := rfl
end
@[simp] theorem permutations_aux2_snd_nil (t : α) (ts : list α) (r : list β) (f : list α → β) :
(permutations_aux2 t ts r [] f).2 = r := rfl
@[simp] theorem permutations_aux2_snd_cons (t : α) (ts : list α) (r : list β) (y : α) (ys : list α)
(f : list α → β) :
(permutations_aux2 t ts r (y::ys) f).2 = f (t :: y :: ys ++ ts) ::
(permutations_aux2 t ts r ys (λx : list α, f (y::x))).2 :=
match _, permutations_aux2_fst t ts r _ _ : ∀ o : list α × list β, o.1 = ys ++ ts →
(permutations_aux2._match_1 t y f o).2 = f (t :: y :: ys ++ ts) :: o.2 with
| ⟨_, zs⟩, rfl := rfl
end
/-- The `r` argument to `permutations_aux2` is the same as appending. -/
theorem permutations_aux2_append (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) :
(permutations_aux2 t ts nil ys f).2 ++ r = (permutations_aux2 t ts r ys f).2 :=
by induction ys generalizing f; simp *
/-- The `ts` argument to `permutations_aux2` can be folded into the `f` argument. -/
theorem permutations_aux2_comp_append {t : α} {ts ys : list α} {r : list β} (f : list α → β) :
(permutations_aux2 t [] r ys $ λ x, f (x ++ ts)).2 = (permutations_aux2 t ts r ys f).2 :=
begin
induction ys generalizing f,
{ simp },
{ simp [ys_ih (λ xs, f (ys_hd :: xs))] },
end
theorem map_permutations_aux2' {α β α' β'} (g : α → α') (g' : β → β')
(t : α) (ts ys : list α) (r : list β) (f : list α → β) (f' : list α' → β')
(H : ∀ a, g' (f a) = f' (map g a)) :
map g' (permutations_aux2 t ts r ys f).2 =
(permutations_aux2 (g t) (map g ts) (map g' r) (map g ys) f').2 :=
begin
induction ys generalizing f f'; simp *,
apply ys_ih, simp [H],
end
/-- The `f` argument to `permutations_aux2` when `r = []` can be eliminated. -/
theorem map_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) :
(permutations_aux2 t ts [] ys id).2.map f = (permutations_aux2 t ts [] ys f).2 :=
begin
convert map_permutations_aux2' id _ _ _ _ _ _ _ _; simp only [map_id, id.def],
exact (λ _, rfl)
end
/-- An expository lemma to show how all of `ts`, `r`, and `f` can be eliminated from
`permutations_aux2`.
`(permutations_aux2 t [] [] ys id).2`, which appears on the RHS, is a list whose elements are
produced by inserting `t` into every non-terminal position of `ys` in order. As an example:
```lean
#eval permutations_aux2 1 [] [] [2, 3, 4] id
-- [[1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4]]
```
-/
lemma permutations_aux2_snd_eq (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) :
(permutations_aux2 t ts r ys f).2 =
(permutations_aux2 t [] [] ys id).2.map (λ x, f (x ++ ts)) ++ r :=
by rw [← permutations_aux2_append, map_permutations_aux2, permutations_aux2_comp_append]
theorem map_map_permutations_aux2 {α α'} (g : α → α') (t : α) (ts ys : list α) :
map (map g) (permutations_aux2 t ts [] ys id).2 =
(permutations_aux2 (g t) (map g ts) [] (map g ys) id).2 :=
map_permutations_aux2' _ _ _ _ _ _ _ _ (λ _, rfl)
theorem map_map_permutations'_aux (f : α → β) (t : α) (ts : list α) :
map (map f) (permutations'_aux t ts) = permutations'_aux (f t) (map f ts) :=
by induction ts with a ts ih; [refl, {simp [← ih], refl}]
theorem permutations'_aux_eq_permutations_aux2 (t : α) (ts : list α) :
permutations'_aux t ts = (permutations_aux2 t [] [ts ++ [t]] ts id).2 :=
begin
induction ts with a ts ih, {refl},
simp [permutations'_aux, permutations_aux2_snd_cons, ih],
simp only [← permutations_aux2_append] {single_pass := tt},
simp [map_permutations_aux2],
end
theorem mem_permutations_aux2 {t : α} {ts : list α} {ys : list α} {l l' : list α} :
l' ∈ (permutations_aux2 t ts [] ys (append l)).2 ↔
∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l' = l ++ l₁ ++ t :: l₂ ++ ts :=
begin
induction ys with y ys ih generalizing l,
{ simp {contextual := tt} },
{ rw [permutations_aux2_snd_cons, show (λ (x : list α), l ++ y :: x) = append (l ++ [y]),
by funext; simp, mem_cons_iff, ih], split; intro h,
{ rcases h with e | ⟨l₁, l₂, l0, ye, _⟩,
{ subst l', exact ⟨[], y::ys, by simp⟩ },
{ substs l' ys, exact ⟨y::l₁, l₂, l0, by simp⟩ } },
{ rcases h with ⟨_ | ⟨y', l₁⟩, l₂, l0, ye, rfl⟩,
{ simp [ye] },
{ simp at ye, rcases ye with ⟨rfl, rfl⟩,
exact or.inr ⟨l₁, l₂, l0, by simp⟩ } } }
end
theorem mem_permutations_aux2' {t : α} {ts : list α} {ys : list α} {l : list α} :
l ∈ (permutations_aux2 t ts [] ys id).2 ↔
∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l = l₁ ++ t :: l₂ ++ ts :=
by rw [show @id (list α) = append nil, by funext; refl]; apply mem_permutations_aux2
theorem length_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) :
length (permutations_aux2 t ts [] ys f).2 = length ys :=
by induction ys generalizing f; simp *
theorem foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) :
foldr (λy r, (permutations_aux2 t ts r y id).2) r L =
L.bind (λ y, (permutations_aux2 t ts [] y id).2) ++ r :=
by induction L with l L ih; [refl, {simp [ih], rw ← permutations_aux2_append}]
theorem mem_foldr_permutations_aux2 {t : α} {ts : list α} {r L : list (list α)} {l' : list α} :
l' ∈ foldr (λy r, (permutations_aux2 t ts r y id).2) r L ↔ l' ∈ r ∨
∃ l₁ l₂, l₁ ++ l₂ ∈ L ∧ l₂ ≠ [] ∧ l' = l₁ ++ t :: l₂ ++ ts :=
have (∃ (a : list α), a ∈ L ∧
∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ a = l₁ ++ l₂ ∧ l' = l₁ ++ t :: (l₂ ++ ts)) ↔
∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ l₁ ++ l₂ ∈ L ∧ l' = l₁ ++ t :: (l₂ ++ ts),
from ⟨λ ⟨a, aL, l₁, l₂, l0, e, h⟩, ⟨l₁, l₂, l0, e ▸ aL, h⟩,
λ ⟨l₁, l₂, l0, aL, h⟩, ⟨_, aL, l₁, l₂, l0, rfl, h⟩⟩,
by rw foldr_permutations_aux2; simp [mem_permutations_aux2', this,
or.comm, or.left_comm, or.assoc, and.comm, and.left_comm, and.assoc]
theorem length_foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) :
length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = sum (map length L) + length r :=
by simp [foldr_permutations_aux2, (∘), length_permutations_aux2]
theorem length_foldr_permutations_aux2' (t : α) (ts : list α) (r L : list (list α))
(n) (H : ∀ l ∈ L, length l = n) :
length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = n * length L + length r :=
begin
rw [length_foldr_permutations_aux2, (_ : sum (map length L) = n * length L)],
induction L with l L ih, {simp},
have sum_map : sum (map length L) = n * length L :=
ih (λ l m, H l (mem_cons_of_mem _ m)),
have length_l : length l = n := H _ (mem_cons_self _ _),
simp [sum_map, length_l, mul_add, add_comm]
end
@[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] :=
by rw [permutations_aux, permutations_aux.rec]
@[simp] theorem permutations_aux_cons (t : α) (ts is : list α) :
permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2)
(permutations_aux ts (t::is)) (permutations is) :=
by rw [permutations_aux, permutations_aux.rec]; refl
@[simp] theorem permutations_nil : permutations ([] : list α) = [[]] :=
by rw [permutations, permutations_aux_nil]
theorem map_permutations_aux (f : α → β) : ∀ (ts is : list α),
map (map f) (permutations_aux ts is) = permutations_aux (map f ts) (map f is) :=
begin
refine permutations_aux.rec (by simp) _,
introv IH1 IH2, rw map at IH2,
simp only [foldr_permutations_aux2, map_append, map, map_map_permutations_aux2, permutations,
bind_map, IH1, append_assoc, permutations_aux_cons, cons_bind, ← IH2, map_bind],
end
theorem map_permutations (f : α → β) (ts : list α) :
map (map f) (permutations ts) = permutations (map f ts) :=
by rw [permutations, permutations, map, map_permutations_aux, map]
theorem map_permutations' (f : α → β) (ts : list α) :
map (map f) (permutations' ts) = permutations' (map f ts) :=
by induction ts with t ts ih; [refl, simp [← ih, map_bind, ← map_map_permutations'_aux, bind_map]]
theorem permutations_aux_append (is is' ts : list α) :
permutations_aux (is ++ ts) is' =
(permutations_aux is is').map (++ ts) ++ permutations_aux ts (is.reverse ++ is') :=
begin
induction is with t is ih generalizing is', {simp},
simp [foldr_permutations_aux2, ih, bind_map],
congr' 2, funext ys, rw [map_permutations_aux2],
simp only [← permutations_aux2_comp_append] {single_pass := tt},
simp only [id, append_assoc],
end
theorem permutations_append (is ts : list α) :
permutations (is ++ ts) = (permutations is).map (++ ts) ++ permutations_aux ts is.reverse :=
by simp [permutations, permutations_aux_append]
end permutations
/-! ### insert -/
section insert
variable [decidable_eq α]
@[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl
theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl
@[simp, priority 980]
theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l :=
by simp only [insert.def, if_pos h]
@[simp, priority 970]
theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l :=
by simp only [insert.def, if_neg h]; split; refl
@[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l :=
begin
by_cases h' : b ∈ l,
{ simp only [insert_of_mem h'],
apply (or_iff_right_of_imp _).symm,
exact λ e, e.symm ▸ h' },
simp only [insert_of_not_mem h', mem_cons_iff]
end
@[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l :=
by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]]
@[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l :=
mem_insert_iff.2 (or.inl rfl)
theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l :=
mem_insert_iff.2 (or.inr h)
theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l :=
mem_insert_iff.1 h
@[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) :
length (insert a l) = length l :=
by rw insert_of_mem h
@[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) :
length (insert a l) = length l + 1 :=
by rw insert_of_not_mem h; refl
end insert
/-! ### erasep -/
section erasep
variables {p : α → Prop} [decidable_pred p]
@[simp] theorem erasep_nil : [].erasep p = [] := rfl
theorem erasep_cons (a : α) (l : list α) :
(a :: l).erasep p = if p a then l else a :: l.erasep p := rfl
@[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l :=
by simp [erasep_cons, h]
@[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) :
(a::l).erasep p = a :: l.erasep p :=
by simp [erasep_cons, h]
theorem erasep_of_forall_not {l : list α}
(h : ∀ a ∈ l, ¬ p a) : l.erasep p = l :=
by induction l with _ _ ih; [refl,
simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]]
theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) :
∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
induction l with b l IH, {cases al},
by_cases pb : p b,
{ exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ },
{ rcases al with rfl | al, {exact pb.elim pa},
rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩,
h₂, by rw h₃; refl, by simp [pb, h₄]⟩ }
end
theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) :
l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
by_cases h : ∃ a ∈ l, p a,
{ rcases h with ⟨a, ha, pa⟩,
exact or.inr (exists_of_erasep ha pa) },
{ simp at h, exact or.inl (erasep_of_forall_not h) }
end
@[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) :
length (l.erasep p) = pred (length l) :=
by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩;
rw e₂; simp [-add_comm, e₁]; refl
theorem erasep_append_left {a : α} (pa : p a) :
∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂
| (x::xs) l₂ h := begin
by_cases h' : p x; simp [h'],
rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h),
rintro rfl, exact pa
end
theorem erasep_append_right :
∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p
| [] l₂ h := rfl
| (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1,
erasep_append_right _ (forall_mem_cons.1 h).2]
theorem erasep_sublist (l : list α) : l.erasep p <+ l :=
by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩;
[rw h, {rw [h₄, h₃], simp}]
theorem erasep_subset (l : list α) : l.erasep p ⊆ l :=
(erasep_sublist l).subset
theorem sublist.erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p :=
begin
induction s,
case list.sublist.slnil { refl },
case list.sublist.cons : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] },
case list.sublist.cons2 : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [s, IH.cons2 _ _ _] }
end
theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l :=
@erasep_subset _ _ _ _ _
@[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l :=
⟨mem_of_mem_erasep, λ al, begin
rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
{ rwa h },
{ rw h₄, rw h₃ at al,
have : a ≠ c, {rintro rfl, exact pa.elim h₂},
simpa [this] using al }
end⟩
theorem erasep_map (f : β → α) :
∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f))
| [] := rfl
| (b::l) := by by_cases p (f b); simp [h, erasep_map l]
@[simp] theorem extractp_eq_find_erasep :
∀ l : list α, extractp p l = (find p l, erasep p l)
| [] := rfl
| (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l]
end erasep
/-! ### erase -/
section erase
variable [decidable_eq α]
@[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl
theorem erase_cons (a b : α) (l : list α) :
(b :: l).erase a = if b = a then l else b :: l.erase a := rfl
@[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l :=
by simp only [erase_cons, if_pos rfl]
@[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) :
(b::l).erase a = b :: l.erase a :=
by simp only [erase_cons, if_neg h]; split; refl
theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) :=
by { induction l with b l, {refl},
by_cases a = b; [simp [h], simp [h, ne.symm h, *]] }
@[simp, priority 980]
theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l :=
by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h'
theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) :
∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ :=
by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩;
rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩
@[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) :
length (l.erase a) = pred (length l) :=
by rw erase_eq_erasep; exact length_erasep_of_mem h rfl
theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) :
(l₁++l₂).erase a = l₁.erase a ++ l₂ :=
by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h
theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) :
(l₁++l₂).erase a = l₁ ++ l₂.erase a :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right];
rintro b h' rfl; exact h h'
theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l :=
by rw erase_eq_erasep; apply erasep_sublist
theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l :=
(erase_sublist a l).subset
theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a :=
by simp [erase_eq_erasep]; exact sublist.erasep h
theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l :=
@erase_subset _ _ _ _ _
@[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l :=
by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm
theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a :=
if ab : a = b then by rw ab else
if ha : a ∈ l then
if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with
| ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb :=
if h₁ : b ∈ l₁ then
by rw [erase_append_left _ h₁, erase_append_left _ h₁,
erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head]
else
by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha',
erase_cons_tail _ ab, erase_cons_head]
end
else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)]
else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)]
theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α}
(l : list α) : map f (l.erase a) = (map f l).erase (f a) :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr;
ext b; simp [finj.eq_iff]
theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ :=
by induction l₂ generalizing l₁; [refl,
simp only [foldl_cons, map_erase finj, *]]
@[simp] theorem count_erase_self (a : α) :
∀ (s : list α), count a (list.erase s a) = pred (count a s)
| [] := by simp
| (h :: t) :=
begin
rw erase_cons,
by_cases p : h = a,
{ rw [if_pos p, count_cons', if_pos p.symm], simp },
{ rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self],
simp, }
end
@[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) :
∀ (s : list α), count a (list.erase s b) = count a s
| [] := by simp
| (x :: xs) :=
begin
rw erase_cons,
split_ifs with h,
{ rw [count_cons', h, if_neg ab], simp },
{ rw [count_cons', count_cons', count_erase_of_ne] }
end
end erase
/-! ### diff -/
section diff
variable [decidable_eq α]
@[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl
@[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ :=
if h : a ∈ l₁ then by simp only [list.diff, if_pos h]
else by simp only [list.diff, if_neg h, erase_of_not_mem h]
lemma diff_cons_right (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.diff l₂).erase a :=
begin
induction l₂ with b l₂ ih generalizing l₁ a,
{ simp_rw [diff_cons, diff_nil] },
{ rw [diff_cons, diff_cons, erase_comm, ← diff_cons, ih, ← diff_cons] }
end
lemma diff_erase (l₁ l₂ : list α) (a : α) : (l₁.diff l₂).erase a = (l₁.erase a).diff l₂ :=
by rw [← diff_cons_right, diff_cons]
@[simp] theorem nil_diff (l : list α) : [].diff l = [] :=
by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]]
theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂
| l₁ [] := rfl
| l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _)
@[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ :=
by simp only [diff_eq_foldl, foldl_append]
@[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) :=
by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj]
theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁
| l₁ [] := sublist.refl _
| l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _
... <+ l₁.erase a : diff_sublist _ _
... <+ l₁ : list.erase_sublist _ _
theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ :=
(diff_sublist _ _).subset
theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂
| l₁ [] h₁ h₂ := h₁
| l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact
mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂)
theorem sublist.diff_right : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃
| l₁ l₂ [] h := h
| l₁ l₂ (a::l₃) h := by simp only
[diff_cons, (h.erase _).diff_right]
theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α},
l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁
| [] l₂ h := erase_sublist _ _
| (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons]
else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons,
erase_comm a b l₂]
using erase_diff_erase_sublist_of_sublist (h.erase b)
end diff
/-! ### enum -/
theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l
| n [] := rfl
| n (a::l) := congr_arg nat.succ (length_enum_from _ _)
theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _
@[simp] theorem enum_from_nth : ∀ n (l : list α) m,
nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m
| n [] m := rfl
| n (a :: l) 0 := rfl
| n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $
by rw [add_right_comm]; refl
@[simp] theorem enum_nth : ∀ (l : list α) n,
nth (enum l) n = (λ a, (n, a)) <$> nth l n :=
by simp only [enum, enum_from_nth, zero_add]; intros; refl
@[simp] theorem enum_from_map_snd : ∀ n (l : list α),
map prod.snd (enum_from n l) = l
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _)
@[simp] theorem enum_map_snd : ∀ (l : list α),
map prod.snd (enum l) = l := enum_from_map_snd _
theorem mem_enum_from {x : α} {i : ℕ} :
∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs
| j [] := by simp [enum_from]
| j (y :: ys) :=
suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys →
j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys),
by simpa [enum_from, mem_enum_from ys],
begin
rintro (h|h),
{ refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩,
apply nat.lt_add_of_pos_right; simp },
{ obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h,
refine ⟨_, _, _⟩,
{ exact le_trans (nat.le_succ _) hji },
{ convert hijlen using 1, ac_refl },
{ simp [hmem] } }
end
/-! ### product -/
@[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl
@[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β)
: product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl
@[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = []
| [] := rfl
| (a::l) := by rw [product_cons, product_nil]; refl
@[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} :
(a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ :=
by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop,
and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right]
theorem length_product (l₁ : list α) (l₂ : list β) :
length (product l₁ l₂) = length l₁ * length l₂ :=
by induction l₁ with x l₁ IH; [exact (zero_mul _).symm,
simp only [length, product_cons, length_append, IH,
right_distrib, one_mul, length_map, add_comm]]
/-! ### sigma -/
section
variable {σ : α → Type*}
@[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl
@[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a))
: (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl
@[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = []
| [] := rfl
| (a::l) := by rw [sigma_cons, sigma_nil]; refl
@[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} :
sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a :=
by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left,
and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right]
theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum :=
by induction l₁ with x l₁ IH; [refl,
simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]]
end
/-! ### disjoint -/
section disjoint
theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁
| a i₂ i₁ := d i₁ i₂
theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl
theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ :=
disjoint_comm
theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) :
disjoint l₁ l₂
| x m₁ := d (ss m₁)
theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) :
disjoint l₁ l₂
| x m m₁ := d m (ss m₁)
theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (list.subset_cons _ _)
theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (list.subset_cons _ _)
@[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l
| a := (not_mem_nil a).elim
@[simp] theorem disjoint_nil_right (l : list α) : disjoint l [] :=
by rw disjoint_comm; exact disjoint_nil_left _
@[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l :=
by simp only [disjoint, mem_singleton, forall_eq]; refl
@[simp, priority 1100] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l :=
by rw disjoint_comm; simp only [singleton_disjoint]
@[simp] theorem disjoint_append_left {l₁ l₂ l : list α} :
disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l :=
by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_append_right {l₁ l₂ l : list α} :
disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} :
disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ :=
(@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint]
@[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} :
disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left]
theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) :
disjoint l₁ l :=
(disjoint_append_left.1 d).1
theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) :
disjoint l₂ l :=
(disjoint_append_left.1 d).2
theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) :
disjoint l l₁ :=
(disjoint_append_right.1 d).1
theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) :
disjoint l l₂ :=
(disjoint_append_right.1 d).2
theorem disjoint_take_drop {l : list α} {m n : ℕ} (hl : l.nodup) (h : m ≤ n) :
disjoint (l.take m) (l.drop n) :=
begin
induction l generalizing m n,
case list.nil : m n
{ simp },
case list.cons : x xs xs_ih m n
{ cases m; cases n; simp only [disjoint_cons_left, mem_cons_iff, disjoint_cons_right, drop,
true_or, eq_self_iff_true, not_true, false_and,
disjoint_nil_left, take],
{ cases h },
cases hl with _ _ h₀ h₁, split,
{ intro h, exact h₀ _ (mem_of_mem_drop h) rfl, },
solve_by_elim [le_of_succ_le_succ] { max_depth := 4 } },
end
end disjoint
/-! ### union -/
section union
variable [decidable_eq α]
@[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl
@[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl
@[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ :=
by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff,
mem_cons_iff, or_assoc, *]
theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inl h)
theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inr h)
theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂
| [] l₂ := ⟨[], by refl, rfl⟩
| (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
if h : a ∈ l₁ ∪ l₂
then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩
else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h];
split; refl⟩
theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ :=
(sublist_suffix_of_union l₁ l₂).imp (λ a, and.right)
theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ :=
let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
e ▸ (append_sublist_append_right _).2 s
theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_union, or_imp_distrib, forall_and_distrib]
theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x :=
(forall_mem_union.1 h).1
theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x :=
(forall_mem_union.1 h).2
end union
/-! ### inter -/
section inter
variable [decidable_eq α]
@[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl
@[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) :
(a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) :=
if_pos h
@[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) :
(a::l₁) ∩ l₂ = l₁ ∩ l₂ :=
if_neg h
theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ :=
mem_of_mem_filter
theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ :=
of_mem_filter
theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ :=
mem_filter_of_mem
@[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ :=
mem_filter
theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ :=
filter_subset _
theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ :=
λ a, mem_of_mem_inter_right
theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ :=
λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩
theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ :=
by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl
theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x)
(l₂ : list α) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_left) h
theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α}
(h : ∀ x ∈ l₂, p x) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_right) h
@[simp] lemma inter_reverse {xs ys : list α} :
xs.inter ys.reverse = xs.inter ys :=
by simp only [list.inter, mem_reverse]; congr
end inter
section choose
variables (p : α → Prop) [decidable_pred p] (l : list α)
lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
/-! ### map₂_left' -/
section map₂_left'
-- The definitional equalities for `map₂_left'` can already be used by the
-- simplifie because `map₂_left'` is marked `@[simp]`.
@[simp] theorem map₂_left'_nil_right (f : α → option β → γ) (as) :
map₂_left' f as [] = (as.map (λ a, f a none), []) :=
by cases as; refl
end map₂_left'
/-! ### map₂_right' -/
section map₂_right'
variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem map₂_right'_nil_left :
map₂_right' f [] bs = (bs.map (f none), []) :=
by cases bs; refl
@[simp] theorem map₂_right'_nil_right :
map₂_right' f as [] = ([], as) :=
rfl
@[simp] theorem map₂_right'_nil_cons :
map₂_right' f [] (b :: bs) = (f none b :: bs.map (f none), []) :=
rfl
@[simp] theorem map₂_right'_cons_cons :
map₂_right' f (a :: as) (b :: bs) =
let rec := map₂_right' f as bs in
(f (some a) b :: rec.fst, rec.snd) :=
rfl
end map₂_right'
/-! ### zip_left' -/
section zip_left'
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_left'_nil_right :
zip_left' as ([] : list β) = (as.map (λ a, (a, none)), []) :=
by cases as; refl
@[simp] theorem zip_left'_nil_left :
zip_left' ([] : list α) bs = ([], bs) :=
rfl
@[simp] theorem zip_left'_cons_nil :
zip_left' (a :: as) ([] : list β) = ((a, none) :: as.map (λ a, (a, none)), []) :=
rfl
@[simp] theorem zip_left'_cons_cons :
zip_left' (a :: as) (b :: bs) =
let rec := zip_left' as bs in
((a, some b) :: rec.fst, rec.snd) :=
rfl
end zip_left'
/-! ### zip_right' -/
section zip_right'
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_right'_nil_left :
zip_right' ([] : list α) bs = (bs.map (λ b, (none, b)), []) :=
by cases bs; refl
@[simp] theorem zip_right'_nil_right :
zip_right' as ([] : list β) = ([], as) :=
rfl
@[simp] theorem zip_right'_nil_cons :
zip_right' ([] : list α) (b :: bs) = ((none, b) :: bs.map (λ b, (none, b)), []) :=
rfl
@[simp] theorem zip_right'_cons_cons :
zip_right' (a :: as) (b :: bs) =
let rec := zip_right' as bs in
((some a, b) :: rec.fst, rec.snd) :=
rfl
end zip_right'
/-! ### map₂_left -/
section map₂_left
variables (f : α → option β → γ) (as : list α)
-- The definitional equalities for `map₂_left` can already be used by the
-- simplifier because `map₂_left` is marked `@[simp]`.
@[simp] theorem map₂_left_nil_right :
map₂_left f as [] = as.map (λ a, f a none) :=
by cases as; refl
theorem map₂_left_eq_map₂_left' : ∀ as bs,
map₂_left f as bs = (map₂_left' f as bs).fst
| [] bs := by simp!
| (a :: as) [] := by simp!
| (a :: as) (b :: bs) := by simp! [*]
theorem map₂_left_eq_map₂ : ∀ as bs,
length as ≤ length bs →
map₂_left f as bs = map₂ (λ a b, f a (some b)) as bs
| [] [] h := by simp!
| [] (b :: bs) h := by simp!
| (a :: as) [] h := by { simp at h, contradiction }
| (a :: as) (b :: bs) h := by { simp at h, simp! [*] }
end map₂_left
/-! ### map₂_right -/
section map₂_right
variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem map₂_right_nil_left :
map₂_right f [] bs = bs.map (f none) :=
by cases bs; refl
@[simp] theorem map₂_right_nil_right :
map₂_right f as [] = [] :=
rfl
@[simp] theorem map₂_right_nil_cons :
map₂_right f [] (b :: bs) = f none b :: bs.map (f none) :=
rfl
@[simp] theorem map₂_right_cons_cons :
map₂_right f (a :: as) (b :: bs) = f (some a) b :: map₂_right f as bs :=
rfl
theorem map₂_right_eq_map₂_right' :
map₂_right f as bs = (map₂_right' f as bs).fst :=
by simp only [map₂_right, map₂_right', map₂_left_eq_map₂_left']
theorem map₂_right_eq_map₂ (h : length bs ≤ length as) :
map₂_right f as bs = map₂ (λ a b, f (some a) b) as bs :=
begin
have : (λ a b, flip f a (some b)) = (flip (λ a b, f (some a) b)) := rfl,
simp only [map₂_right, map₂_left_eq_map₂, map₂_flip, *]
end
end map₂_right
/-! ### zip_left -/
section zip_left
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_left_nil_right :
zip_left as ([] : list β) = as.map (λ a, (a, none)) :=
by cases as; refl
@[simp] theorem zip_left_nil_left :
zip_left ([] : list α) bs = [] :=
rfl
@[simp] theorem zip_left_cons_nil :
zip_left (a :: as) ([] : list β) = (a, none) :: as.map (λ a, (a, none)) :=
rfl
@[simp] theorem zip_left_cons_cons :
zip_left (a :: as) (b :: bs) = (a, some b) :: zip_left as bs :=
rfl
theorem zip_left_eq_zip_left' :
zip_left as bs = (zip_left' as bs).fst :=
by simp only [zip_left, zip_left', map₂_left_eq_map₂_left']
end zip_left
/-! ### zip_right -/
section zip_right
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_right_nil_left :
zip_right ([] : list α) bs = bs.map (λ b, (none, b)) :=
by cases bs; refl
@[simp] theorem zip_right_nil_right :
zip_right as ([] : list β) = [] :=
rfl
@[simp] theorem zip_right_nil_cons :
zip_right ([] : list α) (b :: bs) = (none, b) :: bs.map (λ b, (none, b)) :=
rfl
@[simp] theorem zip_right_cons_cons :
zip_right (a :: as) (b :: bs) = (some a, b) :: zip_right as bs :=
rfl
theorem zip_right_eq_zip_right' :
zip_right as bs = (zip_right' as bs).fst :=
by simp only [zip_right, zip_right', map₂_right_eq_map₂_right']
end zip_right
/-! ### to_chunks -/
section to_chunks
@[simp] theorem to_chunks_nil (n) : @to_chunks α n [] = [] := by cases n; refl
theorem to_chunks_aux_eq (n) : ∀ xs i,
@to_chunks_aux α n xs i = (xs.take i, (xs.drop i).to_chunks (n+1))
| [] i := by cases i; refl
| (x::xs) 0 := by rw [to_chunks_aux, drop, to_chunks]; cases to_chunks_aux n xs n; refl
| (x::xs) (i+1) := by rw [to_chunks_aux, to_chunks_aux_eq]; refl
theorem to_chunks_eq_cons' (n) : ∀ {xs : list α} (h : xs ≠ []),
xs.to_chunks (n+1) = xs.take (n+1) :: (xs.drop (n+1)).to_chunks (n+1)
| [] e := (e rfl).elim
| (x::xs) _ := by rw [to_chunks, to_chunks_aux_eq]; refl
theorem to_chunks_eq_cons : ∀ {n} {xs : list α} (n0 : n ≠ 0) (x0 : xs ≠ []),
xs.to_chunks n = xs.take n :: (xs.drop n).to_chunks n
| 0 _ e := (e rfl).elim
| (n+1) xs _ := to_chunks_eq_cons' _
theorem to_chunks_aux_join {n} : ∀ {xs i l L}, @to_chunks_aux α n xs i = (l, L) → l ++ L.join = xs
| [] _ _ _ rfl := rfl
| (x::xs) i l L e := begin
cases i; [
cases e' : to_chunks_aux n xs n with l L,
cases e' : to_chunks_aux n xs i with l L];
{ rw [to_chunks_aux, e', to_chunks_aux] at e, cases e,
exact (congr_arg (cons x) (to_chunks_aux_join e') : _) }
end
@[simp] theorem to_chunks_join : ∀ n xs, (@to_chunks α n xs).join = xs
| n [] := by cases n; refl
| 0 (x::xs) := by simp only [to_chunks, join]; rw append_nil
| (n+1) (x::xs) := begin
rw to_chunks,
cases e : to_chunks_aux n xs n with l L,
exact (congr_arg (cons x) (to_chunks_aux_join e) : _),
end
theorem to_chunks_length_le : ∀ n xs, n ≠ 0 → ∀ l : list α,
l ∈ @to_chunks α n xs → l.length ≤ n
| 0 _ e _ := (e rfl).elim
| (n+1) xs _ l := begin
refine (measure_wf length).induction xs _, intros xs IH h,
by_cases x0 : xs = [], {subst xs, cases h},
rw to_chunks_eq_cons' _ x0 at h, rcases h with rfl|h,
{ apply length_take_le },
{ refine IH _ _ h,
simp only [measure, inv_image, length_drop],
exact nat.sub_lt_self (length_pos_iff_ne_nil.2 x0) (succ_pos _) },
end
end to_chunks
/-! ### Miscellaneous lemmas -/
theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l
| a [] := or.inl rfl
| a (b::l) := or.inr (ilast'_mem b l)
@[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) :
(L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) :=
calc (L.attach.nth_le i H).1
= (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map'
... = L.nth_le i _ : by congr; apply attach_map_val
end list
@[to_additive]
theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) :
f l.prod = (l.map f).prod :=
(l.prod_hom f).symm
namespace list
@[to_additive]
theorem prod_map_hom {α β γ : Type*} [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) :
(L.map (g ∘ f)).prod = g ((L.map f).prod) :=
by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm}
theorem sum_map_mul_left {α : Type*} [semiring α] {β : Type*} (L : list β)
(f : β → α) (r : α) :
(L.map (λ b, r * f b)).sum = r * (L.map f).sum :=
sum_map_hom L f $ add_monoid_hom.mul_left r
theorem sum_map_mul_right {α : Type*} [semiring α] {β : Type*} (L : list β)
(f : β → α) (r : α) :
(L.map (λ b, f b * r)).sum = (L.map f).sum * r :=
sum_map_hom L f $ add_monoid_hom.mul_right r
universes u v
@[simp]
theorem mem_map_swap {α : Type u} {β : Type v} (x : α) (y : β) (xs : list (α × β)) :
(y, x) ∈ map prod.swap xs ↔ (x, y) ∈ xs :=
begin
induction xs with x xs,
{ simp only [not_mem_nil, map_nil] },
{ cases x with a b,
simp only [mem_cons_iff, prod.mk.inj_iff, map, prod.swap_prod_mk,
prod.exists, xs_ih, and_comm] },
end
lemma slice_eq {α} (xs : list α) (n m : ℕ) :
slice n m xs = xs.take n ++ xs.drop (n+m) :=
begin
induction n generalizing xs,
{ simp [slice] },
{ cases xs; simp [slice, *, nat.succ_add], }
end
lemma sizeof_slice_lt {α} [has_sizeof α] (i j : ℕ) (hj : 0 < j) (xs : list α) (hi : i < xs.length) :
sizeof (list.slice i j xs) < sizeof xs :=
begin
induction xs generalizing i j,
case list.nil : i j h
{ cases hi },
case list.cons : x xs xs_ih i j h
{ cases i; simp only [-slice_eq, list.slice],
{ cases j, cases h,
dsimp only [drop], unfold_wf,
apply @lt_of_le_of_lt _ _ _ xs.sizeof,
{ clear_except,
induction xs generalizing j; unfold_wf,
case list.nil : j
{ refl },
case list.cons : xs_hd xs_tl xs_ih j
{ cases j; unfold_wf, refl,
transitivity, apply xs_ih,
simp }, },
unfold_wf, apply zero_lt_one_add, },
{ unfold_wf, apply xs_ih _ _ h,
apply lt_of_succ_lt_succ hi, } },
end
end list
|
b99f7f92966d38d5dd45bd523489ed0de4aec50a | e09201d437062e1f95e6e5360aab0c9f947901aa | /src/automata/dfa_equivalence.lean | 2f4ecf716a4150239ea74cfb4d261959bfc6fcd0 | [] | no_license | VArtem/lean-regular-languages | 34f4b093f28ef2f09ba7e684e642a0f97c901560 | e877243188253d0ac17ccf0ae2da7bf608686ff0 | refs/heads/master | 1,683,590,111,306 | 1,622,307,234,000 | 1,622,307,234,000 | 284,232,653 | 7 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,493 | lean | import data.fintype.basic
structure dfa (S : Type) [fintype S] :=
(Q : Type) -- states
[Qfin : fintype Q]
(start : Q) -- starting state
(term : set Q) -- terminal states
(next : Q → S → Q) -- transitions
variables {S : Type} [fintype S] (d : dfa S)
namespace dfa
open_locale classical
noncomputable theory
instance : fintype d.Q := d.Qfin
def go {d : dfa S} : d.Q → list S → d.Q
| q [] := q
| q (head :: tail) := go (d.next q head) tail
@[simp] lemma go_nil (a : d.Q) : go a [] = a := rfl
@[simp] lemma go_cons (a : d.Q) (head : S) (tail : list S) : go a (head :: tail) = go (d.next a head) tail := rfl
@[simp] lemma go_append (q : d.Q) (u v : list S) :
go q (u ++ v) = go (go q u) v :=
begin
induction u with hd tl ih generalizing q, {
simp,
}, {
specialize ih (d.next q hd),
simpa using ih,
}
end
def state_equiv (d : dfa S) (u v : d.Q) := ∀ (w : list S), go u w ∈ d.term ↔ go v w ∈ d.term
@[simp] lemma state_equiv_def (u v : d.Q) : state_equiv d u v = ∀ w, go u w ∈ d.term ↔ go v w ∈ d.term := rfl
lemma state_equiv_reflexive : reflexive (state_equiv d) := λ v, by simp
lemma state_equiv_symmetric : symmetric (state_equiv d) := λ u v h w, by simp only [h w]
lemma state_equiv_transitive : transitive (state_equiv d) := λ a b c hab hbc w, by simp only [hab w, hbc w]
lemma state_equiv_equivalence: equivalence (state_equiv d) :=
⟨state_equiv_reflexive d, state_equiv_symmetric d, state_equiv_transitive d⟩
instance setoid : setoid d.Q := ⟨state_equiv d, state_equiv_equivalence d⟩
def Q' (d : dfa S) := quotient d.setoid
@[simp] lemma state_equiv_equiv (a b : d.Q) : a ≈ b ↔ ∀ w, go a w ∈ d.term ↔ go b w ∈ d.term := by refl
def term' (d : dfa S) : set d.Q' := quotient.lift (d.term)
begin
rintro a b hab,
specialize hab [],
simpa using hab,
end
def next' (d : dfa S) (c : S) : d.Q' → d.Q' := quotient.lift (λ q, ⟦d.next q c⟧)
begin
rintro a b hab,
dsimp only,
rw [quotient.eq, state_equiv_equiv],
intro w,
specialize hab (c :: w),
simpa using hab,
end
def min_dfa (d : dfa S) : dfa S :=
{ Q := Q' d,
Qfin := quotient.fintype _,
start := ⟦d.start⟧,
term := term' d,
next := λ q c, next' d c q}
@[simp] lemma min_dfa_Q {d : dfa S} : (min_dfa d).Q = quotient (d.setoid) := rfl
@[simp] lemma min_dfa_start {d : dfa S} : (min_dfa d).start = ⟦d.start⟧ := rfl
@[simp] lemma min_dfa_term {d : dfa S} {q} : ⟦q⟧ ∈ (min_dfa d).term ↔ q ∈ d.term := by refl
@[simp] lemma min_dfa_next {d : dfa S} {q} {c : S}: (min_dfa d).next ⟦q⟧ c = ⟦d.next q c⟧ := by refl
@[simp] theorem min_dfa_go (d : dfa S) {a} {w}: @go _ _ (min_dfa d) ⟦a⟧ w = ⟦go a w⟧ :=
begin
induction w with head tail ih generalizing a, {
simp only [state_equiv_equiv, forall_const, state_equiv_def, iff_self, go_nil],
}, {
specialize @ih (d.next a head),
rw [go, go],
exact ih,
},
end
def language (d : dfa S) := {w | go d.start w ∈ d.term}
@[simp] lemma mem_dfa_language_iff {w : list S} {d : dfa S} :
w ∈ d.language ↔ go d.start w ∈ d.term := iff.rfl
theorem min_dfa_lang_eq_dfa_lang (d : dfa S) : d.language = (min_dfa d).language :=
begin
ext,
simp,
end
theorem min_dfa_card_le (d : dfa S) : fintype.card (min_dfa d).Q ≤ fintype.card d.Q :=
begin
simp,
exact fintype.card_quotient_le (dfa.setoid d),
end
def all_reachable (d : dfa S) := ∀ q : d.Q, ∃ w, go d.start w = q
end dfa
namespace right_ctx
variable {L : set (list S)}
def r (L : set (list S)) (u v : list S) := ∀ w, (u ++ w) ∈ L ↔ (v ++ w) ∈ L
@[simp] lemma r_def {u v} : (r L) u v ↔ ∀ w, (u ++ w) ∈ L ↔ (v ++ w) ∈ L := iff.rfl
def r_refl : reflexive (r L) := λ a, by simp
def r_symm : symmetric (r L) := λ a b hab w, by simp [hab w]
def r_trans : transitive (r L) := λ a b c hab hbc w, by simp [hab w, hbc w]
instance setoid : setoid (list S) := ⟨r L, r_refl, r_symm, r_trans⟩
def right_ctx (L : set (list S)) := quotient (@right_ctx.setoid S _ L)
-- @[simp] lemma right_ctx_equiv (u v : list S) :
-- u ≈ v ↔ ∀ w, (u ++ w) ∈ L ↔ (v ++ w) ∈ L := iff.rfl
end right_ctx
namespace myhill_nerode
open dfa right_ctx
def myhill_nerode_equiv {d : dfa S} (hd : d.all_reachable): (min_dfa d).Q ≃ (right_ctx d.language) :=
begin
letI := @right_ctx.setoid S _ d.language,
exact {
to_fun := quotient.map (λ q, classical.some (hd q))
begin
rintro a b rab,
simp at rab,
simp [has_equiv.equiv, setoid.r, r],
have ha := classical.some_spec (hd a),
have hb := classical.some_spec (hd b),
simpa [ha, hb] using rab,
end,
inv_fun := quotient.map (λ w, go d.start w)
begin
rintro u v ruv,
simpa [has_equiv.equiv, setoid.r] using ruv,
end,
left_inv := λ q,
begin
apply quotient.induction_on q, clear q, intro q,
have hq := classical.some_spec (hd q),
simp [hq],
end,
right_inv := λ w,
begin
apply quotient.induction_on w, clear w, intro w,
have hw := classical.some_spec (hd (go d.start w)),
simp [has_equiv.equiv, setoid.r, hw],
end
},
end
theorem min_dfas_equiv {d d' : dfa S} (hd : d.all_reachable) (hd' : d'.all_reachable) (hl : d.language = d'.language) : (min_dfa d).Q ≃ (min_dfa d').Q :=
begin
have e1 := myhill_nerode_equiv hd,
have e2 := (myhill_nerode_equiv hd').symm,
rw hl at e1,
exact equiv.trans e1 e2,
end
end myhill_nerode |
73bd2ad19db7b8686aea6865131ca7613727a0a7 | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/logic/unnamed_1458.lean | dbf305f336b908da13649c594e02122dbdaf7c92 | [] | no_license | jamescheuk91/mathematics_in_lean | 09f1f87d2b0dce53464ff0cbe592c568ff59cf5e | 4452499264e2975bca2f42565c0925506ba5dda3 | refs/heads/master | 1,679,716,410,967 | 1,613,957,947,000 | 1,613,957,947,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 267 | lean | variable a : ℕ
-- BEGIN
example (h : 0 < 0) : a > 37 :=
begin
exfalso,
apply lt_irrefl 0 h
end
example (h : 0 < 0) : a > 37 :=
absurd h (lt_irrefl 0)
example (h : 0 < 0) : a > 37 :=
begin
have h' : ¬ 0 < 0,
from lt_irrefl 0,
contradiction
end
-- END |
51fd33770a8c3dbe53167c619305214c1efe12ef | 8eeb99d0fdf8125f5d39a0ce8631653f588ee817 | /src/analysis/special_functions/pow.lean | b3740ab7999039c48778cbd693fd5d6a7cda205e | [
"Apache-2.0"
] | permissive | jesse-michael-han/mathlib | a15c58378846011b003669354cbab7062b893cfe | fa6312e4dc971985e6b7708d99a5bc3062485c89 | refs/heads/master | 1,625,200,760,912 | 1,602,081,753,000 | 1,602,081,753,000 | 181,787,230 | 0 | 0 | null | 1,555,460,682,000 | 1,555,460,682,000 | null | UTF-8 | Lean | false | false | 51,498 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel
-/
import analysis.special_functions.trigonometric
import analysis.calculus.extend_deriv
/-!
# Power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ennreal`
We construct the power functions `x ^ y` where
* `x` and `y` are complex numbers,
* or `x` and `y` are real numbers,
* or `x` is a nonnegative real number and `y` is a real number;
* or `x` is a number from `[0, +∞]` (a.k.a. `ennreal`) and `y` is a real number.
We also prove basic properties of these functions.
-/
noncomputable theory
open_locale classical real topological_space nnreal
namespace complex
/-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal
determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for
`y ≠ 0`. -/
noncomputable def cpow (x y : ℂ) : ℂ :=
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y)
noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩
@[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl
lemma cpow_def (x y : ℂ) : x ^ y =
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y) := rfl
@[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def]
@[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 :=
by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] }
@[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 :=
by simp [cpow_def, *]
@[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x :=
if hx : x = 0 then by simp [hx, cpow_def]
else by rw [cpow_def, if_neg (one_ne_zero : (1 : ℂ) ≠ 0), if_neg hx, mul_one, exp_log hx]
@[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 :=
by rw cpow_def; split_ifs; simp [one_ne_zero, *] at *
lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z :=
by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at *
lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) :
x ^ (y * z) = (x ^ y) ^ z :=
begin
simp [cpow_def],
split_ifs;
simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at *
end
lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ :=
by simp [cpow_def]; split_ifs; simp [exp_neg]
lemma cpow_neg_one (x : ℂ) : x ^ (-1 : ℂ) = x⁻¹ :=
by simpa using cpow_neg x 1
@[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n
| 0 := by simp
| (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ,
complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul]
else by simp [cpow_add, hx, pow_add, cpow_nat_cast n]
@[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n
| (n : ℕ) := by simp; refl
| -[1+ n] := by rw fpow_neg_succ_of_nat;
simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div,
int.cast_coe_nat, cpow_nat_cast]
lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x :=
have (log x * (↑n)⁻¹).im = (log x).im / n,
by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im,
of_real_re, of_real_im]; simp,
have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π,
from (le_total (log x).im 0).elim
(λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg]
... ≤ ((log x).im * 1) / n : (le_div_iff (nat.cast_pos.2 hn : (0 : ℝ) < _)).mpr
(mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)
... = (log x * (↑n)⁻¹).im : by simp [this],
this.symm ▸ le_trans (div_nonpos_of_nonpos_of_nonneg h n.cast_nonneg)
(le_of_lt real.pi_pos)⟩)
(λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos)
(div_nonneg h n.cast_nonneg),
calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this]
... ≤ (log x).im : (div_le_iff' (nat.cast_pos.2 hn : (0 : ℝ) < _)).mpr
(mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)
... ≤ _ : by simp [log, arg_le_pi]⟩),
by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2,
inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)),
cpow_one]
end complex
namespace real
/-- The real power function `x^y`, defined as the real part of the complex power function.
For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`.
For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex
determination of the logarithm. With our conventions, it is equal to `exp (y log x) cos (πy)`. -/
noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re
noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩
@[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl
lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl
lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y =
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y) :=
by simp only [rpow_def, complex.cpow_def];
split_ifs;
simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul,
(complex.of_real_mul _ _).symm, complex.exp_of_real_re] at *
lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) :=
by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)]
lemma exp_mul (x y : ℝ) : exp (x * y) = (exp x) ^ y :=
by rw [rpow_def_of_pos (exp_pos _), log_exp]
lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 :=
by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] }
open_locale real
lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log x * y) * cos (y * π) :=
begin
rw [rpow_def, complex.cpow_def, if_neg],
have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I,
simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx,
complex.abs_of_real, complex.of_real_mul], ring,
{ rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos,
← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul,
complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im,
real.log_neg_eq_log],
ring },
{ rw complex.of_real_eq_zero, exact ne_of_lt hx }
end
lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y =
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y) * cos (y * π) :=
by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _
lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y :=
by rw rpow_def_of_pos hx; apply exp_pos
lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y :=
abs_le_of_le_of_neg_le
begin
cases lt_trichotomy 0 x, { rw abs_of_pos h },
cases h, { simp [h.symm] },
rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), log_abs],
calc exp (log x * y) * cos (y * π) ≤ exp (log x * y) * 1 :
mul_le_mul_of_nonneg_left (cos_le_one _) (le_of_lt $ exp_pos _)
... = _ : mul_one _
end
begin
cases lt_trichotomy 0 x, { rw abs_of_pos h, have : 0 < x^y := rpow_pos_of_pos h _, linarith },
cases h, { simp only [h.symm, abs_zero, rpow_def_of_nonneg], split_ifs, repeat {norm_num} },
rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), log_abs],
calc -(exp (log x * y) * cos (y * π)) = exp (log x * y) * (-cos (y * π)) : by ring
... ≤ exp (log x * y) * 1 :
mul_le_mul_of_nonneg_left (neg_le.2 $ neg_one_le_cos _) (le_of_lt $ exp_pos _)
... = exp (log x * y) : mul_one _
end
end real
namespace complex
lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) :=
by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx]
@[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y :=
begin
rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def],
split_ifs;
simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add,
add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I,
(complex.of_real_mul _ _).symm, -complex.of_real_mul] at *
end
@[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) :=
by rw ← abs_cpow_real; simp [-abs_cpow_real]
end complex
namespace real
variables {x y z : ℝ}
@[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def]
@[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 :=
by simp [rpow_def, *]
@[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def]
@[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def]
lemma zero_rpow_le_one (x : ℝ) : (0 : ℝ) ^ x ≤ 1 :=
by { by_cases h : x = 0; simp [h, zero_le_one] }
lemma zero_rpow_nonneg (x : ℝ) : 0 ≤ (0 : ℝ) ^ x :=
by { by_cases h : x = 0; simp [h, zero_le_one] }
lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y :=
by rw [rpow_def_of_nonneg hx];
split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)]
lemma rpow_add {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z :=
by simp only [rpow_def_of_pos hx, mul_add, exp_add]
lemma rpow_add' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z :=
begin
rcases le_iff_eq_or_lt.1 hx with H|pos,
{ simp only [← H, h, rpow_eq_zero_iff_of_nonneg, true_and, zero_rpow, eq_self_iff_true, ne.def,
not_false_iff, zero_eq_mul],
by_contradiction F,
push_neg at F,
apply h,
simp [F] },
{ exact rpow_add pos _ _ }
end
/-- For `0 ≤ x`, the only problematic case in the equality `x ^ y * x ^ z = x ^ (y + z)` is for
`x = 0` and `y + z = 0`, where the right hand side is `1` while the left hand side can vanish.
The inequality is always true, though, and given in this lemma. -/
lemma le_rpow_add {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ y * x ^ z ≤ x ^ (y + z) :=
begin
rcases le_iff_eq_or_lt.1 hx with H|pos,
{ by_cases h : y + z = 0,
{ simp only [H.symm, h, rpow_zero],
calc (0 : ℝ) ^ y * 0 ^ z ≤ 1 * 1 :
mul_le_mul (zero_rpow_le_one y) (zero_rpow_le_one z) (zero_rpow_nonneg z) zero_le_one
... = 1 : by simp },
{ simp [rpow_add', ← H, h] } },
{ simp [rpow_add pos] }
end
lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z :=
by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _),
complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx];
simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm,
complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos]
lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ :=
by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at *
lemma rpow_sub {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z :=
by simp only [sub_eq_add_neg, rpow_add hx, rpow_neg (le_of_lt hx), div_eq_mul_inv]
lemma rpow_sub' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y - z ≠ 0) :
x ^ (y - z) = x ^ y / x ^ z :=
by simp only [sub_eq_add_neg, rpow_add' hx h, rpow_neg hx, div_eq_mul_inv]
@[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n :=
by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast,
complex.of_real_nat_cast, complex.of_real_re]
@[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n :=
by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast,
complex.of_real_int_cast, complex.of_real_re]
lemma rpow_neg_one (x : ℝ) : x ^ (-1 : ℝ) = x⁻¹ :=
begin
suffices H : x ^ ((-1 : ℤ) : ℝ) = x⁻¹, by exact_mod_cast H,
simp only [rpow_int_cast, fpow_one, fpow_neg],
end
lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z :=
begin
iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *,
{ have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂,
have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂,
rw [log_mul (ne_of_gt hx) (ne_of_gt hy), add_mul, exp_add]},
{ exact h₁},
{ exact h},
{ exact mul_nonneg h h₁},
end
lemma inv_rpow (hx : 0 ≤ x) (y : ℝ) : (x⁻¹)^y = (x^y)⁻¹ :=
begin
by_cases hy0 : y = 0, { simp [*] },
by_cases hx0 : x = 0, { simp [*] },
simp only [real.rpow_def_of_nonneg hx, real.rpow_def_of_nonneg (inv_nonneg.2 hx), if_false,
hx0, mt inv_eq_zero.1 hx0, log_inv, ← neg_mul_eq_neg_mul, exp_neg]
end
lemma div_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) (z : ℝ) : (x / y) ^ z = x^z / y^z :=
by simp only [div_eq_mul_inv, mul_rpow hx (inv_nonneg.2 hy), inv_rpow hy]
lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z :=
begin
rw le_iff_eq_or_lt at hx, cases hx,
{ rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ },
rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp],
exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz
end
lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z :=
begin
rcases eq_or_lt_of_le h₁ with rfl|h₁', { refl },
rcases eq_or_lt_of_le h₂ with rfl|h₂', { simp },
exact le_of_lt (rpow_lt_rpow h h₁' h₂')
end
lemma rpow_lt_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z < y ^ z ↔ x < y :=
⟨lt_imp_lt_of_le_imp_le $ λ h, rpow_le_rpow hy h (le_of_lt hz), λ h, rpow_lt_rpow hx h hz⟩
lemma rpow_le_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y :=
le_iff_le_iff_lt_iff_lt.2 $ rpow_lt_rpow_iff hy hx hz
lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z :=
begin
repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]},
rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx),
end
lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z :=
begin
repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]},
rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx),
end
lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) :
x^y < x^z :=
begin
repeat {rw [rpow_def_of_pos hx0]},
rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1),
end
lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) :
x^y ≤ x^z :=
begin
repeat {rw [rpow_def_of_pos hx0]},
rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos (le_of_lt hx0) hx1),
end
lemma rpow_lt_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x < 1) (hz : 0 < z) : x^z < 1 :=
by { rw ← one_rpow z, exact rpow_lt_rpow hx1 hx2 hz }
lemma rpow_le_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 :=
by { rw ← one_rpow z, exact rpow_le_rpow hx1 hx2 hz }
lemma rpow_lt_one_of_one_lt_of_neg {x z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 :=
by { convert rpow_lt_rpow_of_exponent_lt hx hz, exact (rpow_zero x).symm }
lemma rpow_le_one_of_one_le_of_nonpos {x z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 :=
by { convert rpow_le_rpow_of_exponent_le hx hz, exact (rpow_zero x).symm }
lemma one_lt_rpow {x z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z :=
by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz }
lemma one_le_rpow {x z : ℝ} (hx : 1 ≤ x) (hz : 0 ≤ z) : 1 ≤ x^z :=
by { rw ← one_rpow z, exact rpow_le_rpow zero_le_one hx hz }
lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) :
1 < x^z :=
by { convert rpow_lt_rpow_of_exponent_gt hx1 hx2 hz, exact (rpow_zero x).symm }
lemma one_le_rpow_of_pos_of_le_one_of_nonpos {x z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) :
1 ≤ x^z :=
by { convert rpow_le_rpow_of_exponent_ge hx1 hx2 hz, exact (rpow_zero x).symm }
lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) :
(x ^ n) ^ (n⁻¹ : ℝ) = x :=
have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn,
by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one]
lemma rpow_nat_inv_pow_nat {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) :
(x ^ (n⁻¹ : ℝ)) ^ n = x :=
have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn,
by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one]
section prove_rpow_is_continuous
lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) :=
suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)),
by { convert h, ext p, rw rpow_def_of_pos p.2 },
continuous_exp.comp $
(show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from
continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul
(continuous_snd.comp $ continuous_subtype_val.comp continuous_id)
lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) :=
suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)),
by { convert h, ext p, rw [rpow_def_of_neg p.2, log_neg_eq_log] },
(continuous_exp.comp $
(show continuous $ (λp:{p:ℝ//0<p},
log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩),
from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $
continuous_fst.comp continuous_subtype_val).mul
(continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul
(continuous_cos.comp $
(continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const)
lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) :
continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) :=
begin
cases lt_trichotomy 0 x,
exact continuous_within_at.continuous_at
(continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h)
(mem_nhds_sets (by { convert is_open_prod (is_open_lt' (0:ℝ)) is_open_univ, ext, finish }) h),
cases h,
{ exact absurd h.symm hx },
exact continuous_within_at.continuous_at
(continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h)
(mem_nhds_sets (by { convert is_open_prod (is_open_gt' (0:ℝ)) is_open_univ, ext, finish }) h)
end
lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) :=
continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩,
begin
by_cases hx₀ : x₀ = 0,
{ simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), metric.tendsto_nhds_nhds],
assume ε ε0,
rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩,
let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos,
let δ := min (min q (ε ^ (1 / q))) (1/2),
have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num),
have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _),
have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _),
have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num),
use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩,
simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero, subtype.coe_mk],
assume h, rw max_lt_iff at h, cases h with xδ yy₀,
have qy : q < y, calc q < y₀ / 2 : q_lt
... = y₀ - y₀ / 2 : (sub_half _).symm
... ≤ y₀ - δ : by linarith
... < y : sub_lt_of_abs_sub_lt_left yy₀,
calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _
... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy
... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} }
... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} }
... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }},
{ exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1
(continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at }
end
lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) :
continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) :=
continuous_within_at.continuous_at
(continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy)
(mem_nhds_sets (by { convert is_open_prod is_open_univ (is_open_lt' (0:ℝ)), ext, finish }) hy)
lemma continuous_at_rpow {x y : ℝ} (h : x ≠ 0 ∨ 0 < y) :
continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) :=
by { cases h, exact continuous_at_rpow_of_ne_zero h _, exact continuous_at_rpow_of_pos h x }
variables {α : Type*} [topological_space α] {f g : α → ℝ}
/--
`real.rpow` is continuous at all points except for the lower half of the y-axis.
In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`.
Multiple forms of the claim is provided in the current section.
-/
lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g):
continuous (λa:α, (f a) ^ (g a)) :=
continuous_iff_continuous_at.2 $ λ a,
begin
show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a,
refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _),
{ replace h := h a, cases h,
{ exact continuous_at_rpow_of_ne_zero h _ },
{ exact continuous_at_rpow_of_pos h _ }},
end
lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g):
continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg
lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g):
continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg
end prove_rpow_is_continuous
section prove_rpow_is_differentiable
lemma has_deriv_at_rpow_of_pos {x : ℝ} (h : 0 < x) (p : ℝ) :
has_deriv_at (λ x, x^p) (p * x^(p-1)) x :=
begin
have : has_deriv_at (λ x, exp (log x * p)) (p * x^(p-1)) x,
{ convert (has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_gt h)).mul_const p) using 1,
field_simp [rpow_def_of_pos h, mul_sub, exp_sub, exp_log h, ne_of_gt h],
ring },
apply this.congr_of_eventually_eq,
have : set.Ioi (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Ioi h,
exact filter.eventually_of_mem this (λ y hy, rpow_def_of_pos hy _)
end
lemma has_deriv_at_rpow_of_neg {x : ℝ} (h : x < 0) (p : ℝ) :
has_deriv_at (λ x, x^p) (p * x^(p-1)) x :=
begin
have : has_deriv_at (λ x, exp (log x * p) * cos (p * π)) (p * x^(p-1)) x,
{ convert ((has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_lt h)).mul_const p)).mul_const _
using 1,
field_simp [rpow_def_of_neg h, mul_sub, exp_sub, sub_mul, cos_sub, exp_log_of_neg h, ne_of_lt h],
ring },
apply this.congr_of_eventually_eq,
have : set.Iio (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Iio h,
exact filter.eventually_of_mem this (λ y hy, rpow_def_of_neg hy _)
end
lemma has_deriv_at_rpow {x : ℝ} (h : x ≠ 0) (p : ℝ) :
has_deriv_at (λ x, x^p) (p * x^(p-1)) x :=
begin
rcases lt_trichotomy x 0 with H|H|H,
{ exact has_deriv_at_rpow_of_neg H p },
{ exact (h H).elim },
{ exact has_deriv_at_rpow_of_pos H p },
end
lemma has_deriv_at_rpow_zero_of_one_le {p : ℝ} (h : 1 ≤ p) :
has_deriv_at (λ x, x^p) (p * (0 : ℝ)^(p-1)) 0 :=
begin
apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, has_deriv_at_rpow hx p),
{ exact (continuous_rpow_of_pos (λ _, (lt_of_lt_of_le zero_lt_one h))
continuous_id continuous_const).continuous_at },
{ rcases le_iff_eq_or_lt.1 h with rfl|h,
{ simp [continuous_const.continuous_at] },
{ exact (continuous_const.mul (continuous_rpow_of_pos (λ _, sub_pos_of_lt h)
continuous_id continuous_const)).continuous_at } }
end
lemma has_deriv_at_rpow_of_one_le (x : ℝ) {p : ℝ} (h : 1 ≤ p) :
has_deriv_at (λ x, x^p) (p * x^(p-1)) x :=
begin
by_cases hx : x = 0,
{ rw hx, exact has_deriv_at_rpow_zero_of_one_le h },
{ exact has_deriv_at_rpow hx p }
end
end prove_rpow_is_differentiable
section sqrt
lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) :=
begin
funext, by_cases h : 0 ≤ x,
{ rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h],
norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ },
{ replace h : x < 0 := lt_of_not_ge h,
have : 1 / (2:ℝ) * π = π / (2:ℝ), ring,
rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] }
end
lemma continuous_sqrt : continuous sqrt :=
by rw sqrt_eq_rpow; exact continuous_rpow_of_pos (λa, by norm_num) continuous_id continuous_const
end sqrt
end real
section differentiability
open real
variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ} (p : ℝ)
/- Differentiability statements for the power of a function, when the function does not vanish
and the exponent is arbitrary-/
lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) :
has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x :=
begin
convert (has_deriv_at_rpow hx p).comp_has_deriv_within_at x hf using 1,
ring
end
lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hx : f x ≠ 0) :
has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hf.rpow p hx
end
lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) :
differentiable_within_at ℝ (λx, (f x)^p) s x :=
(hf.has_deriv_within_at.rpow p hx).differentiable_within_at
@[simp] lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
differentiable_at ℝ (λx, (f x)^p) x :=
(hf.has_deriv_at.rpow p hx).differentiable_at
lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) :
differentiable_on ℝ (λx, (f x)^p) s :=
λx h, (hf x h).rpow p (hx x h)
@[simp] lemma differentiable.rpow (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) :
differentiable ℝ (λx, (f x)^p) :=
λx, (hf x).rpow p (hx x)
lemma deriv_within_rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) :=
(hf.has_deriv_within_at.rpow p hx).deriv_within hxs
@[simp] lemma deriv_rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) :=
(hf.has_deriv_at.rpow p hx).deriv
/- Differentiability statements for the power of a function, when the function may vanish
but the exponent is at least one. -/
variable {p}
lemma has_deriv_within_at.rpow_of_one_le (hf : has_deriv_within_at f f' s x) (hp : 1 ≤ p) :
has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x :=
begin
convert (has_deriv_at_rpow_of_one_le (f x) hp).comp_has_deriv_within_at x hf using 1,
ring
end
lemma has_deriv_at.rpow_of_one_le (hf : has_deriv_at f f' x) (hp : 1 ≤ p) :
has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hf.rpow_of_one_le hp
end
lemma differentiable_within_at.rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) :
differentiable_within_at ℝ (λx, (f x)^p) s x :=
(hf.has_deriv_within_at.rpow_of_one_le hp).differentiable_within_at
@[simp] lemma differentiable_at.rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) :
differentiable_at ℝ (λx, (f x)^p) x :=
(hf.has_deriv_at.rpow_of_one_le hp).differentiable_at
lemma differentiable_on.rpow_of_one_le (hf : differentiable_on ℝ f s) (hp : 1 ≤ p) :
differentiable_on ℝ (λx, (f x)^p) s :=
λx h, (hf x h).rpow_of_one_le hp
@[simp] lemma differentiable.rpow_of_one_le (hf : differentiable ℝ f) (hp : 1 ≤ p) :
differentiable ℝ (λx, (f x)^p) :=
λx, (hf x).rpow_of_one_le hp
lemma deriv_within_rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) :=
(hf.has_deriv_within_at.rpow_of_one_le hp).deriv_within hxs
@[simp] lemma deriv_rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) :
deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) :=
(hf.has_deriv_at.rpow_of_one_le hp).deriv
/- Differentiability statements for the square root of a function, when the function does not
vanish -/
lemma has_deriv_within_at.sqrt (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) :
has_deriv_within_at (λ y, sqrt (f y)) (f' / (2 * sqrt (f x))) s x :=
begin
simp only [sqrt_eq_rpow],
convert hf.rpow (1/2) hx,
rcases lt_trichotomy (f x) 0 with H|H|H,
{ have A : (f x)^((1:ℝ)/2) = 0,
{ rw rpow_def_of_neg H,
have : cos (1/2 * π) = 0, by { convert cos_pi_div_two using 2, ring },
rw [this],
simp },
have B : f x ^ ((1:ℝ) / 2 - 1) = 0,
{ rw rpow_def_of_neg H,
have : cos (π/2 - π) = 0, by simp [cos_sub],
have : cos (((1:ℝ)/2 - 1) * π) = 0, by { convert this using 2, ring },
rw this,
simp },
rw [A, B],
simp },
{ exact (hx H).elim },
{ have A : 0 < (f x)^((1:ℝ)/2) := rpow_pos_of_pos H _,
have B : (f x) ^ (-(1:ℝ)) = (f x)^(-((1:ℝ)/2)) * (f x)^(-((1:ℝ)/2)),
{ rw [← rpow_add H],
congr,
norm_num },
rw [sub_eq_add_neg, rpow_add H, B, rpow_neg (le_of_lt H)],
field_simp [hx, ne_of_gt A],
ring }
end
lemma has_deriv_at.sqrt (hf : has_deriv_at f f' x) (hx : f x ≠ 0) :
has_deriv_at (λ y, sqrt (f y)) (f' / (2 * sqrt(f x))) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hf.sqrt hx
end
lemma differentiable_within_at.sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) :
differentiable_within_at ℝ (λx, sqrt (f x)) s x :=
(hf.has_deriv_within_at.sqrt hx).differentiable_within_at
@[simp] lemma differentiable_at.sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
differentiable_at ℝ (λx, sqrt (f x)) x :=
(hf.has_deriv_at.sqrt hx).differentiable_at
lemma differentiable_on.sqrt (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) :
differentiable_on ℝ (λx, sqrt (f x)) s :=
λx h, (hf x h).sqrt (hx x h)
@[simp] lemma differentiable.sqrt (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) :
differentiable ℝ (λx, sqrt (f x)) :=
λx, (hf x).sqrt (hx x)
lemma deriv_within_sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, sqrt (f x)) s x = (deriv_within f s x) / (2 * sqrt (f x)) :=
(hf.has_deriv_within_at.sqrt hx).deriv_within hxs
@[simp] lemma deriv_sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) :
deriv (λx, sqrt (f x)) x = (deriv f x) / (2 * sqrt (f x)) :=
(hf.has_deriv_at.sqrt hx).deriv
end differentiability
namespace nnreal
/-- The nonnegative real power function `x^y`, defined for `x : ℝ≥0` and `y : ℝ ` as the
restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`,
one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/
noncomputable def rpow (x : ℝ≥0) (y : ℝ) : ℝ≥0 :=
⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩
noncomputable instance : has_pow ℝ≥0 ℝ := ⟨rpow⟩
@[simp] lemma rpow_eq_pow (x : ℝ≥0) (y : ℝ) : rpow x y = x ^ y := rfl
@[simp, norm_cast] lemma coe_rpow (x : ℝ≥0) (y : ℝ) : ((x ^ y : ℝ≥0) : ℝ) = (x : ℝ) ^ y := rfl
@[simp] lemma rpow_zero (x : ℝ≥0) : x ^ (0 : ℝ) = 1 :=
nnreal.eq $ real.rpow_zero _
@[simp] lemma rpow_eq_zero_iff {x : ℝ≥0} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 :=
begin
rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero],
exact real.rpow_eq_zero_iff_of_nonneg x.2
end
@[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ≥0) ^ x = 0 :=
nnreal.eq $ real.zero_rpow h
@[simp] lemma rpow_one (x : ℝ≥0) : x ^ (1 : ℝ) = x :=
nnreal.eq $ real.rpow_one _
@[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0) ^ x = 1 :=
nnreal.eq $ real.one_rpow _
lemma rpow_add {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z :=
nnreal.eq $ real.rpow_add (zero_lt_iff_ne_zero.2 hx) _ _
lemma rpow_add' (x : ℝ≥0) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z :=
nnreal.eq $ real.rpow_add' x.2 h
lemma rpow_mul (x : ℝ≥0) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z :=
nnreal.eq $ real.rpow_mul x.2 y z
lemma rpow_neg (x : ℝ≥0) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ :=
nnreal.eq $ real.rpow_neg x.2 _
lemma rpow_neg_one (x : ℝ≥0) : x ^ (-1 : ℝ) = x ⁻¹ :=
by simp [rpow_neg]
lemma rpow_sub {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z :=
nnreal.eq $ real.rpow_sub (zero_lt_iff_ne_zero.2 hx) y z
lemma rpow_sub' (x : ℝ≥0) {y z : ℝ} (h : y - z ≠ 0) :
x ^ (y - z) = x ^ y / x ^ z :=
nnreal.eq $ real.rpow_sub' x.2 h
lemma inv_rpow (x : ℝ≥0) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ :=
nnreal.eq $ real.inv_rpow x.2 y
lemma div_rpow (x y : ℝ≥0) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z :=
nnreal.eq $ real.div_rpow x.2 y.2 z
@[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0) (n : ℕ) : x ^ (n : ℝ) = x ^ n :=
nnreal.eq $ by simpa only [coe_rpow, coe_pow] using real.rpow_nat_cast x n
lemma mul_rpow {x y : ℝ≥0} {z : ℝ} : (x*y)^z = x^z * y^z :=
nnreal.eq $ real.mul_rpow x.2 y.2
lemma rpow_le_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z :=
real.rpow_le_rpow x.2 h₁ h₂
lemma rpow_lt_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z :=
real.rpow_lt_rpow x.2 h₁ h₂
lemma rpow_lt_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y :=
real.rpow_lt_rpow_iff x.2 y.2 hz
lemma rpow_le_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y :=
real.rpow_le_rpow_iff x.2 y.2 hz
lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z :=
real.rpow_lt_rpow_of_exponent_lt hx hyz
lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z :=
real.rpow_le_rpow_of_exponent_le hx hyz
lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) :
x^y < x^z :=
real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz
lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) :
x^y ≤ x^z :=
real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz
lemma rpow_lt_one {x : ℝ≥0} {z : ℝ} (hx : 0 ≤ x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 :=
real.rpow_lt_one hx hx1 hz
lemma rpow_le_one {x : ℝ≥0} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 :=
real.rpow_le_one x.2 hx2 hz
lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 :=
real.rpow_lt_one_of_one_lt_of_neg hx hz
lemma rpow_le_one_of_one_le_of_nonpos {x : ℝ≥0} {z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 :=
real.rpow_le_one_of_one_le_of_nonpos hx hz
lemma one_lt_rpow {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z :=
real.one_lt_rpow hx hz
lemma one_le_rpow {x : ℝ≥0} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z :=
real.one_le_rpow h h₁
lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1)
(hz : z < 0) : 1 < x^z :=
real.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz
lemma one_le_rpow_of_pos_of_le_one_of_nonpos {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1)
(hz : z ≤ 0) : 1 ≤ x^z :=
real.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 hz
lemma pow_nat_rpow_nat_inv (x : ℝ≥0) {n : ℕ} (hn : 0 < n) :
(x ^ n) ^ (n⁻¹ : ℝ) = x :=
by { rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn }
lemma rpow_nat_inv_pow_nat (x : ℝ≥0) {n : ℕ} (hn : 0 < n) :
(x ^ (n⁻¹ : ℝ)) ^ n = x :=
by { rw [← nnreal.coe_eq, nnreal.coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn }
lemma continuous_at_rpow {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) :
continuous_at (λp:ℝ≥0×ℝ, p.1^p.2) (x, y) :=
begin
have : (λp:ℝ≥0×ℝ, p.1^p.2) = nnreal.of_real ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:ℝ≥0 × ℝ, (p.1.1, p.2)),
{ ext p,
rw [coe_rpow, nnreal.coe_of_real _ (real.rpow_nonneg_of_nonneg p.1.2 _)],
refl },
rw this,
refine nnreal.continuous_of_real.continuous_at.comp (continuous_at.comp _ _),
{ apply real.continuous_at_rpow,
simp at h,
rw ← (nnreal.coe_eq_zero x) at h,
exact h },
{ exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at }
end
end nnreal
open filter
lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → ℝ≥0} {v : α → ℝ} {x : ℝ≥0} {y : ℝ}
(hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) :
tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) :=
tendsto.comp (nnreal.continuous_at_rpow h) (hx.prod_mk_nhds hy)
namespace nnreal
lemma continuous_at_rpow_const {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 ≤ y) :
continuous_at (λ z, z^y) x :=
h.elim (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inl h)) $
λ h, h.eq_or_lt.elim
(λ h, h ▸ by simp only [rpow_zero, continuous_at_const])
(λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inr h))
lemma continuous_rpow_const {y : ℝ} (h : 0 ≤ y) :
continuous (λ x : ℝ≥0, x^y) :=
continuous_iff_continuous_at.2 $ λ x, continuous_at_rpow_const (or.inr h)
end nnreal
namespace ennreal
/-- The real power function `x^y` on extended nonnegative reals, defined for `x : ennreal` and
`y : ℝ` as the restriction of the real power function if `0 < x < ⊤`, and with the natural values
for `0` and `⊤` (i.e., `0 ^ x = 0` for `x > 0`, `1` for `x = 0` and `⊤` for `x < 0`, and
`⊤ ^ x = 1 / 0 ^ x`). -/
noncomputable def rpow : ennreal → ℝ → ennreal
| (some x) y := if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0)
| none y := if 0 < y then ⊤ else if y = 0 then 1 else 0
noncomputable instance : has_pow ennreal ℝ := ⟨rpow⟩
@[simp] lemma rpow_eq_pow (x : ennreal) (y : ℝ) : rpow x y = x ^ y := rfl
@[simp] lemma rpow_zero {x : ennreal} : x ^ (0 : ℝ) = 1 :=
by cases x; { dsimp only [(^), rpow], simp [lt_irrefl] }
lemma top_rpow_def (y : ℝ) : (⊤ : ennreal) ^ y = if 0 < y then ⊤ else if y = 0 then 1 else 0 :=
rfl
@[simp] lemma top_rpow_of_pos {y : ℝ} (h : 0 < y) : (⊤ : ennreal) ^ y = ⊤ :=
by simp [top_rpow_def, h]
@[simp] lemma top_rpow_of_neg {y : ℝ} (h : y < 0) : (⊤ : ennreal) ^ y = 0 :=
by simp [top_rpow_def, asymm h, ne_of_lt h]
@[simp] lemma zero_rpow_of_pos {y : ℝ} (h : 0 < y) : (0 : ennreal) ^ y = 0 :=
begin
rw [← ennreal.coe_zero, ← ennreal.some_eq_coe],
dsimp only [(^), rpow],
simp [h, asymm h, ne_of_gt h],
end
@[simp] lemma zero_rpow_of_neg {y : ℝ} (h : y < 0) : (0 : ennreal) ^ y = ⊤ :=
begin
rw [← ennreal.coe_zero, ← ennreal.some_eq_coe],
dsimp only [(^), rpow],
simp [h, ne_of_gt h],
end
lemma zero_rpow_def (y : ℝ) : (0 : ennreal) ^ y = if 0 < y then 0 else if y = 0 then 1 else ⊤ :=
begin
rcases lt_trichotomy 0 y with H|rfl|H,
{ simp [H, ne_of_gt, zero_rpow_of_pos, lt_irrefl] },
{ simp [lt_irrefl] },
{ simp [H, asymm H, ne_of_lt, zero_rpow_of_neg] }
end
@[norm_cast] lemma coe_rpow_of_ne_zero {x : ℝ≥0} (h : x ≠ 0) (y : ℝ) :
(x : ennreal) ^ y = (x ^ y : ℝ≥0) :=
begin
rw [← ennreal.some_eq_coe],
dsimp only [(^), rpow],
simp [h]
end
@[norm_cast] lemma coe_rpow_of_nonneg (x : ℝ≥0) {y : ℝ} (h : 0 ≤ y) :
(x : ennreal) ^ y = (x ^ y : ℝ≥0) :=
begin
by_cases hx : x = 0,
{ rcases le_iff_eq_or_lt.1 h with H|H,
{ simp [hx, H.symm] },
{ simp [hx, zero_rpow_of_pos H, nnreal.zero_rpow (ne_of_gt H)] } },
{ exact coe_rpow_of_ne_zero hx _ }
end
@[simp] lemma rpow_one (x : ennreal) : x ^ (1 : ℝ) = x :=
by cases x; dsimp only [(^), rpow]; simp [zero_lt_one, not_lt_of_le zero_le_one]
@[simp] lemma one_rpow (x : ℝ) : (1 : ennreal) ^ x = 1 :=
by { rw [← coe_one, coe_rpow_of_ne_zero one_ne_zero], simp }
@[simp] lemma rpow_eq_zero_iff {x : ennreal} {y : ℝ} :
x ^ y = 0 ↔ (x = 0 ∧ 0 < y) ∨ (x = ⊤ ∧ y < 0) :=
begin
cases x,
{ rcases lt_trichotomy y 0 with H|H|H;
simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] },
{ by_cases h : x = 0,
{ rcases lt_trichotomy y 0 with H|H|H;
simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] },
{ simp [coe_rpow_of_ne_zero h, h] } }
end
@[simp] lemma rpow_eq_top_iff {x : ennreal} {y : ℝ} :
x ^ y = ⊤ ↔ (x = 0 ∧ y < 0) ∨ (x = ⊤ ∧ 0 < y) :=
begin
cases x,
{ rcases lt_trichotomy y 0 with H|H|H;
simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] },
{ by_cases h : x = 0,
{ rcases lt_trichotomy y 0 with H|H|H;
simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] },
{ simp [coe_rpow_of_ne_zero h, h] } }
end
lemma rpow_add {x : ennreal} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y + z) = x ^ y * x ^ z :=
begin
cases x, { exact (h'x rfl).elim },
have : x ≠ 0 := λ h, by simpa [h] using hx,
simp [coe_rpow_of_ne_zero this, nnreal.rpow_add this]
end
lemma rpow_neg (x : ennreal) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ :=
begin
cases x,
{ rcases lt_trichotomy y 0 with H|H|H;
simp [top_rpow_of_pos, top_rpow_of_neg, H, neg_pos.mpr] },
{ by_cases h : x = 0,
{ rcases lt_trichotomy y 0 with H|H|H;
simp [h, zero_rpow_of_pos, zero_rpow_of_neg, H, neg_pos.mpr] },
{ have A : x ^ y ≠ 0, by simp [h],
simp [coe_rpow_of_ne_zero h, ← coe_inv A, nnreal.rpow_neg] } }
end
lemma rpow_neg_one (x : ennreal) : x ^ (-1 : ℝ) = x ⁻¹ :=
by simp [rpow_neg]
lemma rpow_mul (x : ennreal) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z :=
begin
cases x,
{ rcases lt_trichotomy y 0 with Hy|Hy|Hy;
rcases lt_trichotomy z 0 with Hz|Hz|Hz;
simp [Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos,
mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] },
{ by_cases h : x = 0,
{ rcases lt_trichotomy y 0 with Hy|Hy|Hy;
rcases lt_trichotomy z 0 with Hz|Hz|Hz;
simp [h, Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos,
mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] },
{ have : x ^ y ≠ 0, by simp [h],
simp [coe_rpow_of_ne_zero h, coe_rpow_of_ne_zero this, nnreal.rpow_mul] } }
end
@[simp, norm_cast] lemma rpow_nat_cast (x : ennreal) (n : ℕ) : x ^ (n : ℝ) = x ^ n :=
begin
cases x,
{ cases n;
simp [top_rpow_of_pos (nat.cast_add_one_pos _), top_pow (nat.succ_pos _)] },
{ simp [coe_rpow_of_nonneg _ (nat.cast_nonneg n)] }
end
@[norm_cast] lemma coe_mul_rpow (x y : ℝ≥0) (z : ℝ) :
((x : ennreal) * y) ^ z = x^z * y^z :=
begin
rcases lt_trichotomy z 0 with H|H|H,
{ by_cases hx : x = 0; by_cases hy : y = 0,
{ simp [hx, hy, zero_rpow_of_neg, H] },
{ have : (y : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy],
simp [hx, hy, zero_rpow_of_neg, H, with_top.top_mul this] },
{ have : (x : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx],
simp [hx, hy, zero_rpow_of_neg H, with_top.mul_top this] },
{ rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul,
coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy],
simp [hx, hy] } },
{ simp [H] },
{ by_cases hx : x = 0; by_cases hy : y = 0,
{ simp [hx, hy, zero_rpow_of_pos, H] },
{ have : (y : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy],
simp [hx, hy, zero_rpow_of_pos H, with_top.top_mul this] },
{ have : (x : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx],
simp [hx, hy, zero_rpow_of_pos H, with_top.mul_top this] },
{ rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul,
coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy],
simp [hx, hy] } },
end
lemma mul_rpow_of_ne_top {x y : ennreal} (hx : x ≠ ⊤) (hy : y ≠ ⊤) (z : ℝ) :
(x * y) ^ z = x^z * y^z :=
begin
lift x to ℝ≥0 using hx,
lift y to ℝ≥0 using hy,
exact coe_mul_rpow x y z
end
lemma mul_rpow_of_ne_zero {x y : ennreal} (hx : x ≠ 0) (hy : y ≠ 0) (z : ℝ) :
(x * y) ^ z = x ^ z * y ^ z :=
begin
rcases lt_trichotomy z 0 with H|H|H,
{ cases x; cases y,
{ simp [hx, hy, top_rpow_of_neg, H] },
{ have : y ≠ 0, by simpa using hy,
simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] },
{ have : x ≠ 0, by simpa using hx,
simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] },
{ have hx' : x ≠ 0, by simpa using hx,
have hy' : y ≠ 0, by simpa using hy,
simp only [some_eq_coe],
rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul,
coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'],
simp [hx', hy'] } },
{ simp [H] },
{ cases x; cases y,
{ simp [hx, hy, top_rpow_of_pos, H] },
{ have : y ≠ 0, by simpa using hy,
simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] },
{ have : x ≠ 0, by simpa using hx,
simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] },
{ have hx' : x ≠ 0, by simpa using hx,
have hy' : y ≠ 0, by simpa using hy,
simp only [some_eq_coe],
rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul,
coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'],
simp [hx', hy'] } }
end
lemma mul_rpow_of_nonneg (x y : ennreal) {z : ℝ} (hz : 0 ≤ z) :
(x * y) ^ z = x ^ z * y ^ z :=
begin
rcases le_iff_eq_or_lt.1 hz with H|H, { simp [← H] },
by_cases h : x = 0 ∨ y = 0,
{ cases h; simp [h, zero_rpow_of_pos H] },
push_neg at h,
exact mul_rpow_of_ne_zero h.1 h.2 z
end
lemma rpow_le_rpow {x y : ennreal} {z : ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z :=
begin
rcases le_iff_eq_or_lt.1 h₂ with H|H, { simp [← H, le_refl] },
cases y, { simp [top_rpow_of_pos H] },
cases x, { exact (not_top_le_coe h₁).elim },
simp at h₁,
simp [coe_rpow_of_nonneg _ h₂, nnreal.rpow_le_rpow h₁ h₂]
end
lemma rpow_lt_rpow {x y : ennreal} {z : ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z :=
begin
cases x, { exact (not_top_lt h₁).elim },
cases y, { simp [top_rpow_of_pos h₂, coe_rpow_of_nonneg _ (le_of_lt h₂)] },
simp at h₁,
simp [coe_rpow_of_nonneg _ (le_of_lt h₂), nnreal.rpow_lt_rpow h₁ h₂]
end
lemma rpow_lt_rpow_of_exponent_lt {x : ennreal} {y z : ℝ} (hx : 1 < x) (hx' : x ≠ ⊤) (hyz : y < z) :
x^y < x^z :=
begin
lift x to ℝ≥0 using hx',
rw [one_lt_coe_iff] at hx,
simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)),
nnreal.rpow_lt_rpow_of_exponent_lt hx hyz]
end
lemma rpow_le_rpow_of_exponent_le {x : ennreal} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z :=
begin
cases x,
{ rcases lt_trichotomy y 0 with Hy|Hy|Hy;
rcases lt_trichotomy z 0 with Hz|Hz|Hz;
simp [Hy, Hz, top_rpow_of_neg, top_rpow_of_pos, le_refl];
linarith },
{ simp only [one_le_coe_iff, some_eq_coe] at hx,
simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)),
nnreal.rpow_le_rpow_of_exponent_le hx hyz] }
end
lemma rpow_lt_rpow_of_exponent_gt {x : ennreal} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) :
x^y < x^z :=
begin
lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top),
simp at hx0 hx1,
simp [coe_rpow_of_ne_zero (ne_of_gt hx0), nnreal.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz]
end
lemma rpow_le_rpow_of_exponent_ge {x : ennreal} {y z : ℝ} (hx1 : x ≤ 1) (hyz : z ≤ y) :
x^y ≤ x^z :=
begin
lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx1 coe_lt_top),
by_cases h : x = 0,
{ rcases lt_trichotomy y 0 with Hy|Hy|Hy;
rcases lt_trichotomy z 0 with Hz|Hz|Hz;
simp [Hy, Hz, h, zero_rpow_of_neg, zero_rpow_of_pos, le_refl];
linarith },
{ simp at hx1,
simp [coe_rpow_of_ne_zero h,
nnreal.rpow_le_rpow_of_exponent_ge (bot_lt_iff_ne_bot.mpr h) hx1 hyz] }
end
lemma rpow_lt_one {x : ennreal} {z : ℝ} (hx : x < 1) (hz : 0 < z) : x^z < 1 :=
begin
lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx le_top),
simp only [coe_lt_one_iff] at hx,
simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.rpow_lt_one (zero_le x) hx hz],
end
lemma rpow_le_one {x : ennreal} {z : ℝ} (hx : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 :=
begin
lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx coe_lt_top),
simp only [coe_le_one_iff] at hx,
simp [coe_rpow_of_nonneg _ hz, nnreal.rpow_le_one hx hz],
end
lemma rpow_lt_one_of_one_lt_of_neg {x : ennreal} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 :=
begin
cases x,
{ simp [top_rpow_of_neg hz, ennreal.zero_lt_one] },
{ simp only [some_eq_coe, one_lt_coe_iff] at hx,
simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)),
nnreal.rpow_lt_one_of_one_lt_of_neg hx hz] },
end
lemma rpow_le_one_of_one_le_of_neg {x : ennreal} {z : ℝ} (hx : 1 ≤ x) (hz : z < 0) : x^z ≤ 1 :=
begin
cases x,
{ simp [top_rpow_of_neg hz, ennreal.zero_lt_one] },
{ simp only [one_le_coe_iff, some_eq_coe] at hx,
simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)),
nnreal.rpow_le_one_of_one_le_of_nonpos hx (le_of_lt hz)] },
end
lemma one_lt_rpow {x : ennreal} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z :=
begin
cases x,
{ simp [top_rpow_of_pos hz] },
{ simp only [some_eq_coe, one_lt_coe_iff] at hx,
simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_lt_rpow hx hz] }
end
lemma one_le_rpow {x : ennreal} {z : ℝ} (hx : 1 ≤ x) (hz : 0 < z) : 1 ≤ x^z :=
begin
cases x,
{ simp [top_rpow_of_pos hz] },
{ simp only [one_le_coe_iff, some_eq_coe] at hx,
simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_le_rpow hx (le_of_lt hz)] },
end
lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ennreal} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1)
(hz : z < 0) : 1 < x^z :=
begin
lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx2 le_top),
simp only [coe_lt_one_iff, coe_pos] at ⊢ hx1 hx2,
simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz],
end
lemma one_le_rpow_of_pos_of_le_one_of_neg {x : ennreal} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1)
(hz : z < 0) : 1 ≤ x^z :=
begin
lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx2 coe_lt_top),
simp only [coe_le_one_iff, coe_pos] at ⊢ hx1 hx2,
simp [coe_rpow_of_ne_zero (ne_of_gt hx1),
nnreal.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 (le_of_lt hz)],
end
lemma to_real_rpow (x : ennreal) (z : ℝ) :
(x.to_real) ^ z = (x ^ z).to_real :=
begin
rcases lt_trichotomy z 0 with H|H|H,
{ cases x, { simp [H, ne_of_lt] },
by_cases hx : x = 0,
{ simp [hx, H, ne_of_lt] },
{ simp [coe_rpow_of_ne_zero hx] } },
{ simp [H] },
{ cases x, { simp [H, ne_of_gt] },
simp [coe_rpow_of_nonneg _ (le_of_lt H)] }
end
end ennreal
|
2e967ae8bc2f1ac576ff04192a98a826eb53336f | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/preadditive/single_obj.lean | cc81ad832307bb34f9475bda533c1eefb52ebf7c | [
"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 | 608 | 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 category_theory.preadditive.basic
import category_theory.single_obj
/-!
# `single_obj α` is preadditive when `α` is a ring.
-/
namespace category_theory
variables {α : Type*} [ring α]
instance : preadditive (single_obj α) :=
{ add_comp' := λ _ _ _ f f' g, mul_add g f f',
comp_add' := λ _ _ _ f g g', add_mul g g' f, }
-- TODO define `PreAddCat` (with additive functors as morphisms), and `Ring ⥤ PreAddCat`.
end category_theory
|
800708b020b234ebf881f90c603d2054ca89d684 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/psigma/order.lean | 30bdb78fcd51869040e0e65368af90ccf6c0a7de | [
"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 | 7,410 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Minchao Wu
-/
import data.sigma.lex
import order.bounded_order
/-!
# Lexicographic order on a sigma type
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> https://github.com/leanprover-community/mathlib4/pull/815
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the lexicographic order on `Σₗ' i, α i`. `a` is less than `b` if its summand is
strictly less than the summand of `b` or they are in the same summand and `a` is less than `b`
there.
## Notation
* `Σₗ' i, α i`: Sigma type equipped with the lexicographic order. A type synonym of `Σ' i, α i`.
## See also
Related files are:
* `data.finset.colex`: Colexicographic order on finite sets.
* `data.list.lex`: Lexicographic order on lists.
* `data.pi.lex`: Lexicographic order on `Πₗ i, α i`.
* `data.sigma.order`: Lexicographic order on `Σₗ i, α i`. Basically a twin of this file.
* `data.prod.lex`: Lexicographic order on `α × β`.
## TODO
Define the disjoint order on `Σ' i, α i`, where `x ≤ y` only if `x.fst = y.fst`.
Prove that a sigma type is a `no_max_order`, `no_min_order`, `densely_ordered` when its summands
are.
-/
variables {ι : Type*} {α : ι → Type*}
namespace psigma
notation `Σₗ'` binders `, ` r:(scoped p, _root_.lex (psigma p)) := r
namespace lex
/-- The lexicographical `≤` on a sigma type. -/
instance has_le [has_lt ι] [Π i, has_le (α i)] : has_le (Σₗ' i, α i) := ⟨lex (<) (λ i, (≤))⟩
/-- The lexicographical `<` on a sigma type. -/
instance has_lt [has_lt ι] [Π i, has_lt (α i)] : has_lt (Σₗ' i, α i) := ⟨lex (<) (λ i, (<))⟩
instance preorder [preorder ι] [Π i, preorder (α i)] : preorder (Σₗ' i, α i) :=
{ le_refl := λ ⟨i, a⟩, lex.right _ le_rfl,
le_trans :=
begin
rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ ⟨a₃, b₃⟩ ⟨h₁r⟩ ⟨h₂r⟩,
{ left, apply lt_trans, repeat { assumption } },
{ left, assumption },
{ left, assumption },
{ right, apply le_trans, repeat { assumption } }
end,
lt_iff_le_not_le :=
begin
refine λ a b, ⟨λ hab, ⟨hab.mono_right (λ i a b, le_of_lt), _⟩, _⟩,
{ rintro (⟨i, a, hji⟩ | ⟨i, hba⟩);
obtain (⟨_, _, hij⟩ | ⟨_, hab⟩) := hab,
{ exact hij.not_lt hji },
{ exact lt_irrefl _ hji },
{ exact lt_irrefl _ hij },
{ exact hab.not_le hba } },
{ rintro ⟨⟨j, b, hij⟩ | ⟨i, hab⟩, hba⟩,
{ exact lex.left _ _ hij },
{ exact lex.right _ (hab.lt_of_not_le $ λ h, hba $ lex.right _ h) } }
end,
.. lex.has_le,
.. lex.has_lt }
/-- Dictionary / lexicographic partial_order for dependent pairs. -/
instance partial_order [partial_order ι] [Π i, partial_order (α i)] :
partial_order (Σₗ' i, α i) :=
{ le_antisymm :=
begin
rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (⟨_, _, hlt₁⟩ | ⟨_, hlt₁⟩) (⟨_, _, hlt₂⟩ | ⟨_, hlt₂⟩),
{ exact (lt_irrefl a₁ $ hlt₁.trans hlt₂).elim },
{ exact (lt_irrefl a₁ hlt₁).elim },
{ exact (lt_irrefl a₁ hlt₂).elim },
{ rw hlt₁.antisymm hlt₂ }
end
.. lex.preorder }
/-- Dictionary / lexicographic linear_order for pairs. -/
instance linear_order [linear_order ι] [Π i, linear_order (α i)] : linear_order (Σₗ' i, α i) :=
{ le_total :=
begin
rintro ⟨i, a⟩ ⟨j, b⟩,
obtain hij | rfl | hji := lt_trichotomy i j,
{ exact or.inl (lex.left _ _ hij) },
{ obtain hab | hba := le_total a b,
{ exact or.inl (lex.right _ hab) },
{ exact or.inr (lex.right _ hba) } },
{ exact or.inr (lex.left _ _ hji) }
end,
decidable_eq := psigma.decidable_eq,
decidable_le := lex.decidable _ _,
decidable_lt := lex.decidable _ _,
.. lex.partial_order }
/-- The lexicographical linear order on a sigma type. -/
instance order_bot [partial_order ι] [order_bot ι] [Π i, preorder (α i)] [order_bot (α ⊥)] :
order_bot (Σₗ' i, α i) :=
{ bot := ⟨⊥, ⊥⟩,
bot_le := λ ⟨a, b⟩, begin
obtain rfl | ha := eq_bot_or_bot_lt a,
{ exact lex.right _ bot_le },
{ exact lex.left _ _ ha }
end }
/-- The lexicographical linear order on a sigma type. -/
instance order_top [partial_order ι] [order_top ι] [Π i, preorder (α i)] [order_top (α ⊤)] :
order_top (Σₗ' i, α i) :=
{ top := ⟨⊤, ⊤⟩,
le_top := λ ⟨a, b⟩, begin
obtain rfl | ha := eq_top_or_lt_top a,
{ exact lex.right _ le_top },
{ exact lex.left _ _ ha }
end }
/-- The lexicographical linear order on a sigma type. -/
instance bounded_order [partial_order ι] [bounded_order ι] [Π i, preorder (α i)]
[order_bot (α ⊥)] [order_top (α ⊤)] :
bounded_order (Σₗ' i, α i) :=
{ .. lex.order_bot, .. lex.order_top }
instance densely_ordered [preorder ι] [densely_ordered ι] [Π i, nonempty (α i)]
[Π i, preorder (α i)] [Π i, densely_ordered (α i)] :
densely_ordered (Σₗ' i, α i) :=
⟨begin
rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | @⟨_, _, b, h⟩),
{ obtain ⟨k, hi, hj⟩ := exists_between h,
obtain ⟨c⟩ : nonempty (α k) := infer_instance,
exact ⟨⟨k, c⟩, left _ _ hi, left _ _ hj⟩ },
{ obtain ⟨c, ha, hb⟩ := exists_between h,
exact ⟨⟨i, c⟩, right _ ha, right _ hb⟩ }
end⟩
instance densely_ordered_of_no_max_order [preorder ι] [Π i, preorder (α i)]
[Π i, densely_ordered (α i)] [Π i, no_max_order (α i)] :
densely_ordered (Σₗ' i, α i) :=
⟨begin
rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | @⟨_, _, b, h⟩),
{ obtain ⟨c, ha⟩ := exists_gt a,
exact ⟨⟨i, c⟩, right _ ha, left _ _ h⟩ },
{ obtain ⟨c, ha, hb⟩ := exists_between h,
exact ⟨⟨i, c⟩, right _ ha, right _ hb⟩ }
end⟩
instance densely_ordered_of_no_min_order [preorder ι] [Π i, preorder (α i)]
[Π i, densely_ordered (α i)] [Π i, no_min_order (α i)] :
densely_ordered (Σₗ' i, α i) :=
⟨begin
rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | @⟨_, _, b, h⟩),
{ obtain ⟨c, hb⟩ := exists_lt b,
exact ⟨⟨j, c⟩, left _ _ h, right _ hb⟩ },
{ obtain ⟨c, ha, hb⟩ := exists_between h,
exact ⟨⟨i, c⟩, right _ ha, right _ hb⟩ }
end⟩
instance no_max_order_of_nonempty [preorder ι] [Π i, preorder (α i)] [no_max_order ι]
[Π i, nonempty (α i)] :
no_max_order (Σₗ' i, α i) :=
⟨begin
rintro ⟨i, a⟩,
obtain ⟨j, h⟩ := exists_gt i,
obtain ⟨b⟩ : nonempty (α j) := infer_instance,
exact ⟨⟨j, b⟩, left _ _ h⟩
end⟩
instance no_min_order_of_nonempty [preorder ι] [Π i, preorder (α i)] [no_max_order ι]
[Π i, nonempty (α i)] :
no_max_order (Σₗ' i, α i) :=
⟨begin
rintro ⟨i, a⟩,
obtain ⟨j, h⟩ := exists_gt i,
obtain ⟨b⟩ : nonempty (α j) := infer_instance,
exact ⟨⟨j, b⟩, left _ _ h⟩
end⟩
instance no_max_order [preorder ι] [Π i, preorder (α i)] [Π i, no_max_order (α i)] :
no_max_order (Σₗ' i, α i) :=
⟨by { rintro ⟨i, a⟩, obtain ⟨b, h⟩ := exists_gt a, exact ⟨⟨i, b⟩, right _ h⟩ }⟩
instance no_min_order [preorder ι] [Π i, preorder (α i)] [Π i, no_min_order (α i)] :
no_min_order (Σₗ' i, α i) :=
⟨by { rintro ⟨i, a⟩, obtain ⟨b, h⟩ := exists_lt a, exact ⟨⟨i, b⟩, right _ h⟩ }⟩
end lex
end psigma
|
efc439be4c2a77d749ef7c9a8829f7eec8295eec | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/finset/nat_antidiagonal.lean | cd4a27c25349a0a31583cce2b77a7fb8b487e79b | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 1,948 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.finset.basic
import data.multiset.nat_antidiagonal
/-!
# The "antidiagonal" {(0,n), (1,n-1), ..., (n,0)} as a finset.
-/
namespace finset
namespace nat
/-- The antidiagonal of a natural number `n` is
the finset of pairs `(i,j)` such that `i+j = n`. -/
def antidiagonal (n : ℕ) : finset (ℕ × ℕ) :=
⟨multiset.nat.antidiagonal n, multiset.nat.nodup_antidiagonal n⟩
/-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/
@[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} :
x ∈ antidiagonal n ↔ x.1 + x.2 = n :=
by rw [antidiagonal, mem_def, multiset.nat.mem_antidiagonal]
/-- The cardinality of the antidiagonal of `n` is `n+1`. -/
@[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 :=
by simp [antidiagonal]
/-- The antidiagonal of `0` is the list `[(0,0)]` -/
@[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} :=
rfl
lemma antidiagonal_succ {n : ℕ} :
antidiagonal (n + 1) = insert (0, n + 1) ((antidiagonal n).map
(function.embedding.prod_map ⟨nat.succ, nat.succ_injective⟩ (function.embedding.refl _))) :=
begin
apply eq_of_veq,
rw [insert_val_of_not_mem, map_val],
{apply multiset.nat.antidiagonal_succ},
{ intro con, rcases mem_map.1 con with ⟨⟨a,b⟩, ⟨h1, h2⟩⟩,
simp only [prod.mk.inj_iff, function.embedding.coe_prod_map, prod.map_mk] at h2,
apply nat.succ_ne_zero a h2.1, }
end
lemma map_swap_antidiagonal {n : ℕ} :
(antidiagonal n).map ⟨prod.swap, prod.swap_right_inverse.injective⟩ = antidiagonal n :=
begin
ext,
simp only [exists_prop, mem_map, mem_antidiagonal, prod.exists],
rw add_comm,
split,
{ rintro ⟨b, c, ⟨rfl, rfl⟩⟩,
simp },
{ rintro rfl,
use [a.snd, a.fst],
simp }
end
end nat
end finset
|
29cc3bfbbe4233b8c298ea548dd4b1ac3dfd8f54 | 80746c6dba6a866de5431094bf9f8f841b043d77 | /src/tactic/replacer.lean | b84ca6e68d1312e79bfae8c3a77cea8b0b630d9a | [
"Apache-2.0"
] | permissive | leanprover-fork/mathlib-backup | 8b5c95c535b148fca858f7e8db75a76252e32987 | 0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0 | refs/heads/master | 1,585,156,056,139 | 1,548,864,430,000 | 1,548,864,438,000 | 143,964,213 | 0 | 0 | Apache-2.0 | 1,550,795,966,000 | 1,533,705,322,000 | Lean | UTF-8 | Lean | false | false | 4,081 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
A mechanism for defining tactics for use in auto params, whose
meaning is defined incrementally through attributes.
-/
import tactic.basic
namespace tactic
meta def replacer_core {α : Type} [reflected α]
(ntac : name) (eval : ∀ β [reflected β], expr → tactic β) :
list name → tactic α
| [] := fail ("no implementation defined for " ++ to_string ntac)
| (n::ns) := do d ← get_decl n, let t := d.type,
do { tac ← mk_const n >>= eval (tactic α), tac } <|>
do { tac ← mk_const n >>= eval (tactic α → tactic α),
tac (replacer_core ns) } <|>
do { tac ← mk_const n >>= eval (option (tactic α) → tactic α),
tac (guard (ns ≠ []) >> some (replacer_core ns)) }
meta def replacer (ntac : name) {α : Type} [reflected α]
(F : Type → Type) (eF : ∀ β, reflected β → reflected (F β))
(R : ∀ β, F β → β) : tactic α :=
attribute.get_instances ntac >>= replacer_core ntac
(λ β eβ e, R β <$> @eval_expr' (F β) (eF β eβ) e)
meta def mk_replacer₁ : expr → nat → expr × expr
| (expr.pi n bi d b) i :=
let (e₁, e₂) := mk_replacer₁ b (i+1) in
(expr.pi n bi d e₁, (`(expr.pi n bi d) : expr) e₂)
| _ i := (expr.var i, expr.var 0)
meta def mk_replacer₂ (ntac : name) (v : expr × expr) : expr → nat → option expr
| (expr.pi n bi d b) i := do
b' ← mk_replacer₂ b (i+1),
some (expr.lam n bi d b')
| `(tactic %%β) i := some $
(expr.const ``replacer []).mk_app [
reflect ntac, β, reflect β,
expr.lam `γ binder_info.default `(Type) v.1,
expr.lam `γ binder_info.default `(Type) $
expr.lam `eγ binder_info.inst_implicit ((`(@reflected Type) : expr) β) v.2,
expr.lam `γ binder_info.default `(Type) $
expr.lam `f binder_info.default v.1 $
(list.range i).foldr (λ i e', e' (expr.var (i+2))) (expr.var 0)
]
| _ i := none
meta def mk_replacer (ntac : name) (e : expr) : tactic expr :=
mk_replacer₂ ntac (mk_replacer₁ e 0) e 0
meta def valid_types : expr → list expr
| (expr.pi n bi d b) := expr.pi n bi d <$> valid_types b
| `(tactic %%β) := [`(tactic.{0} %%β),
`(tactic.{0} %%β → tactic.{0} %%β),
`(option (tactic.{0} %%β) → tactic.{0} %%β)]
| _ := []
meta def replacer_attr (ntac : name) : user_attribute :=
{ name := ntac,
descr :=
"Replaces the definition of `" ++ to_string ntac ++ "`. This should be " ++
"applied to a definition with the type `tactic unit`, which will be " ++
"called whenever `" ++ to_string ntac ++ "` is called. The definition " ++
"can optionally have an argument of type `tactic unit` or " ++
"`option (tactic unit)` which refers to the previous definition, if any.",
after_set := some $ λ n _ _, do
d ← get_decl n,
base ← get_decl ntac,
guardb ((valid_types base.type).any (=ₐ d.type))
<|> fail format!"incorrect type for @[{ntac}]" }
/-- Define a new replaceable tactic. -/
meta def def_replacer (ntac : name) (ty : expr) : tactic unit :=
let nattr := ntac <.> "attr" in do
add_meta_definition nattr []
`(user_attribute) `(replacer_attr %%(reflect ntac)),
set_basic_attribute `user_attribute nattr tt,
v ← mk_replacer ntac ty,
add_meta_definition ntac [] ty v,
add_doc_string ntac $
"The `" ++ to_string ntac ++ "` tactic is a \"replaceable\" " ++
"tactic, which means that its meaning is defined by tactics that " ++
"are defined later with the `@[" ++ to_string ntac ++ "]` attribute. " ++
"It is intended for use with `auto_param`s for structure fields."
open interactive lean.parser
/-- Define a new replaceable tactic. -/
@[user_command] meta def def_replacer_cmd (meta_info : decl_meta_info)
(_ : parse $ tk "def_replacer") : lean.parser unit :=
do ntac ← ident,
ty ← optional (tk ":" *> types.texpr),
match ty with
| (some p) := do t ← to_expr p, def_replacer ntac t
| none := def_replacer ntac `(tactic unit)
end
end tactic
|
ce175dd330158243792b3e6cab2c047348026737 | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /src/linear_algebra/finsupp.lean | 4e9559bbc241e1b36ca6bc6d32de048ca5ecdca0 | [
"Apache-2.0"
] | permissive | johoelzl/mathlib | 253f46daa30b644d011e8e119025b01ad69735c4 | 592e3c7a2dfbd5826919b4605559d35d4d75938f | refs/heads/master | 1,625,657,216,488 | 1,551,374,946,000 | 1,551,374,946,000 | 98,915,829 | 0 | 0 | Apache-2.0 | 1,522,917,267,000 | 1,501,524,499,000 | Lean | UTF-8 | Lean | false | false | 14,171 | 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
Linear structures on function with finit support `α →₀ β` and multivariate polynomials.
-/
import data.finsupp data.multivariate_polynomial
import linear_algebra.dimension
noncomputable theory
local attribute [instance, priority 0] classical.prop_decidable
open lattice set linear_map submodule
namespace finsupp
section module
variables {α : Type*} {β : Type*} {γ : Type*}
variables [decidable_eq α] [decidable_eq β] [ring γ] [add_comm_group β] [module γ β]
instance : module γ (α →₀ β) := finsupp.to_module α β
def lsingle (a : α) : β →ₗ[γ] (α →₀ β) :=
⟨single a, assume a b, single_add, assume c b, (smul_single _ _ _).symm⟩
def lapply (a : α) : (α →₀ β) →ₗ[γ] β := ⟨λg, g a, assume a b, rfl, assume a b, rfl⟩
section lmap_domain
variables {α' : Type*} [decidable_eq α']
def lmap_domain (i : α → α') : (α →₀ β) →ₗ[γ] (α' →₀ β) :=
⟨map_domain i, assume a b, map_domain_add, map_domain_smul⟩
lemma lmap_domain_apply (i : α → α') (f : α →₀ β) :
(lmap_domain i : (α →₀ β) →ₗ[γ] (α' →₀ β)) f = map_domain i f := rfl
end lmap_domain
protected def dom_lcongr
{α₁ : Type*} {α₂ : Type*} [decidable_eq α₁] [decidable_eq α₂] (e : α₁ ≃ α₂) :
(α₁ →₀ β) ≃ₗ[γ] (α₂ →₀ β) :=
(finsupp.dom_congr e).to_linear_equiv
begin
change is_linear_map γ (lmap_domain e : (α₁ →₀ β) →ₗ[γ] (α₂ →₀ β)),
exact linear_map.is_linear _
end
section lsubtype_domain
variables (s : set α) [decidable_pred (λx, x ∈ s)]
def lsubtype_domain : (α →₀ β) →ₗ[γ] (s →₀ β) :=
⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩
lemma lsubtype_domain_apply (f : α →₀ β) :
(lsubtype_domain s : (α →₀ β) →ₗ[γ] (s →₀ β)) f = subtype_domain (λx, x ∈ s) f := rfl
end lsubtype_domain
lemma lsingle_apply (a : α) (b : β) : (lsingle a : β →ₗ[γ] (α →₀ β)) b = single a b :=
rfl
lemma lapply_apply (a : α) (f : α →₀ β) : (lapply a : (α →₀ β) →ₗ[γ] β) f = f a :=
rfl
lemma ker_lsingle (a : α) : (lsingle a : β →ₗ[γ] (α →₀ β)).ker = ⊥ :=
ker_eq_bot.2 (injective_single a)
lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) :
(⨆a∈s, (lsingle a : β →ₗ[γ] (α →₀ β)).range) ≤ (⨅a∈t, ker (lapply a)) :=
begin
refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _),
simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi],
assume b hb a₂ h₂,
have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩,
exact single_eq_of_ne this
end
lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ β) →ₗ[γ] β)) ≤ ⊥ :=
begin
simp only [le_def', mem_infi, mem_ker, mem_bot, lapply_apply],
exact assume a h, finsupp.ext h
end
lemma supr_lsingle_range : (⨆a, (lsingle a : β →ₗ[γ] (α →₀ β)).range) = ⊤ :=
begin
refine (eq_top_iff.2 $ le_def'.2 $ assume f _, _),
rw [← sum_single f],
refine sum_mem _ (assume a ha, submodule.mem_supr_of_mem _ a $ set.mem_image_of_mem _ trivial)
end
lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) :
disjoint (⨆a∈s, (lsingle a : β →ₗ[γ] (α →₀ β)).range) (⨆a∈t, (lsingle a).range) :=
begin
refine disjoint_mono
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl s)
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl t)
(le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot),
classical,
by_cases his : i ∈ s,
{ by_cases hit : i ∈ t,
{ exact (hs ⟨his, hit⟩).elim },
exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) },
exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his)
end
lemma span_single_image (s : set β) (a : α) :
submodule.span γ (single a '' s) = (submodule.span γ s).map (lsingle a) :=
by rw ← span_image; refl
lemma linear_independent_single {f : α → set β}
(hf : ∀a, linear_independent γ (f a)) : linear_independent γ (⋃a, single a '' f a) :=
begin
refine linear_independent_Union_finite _ _ ,
{ refine assume a, @linear_independent.image _ _ _ _ _ _ _ _ _ (lsingle a) (hf a) _,
rw ker_lsingle,
exact disjoint_bot_right },
{ assume a s hs hat,
have : ∀a, span γ (single a '' f a) ≤ range (lsingle a),
{ simp only [span_single_image],
exact assume a, map_mono le_top },
refine disjoint_mono _ _ (disjoint_lsingle_lsingle {a} s _),
{ simp only [supr_singleton, this] },
{ exact supr_le_supr (assume a, supr_le_supr (assume ha, this a)) },
{ rwa [disjoint_singleton_left] } }
end
section
variables (β γ)
def restrict_dom (s : set α) : submodule γ (α →₀ β) :=
begin
refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩,
{ simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply],
assume h ha, exact (ha rfl).elim },
{ assume p q hp hq,
refine subset.trans
(subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq),
rw [finset.coe_union] },
{ assume a p hp,
refine subset.trans (finset.coe_subset.2 support_smul) hp }
end
lemma mem_restrict_dom {s : set α} (p : α →₀ β) : p ∈ (restrict_dom β γ s) ↔ ↑p.support ⊆ s :=
iff.rfl
section
set_option class.instance_max_depth 37
def restrict_dom_equiv_finsupp (s : set α) [decidable_pred (λ (x : α), x ∈ s)] :
(restrict_dom β γ s) ≃ₗ[γ] (s →₀ β) :=
(restrict_support_equiv s).to_linear_equiv
begin
show is_linear_map γ ((lsubtype_domain s : (α →₀ β) →ₗ[γ] (s →₀ β)).comp
(submodule.subtype (restrict_dom β γ s))),
exact linear_map.is_linear _
end
end
end
end module
section vector_space
variables {α : Type*} {β : Type*} {γ : Type*}
variables [decidable_eq α] [decidable_eq β] [discrete_field γ] [add_comm_group β] [vector_space γ β]
open linear_map submodule
instance : vector_space γ (α →₀ β) :=
{ to_module := finsupp.module }
lemma is_basis_single {f : α → set β} (hf : ∀a, is_basis γ (f a)) :
is_basis γ (⋃a, single a '' f a) :=
⟨linear_independent_single $ assume a, (hf a).1,
by simp only [span_Union, span_single_image, (hf _).2, map_top, supr_lsingle_range]⟩
end vector_space
section dim
universes u v
variables {α : Type u} {β : Type u} {γ : Type v}
variables [decidable_eq α] [decidable_eq β] [discrete_field γ] [add_comm_group β] [vector_space γ β]
lemma dim_eq : vector_space.dim γ (α →₀ β) = cardinal.mk α * vector_space.dim γ β :=
begin
rcases exists_is_basis γ β with ⟨bs, hbs⟩,
rw [← hbs.mk_eq_dim, ← (is_basis_single (λa:α, hbs)).mk_eq_dim, cardinal.mk_Union_eq_sum_mk],
{ simp only [cardinal.mk_eq_of_injective (injective_single.{u u} _), cardinal.sum_const] },
{ refine assume i j h, disjoint_image_image (assume b hb c hc, _),
simp only [(≠), single_eq_single_iff, not_or_distrib, not_and_distrib],
have : (0:β) ∉ bs := zero_not_mem_of_linear_independent (zero_ne_one : (0:γ) ≠ 1) hbs.1,
exact ⟨or.inl h, or.inl (assume eq, this $ eq ▸ hb)⟩ }
end
end dim
end finsupp
namespace lc
universes u v w
variables (α : Type v) {β : Type u} {γ : Type w}
variables [ring α]
variables [add_comm_group β] [module α β]
variables [add_comm_group γ] [module α γ]
local attribute [instance, priority 0] classical.prop_decidable
noncomputable def congr (s : set β) (t : set γ) (e : s ≃ t) : supported α s ≃ₗ[α] supported α t :=
begin
show (finsupp.restrict_dom α α s) ≃ₗ[α] (finsupp.restrict_dom α α t),
refine linear_equiv.trans (finsupp.restrict_dom_equiv_finsupp α α s)
(linear_equiv.trans _ (finsupp.restrict_dom_equiv_finsupp α α t).symm),
exact finsupp.dom_lcongr e
end
-- TODO: this is super slow
set_option class.instance_max_depth 80
noncomputable def supported_equiv [decidable_eq β] (s : set β) :
lc.supported α s ≃ₗ[α] (s →₀ α) :=
begin
refine linear_equiv.trans _ (finsupp.restrict_dom_equiv_finsupp α α s),
convert linear_equiv.refl (lc.supported α s); ext; exact subsingleton.elim _ _,
end
end lc
section vector_space
universes u v
variables {α : Type u} {β γ : Type v}
variables [discrete_field α]
variables [add_comm_group β] [vector_space α β]
variables [add_comm_group γ] [vector_space α γ]
open vector_space
set_option class.instance_max_depth 100
lemma equiv_of_dim_eq_dim (h : dim α β = dim α γ) : nonempty (β ≃ₗ[α] γ) :=
begin
rcases exists_is_basis α β with ⟨b, hb⟩,
rcases exists_is_basis α γ with ⟨c, hc⟩,
rw [← hb.mk_eq_dim, ← hc.mk_eq_dim] at h,
rcases quotient.exact h with ⟨e⟩,
exact ⟨ (module_equiv_lc hb).trans (linear_equiv.trans (lc.congr α b c e) (module_equiv_lc hc).symm) ⟩
end
lemma eq_bot_iff_dim_eq_zero (p : submodule α β) (h : dim α p = 0) : p = ⊥ :=
begin
have : dim α p = dim α (⊥ : submodule α β) := by rwa [dim_bot],
rcases equiv_of_dim_eq_dim this with ⟨e⟩,
exact e.eq_bot_of_equiv _
end
lemma injective_of_surjective (f : β →ₗ[α] γ)
(hβ : dim α β < cardinal.omega) (heq : dim α γ = dim α β) (hf : f.range = ⊤) : f.ker = ⊥ :=
have hk : dim α f.ker < cardinal.omega := lt_of_le_of_lt (dim_submodule_le _) hβ,
begin
rcases cardinal.lt_omega.1 hβ with ⟨d₁, eq₁⟩,
rcases cardinal.lt_omega.1 hk with ⟨d₂, eq₂⟩,
have : 0 = d₂,
{ have := dim_eq_surjective f (linear_map.range_eq_top.1 hf),
rw [heq, eq₁, eq₂, ← nat.cast_add, cardinal.nat_cast_inj] at this,
exact nat.add_left_cancel this },
refine eq_bot_iff_dim_eq_zero _ _,
rw [eq₂, ← this, nat.cast_zero]
end
end vector_space
section vector_space
universes u
open vector_space
set_option class.instance_max_depth 70
lemma cardinal_mk_eq_cardinal_mk_field_pow_dim
{α β : Type u} [discrete_field α] [add_comm_group β] [vector_space α β]
(h : dim α β < cardinal.omega) : cardinal.mk β = cardinal.mk α ^ dim α β :=
begin
rcases exists_is_basis α β with ⟨s, hs⟩,
have : nonempty (fintype s),
{ rwa [← cardinal.lt_omega_iff_fintype, hs.mk_eq_dim] },
cases this with hsf, letI := hsf,
calc cardinal.mk β = cardinal.mk (↥(lc.supported α s)) :
quotient.sound ⟨(module_equiv_lc hs).to_equiv⟩
... = cardinal.mk (s →₀ α) :
begin
refine quotient.sound ⟨@linear_equiv.to_equiv α _ _ _ _ _ _ _ _⟩,
convert @lc.supported_equiv α β _ _ _ _ s,
{ funext, exact subsingleton.elim _ _ },
end
... = cardinal.mk (s → α) : quotient.sound ⟨finsupp.equiv_fun_on_fintype⟩
... = _ : by rw [← hs.mk_eq_dim, cardinal.power_def]
end
lemma cardinal_lt_omega_of_dim_lt_omega
{α β : Type u} [discrete_field α] [add_comm_group β] [vector_space α β] [fintype α]
(h : dim α β < cardinal.omega) : cardinal.mk β < cardinal.omega :=
begin
rw [cardinal_mk_eq_cardinal_mk_field_pow_dim h],
exact cardinal.power_lt_omega (cardinal.lt_omega_iff_fintype.2 ⟨infer_instance⟩) h
end
end vector_space
namespace mv_polynomial
universes u v
variables {σ : Type u} {α : Type v} [decidable_eq σ]
instance [discrete_field α] : vector_space α (mv_polynomial σ α) :=
finsupp.vector_space
section
variables (σ α) [discrete_field α] (m : ℕ)
def restrict_total_degree : submodule α (mv_polynomial σ α) :=
finsupp.restrict_dom _ _ {n | n.sum (λn e, e) ≤ m }
lemma mem_restrict_total_degree (p : mv_polynomial σ α) :
p ∈ restrict_total_degree σ α m ↔ p.total_degree ≤ m :=
begin
rw [total_degree, finset.sup_le_iff],
refl
end
end
noncomputable instance decidable_restrict_degree (m : ℕ) :
decidable_pred (λn, n ∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) :=
assume n, classical.prop_decidable _
section
variables (σ α)
def restrict_degree (m : ℕ) [discrete_field α] : submodule α (mv_polynomial σ α) :=
finsupp.restrict_dom _ _ {n | ∀i, n i ≤ m }
end
lemma mem_restrict_degree [discrete_field α] (p : mv_polynomial σ α) (n : ℕ) :
p ∈ restrict_degree σ α n ↔ (∀s ∈ p.support, ∀i, (s : σ →₀ ℕ) i ≤ n) :=
begin
rw [restrict_degree, finsupp.mem_restrict_dom],
refl
end
lemma mem_restrict_degree_iff_sup [discrete_field α] (p : mv_polynomial σ α) (n : ℕ) :
p ∈ restrict_degree σ α n ↔ ∀i, p.degrees.count i ≤ n :=
begin
simp only [mem_restrict_degree, degrees, multiset.count_sup, finsupp.count_to_multiset,
finset.sup_le_iff],
exact ⟨assume h n s hs, h s hs n, assume h s hs n, h n s hs⟩
end
lemma map_range_eq_map {β : Type*}
[decidable_eq α] [comm_ring α] [decidable_eq β] [comm_ring β] (p : mv_polynomial σ α)
(f : α → β) [is_semiring_hom f]:
finsupp.map_range f (is_semiring_hom.map_zero f) p = p.map f :=
begin
rw [← finsupp.sum_single p, finsupp.sum, finsupp.map_range_finset_sum,
← finset.sum_hom (map f)],
{ refine finset.sum_congr rfl (assume n _, _),
rw [finsupp.map_range_single, ← monomial, ← monomial, map_monomial] },
apply_instance
end
section
variables (σ α)
lemma is_basis_monomials [discrete_field α] :
is_basis α (range (λs, monomial s 1) : set (mv_polynomial σ α)) :=
suffices is_basis α (⋃i, (monomial i : α → mv_polynomial σ α) '' {1}),
by simpa only [range_eq_Union, image_singleton],
finsupp.is_basis_single (assume s, is_basis_singleton_one α)
end
end mv_polynomial
namespace mv_polynomial
universe u
variables (σ : Type u) (α : Type u) [decidable_eq σ] [discrete_field α]
lemma dim_mv_polynomial : vector_space.dim α (mv_polynomial σ α) = cardinal.mk (σ →₀ ℕ) :=
begin
rw [← (is_basis_monomials σ α).mk_eq_dim, ← set.image_univ, cardinal.mk_eq_of_injective,
cardinal.mk_univ],
assume a b h,
rcases (finsupp.single_eq_single_iff _ _ _ _).1 h with ⟨rfl, _⟩ | ⟨h, _⟩,
{ refl },
{ exact (zero_ne_one.symm h).elim }
end
end mv_polynomial
|
557fc27527fe4c455158063258d820d3bc06467b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/group_theory/submonoid/operations.lean | 6226d6e25dc7632887d9085731c96b6738294eb8 | [
"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 | 46,281 | 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, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard,
Amelia Livingston, Yury Kudryashov
-/
import algebra.order.monoid.cancel.basic
import group_theory.group_action.defs
import group_theory.submonoid.basic
import group_theory.subsemigroup.operations
/-!
# Operations on `submonoid`s
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define various operations on `submonoid`s and `monoid_hom`s.
## Main definitions
### Conversion between multiplicative and additive definitions
* `submonoid.to_add_submonoid`, `submonoid.to_add_submonoid'`, `add_submonoid.to_submonoid`,
`add_submonoid.to_submonoid'`: convert between multiplicative and additive submonoids of `M`,
`multiplicative M`, and `additive M`. These are stated as `order_iso`s.
### (Commutative) monoid structure on a submonoid
* `submonoid.to_monoid`, `submonoid.to_comm_monoid`: a submonoid inherits a (commutative) monoid
structure.
### Group actions by submonoids
* `submonoid.mul_action`, `submonoid.distrib_mul_action`: a submonoid inherits (distributive)
multiplicative actions.
### Operations on submonoids
* `submonoid.comap`: preimage of a submonoid under a monoid homomorphism as a submonoid of the
domain;
* `submonoid.map`: image of a submonoid under a monoid homomorphism as a submonoid of the codomain;
* `submonoid.prod`: product of two submonoids `s : submonoid M` and `t : submonoid N` as a submonoid
of `M × N`;
### Monoid homomorphisms between submonoid
* `submonoid.subtype`: embedding of a submonoid into the ambient monoid.
* `submonoid.inclusion`: given two submonoids `S`, `T` such that `S ≤ T`, `S.inclusion T` is the
inclusion of `S` into `T` as a monoid homomorphism;
* `mul_equiv.submonoid_congr`: converts a proof of `S = T` into a monoid isomorphism between `S`
and `T`.
* `submonoid.prod_equiv`: monoid isomorphism between `s.prod t` and `s × t`;
### Operations on `monoid_hom`s
* `monoid_hom.mrange`: range of a monoid homomorphism as a submonoid of the codomain;
* `monoid_hom.mker`: kernel of a monoid homomorphism as a submonoid of the domain;
* `monoid_hom.restrict`: restrict a monoid homomorphism to a submonoid;
* `monoid_hom.cod_restrict`: restrict the codomain of a monoid homomorphism to a submonoid;
* `monoid_hom.mrange_restrict`: restrict a monoid homomorphism to its range;
## Tags
submonoid, range, product, map, comap
-/
variables {M N P : Type*} [mul_one_class M] [mul_one_class N] [mul_one_class P] (S : submonoid M)
/-!
### Conversion to/from `additive`/`multiplicative`
-/
section
/-- Submonoids of monoid `M` are isomorphic to additive submonoids of `additive M`. -/
@[simps]
def submonoid.to_add_submonoid : submonoid M ≃o add_submonoid (additive M) :=
{ to_fun := λ S,
{ carrier := additive.to_mul ⁻¹' S,
zero_mem' := S.one_mem',
add_mem' := λ _ _, S.mul_mem' },
inv_fun := λ S,
{ carrier := additive.of_mul ⁻¹' S,
one_mem' := S.zero_mem',
mul_mem' := λ _ _, S.add_mem' },
left_inv := λ x, by cases x; refl,
right_inv := λ x, by cases x; refl,
map_rel_iff' := λ a b, iff.rfl, }
/-- Additive submonoids of an additive monoid `additive M` are isomorphic to submonoids of `M`. -/
abbreviation add_submonoid.to_submonoid' : add_submonoid (additive M) ≃o submonoid M :=
submonoid.to_add_submonoid.symm
lemma submonoid.to_add_submonoid_closure (S : set M) :
(submonoid.closure S).to_add_submonoid = add_submonoid.closure (additive.to_mul ⁻¹' S) :=
le_antisymm
(submonoid.to_add_submonoid.le_symm_apply.1 $
submonoid.closure_le.2 add_submonoid.subset_closure)
(add_submonoid.closure_le.2 submonoid.subset_closure)
lemma add_submonoid.to_submonoid'_closure (S : set (additive M)) :
(add_submonoid.closure S).to_submonoid' = submonoid.closure (multiplicative.of_add ⁻¹' S) :=
le_antisymm
(add_submonoid.to_submonoid'.le_symm_apply.1 $
add_submonoid.closure_le.2 submonoid.subset_closure)
(submonoid.closure_le.2 add_submonoid.subset_closure)
end
section
variables {A : Type*} [add_zero_class A]
/-- Additive submonoids of an additive monoid `A` are isomorphic to
multiplicative submonoids of `multiplicative A`. -/
@[simps]
def add_submonoid.to_submonoid : add_submonoid A ≃o submonoid (multiplicative A) :=
{ to_fun := λ S,
{ carrier := multiplicative.to_add ⁻¹' S,
one_mem' := S.zero_mem',
mul_mem' := λ _ _, S.add_mem' },
inv_fun := λ S,
{ carrier := multiplicative.of_add ⁻¹' S,
zero_mem' := S.one_mem',
add_mem' := λ _ _, S.mul_mem' },
left_inv := λ x, by cases x; refl,
right_inv := λ x, by cases x; refl,
map_rel_iff' := λ a b, iff.rfl, }
/-- Submonoids of a monoid `multiplicative A` are isomorphic to additive submonoids of `A`. -/
abbreviation submonoid.to_add_submonoid' : submonoid (multiplicative A) ≃o add_submonoid A :=
add_submonoid.to_submonoid.symm
lemma add_submonoid.to_submonoid_closure (S : set A) :
(add_submonoid.closure S).to_submonoid = submonoid.closure (multiplicative.to_add ⁻¹' S) :=
le_antisymm
(add_submonoid.to_submonoid.to_galois_connection.l_le $
add_submonoid.closure_le.2 submonoid.subset_closure)
(submonoid.closure_le.2 add_submonoid.subset_closure)
lemma submonoid.to_add_submonoid'_closure (S : set (multiplicative A)) :
(submonoid.closure S).to_add_submonoid' = add_submonoid.closure (additive.of_mul ⁻¹' S) :=
le_antisymm
(submonoid.to_add_submonoid'.to_galois_connection.l_le $
submonoid.closure_le.2 add_submonoid.subset_closure)
(add_submonoid.closure_le.2 submonoid.subset_closure)
end
namespace submonoid
variables {F : Type*} [mc : monoid_hom_class F M N]
open set
/-!
### `comap` and `map`
-/
include mc
/-- The preimage of a submonoid along a monoid homomorphism is a submonoid. -/
@[to_additive "The preimage of an `add_submonoid` along an `add_monoid` homomorphism is an
`add_submonoid`."]
def comap (f : F) (S : submonoid N) : submonoid M :=
{ carrier := (f ⁻¹' S),
one_mem' := show f 1 ∈ S, by rw map_one; exact S.one_mem,
mul_mem' := λ a b ha hb,
show f (a * b) ∈ S, by rw map_mul; exact S.mul_mem ha hb }
@[simp, to_additive]
lemma coe_comap (S : submonoid N) (f : F) : (S.comap f : set M) = f ⁻¹' S := rfl
@[simp, to_additive]
lemma mem_comap {S : submonoid N} {f : F} {x : M} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl
omit mc
@[to_additive]
lemma comap_comap (S : submonoid P) (g : N →* P) (f : M →* N) :
(S.comap g).comap f = S.comap (g.comp f) :=
rfl
@[simp, to_additive]
lemma comap_id (S : submonoid P) : S.comap (monoid_hom.id P) = S :=
ext (by simp)
include mc
/-- The image of a submonoid along a monoid homomorphism is a submonoid. -/
@[to_additive "The image of an `add_submonoid` along an `add_monoid` homomorphism is
an `add_submonoid`."]
def map (f : F) (S : submonoid M) : submonoid N :=
{ carrier := (f '' S),
one_mem' := ⟨1, S.one_mem, map_one f⟩,
mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, S.mul_mem hx hy,
by rw map_mul; refl⟩ end }
@[simp, to_additive]
lemma coe_map (f : F) (S : submonoid M) :
(S.map f : set N) = f '' S := rfl
@[simp, to_additive]
lemma mem_map {f : F} {S : submonoid M} {y : N} :
y ∈ S.map f ↔ ∃ x ∈ S, f x = y :=
mem_image_iff_bex
@[to_additive]
lemma mem_map_of_mem (f : F) {S : submonoid M} {x : M} (hx : x ∈ S) : f x ∈ S.map f :=
mem_image_of_mem f hx
@[to_additive]
lemma apply_coe_mem_map (f : F) (S : submonoid M) (x : S) : f x ∈ S.map f :=
mem_map_of_mem f x.prop
omit mc
@[to_additive]
lemma map_map (g : N →* P) (f : M →* N) : (S.map f).map g = S.map (g.comp f) :=
set_like.coe_injective $ image_image _ _ _
include mc
@[to_additive]
lemma mem_map_iff_mem {f : F} (hf : function.injective f) {S : submonoid M} {x : M} :
f x ∈ S.map f ↔ x ∈ S :=
hf.mem_set_image
@[to_additive]
lemma map_le_iff_le_comap {f : F} {S : submonoid M} {T : submonoid N} :
S.map f ≤ T ↔ S ≤ T.comap f :=
image_subset_iff
@[to_additive]
lemma gc_map_comap (f : F) : galois_connection (map f) (comap f) :=
λ S T, map_le_iff_le_comap
@[to_additive]
lemma map_le_of_le_comap {T : submonoid N} {f : F} : S ≤ T.comap f → S.map f ≤ T :=
(gc_map_comap f).l_le
@[to_additive]
lemma le_comap_of_map_le {T : submonoid N} {f : F} : S.map f ≤ T → S ≤ T.comap f :=
(gc_map_comap f).le_u
@[to_additive]
lemma le_comap_map {f : F} : S ≤ (S.map f).comap f :=
(gc_map_comap f).le_u_l _
@[to_additive]
lemma map_comap_le {S : submonoid N} {f : F} : (S.comap f).map f ≤ S :=
(gc_map_comap f).l_u_le _
@[to_additive]
lemma monotone_map {f : F} : monotone (map f) :=
(gc_map_comap f).monotone_l
@[to_additive]
lemma monotone_comap {f : F} : monotone (comap f) :=
(gc_map_comap f).monotone_u
@[simp, to_additive]
lemma map_comap_map {f : F} : ((S.map f).comap f).map f = S.map f :=
(gc_map_comap f).l_u_l_eq_l _
@[simp, to_additive]
lemma comap_map_comap {S : submonoid N} {f : F} : ((S.comap f).map f).comap f = S.comap f :=
(gc_map_comap f).u_l_u_eq_u _
@[to_additive]
lemma map_sup (S T : submonoid M) (f : F) : (S ⊔ T).map f = S.map f ⊔ T.map f :=
(gc_map_comap f : galois_connection (map f) (comap f)).l_sup
@[to_additive]
lemma map_supr {ι : Sort*} (f : F) (s : ι → submonoid M) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f : galois_connection (map f) (comap f)).l_supr
@[to_additive]
lemma comap_inf (S T : submonoid N) (f : F) : (S ⊓ T).comap f = S.comap f ⊓ T.comap f :=
(gc_map_comap f : galois_connection (map f) (comap f)).u_inf
@[to_additive]
lemma comap_infi {ι : Sort*} (f : F) (s : ι → submonoid N) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f : galois_connection (map f) (comap f)).u_infi
@[simp, to_additive] lemma map_bot (f : F) : (⊥ : submonoid M).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp, to_additive] lemma comap_top (f : F) : (⊤ : submonoid N).comap f = ⊤ :=
(gc_map_comap f).u_top
omit mc
@[simp, to_additive] lemma map_id (S : submonoid M) : S.map (monoid_hom.id M) = S :=
ext (λ x, ⟨λ ⟨_, h, rfl⟩, h, λ h, ⟨_, h, rfl⟩⟩)
section galois_coinsertion
variables {ι : Type*} {f : F} (hf : function.injective f)
include hf
/-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/
@[to_additive /-" `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. "-/]
def gci_map_comap : galois_coinsertion (map f) (comap f) :=
(gc_map_comap f).to_galois_coinsertion
(λ S x, by simp [mem_comap, mem_map, hf.eq_iff])
@[to_additive]
lemma comap_map_eq_of_injective (S : submonoid M) : (S.map f).comap f = S :=
(gci_map_comap hf).u_l_eq _
@[to_additive]
lemma comap_surjective_of_injective : function.surjective (comap f) :=
(gci_map_comap hf).u_surjective
@[to_additive]
lemma map_injective_of_injective : function.injective (map f) :=
(gci_map_comap hf).l_injective
@[to_additive]
lemma comap_inf_map_of_injective (S T : submonoid M) : (S.map f ⊓ T.map f).comap f = S ⊓ T :=
(gci_map_comap hf).u_inf_l _ _
@[to_additive]
lemma comap_infi_map_of_injective (S : ι → submonoid M) : (⨅ i, (S i).map f).comap f = infi S :=
(gci_map_comap hf).u_infi_l _
@[to_additive]
lemma comap_sup_map_of_injective (S T : submonoid M) : (S.map f ⊔ T.map f).comap f = S ⊔ T :=
(gci_map_comap hf).u_sup_l _ _
@[to_additive]
lemma comap_supr_map_of_injective (S : ι → submonoid M) : (⨆ i, (S i).map f).comap f = supr S :=
(gci_map_comap hf).u_supr_l _
@[to_additive]
lemma map_le_map_iff_of_injective {S T : submonoid M} : S.map f ≤ T.map f ↔ S ≤ T :=
(gci_map_comap hf).l_le_l_iff
@[to_additive]
lemma map_strict_mono_of_injective : strict_mono (map f) :=
(gci_map_comap hf).strict_mono_l
end galois_coinsertion
section galois_insertion
variables {ι : Type*} {f : F} (hf : function.surjective f)
include hf
/-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/
@[to_additive /-" `map f` and `comap f` form a `galois_insertion` when `f` is surjective. "-/]
def gi_map_comap : galois_insertion (map f) (comap f) :=
(gc_map_comap f).to_galois_insertion
(λ S x h, let ⟨y, hy⟩ := hf x in mem_map.2 ⟨y, by simp [hy, h]⟩)
@[to_additive]
lemma map_comap_eq_of_surjective (S : submonoid N) : (S.comap f).map f = S :=
(gi_map_comap hf).l_u_eq _
@[to_additive]
lemma map_surjective_of_surjective : function.surjective (map f) :=
(gi_map_comap hf).l_surjective
@[to_additive]
lemma comap_injective_of_surjective : function.injective (comap f) :=
(gi_map_comap hf).u_injective
@[to_additive]
lemma map_inf_comap_of_surjective (S T : submonoid N) : (S.comap f ⊓ T.comap f).map f = S ⊓ T :=
(gi_map_comap hf).l_inf_u _ _
@[to_additive]
lemma map_infi_comap_of_surjective (S : ι → submonoid N) : (⨅ i, (S i).comap f).map f = infi S :=
(gi_map_comap hf).l_infi_u _
@[to_additive]
lemma map_sup_comap_of_surjective (S T : submonoid N) : (S.comap f ⊔ T.comap f).map f = S ⊔ T :=
(gi_map_comap hf).l_sup_u _ _
@[to_additive]
lemma map_supr_comap_of_surjective (S : ι → submonoid N) : (⨆ i, (S i).comap f).map f = supr S :=
(gi_map_comap hf).l_supr_u _
@[to_additive]
lemma comap_le_comap_iff_of_surjective {S T : submonoid N} : S.comap f ≤ T.comap f ↔ S ≤ T :=
(gi_map_comap hf).u_le_u_iff
@[to_additive]
lemma comap_strict_mono_of_surjective : strict_mono (comap f) :=
(gi_map_comap hf).strict_mono_u
end galois_insertion
end submonoid
namespace one_mem_class
variables {A M₁ : Type*} [set_like A M₁] [has_one M₁] [hA : one_mem_class A M₁] (S' : A)
include hA
/-- A submonoid of a monoid inherits a 1. -/
@[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."]
instance has_one : has_one S' := ⟨⟨1, one_mem_class.one_mem S'⟩⟩
@[simp, norm_cast, to_additive] lemma coe_one : ((1 : S') : M₁) = 1 := rfl
variables {S'}
@[simp, norm_cast, to_additive] lemma coe_eq_one {x : S'} : (↑x : M₁) = 1 ↔ x = 1 :=
(subtype.ext_iff.symm : (x : M₁) = (1 : S') ↔ x = 1)
variables (S')
@[to_additive] lemma one_def : (1 : S') = ⟨1, one_mem_class.one_mem S'⟩ := rfl
end one_mem_class
namespace submonoid_class
variables {A : Type*} [set_like A M] [hA : submonoid_class A M] (S' : A)
/-- An `add_submonoid` of an `add_monoid` inherits a scalar multiplication. -/
instance _root_.add_submonoid_class.has_nsmul {M} [add_monoid M] {A : Type*} [set_like A M]
[add_submonoid_class A M] (S : A) :
has_smul ℕ S :=
⟨λ n a, ⟨n • a.1, nsmul_mem a.2 n⟩⟩
/-- A submonoid of a monoid inherits a power operator. -/
instance has_pow {M} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) :
has_pow S ℕ :=
⟨λ a n, ⟨a.1 ^ n, pow_mem a.2 n⟩⟩
attribute [to_additive] submonoid_class.has_pow
@[simp, norm_cast, to_additive] lemma coe_pow {M} [monoid M] {A : Type*} [set_like A M]
[submonoid_class A M] {S : A} (x : S) (n : ℕ) :
(↑(x ^ n) : M) = ↑x ^ n :=
rfl
@[simp, to_additive] lemma mk_pow {M} [monoid M] {A : Type*} [set_like A M]
[submonoid_class A M] {S : A} (x : M) (hx : x ∈ S) (n : ℕ) :
(⟨x, hx⟩ : S) ^ n = ⟨x ^ n, pow_mem hx n⟩ :=
rfl
/-- A submonoid of a unital magma inherits a unital magma structure. -/
@[to_additive "An `add_submonoid` of an unital additive magma inherits an unital additive magma
structure.",
priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`.
instance to_mul_one_class {M : Type*} [mul_one_class M] {A : Type*} [set_like A M]
[submonoid_class A M] (S : A) : mul_one_class S :=
subtype.coe_injective.mul_one_class _ rfl (λ _ _, rfl)
/-- A submonoid of a monoid inherits a monoid structure. -/
@[to_additive "An `add_submonoid` of an `add_monoid` inherits an `add_monoid`
structure.",
priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`.
instance to_monoid {M : Type*} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M]
(S : A) : monoid S :=
subtype.coe_injective.monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
/-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/
@[to_additive "An `add_submonoid` of an `add_comm_monoid` is
an `add_comm_monoid`.",
priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`.
instance to_comm_monoid {M} [comm_monoid M] {A : Type*} [set_like A M] [submonoid_class A M]
(S : A) : comm_monoid S :=
subtype.coe_injective.comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
/-- A submonoid of an `ordered_comm_monoid` is an `ordered_comm_monoid`. -/
@[to_additive "An `add_submonoid` of an `ordered_add_comm_monoid` is
an `ordered_add_comm_monoid`.",
priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`.
instance to_ordered_comm_monoid {M} [ordered_comm_monoid M] {A : Type*} [set_like A M]
[submonoid_class A M] (S : A) : ordered_comm_monoid S :=
subtype.coe_injective.ordered_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
/-- A submonoid of a `linear_ordered_comm_monoid` is a `linear_ordered_comm_monoid`. -/
@[to_additive "An `add_submonoid` of a `linear_ordered_add_comm_monoid` is
a `linear_ordered_add_comm_monoid`.",
priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`.
instance to_linear_ordered_comm_monoid {M} [linear_ordered_comm_monoid M] {A : Type*}
[set_like A M] [submonoid_class A M] (S : A) :
linear_ordered_comm_monoid S :=
subtype.coe_injective.linear_ordered_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
(λ _ _, rfl) (λ _ _, rfl)
/-- A submonoid of an `ordered_cancel_comm_monoid` is an `ordered_cancel_comm_monoid`. -/
@[to_additive "An `add_submonoid` of an `ordered_cancel_add_comm_monoid` is
an `ordered_cancel_add_comm_monoid`.",
priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`.
instance to_ordered_cancel_comm_monoid {M} [ordered_cancel_comm_monoid M] {A : Type*}
[set_like A M] [submonoid_class A M] (S : A) :
ordered_cancel_comm_monoid S :=
subtype.coe_injective.ordered_cancel_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
/-- A submonoid of a `linear_ordered_cancel_comm_monoid` is a `linear_ordered_cancel_comm_monoid`.
-/
@[to_additive "An `add_submonoid` of a `linear_ordered_cancel_add_comm_monoid` is
a `linear_ordered_cancel_add_comm_monoid`.",
priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`.
instance to_linear_ordered_cancel_comm_monoid {M} [linear_ordered_cancel_comm_monoid M]
{A : Type*} [set_like A M] [submonoid_class A M] (S : A) : linear_ordered_cancel_comm_monoid S :=
subtype.coe_injective.linear_ordered_cancel_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
(λ _ _, rfl) (λ _ _, rfl)
include hA
/-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/
@[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."]
def subtype : S' →* M := ⟨coe, rfl, λ _ _, rfl⟩
@[simp, to_additive] theorem coe_subtype : (submonoid_class.subtype S' : S' → M) = coe := rfl
end submonoid_class
namespace submonoid
/-- A submonoid of a monoid inherits a multiplication. -/
@[to_additive "An `add_submonoid` of an `add_monoid` inherits an addition."]
instance has_mul : has_mul S := ⟨λ a b, ⟨a.1 * b.1, S.mul_mem a.2 b.2⟩⟩
/-- A submonoid of a monoid inherits a 1. -/
@[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."]
instance has_one : has_one S := ⟨⟨_, S.one_mem⟩⟩
@[simp, norm_cast, to_additive] lemma coe_mul (x y : S) : (↑(x * y) : M) = ↑x * ↑y := rfl
@[simp, norm_cast, to_additive] lemma coe_one : ((1 : S) : M) = 1 := rfl
@[simp, to_additive] lemma mk_mul_mk (x y : M) (hx : x ∈ S) (hy : y ∈ S) :
(⟨x, hx⟩ : S) * ⟨y, hy⟩ = ⟨x * y, S.mul_mem hx hy⟩ := rfl
@[to_additive] lemma mul_def (x y : S) : x * y = ⟨x * y, S.mul_mem x.2 y.2⟩ := rfl
@[to_additive] lemma one_def : (1 : S) = ⟨1, S.one_mem⟩ := rfl
/-- A submonoid of a unital magma inherits a unital magma structure. -/
@[to_additive "An `add_submonoid` of an unital additive magma inherits an unital additive magma
structure."]
instance to_mul_one_class {M : Type*} [mul_one_class M] (S : submonoid M) : mul_one_class S :=
subtype.coe_injective.mul_one_class coe rfl (λ _ _, rfl)
@[to_additive] protected lemma pow_mem {M : Type*} [monoid M] (S : submonoid M) {x : M}
(hx : x ∈ S) (n : ℕ) : x ^ n ∈ S :=
pow_mem hx n
@[simp, norm_cast, to_additive] theorem coe_pow {M : Type*} [monoid M] {S : submonoid M}
(x : S) (n : ℕ) : ↑(x ^ n) = (x ^ n : M) :=
rfl
/-- A submonoid of a monoid inherits a monoid structure. -/
@[to_additive "An `add_submonoid` of an `add_monoid` inherits an `add_monoid`
structure."]
instance to_monoid {M : Type*} [monoid M] (S : submonoid M) : monoid S :=
subtype.coe_injective.monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
/-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/
@[to_additive "An `add_submonoid` of an `add_comm_monoid` is
an `add_comm_monoid`."]
instance to_comm_monoid {M} [comm_monoid M] (S : submonoid M) : comm_monoid S :=
subtype.coe_injective.comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
/-- A submonoid of an `ordered_comm_monoid` is an `ordered_comm_monoid`. -/
@[to_additive "An `add_submonoid` of an `ordered_add_comm_monoid` is
an `ordered_add_comm_monoid`."]
instance to_ordered_comm_monoid {M} [ordered_comm_monoid M] (S : submonoid M) :
ordered_comm_monoid S :=
subtype.coe_injective.ordered_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
/-- A submonoid of a `linear_ordered_comm_monoid` is a `linear_ordered_comm_monoid`. -/
@[to_additive "An `add_submonoid` of a `linear_ordered_add_comm_monoid` is
a `linear_ordered_add_comm_monoid`."]
instance to_linear_ordered_comm_monoid {M} [linear_ordered_comm_monoid M] (S : submonoid M) :
linear_ordered_comm_monoid S :=
subtype.coe_injective.linear_ordered_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
(λ _ _, rfl)
/-- A submonoid of an `ordered_cancel_comm_monoid` is an `ordered_cancel_comm_monoid`. -/
@[to_additive "An `add_submonoid` of an `ordered_cancel_add_comm_monoid` is
an `ordered_cancel_add_comm_monoid`."]
instance to_ordered_cancel_comm_monoid {M} [ordered_cancel_comm_monoid M] (S : submonoid M) :
ordered_cancel_comm_monoid S :=
subtype.coe_injective.ordered_cancel_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
/-- A submonoid of a `linear_ordered_cancel_comm_monoid` is a `linear_ordered_cancel_comm_monoid`.
-/
@[to_additive "An `add_submonoid` of a `linear_ordered_cancel_add_comm_monoid` is
a `linear_ordered_cancel_add_comm_monoid`."]
instance to_linear_ordered_cancel_comm_monoid {M} [linear_ordered_cancel_comm_monoid M]
(S : submonoid M) : linear_ordered_cancel_comm_monoid S :=
subtype.coe_injective.linear_ordered_cancel_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
(λ _ _, rfl) (λ _ _, rfl)
/-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/
@[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."]
def subtype : S →* M := ⟨coe, rfl, λ _ _, rfl⟩
@[simp, to_additive] theorem coe_subtype : ⇑S.subtype = coe := rfl
/-- The top submonoid is isomorphic to the monoid. -/
@[to_additive "The top additive submonoid is isomorphic to the additive monoid.", simps]
def top_equiv : (⊤ : submonoid M) ≃* M :=
{ to_fun := λ x, x,
inv_fun := λ x, ⟨x, mem_top x⟩,
left_inv := λ x, x.eta _,
right_inv := λ _, rfl,
map_mul' := λ _ _, rfl }
@[simp, to_additive] lemma top_equiv_to_monoid_hom :
(top_equiv : _ ≃* M).to_monoid_hom = (⊤ : submonoid M).subtype :=
rfl
/-- A subgroup is isomorphic to its image under an injective function. If you have an isomorphism,
use `mul_equiv.submonoid_map` for better definitional equalities. -/
@[to_additive "An additive subgroup is isomorphic to its image under an injective function. If you
have an isomorphism, use `add_equiv.add_submonoid_map` for better definitional equalities."]
noncomputable def equiv_map_of_injective
(f : M →* N) (hf : function.injective f) : S ≃* S.map f :=
{ map_mul' := λ _ _, subtype.ext (f.map_mul _ _), ..equiv.set.image f S hf }
@[simp, to_additive] lemma coe_equiv_map_of_injective_apply
(f : M →* N) (hf : function.injective f) (x : S) :
(equiv_map_of_injective S f hf x : N) = f x := rfl
@[simp, to_additive]
lemma closure_closure_coe_preimage {s : set M} : closure ((coe : closure s → M) ⁻¹' s) = ⊤ :=
eq_top_iff.2 $ λ x, subtype.rec_on x $ λ x hx _, begin
refine closure_induction' _ (λ g hg, _) _ (λ g₁ g₂ hg₁ hg₂, _) hx,
{ exact subset_closure hg },
{ exact submonoid.one_mem _ },
{ exact submonoid.mul_mem _ },
end
/-- Given `submonoid`s `s`, `t` of monoids `M`, `N` respectively, `s × t` as a submonoid
of `M × N`. -/
@[to_additive prod "Given `add_submonoid`s `s`, `t` of `add_monoid`s `A`, `B` respectively, `s × t`
as an `add_submonoid` of `A × B`."]
def prod (s : submonoid M) (t : submonoid N) : submonoid (M × N) :=
{ carrier := s ×ˢ t,
one_mem' := ⟨s.one_mem, t.one_mem⟩,
mul_mem' := λ p q hp hq, ⟨s.mul_mem hp.1 hq.1, t.mul_mem hp.2 hq.2⟩ }
@[to_additive coe_prod]
lemma coe_prod (s : submonoid M) (t : submonoid N) : (s.prod t : set (M × N)) = s ×ˢ t := rfl
@[to_additive mem_prod]
lemma mem_prod {s : submonoid M} {t : submonoid N} {p : M × N} :
p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl
@[to_additive prod_mono]
lemma prod_mono {s₁ s₂ : submonoid M} {t₁ t₂ : submonoid N} (hs : s₁ ≤ s₂) (ht : t₁ ≤ t₂) :
s₁.prod t₁ ≤ s₂.prod t₂ :=
set.prod_mono hs ht
@[to_additive prod_top]
lemma prod_top (s : submonoid M) :
s.prod (⊤ : submonoid N) = s.comap (monoid_hom.fst M N) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst]
@[to_additive top_prod]
lemma top_prod (s : submonoid N) :
(⊤ : submonoid M).prod s = s.comap (monoid_hom.snd M N) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd]
@[simp, to_additive top_prod_top]
lemma top_prod_top : (⊤ : submonoid M).prod (⊤ : submonoid N) = ⊤ :=
(top_prod _).trans $ comap_top _
@[to_additive] lemma bot_prod_bot : (⊥ : submonoid M).prod (⊥ : submonoid N) = ⊥ :=
set_like.coe_injective $ by simp [coe_prod, prod.one_eq_mk]
/-- The product of submonoids is isomorphic to their product as monoids. -/
@[to_additive prod_equiv "The product of additive submonoids is isomorphic to their product
as additive monoids"]
def prod_equiv (s : submonoid M) (t : submonoid N) : s.prod t ≃* s × t :=
{ map_mul' := λ x y, rfl, .. equiv.set.prod ↑s ↑t }
open monoid_hom
@[to_additive]
lemma map_inl (s : submonoid M) : s.map (inl M N) = s.prod ⊥ :=
ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨hx, set.mem_singleton 1⟩,
λ ⟨hps, hp1⟩, ⟨p.1, hps, prod.ext rfl $ (set.eq_of_mem_singleton hp1).symm⟩⟩
@[to_additive]
lemma map_inr (s : submonoid N) : s.map (inr M N) = prod ⊥ s :=
ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨set.mem_singleton 1, hx⟩,
λ ⟨hp1, hps⟩, ⟨p.2, hps, prod.ext (set.eq_of_mem_singleton hp1).symm rfl⟩⟩
@[simp, to_additive prod_bot_sup_bot_prod]
lemma prod_bot_sup_bot_prod (s : submonoid M) (t : submonoid N) :
(s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t :=
le_antisymm (sup_le (prod_mono (le_refl s) bot_le) (prod_mono bot_le (le_refl t))) $
assume p hp, prod.fst_mul_snd p ▸ mul_mem
((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set.mem_singleton 1⟩)
((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set.mem_singleton 1, hp.2⟩)
@[to_additive]
lemma mem_map_equiv {f : M ≃* N} {K : submonoid M} {x : N} :
x ∈ K.map f.to_monoid_hom ↔ f.symm x ∈ K :=
@set.mem_image_equiv _ _ ↑K f.to_equiv x
@[to_additive]
lemma map_equiv_eq_comap_symm (f : M ≃* N) (K : submonoid M) :
K.map f.to_monoid_hom = K.comap f.symm.to_monoid_hom :=
set_like.coe_injective (f.to_equiv.image_eq_preimage K)
@[to_additive]
lemma comap_equiv_eq_map_symm (f : N ≃* M) (K : submonoid M) :
K.comap f.to_monoid_hom = K.map f.symm.to_monoid_hom :=
(map_equiv_eq_comap_symm f.symm K).symm
@[simp, to_additive]
lemma map_equiv_top (f : M ≃* N) : (⊤ : submonoid M).map f.to_monoid_hom = ⊤ :=
set_like.coe_injective $ set.image_univ.trans f.surjective.range_eq
@[to_additive le_prod_iff]
lemma le_prod_iff {s : submonoid M} {t : submonoid N} {u : submonoid (M × N)} :
u ≤ s.prod t ↔ u.map (fst M N) ≤ s ∧ u.map (snd M N) ≤ t :=
begin
split,
{ intros h,
split,
{ rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).1 },
{ rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).2 }, },
{ rintros ⟨hH, hK⟩ ⟨x1, x2⟩ h, exact ⟨hH ⟨_ , h, rfl⟩, hK ⟨ _, h, rfl⟩⟩, }
end
@[to_additive prod_le_iff]
lemma prod_le_iff {s : submonoid M} {t : submonoid N} {u : submonoid (M × N)} :
s.prod t ≤ u ↔ s.map (inl M N) ≤ u ∧ t.map (inr M N) ≤ u :=
begin
split,
{ intros h,
split,
{ rintros _ ⟨x, hx, rfl⟩, apply h, exact ⟨hx, (submonoid.one_mem _)⟩, },
{ rintros _ ⟨x, hx, rfl⟩, apply h, exact ⟨submonoid.one_mem _, hx⟩, }, },
{ rintros ⟨hH, hK⟩ ⟨x1, x2⟩ ⟨h1, h2⟩,
have h1' : inl M N x1 ∈ u, { apply hH, simpa using h1, },
have h2' : inr M N x2 ∈ u, { apply hK, simpa using h2, },
simpa using submonoid.mul_mem _ h1' h2', }
end
end submonoid
namespace monoid_hom
variables {F : Type*} [mc : monoid_hom_class F M N]
open submonoid
/-- For many categories (monoids, modules, rings, ...) the set-theoretic image of a morphism `f` is
a subobject of the codomain. When this is the case, it is useful to define the range of a morphism
in such a way that the underlying carrier set of the range subobject is definitionally
`set.range f`. In particular this means that the types `↥(set.range f)` and `↥f.range` are
interchangeable without proof obligations.
A convenient candidate definition for range which is mathematically correct is `map ⊤ f`, just as
`set.range` could have been defined as `f '' set.univ`. However, this lacks the desired definitional
convenience, in that it both does not match `set.range`, and that it introduces a redudant `x ∈ ⊤`
term which clutters proofs. In such a case one may resort to the `copy`
pattern. A `copy` function converts the definitional problem for the carrier set of a subobject
into a one-off propositional proof obligation which one discharges while writing the definition of
the definitionally convenient range (the parameter `hs` in the example below).
A good example is the case of a morphism of monoids. A convenient definition for
`monoid_hom.mrange` would be `(⊤ : submonoid M).map f`. However since this lacks the required
definitional convenience, we first define `submonoid.copy` as follows:
```lean
protected def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M :=
{ carrier := s,
one_mem' := hs.symm ▸ S.one_mem',
mul_mem' := hs.symm ▸ S.mul_mem' }
```
and then finally define:
```lean
def mrange (f : M →* N) : submonoid N :=
((⊤ : submonoid M).map f).copy (set.range f) set.image_univ.symm
```
-/
library_note "range copy pattern"
include mc
/-- The range of a monoid homomorphism is a submonoid. See Note [range copy pattern]. -/
@[to_additive "The range of an `add_monoid_hom` is an `add_submonoid`."]
def mrange (f : F) : submonoid N :=
((⊤ : submonoid M).map f).copy (set.range f) set.image_univ.symm
@[simp, to_additive]
lemma coe_mrange (f : F) :
(mrange f : set N) = set.range f :=
rfl
@[simp, to_additive] lemma mem_mrange {f : F} {y : N} :
y ∈ mrange f ↔ ∃ x, f x = y :=
iff.rfl
@[to_additive] lemma mrange_eq_map (f : F) : mrange f = (⊤ : submonoid M).map f :=
submonoid.copy_eq _
omit mc
@[to_additive]
lemma map_mrange (g : N →* P) (f : M →* N) : f.mrange.map g = (g.comp f).mrange :=
by simpa only [mrange_eq_map] using (⊤ : submonoid M).map_map g f
include mc
@[to_additive]
lemma mrange_top_iff_surjective {f : F} :
mrange f = (⊤ : submonoid N) ↔ function.surjective f :=
set_like.ext'_iff.trans $ iff.trans (by rw [coe_mrange, coe_top]) set.range_iff_surjective
/-- The range of a surjective monoid hom is the whole of the codomain. -/
@[to_additive "The range of a surjective `add_monoid` hom is the whole of the codomain."]
lemma mrange_top_of_surjective (f : F) (hf : function.surjective f) :
mrange f = (⊤ : submonoid N) :=
mrange_top_iff_surjective.2 hf
@[to_additive]
lemma mclosure_preimage_le (f : F) (s : set N) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx
/-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated
by the image of the set. -/
@[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals
the `add_submonoid` generated by the image of the set."]
lemma map_mclosure (f : F) (s : set M) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _)
(mclosure_preimage_le _ _))
(closure_le.2 $ set.image_subset _ subset_closure)
omit mc
/-- Restriction of a monoid hom to a submonoid of the domain. -/
@[to_additive "Restriction of an add_monoid hom to an `add_submonoid` of the domain."]
def restrict {N S : Type*} [mul_one_class N] [set_like S M] [submonoid_class S M]
(f : M →* N) (s : S) : s →* N :=
f.comp (submonoid_class.subtype _)
@[simp, to_additive]
lemma restrict_apply {N S : Type*} [mul_one_class N] [set_like S M] [submonoid_class S M]
(f : M →* N) (s : S) (x : s) : f.restrict s x = f x :=
rfl
@[simp, to_additive] lemma restrict_mrange (f : M →* N) : (f.restrict S).mrange = S.map f :=
by simp_rw [set_like.ext_iff, mem_mrange, mem_map, restrict_apply, set_like.exists, subtype.coe_mk,
iff_self, forall_const]
/-- Restriction of a monoid hom to a submonoid of the codomain. -/
@[to_additive "Restriction of an `add_monoid` hom to an `add_submonoid` of the codomain.",
simps apply]
def cod_restrict {S} [set_like S N] [submonoid_class S N] (f : M →* N) (s : S)
(h : ∀ x, f x ∈ s) : M →* s :=
{ to_fun := λ n, ⟨f n, h n⟩,
map_one' := subtype.eq f.map_one,
map_mul' := λ x y, subtype.eq (f.map_mul x y) }
/-- Restriction of a monoid hom to its range interpreted as a submonoid. -/
@[to_additive "Restriction of an `add_monoid` hom to its range interpreted as a submonoid."]
def mrange_restrict {N} [mul_one_class N] (f : M →* N) : M →* f.mrange :=
f.cod_restrict f.mrange $ λ x, ⟨x, rfl⟩
@[simp, to_additive]
lemma coe_mrange_restrict {N} [mul_one_class N] (f : M →* N) (x : M) :
(f.mrange_restrict x : N) = f x :=
rfl
@[to_additive]
lemma mrange_restrict_surjective (f : M →* N) : function.surjective f.mrange_restrict :=
λ ⟨_, ⟨x, rfl⟩⟩, ⟨x, rfl⟩
include mc
/-- The multiplicative kernel of a monoid homomorphism is the submonoid of elements `x : G` such
that `f x = 1` -/
@[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_submonoid` of
elements such that `f x = 0`"]
def mker (f : F) : submonoid M := (⊥ : submonoid N).comap f
@[to_additive]
lemma mem_mker (f : F) {x : M} : x ∈ mker f ↔ f x = 1 := iff.rfl
@[to_additive]
lemma coe_mker (f : F) : (mker f : set M) = (f : M → N) ⁻¹' {1} := rfl
@[to_additive]
instance decidable_mem_mker [decidable_eq N] (f : F) :
decidable_pred (∈ mker f) :=
λ x, decidable_of_iff (f x = 1) (mem_mker f)
omit mc
@[to_additive]
lemma comap_mker (g : N →* P) (f : M →* N) : g.mker.comap f = (g.comp f).mker := rfl
include mc
@[simp, to_additive] lemma comap_bot' (f : F) :
(⊥ : submonoid N).comap f = mker f := rfl
omit mc
@[simp, to_additive]
lemma restrict_mker (f : M →* N) : (f.restrict S).mker = f.mker.comap S.subtype :=
rfl
@[to_additive] lemma range_restrict_mker (f : M →* N) : mker (mrange_restrict f) = mker f :=
begin
ext,
change (⟨f x, _⟩ : mrange f) = ⟨1, _⟩ ↔ f x = 1,
simp only [],
end
@[simp, to_additive]
lemma mker_one : (1 : M →* N).mker = ⊤ :=
by { ext, simp [mem_mker] }
@[to_additive]
lemma prod_map_comap_prod' {M' : Type*} {N' : Type*} [mul_one_class M'] [mul_one_class N']
(f : M →* N) (g : M' →* N') (S : submonoid N) (S' : submonoid N') :
(S.prod S').comap (prod_map f g) = (S.comap f).prod (S'.comap g) :=
set_like.coe_injective $ set.preimage_prod_map_prod f g _ _
@[to_additive]
lemma mker_prod_map {M' : Type*} {N' : Type*} [mul_one_class M'] [mul_one_class N'] (f : M →* N)
(g : M' →* N') : (prod_map f g).mker = f.mker.prod g.mker :=
by rw [←comap_bot', ←comap_bot', ←comap_bot', ←prod_map_comap_prod', bot_prod_bot]
@[simp, to_additive]
lemma mker_inl : (inl M N).mker = ⊥ := by { ext x, simp [mem_mker] }
@[simp, to_additive]
lemma mker_inr : (inr M N).mker = ⊥ := by { ext x, simp [mem_mker] }
/-- The `monoid_hom` from the preimage of a submonoid to itself. -/
@[to_additive "the `add_monoid_hom` from the preimage of an additive submonoid to itself.", simps]
def submonoid_comap (f : M →* N) (N' : submonoid N) :
N'.comap f →* N' :=
{ to_fun := λ x, ⟨f x, x.prop⟩,
map_one' := subtype.eq f.map_one,
map_mul' := λ x y, subtype.eq (f.map_mul x y) }
/-- The `monoid_hom` from a submonoid to its image.
See `mul_equiv.submonoid_map` for a variant for `mul_equiv`s. -/
@[to_additive "the `add_monoid_hom` from an additive submonoid to its image. See
`add_equiv.add_submonoid_map` for a variant for `add_equiv`s.", simps]
def submonoid_map (f : M →* N) (M' : submonoid M) :
M' →* M'.map f :=
{ to_fun := λ x, ⟨f x, ⟨x, x.prop, rfl⟩⟩,
map_one' := subtype.eq $ f.map_one,
map_mul' := λ x y, subtype.eq $ f.map_mul x y }
@[to_additive]
lemma submonoid_map_surjective (f : M →* N) (M' : submonoid M) :
function.surjective (f.submonoid_map M') :=
by { rintro ⟨_, x, hx, rfl⟩, exact ⟨⟨x, hx⟩, rfl⟩ }
end monoid_hom
namespace submonoid
open monoid_hom
@[to_additive]
lemma mrange_inl : (inl M N).mrange = prod ⊤ ⊥ :=
by simpa only [mrange_eq_map] using map_inl ⊤
@[to_additive]
lemma mrange_inr : (inr M N).mrange = prod ⊥ ⊤ :=
by simpa only [mrange_eq_map] using map_inr ⊤
@[to_additive]
lemma mrange_inl' : (inl M N).mrange = comap (snd M N) ⊥ := mrange_inl.trans (top_prod _)
@[to_additive]
lemma mrange_inr' : (inr M N).mrange = comap (fst M N) ⊥ := mrange_inr.trans (prod_top _)
@[simp, to_additive]
lemma mrange_fst : (fst M N).mrange = ⊤ :=
mrange_top_of_surjective (fst M N) $ @prod.fst_surjective _ _ ⟨1⟩
@[simp, to_additive]
lemma mrange_snd : (snd M N).mrange = ⊤ :=
mrange_top_of_surjective (snd M N) $ @prod.snd_surjective _ _ ⟨1⟩
@[to_additive]
lemma prod_eq_bot_iff {s : submonoid M} {t : submonoid N} :
s.prod t = ⊥ ↔ s = ⊥ ∧ t = ⊥ :=
by simp only [eq_bot_iff, prod_le_iff, (gc_map_comap _).le_iff_le, comap_bot', mker_inl, mker_inr]
@[to_additive]
lemma prod_eq_top_iff {s : submonoid M} {t : submonoid N} :
s.prod t = ⊤ ↔ s = ⊤ ∧ t = ⊤ :=
by simp only [eq_top_iff, le_prod_iff, ← (gc_map_comap _).le_iff_le, ← mrange_eq_map,
mrange_fst, mrange_snd]
@[simp, to_additive]
lemma mrange_inl_sup_mrange_inr : (inl M N).mrange ⊔ (inr M N).mrange = ⊤ :=
by simp only [mrange_inl, mrange_inr, prod_bot_sup_bot_prod, top_prod_top]
/-- The monoid hom associated to an inclusion of submonoids. -/
@[to_additive "The `add_monoid` hom associated to an inclusion of submonoids."]
def inclusion {S T : submonoid M} (h : S ≤ T) : S →* T :=
S.subtype.cod_restrict _ (λ x, h x.2)
@[simp, to_additive]
lemma range_subtype (s : submonoid M) : s.subtype.mrange = s :=
set_like.coe_injective $ (coe_mrange _).trans $ subtype.range_coe
@[to_additive] lemma eq_top_iff' : S = ⊤ ↔ ∀ x : M, x ∈ S :=
eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩
@[to_additive] lemma eq_bot_iff_forall : S = ⊥ ↔ ∀ x ∈ S, x = (1 : M) :=
set_like.ext_iff.trans $ by simp [iff_def, S.one_mem] { contextual := tt }
@[to_additive] lemma nontrivial_iff_exists_ne_one (S : submonoid M) :
nontrivial S ↔ ∃ x ∈ S, x ≠ (1:M) :=
calc nontrivial S ↔ ∃ x : S, x ≠ 1 : nontrivial_iff_exists_ne 1
... ↔ ∃ x (hx : x ∈ S), (⟨x, hx⟩ : S) ≠ ⟨1, S.one_mem⟩ : subtype.exists
... ↔ ∃ x ∈ S, x ≠ (1 : M) : by simp only [ne.def]
/-- A submonoid is either the trivial submonoid or nontrivial. -/
@[to_additive "An additive submonoid is either the trivial additive submonoid or nontrivial."]
lemma bot_or_nontrivial (S : submonoid M) : S = ⊥ ∨ nontrivial S :=
by simp only [eq_bot_iff_forall, nontrivial_iff_exists_ne_one, ← not_forall, classical.em]
/-- A submonoid is either the trivial submonoid or contains a nonzero element. -/
@[to_additive "An additive submonoid is either the trivial additive submonoid or contains a nonzero
element."]
lemma bot_or_exists_ne_one (S : submonoid M) : S = ⊥ ∨ ∃ x ∈ S, x ≠ (1:M) :=
S.bot_or_nontrivial.imp_right S.nontrivial_iff_exists_ne_one.mp
end submonoid
namespace mul_equiv
variables {S} {T : submonoid M}
/-- Makes the identity isomorphism from a proof that two submonoids of a multiplicative
monoid are equal. -/
@[to_additive "Makes the identity additive isomorphism from a proof two
submonoids of an additive monoid are equal."]
def submonoid_congr (h : S = T) : S ≃* T :=
{ map_mul' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h }
-- this name is primed so that the version to `f.range` instead of `f.mrange` can be unprimed.
/-- A monoid homomorphism `f : M →* N` with a left-inverse `g : N → M` defines a multiplicative
equivalence between `M` and `f.mrange`.
This is a bidirectional version of `monoid_hom.mrange_restrict`. -/
@[to_additive /-"
An additive monoid homomorphism `f : M →+ N` with a left-inverse `g : N → M` defines an additive
equivalence between `M` and `f.mrange`.
This is a bidirectional version of `add_monoid_hom.mrange_restrict`. "-/, simps {simp_rhs := tt}]
def of_left_inverse' (f : M →* N) {g : N → M} (h : function.left_inverse g f) : M ≃* f.mrange :=
{ to_fun := f.mrange_restrict,
inv_fun := g ∘ f.mrange.subtype,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := monoid_hom.mem_mrange.mp x.prop in
show f (g x) = x, by rw [←hx', h x'],
.. f.mrange_restrict }
/-- A `mul_equiv` `φ` between two monoids `M` and `N` induces a `mul_equiv` between
a submonoid `S ≤ M` and the submonoid `φ(S) ≤ N`.
See `monoid_hom.submonoid_map` for a variant for `monoid_hom`s. -/
@[to_additive "An `add_equiv` `φ` between two additive monoids `M` and `N` induces an `add_equiv`
between a submonoid `S ≤ M` and the submonoid `φ(S) ≤ N`. See `add_monoid_hom.add_submonoid_map`
for a variant for `add_monoid_hom`s."]
def submonoid_map (e : M ≃* N) (S : submonoid M) : S ≃* S.map e.to_monoid_hom :=
{ map_mul' := λ _ _, subtype.ext (map_mul e _ _), ..(e : M ≃ N).image S }
@[simp, to_additive]
lemma coe_submonoid_map_apply (e : M ≃* N) (S : submonoid M) (g : S) :
((submonoid_map e S g : S.map (e : M →* N)) : N) = e g := rfl
@[simp, to_additive add_equiv.add_submonoid_map_symm_apply]
lemma submonoid_map_symm_apply (e : M ≃* N) (S : submonoid M) (g : S.map (e : M →* N)) :
(e.submonoid_map S).symm g = ⟨e.symm g, set_like.mem_coe.1 $ set.mem_image_equiv.1 g.2⟩ := rfl
end mul_equiv
@[simp, to_additive]
lemma submonoid.equiv_map_of_injective_coe_mul_equiv (e : M ≃* N) :
S.equiv_map_of_injective (e : M →* N) (equiv_like.injective e) = e.submonoid_map S :=
by { ext, refl }
section actions
/-! ### Actions by `submonoid`s
These instances tranfer the action by an element `m : M` of a monoid `M` written as `m • a` onto the
action by an element `s : S` of a submonoid `S : submonoid M` such that `s • a = (s : M) • a`.
These instances work particularly well in conjunction with `monoid.to_mul_action`, enabling
`s • m` as an alias for `↑s * m`.
-/
namespace submonoid
variables {M' : Type*} {α β : Type*}
section mul_one_class
variables [mul_one_class M']
@[to_additive]
instance [has_smul M' α] (S : submonoid M') : has_smul S α := has_smul.comp _ S.subtype
@[to_additive]
instance smul_comm_class_left
[has_smul M' β] [has_smul α β] [smul_comm_class M' α β] (S : submonoid M') :
smul_comm_class S α β :=
⟨λ a, (smul_comm (a : M') : _)⟩
@[to_additive]
instance smul_comm_class_right
[has_smul α β] [has_smul M' β] [smul_comm_class α M' β] (S : submonoid M') :
smul_comm_class α S β :=
⟨λ a s, (smul_comm a (s : M') : _)⟩
/-- Note that this provides `is_scalar_tower S M' M'` which is needed by `smul_mul_assoc`. -/
instance
[has_smul α β] [has_smul M' α] [has_smul M' β] [is_scalar_tower M' α β] (S : submonoid M') :
is_scalar_tower S α β :=
⟨λ a, (smul_assoc (a : M') : _)⟩
@[to_additive]
lemma smul_def [has_smul M' α] {S : submonoid M'} (g : S) (m : α) : g • m = (g : M') • m := rfl
instance [has_smul M' α] [has_faithful_smul M' α] (S : submonoid M') :
has_faithful_smul S α :=
⟨λ x y h, subtype.ext $ eq_of_smul_eq_smul h⟩
end mul_one_class
variables [monoid M']
/-- The action by a submonoid is the action by the underlying monoid. -/
@[to_additive /-"The additive action by an add_submonoid is the action by the underlying
add_monoid. "-/]
instance [mul_action M' α] (S : submonoid M') : mul_action S α := mul_action.comp_hom _ S.subtype
/-- The action by a submonoid is the action by the underlying monoid. -/
instance [add_monoid α] [distrib_mul_action M' α] (S : submonoid M') : distrib_mul_action S α :=
distrib_mul_action.comp_hom _ S.subtype
/-- The action by a submonoid is the action by the underlying monoid. -/
instance [monoid α] [mul_distrib_mul_action M' α] (S : submonoid M') : mul_distrib_mul_action S α :=
mul_distrib_mul_action.comp_hom _ S.subtype
example {S : submonoid M'} : is_scalar_tower S M' M' := by apply_instance
end submonoid
end actions
|
9e71960880d4da684dd81efeb65a19a13a2427ac | b2e508d02500f1512e1618150413e6be69d9db10 | /src/category_theory/adjunction/basic.lean | 5ee0026b6d658e65b29497b227e6b1134d41d865 | [
"Apache-2.0"
] | permissive | callum-sutton/mathlib | c3788f90216e9cd43eeffcb9f8c9f959b3b01771 | afd623825a3ac6bfbcc675a9b023edad3f069e89 | refs/heads/master | 1,591,371,888,053 | 1,560,990,690,000 | 1,560,990,690,000 | 192,476,045 | 0 | 0 | Apache-2.0 | 1,568,941,843,000 | 1,560,837,965,000 | Lean | UTF-8 | Lean | false | false | 9,588 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Johan Commelin
-/
import category_theory.equivalence
import data.equiv.basic
namespace category_theory
open category
universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation
local attribute [elab_simple] whisker_left whisker_right
variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D]
include 𝒞 𝒟
/--
`F ⊣ G` represents the data of an adjunction between two functors
`F : C ⥤ D` and `G : D ⥤ C`. `F` is the left adjoint and `G` is the right adjoint.
-/
structure adjunction (F : C ⥤ D) (G : D ⥤ C) :=
(hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y))
(unit : functor.id C ⟶ F.comp G)
(counit : G.comp F ⟶ functor.id D)
(hom_equiv_unit' : Π {X Y f}, (hom_equiv X Y) f = (unit : _ ⟶ _).app X ≫ G.map f . obviously)
(hom_equiv_counit' : Π {X Y g}, (hom_equiv X Y).symm g = F.map g ≫ counit.app Y . obviously)
infix ` ⊣ `:15 := adjunction
namespace adjunction
restate_axiom hom_equiv_unit'
restate_axiom hom_equiv_counit'
attribute [simp, priority 1] hom_equiv_unit hom_equiv_counit
section
variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X' X : C} {Y Y' : D}
@[simp, priority 1] lemma hom_equiv_naturality_left_symm (f : X' ⟶ X) (g : X ⟶ G.obj Y) :
(adj.hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (adj.hom_equiv X Y).symm g :=
by rw [hom_equiv_counit, F.map_comp, assoc, adj.hom_equiv_counit.symm]
@[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) :
(adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g :=
by rw [← equiv.eq_symm_apply]; simp [-hom_equiv_unit]
@[simp, priority 1] lemma hom_equiv_naturality_right (f : F.obj X ⟶ Y) (g : Y ⟶ Y') :
(adj.hom_equiv X Y') (f ≫ g) = (adj.hom_equiv X Y) f ≫ G.map g :=
by rw [hom_equiv_unit, G.map_comp, ← assoc, ←hom_equiv_unit]
@[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') :
(adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g :=
by rw [equiv.symm_apply_eq]; simp [-hom_equiv_counit]
@[simp] lemma left_triangle :
(whisker_right adj.unit F) ≫ (whisker_left F adj.counit) = nat_trans.id _ :=
begin
ext1 X, dsimp,
erw [← adj.hom_equiv_counit, equiv.symm_apply_eq, adj.hom_equiv_unit],
simp
end
@[simp] lemma right_triangle :
(whisker_left G adj.unit) ≫ (whisker_right adj.counit G) = nat_trans.id _ :=
begin
ext1 Y, dsimp,
erw [← adj.hom_equiv_unit, ← equiv.eq_symm_apply, adj.hom_equiv_counit],
simp
end
@[simp] lemma left_triangle_components :
F.map (adj.unit.app X) ≫ adj.counit.app (F.obj X) = 𝟙 _ :=
congr_arg (λ (t : nat_trans _ (functor.id C ⋙ F)), t.app X) adj.left_triangle
@[simp] lemma right_triangle_components {Y : D} :
adj.unit.app (G.obj Y) ≫ G.map (adj.counit.app Y) = 𝟙 _ :=
congr_arg (λ (t : nat_trans _ (G ⋙ functor.id C)), t.app Y) adj.right_triangle
end
structure core_hom_equiv (F : C ⥤ D) (G : D ⥤ C) :=
(hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y))
(hom_equiv_naturality_left_symm' : Π {X' X Y} (f : X' ⟶ X) (g : X ⟶ G.obj Y),
(hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (hom_equiv X Y).symm g . obviously)
(hom_equiv_naturality_right' : Π {X Y Y'} (f : F.obj X ⟶ Y) (g : Y ⟶ Y'),
(hom_equiv X Y') (f ≫ g) = (hom_equiv X Y) f ≫ G.map g . obviously)
namespace core_hom_equiv
restate_axiom hom_equiv_naturality_left_symm'
restate_axiom hom_equiv_naturality_right'
attribute [simp, priority 1] hom_equiv_naturality_left_symm hom_equiv_naturality_right
variables {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) {X' X : C} {Y Y' : D}
@[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) :
(adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g :=
by rw [← equiv.eq_symm_apply]; simp
@[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') :
(adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g :=
by rw [equiv.symm_apply_eq]; simp
end core_hom_equiv
structure core_unit_counit (F : C ⥤ D) (G : D ⥤ C) :=
(unit : functor.id C ⟶ F.comp G)
(counit : G.comp F ⟶ functor.id D)
(left_triangle' : whisker_right unit F ≫ whisker_left F counit = nat_trans.id _ . obviously)
(right_triangle' : whisker_left G unit ≫ whisker_right counit G = nat_trans.id _ . obviously)
namespace core_unit_counit
restate_axiom left_triangle'
restate_axiom right_triangle'
attribute [simp] left_triangle right_triangle
end core_unit_counit
variables {F : C ⥤ D} {G : D ⥤ C}
def mk_of_hom_equiv (adj : core_hom_equiv F G) : F ⊣ G :=
{ unit :=
{ app := λ X, (adj.hom_equiv X (F.obj X)) (𝟙 (F.obj X)),
naturality' :=
begin
intros,
erw [← adj.hom_equiv_naturality_left, ← adj.hom_equiv_naturality_right],
dsimp, simp
end },
counit :=
{ app := λ Y, (adj.hom_equiv _ _).inv_fun (𝟙 (G.obj Y)),
naturality' :=
begin
intros,
erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm],
dsimp, simp
end },
hom_equiv_unit' := λ X Y f, by erw [← adj.hom_equiv_naturality_right]; simp,
hom_equiv_counit' := λ X Y f, by erw [← adj.hom_equiv_naturality_left_symm]; simp,
.. adj }
def mk_of_unit_counit (adj : core_unit_counit F G) : F ⊣ G :=
{ hom_equiv := λ X Y,
{ to_fun := λ f, adj.unit.app X ≫ G.map f,
inv_fun := λ g, F.map g ≫ adj.counit.app Y,
left_inv := λ f, begin
change F.map (_ ≫ _) ≫ _ = _,
rw [F.map_comp, assoc, ←functor.comp_map, adj.counit.naturality, ←assoc],
convert id_comp _ f,
exact congr_arg (λ t : nat_trans _ _, t.app _) adj.left_triangle
end,
right_inv := λ g, begin
change _ ≫ G.map (_ ≫ _) = _,
rw [G.map_comp, ←assoc, ←functor.comp_map, ←adj.unit.naturality, assoc],
convert comp_id _ g,
exact congr_arg (λ t : nat_trans _ _, t.app _) adj.right_triangle
end },
.. adj }
section
omit 𝒟
def id : functor.id C ⊣ functor.id C :=
{ hom_equiv := λ X Y, equiv.refl _,
unit := 𝟙 _,
counit := 𝟙 _ }
end
section
variables {E : Type u₃} [ℰ : category.{v₃} E] (H : D ⥤ E) (I : E ⥤ D)
def comp (adj₁ : F ⊣ G) (adj₂ : H ⊣ I) : F ⋙ H ⊣ I ⋙ G :=
{ hom_equiv := λ X Z, equiv.trans (adj₂.hom_equiv _ _) (adj₁.hom_equiv _ _),
unit := adj₁.unit ≫
(whisker_left F $ whisker_right adj₂.unit G) ≫ (functor.associator _ _ _).inv,
counit := (functor.associator _ _ _).hom ≫
(whisker_left I $ whisker_right adj₁.counit H) ≫ adj₂.counit }
end
structure is_left_adjoint (left : C ⥤ D) :=
(right : D ⥤ C)
(adj : left ⊣ right)
structure is_right_adjoint (right : D ⥤ C) :=
(left : C ⥤ D)
(adj : left ⊣ right)
section construct_left
-- Construction of a left adjoint. In order to construct a left
-- adjoint to a functor G : D → C, it suffices to give the object part
-- of a functor F : C → D together with isomorphisms Hom(FX, Y) ≃
-- Hom(X, GY) natural in Y. The action of F on morphisms can be
-- constructed from this data.
variables {F_obj : C → D} {G}
variables (e : Π X Y, (F_obj X ⟶ Y) ≃ (X ⟶ G.obj Y))
variables (he : Π X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g)
include he
private lemma he' {X Y Y'} (f g) : (e X Y').symm (f ≫ G.map g) = (e X Y).symm f ≫ g :=
by intros; rw [equiv.symm_apply_eq, he]; simp
def left_adjoint_of_equiv : C ⥤ D :=
{ obj := F_obj,
map := λ X X' f, (e X (F_obj X')).symm (f ≫ e X' (F_obj X') (𝟙 _)),
map_comp' := λ X X' X'' f f', begin
rw [equiv.symm_apply_eq, he, equiv.apply_symm_apply],
conv { to_rhs, rw [assoc, ←he, id_comp, equiv.apply_symm_apply] },
simp
end }
def adjunction_of_equiv_left : left_adjoint_of_equiv e he ⊣ G :=
mk_of_hom_equiv
{ hom_equiv := e,
hom_equiv_naturality_left_symm' :=
begin
intros,
erw [← he' e he, ← equiv.apply_eq_iff_eq],
simp [(he _ _ _ _ _).symm]
end }
end construct_left
section construct_right
-- Construction of a right adjoint, analogous to the above.
variables {F} {G_obj : D → C}
variables (e : Π X Y, (F.obj X ⟶ Y) ≃ (X ⟶ G_obj Y))
variables (he : Π X' X Y f g, e X' Y (F.map f ≫ g) = f ≫ e X Y g)
include he
private lemma he' {X' X Y} (f g) : F.map f ≫ (e X Y).symm g = (e X' Y).symm (f ≫ g) :=
by intros; rw [equiv.eq_symm_apply, he]; simp
def right_adjoint_of_equiv : D ⥤ C :=
{ obj := G_obj,
map := λ Y Y' g, (e (G_obj Y) Y') ((e (G_obj Y) Y).symm (𝟙 _) ≫ g),
map_comp' := λ Y Y' Y'' g g', begin
rw [← equiv.eq_symm_apply, ← he' e he, equiv.symm_apply_apply],
conv { to_rhs, rw [← assoc, he' e he, comp_id, equiv.symm_apply_apply] },
simp
end }
def adjunction_of_equiv_right : F ⊣ right_adjoint_of_equiv e he :=
mk_of_hom_equiv
{ hom_equiv := e,
hom_equiv_naturality_left_symm' := by intros; rw [equiv.symm_apply_eq, he]; simp,
hom_equiv_naturality_right' :=
begin
intros X Y Y' g h,
erw [←he, equiv.apply_eq_iff_eq, ←assoc, he' e he, comp_id, equiv.symm_apply_apply]
end }
end construct_right
namespace equivalence
def to_adjunction (e : C ≌ D) : e.functor ⊣ e.inverse :=
mk_of_unit_counit ⟨e.unit, e.counit, by { ext, exact e.functor_unit_comp X },
by { ext, exact e.unit_inverse_comp X }⟩
end equivalence
end adjunction
end category_theory
|
8bd5ba2db669427420d388e975b7395fddefbe1e | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/ring_theory/jacobson_ideal.lean | 2e61dbd248b68d4598249706792b4da5bc8d7cbb | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 11,528 | lean | /-
Copyright (c) 2020 Devon Tuma. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Devon Tuma
-/
import ring_theory.ideal.operations
/-!
# Jacobson radical
The Jacobson radical of a ring `R` is defined to be the intersection of all maximal ideals of `R`.
This is similar to how the nilradical is equal to the intersection of all prime ideals of `R`.
We can extend the idea of the nilradical to ideals of `R`,
by letting the radical of an ideal `I` be the intersection of prime ideals containing `I`.
Under this extension, the original nilradical is the radical of the zero ideal `⊥`.
Here we define the Jacobson radical of an ideal `I` in a similar way,
as the intersection of maximal ideals containing `I`.
## Main definitions
Let `R` be a commutative ring, and `I` be an ideal of `R`
* `jacobson I` is the jacobson radical, i.e. the infimum of all maximal ideals containing I.
* `is_local I` is the proposition that the jacobson radical of `I` is itself a maximal ideal
## Main statements
* `mem_jacobson_iff` gives a characterization of members of the jacobson of I
* `is_local_of_is_maximal_radical`: if the radical of I is maximal then so is the jacobson radical
## Tags
Jacobson, Jacobson radical, Local Ideal
-/
universes u v
namespace ideal
variables {R : Type u} [comm_ring R]
variables {S : Type v} [comm_ring S]
section jacobson
/-- The Jacobson radical of `I` is the infimum of all maximal ideals containing `I`. -/
def jacobson (I : ideal R) : ideal R :=
Inf {J : ideal R | I ≤ J ∧ is_maximal J}
lemma le_jacobson {I : ideal R} : I ≤ jacobson I :=
λ x hx, mem_Inf.mpr (λ J hJ, hJ.left hx)
lemma radical_le_jacobson {I : ideal R} : radical I ≤ jacobson I :=
le_Inf (λ J hJ, (radical_eq_Inf I).symm ▸ Inf_le ⟨hJ.left, is_maximal.is_prime hJ.right⟩)
lemma eq_radical_of_eq_jacobson {I : ideal R} : jacobson I = I → radical I = I :=
λ h, le_antisymm (le_trans radical_le_jacobson (le_of_eq h)) le_radical
@[simp] lemma jacobson_top : jacobson (⊤ : ideal R) = ⊤ :=
eq_top_iff.2 le_jacobson
@[simp] theorem jacobson_eq_top_iff {I : ideal R} : jacobson I = ⊤ ↔ I = ⊤ :=
⟨λ H, classical.by_contradiction $ λ hi, let ⟨M, hm, him⟩ := exists_le_maximal I hi in
lt_top_iff_ne_top.1 (lt_of_le_of_lt (show jacobson I ≤ M, from Inf_le ⟨him, hm⟩) $ lt_top_iff_ne_top.2 hm.1) H,
λ H, eq_top_iff.2 $ le_Inf $ λ J ⟨hij, hj⟩, H ▸ hij⟩
lemma jacobson_eq_bot {I : ideal R} : jacobson I = ⊥ → I = ⊥ :=
λ h, eq_bot_iff.mpr (h ▸ le_jacobson)
lemma jacobson_eq_self_of_is_maximal {I : ideal R} [H : is_maximal I] : I.jacobson = I :=
le_antisymm (Inf_le ⟨le_of_eq rfl, H⟩) le_jacobson
@[priority 100]
instance jacobson.is_maximal {I : ideal R} [H : is_maximal I] : is_maximal (jacobson I) :=
⟨λ htop, H.left (jacobson_eq_top_iff.1 htop),
λ J hJ, H.right _ (lt_of_le_of_lt le_jacobson hJ)⟩
theorem mem_jacobson_iff {I : ideal R} {x : R} :
x ∈ jacobson I ↔ ∀ y, ∃ z, x * y * z + z - 1 ∈ I :=
⟨λ hx y, classical.by_cases
(assume hxy : I ⊔ span {x * y + 1} = ⊤,
let ⟨p, hpi, q, hq, hpq⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 hxy) in
let ⟨r, hr⟩ := mem_span_singleton.1 hq in
⟨r, by rw [← one_mul r, ← mul_assoc, ← add_mul, mul_one, ← hr, ← hpq, ← neg_sub, add_sub_cancel]; exact I.neg_mem hpi⟩)
(assume hxy : I ⊔ span {x * y + 1} ≠ ⊤,
let ⟨M, hm1, hm2⟩ := exists_le_maximal _ hxy in
suffices x ∉ M, from (this $ mem_Inf.1 hx ⟨le_trans le_sup_left hm2, hm1⟩).elim,
λ hxm, hm1.1 $ (eq_top_iff_one _).2 $ add_sub_cancel' (x * y) 1 ▸ M.sub_mem
(le_trans le_sup_right hm2 $ mem_span_singleton.2 $ dvd_refl _)
(M.mul_mem_right hxm)),
λ hx, mem_Inf.2 $ λ M ⟨him, hm⟩, classical.by_contradiction $ λ hxm,
let ⟨y, hy⟩ := hm.exists_inv hxm, ⟨z, hz⟩ := hx (-y) in
hm.1 $ (eq_top_iff_one _).2 $ sub_sub_cancel (x * -y * z + z) 1 ▸ M.sub_mem
(by rw [← one_mul z, ← mul_assoc, ← add_mul, mul_one, mul_neg_eq_neg_mul_symm, neg_add_eq_sub, ← neg_sub,
neg_mul_eq_neg_mul_symm, neg_mul_eq_mul_neg, mul_comm x y]; exact M.mul_mem_right hy)
(him hz)⟩
/-- An ideal equals its Jacobson radical iff it is the intersection of a set of maximal ideals.
Allowing the set to include ⊤ is equivalent, and is included only to simplify some proofs. -/
theorem eq_jacobson_iff_Inf_maximal {I : ideal R} :
I.jacobson = I ↔ ∃ M : set (ideal R), (∀ J ∈ M, is_maximal J ∨ J = ⊤) ∧ I = Inf M :=
begin
use λ hI, ⟨{J : ideal R | I ≤ J ∧ J.is_maximal}, ⟨λ _ hJ, or.inl hJ.right, hI.symm⟩⟩,
rintros ⟨M, hM, hInf⟩,
refine le_antisymm (λ x hx, _) le_jacobson,
rw [hInf, mem_Inf],
intros I hI,
cases hM I hI with is_max is_top,
{ exact (mem_Inf.1 hx) ⟨le_Inf_iff.1 (le_of_eq hInf) I hI, is_max⟩ },
{ exact is_top.symm ▸ submodule.mem_top }
end
theorem eq_jacobson_iff_Inf_maximal' {I : ideal R} :
I.jacobson = I ↔ ∃ M : set (ideal R), (∀ (J ∈ M) (K : ideal R), J < K → K = ⊤) ∧ I = Inf M :=
eq_jacobson_iff_Inf_maximal.trans
⟨λ h, let ⟨M, hM⟩ := h in ⟨M, ⟨λ J hJ K hK, or.rec_on (hM.1 J hJ) (λ h, h.2 K hK)
(λ h, eq_top_iff.2 (le_of_lt (h ▸ hK))), hM.2⟩⟩,
λ h, let ⟨M, hM⟩ := h in ⟨M, ⟨λ J hJ, or.rec_on (classical.em (J = ⊤)) (λ h, or.inr h)
(λ h, or.inl ⟨h, hM.1 J hJ⟩), hM.2⟩⟩⟩
/-- An ideal `I` equals its Jacobson radical if and only if every element outside `I`
also lies outside of a maximal ideal containing `I`. -/
lemma eq_jacobson_iff_not_mem {I : ideal R} :
I.jacobson = I ↔ ∀ x ∉ I, ∃ M : ideal R, (I ≤ M ∧ M.is_maximal) ∧ x ∉ M :=
begin
split,
{ intros h x hx,
erw [← h, mem_Inf] at hx,
push_neg at hx,
exact hx },
{ refine λ h, le_antisymm (λ x hx, _) le_jacobson,
contrapose hx,
erw mem_Inf,
push_neg,
exact h x hx }
end
theorem map_jacobson_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} :
ring_hom.ker f ≤ I → map f (I.jacobson) = (map f I).jacobson :=
begin
intro h,
unfold ideal.jacobson,
have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_maximal}, f.ker ≤ J := λ J hJ, le_trans h hJ.left,
refine trans (map_Inf hf this) (le_antisymm _ _),
{ refine Inf_le_Inf (λ J hJ, ⟨comap f J, ⟨⟨le_comap_of_map_le hJ.1, _⟩, map_comap_of_surjective f hf J⟩⟩),
haveI : J.is_maximal := hJ.right,
exact comap_is_maximal_of_surjective f hf },
{ refine Inf_le_Inf_of_subset_insert_top (λ j hj, hj.rec_on (λ J hJ, _)),
rw ← hJ.2,
cases map_eq_top_or_is_maximal_of_surjective f hf hJ.left.right with htop hmax,
{ exact htop.symm ▸ set.mem_insert ⊤ _ },
{ exact set.mem_insert_of_mem ⊤ ⟨map_mono hJ.1.1, hmax⟩ } },
end
theorem comap_jacobson_of_surjective {f : R →+* S} (hf : function.surjective f) {K : ideal S} :
comap f (K.jacobson) = (comap f K).jacobson :=
begin
unfold ideal.jacobson,
refine le_antisymm _ _,
{ refine le_trans (comap_mono (le_of_eq (trans top_inf_eq.symm Inf_insert.symm))) _,
rw [comap_Inf', Inf_eq_infi],
refine infi_le_infi_of_subset (λ J hJ, _),
have : comap f (map f J) = J := trans (comap_map_of_surjective f hf J)
(le_antisymm (sup_le_iff.2 ⟨le_of_eq rfl, le_trans (comap_mono bot_le) hJ.left⟩) le_sup_left),
cases map_eq_top_or_is_maximal_of_surjective _ hf hJ.right with htop hmax,
{ refine ⟨⊤, ⟨set.mem_insert ⊤ _, htop ▸ this⟩⟩ },
{ refine ⟨map f J, ⟨set.mem_insert_of_mem _
⟨le_map_of_comap_le_of_surjective f hf hJ.1, hmax⟩, this⟩⟩ } },
{ rw comap_Inf,
refine le_infi_iff.2 (λ J, (le_infi_iff.2 (λ hJ, _))),
haveI : J.is_maximal := hJ.right,
refine Inf_le ⟨comap_mono hJ.left, comap_is_maximal_of_surjective _ hf⟩ }
end
/-- An ideal `I` of `R` is equal to its Jacobson radical if and only if
the Jacobson radical of the quotient ring `R/I` is the zero ideal -/
theorem jacobson_eq_iff_jacobson_quotient_eq_bot {I : ideal R} :
I.jacobson = I ↔ jacobson (⊥ : ideal (I.quotient)) = ⊥ :=
begin
have hf : function.surjective (quotient.mk I) := submodule.quotient.mk_surjective I,
split,
{ intro h,
replace h := congr_arg (map (quotient.mk I)) h,
rw map_jacobson_of_surjective hf (le_of_eq mk_ker) at h,
simpa using h },
{ intro h,
replace h := congr_arg (comap (quotient.mk I)) h,
rw [comap_jacobson_of_surjective hf, ← (quotient.mk I).ker_eq_comap_bot] at h,
simpa using h }
end
/-- The standard radical and Jacobson radical of an ideal `I` of `R` are equal if and only if
the nilradical and Jacobson radical of the quotient ring `R/I` coincide -/
theorem radical_eq_jacobson_iff_radical_quotient_eq_jacobson_bot {I : ideal R} :
I.radical = I.jacobson ↔ radical (⊥ : ideal (I.quotient)) = jacobson ⊥ :=
begin
have hf : function.surjective (quotient.mk I) := submodule.quotient.mk_surjective I,
split,
{ intro h,
have := congr_arg (map (quotient.mk I)) h,
rw [map_radical_of_surjective hf (le_of_eq mk_ker),
map_jacobson_of_surjective hf (le_of_eq mk_ker)] at this,
simpa using this },
{ intro h,
have := congr_arg (comap (quotient.mk I)) h,
rw [comap_radical, comap_jacobson_of_surjective hf, ← (quotient.mk I).ker_eq_comap_bot] at this,
simpa using this }
end
@[mono] lemma jacobson_mono {I J : ideal R} : I ≤ J → I.jacobson ≤ J.jacobson :=
begin
intros h x hx,
erw mem_Inf at ⊢ hx,
exact λ K ⟨hK, hK_max⟩, hx ⟨trans h hK, hK_max⟩
end
end jacobson
section is_local
/-- An ideal `I` is local iff its Jacobson radical is maximal. -/
@[class] def is_local (I : ideal R) : Prop :=
is_maximal (jacobson I)
theorem is_local_of_is_maximal_radical {I : ideal R} (hi : is_maximal (radical I)) : is_local I :=
have radical I = jacobson I,
from le_antisymm (le_Inf $ λ M ⟨him, hm⟩, hm.is_prime.radical_le_iff.2 him)
(Inf_le ⟨le_radical, hi⟩),
show is_maximal (jacobson I), from this ▸ hi
theorem is_local.le_jacobson {I J : ideal R} (hi : is_local I) (hij : I ≤ J) (hj : J ≠ ⊤) : J ≤ jacobson I :=
let ⟨M, hm, hjm⟩ := exists_le_maximal J hj in
le_trans hjm $ le_of_eq $ eq.symm $ hi.eq_of_le hm.1 $ Inf_le ⟨le_trans hij hjm, hm⟩
theorem is_local.mem_jacobson_or_exists_inv {I : ideal R} (hi : is_local I) (x : R) :
x ∈ jacobson I ∨ ∃ y, y * x - 1 ∈ I :=
classical.by_cases
(assume h : I ⊔ span {x} = ⊤,
let ⟨p, hpi, q, hq, hpq⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in
let ⟨r, hr⟩ := mem_span_singleton.1 hq in
or.inr ⟨r, by rw [← hpq, mul_comm, ← hr, ← neg_sub, add_sub_cancel]; exact I.neg_mem hpi⟩)
(assume h : I ⊔ span {x} ≠ ⊤,
or.inl $ le_trans le_sup_right (hi.le_jacobson le_sup_left h) $ mem_span_singleton.2 $ dvd_refl x)
end is_local
theorem is_primary_of_is_maximal_radical {I : ideal R} (hi : is_maximal (radical I)) : is_primary I :=
have radical I = jacobson I,
from le_antisymm (le_Inf $ λ M ⟨him, hm⟩, hm.is_prime.radical_le_iff.2 him)
(Inf_le ⟨le_radical, hi⟩),
⟨ne_top_of_lt $ lt_of_le_of_lt le_radical (lt_top_iff_ne_top.2 hi.1),
λ x y hxy, ((is_local_of_is_maximal_radical hi).mem_jacobson_or_exists_inv y).symm.imp
(λ ⟨z, hz⟩, by rw [← mul_one x, ← sub_sub_cancel (z * y) 1, mul_sub, mul_left_comm]; exact
I.sub_mem (I.mul_mem_left hxy) (I.mul_mem_left hz))
(this ▸ id)⟩
end ideal
|
b82a0b82cedabe68d5d9507d7ec0600b6aecd128 | ac1c2a2f522b0fdf854095ba00f882ca849669e7 | /library/init/meta/default.lean | 8ebbb1cec3927be6044cd821584a46d96bdc9d30 | [
"Apache-2.0"
] | permissive | abliss/lean | b8b336abc8d50dbb0726dcff9dd16793c23bfbe1 | fb24cc99573c153f97a1951ee94bbbdda300b6be | refs/heads/master | 1,611,536,584,520 | 1,497,811,981,000 | 1,497,811,981,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 963 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.name init.meta.options init.meta.format init.meta.rb_map
import init.meta.level init.meta.expr init.meta.environment init.meta.attribute
import init.meta.tactic init.meta.contradiction_tactic init.meta.constructor_tactic
import init.meta.injection_tactic init.meta.relation_tactics init.meta.fun_info
import init.meta.congr_lemma init.meta.match_tactic init.meta.ac_tactics
import init.meta.backward init.meta.rewrite_tactic
import init.meta.mk_dec_eq_instance init.meta.mk_inhabited_instance
import init.meta.simp_tactic init.meta.set_get_option_tactics
import init.meta.interactive init.meta.converter init.meta.vm
import init.meta.comp_value_tactics init.meta.smt
import init.meta.async_tactic init.meta.ref init.meta.coinductive_predicates
import init.meta.hole_command
|
a437e4a195ff9ef78ab67f8ce9e823e6660281fc | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /src/Lean/Compiler/IR/Basic.lean | a99ec8289120dbb29a05f00c402c7cdb2db02ed4 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | Kha/lean4 | 1005785d2c8797ae266a303968848e5f6ce2fe87 | b99e11346948023cd6c29d248cd8f3e3fb3474cf | refs/heads/master | 1,693,355,498,027 | 1,669,080,461,000 | 1,669,113,138,000 | 184,748,176 | 0 | 0 | Apache-2.0 | 1,665,995,520,000 | 1,556,884,930,000 | Lean | UTF-8 | Lean | false | false | 26,403 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.KVMap
import Lean.Data.Name
import Lean.Data.Format
import Lean.Compiler.ExternAttr
/-!
Implements (extended) λPure and λRc proposed in the article
"Counting Immutable Beans", Sebastian Ullrich and Leonardo de Moura.
The Lean to IR transformation produces λPure code, and
this part is implemented in C++. The procedures described in the paper
above are implemented in Lean.
-/
namespace Lean.IR
/-- Function identifier -/
abbrev FunId := Name
abbrev Index := Nat
/-- Variable identifier -/
structure VarId where
idx : Index
deriving Inhabited
/-- Join point identifier -/
structure JoinPointId where
idx : Index
deriving Inhabited
abbrev Index.lt (a b : Index) : Bool := a < b
instance : BEq VarId := ⟨fun a b => a.idx == b.idx⟩
instance : ToString VarId := ⟨fun a => "x_" ++ toString a.idx⟩
instance : ToFormat VarId := ⟨fun a => toString a⟩
instance : Hashable VarId := ⟨fun a => hash a.idx⟩
instance : BEq JoinPointId := ⟨fun a b => a.idx == b.idx⟩
instance : ToString JoinPointId := ⟨fun a => "block_" ++ toString a.idx⟩
instance : ToFormat JoinPointId := ⟨fun a => toString a⟩
instance : Hashable JoinPointId := ⟨fun a => hash a.idx⟩
abbrev MData := KVMap
abbrev MData.empty : MData := {}
/-- Low Level IR types. Most are self explanatory.
- `usize` represents the C++ `size_t` Type. We have it here
because it is 32-bit in 32-bit machines, and 64-bit in 64-bit machines,
and we want the C++ backend for our Compiler to generate platform independent code.
- `irrelevant` for Lean types, propositions and proofs.
- `object` a pointer to a value in the heap.
- `tobject` a pointer to a value in the heap or tagged pointer
(i.e., the least significant bit is 1) storing a scalar value.
- `struct` and `union` are used to return small values (e.g., `Option`, `Prod`, `Except`)
on the stack.
Remark: the RC operations for `tobject` are slightly more expensive because we
first need to test whether the `tobject` is really a pointer or not.
Remark: the Lean runtime assumes that sizeof(void*) == sizeof(sizeT).
Lean cannot be compiled on old platforms where this is not True.
Since values of type `struct` and `union` are only used to return values,
We assume they must be used/consumed "linearly". We use the term "linear" here
to mean "exactly once" in each execution. That is, given `x : S`, where `S` is a struct,
then one of the following must hold in each (execution) branch.
1- `x` occurs only at a single `ret x` instruction. That is, it is being consumed by being returned.
2- `x` occurs only at a single `ctor`. That is, it is being "consumed" by being stored into another `struct/union`.
3- We extract (aka project) every single field of `x` exactly once. That is, we are consuming `x` by consuming each
of one of its components. Minor refinement: we don't need to consume scalar fields or struct/union
fields that do not contain object fields.
-/
inductive IRType where
| float | uint8 | uint16 | uint32 | uint64 | usize
| irrelevant | object | tobject
| struct (leanTypeName : Option Name) (types : Array IRType) : IRType
| union (leanTypeName : Name) (types : Array IRType) : IRType
deriving Inhabited
namespace IRType
partial def beq : IRType → IRType → Bool
| float, float => true
| uint8, uint8 => true
| uint16, uint16 => true
| uint32, uint32 => true
| uint64, uint64 => true
| usize, usize => true
| irrelevant, irrelevant => true
| object, object => true
| tobject, tobject => true
| struct n₁ tys₁, struct n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq
| union n₁ tys₁, union n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq
| _, _ => false
instance : BEq IRType := ⟨beq⟩
def isScalar : IRType → Bool
| float => true
| uint8 => true
| uint16 => true
| uint32 => true
| uint64 => true
| usize => true
| _ => false
def isObj : IRType → Bool
| object => true
| tobject => true
| _ => false
def isIrrelevant : IRType → Bool
| irrelevant => true
| _ => false
def isStruct : IRType → Bool
| struct _ _ => true
| _ => false
def isUnion : IRType → Bool
| union _ _ => true
| _ => false
end IRType
/-- Arguments to applications, constructors, etc.
We use `irrelevant` for Lean types, propositions and proofs that have been erased.
Recall that for a Function `f`, we also generate `f._rarg` which does not take
`irrelevant` arguments. However, `f._rarg` is only safe to be used in full applications. -/
inductive Arg where
| var (id : VarId)
| irrelevant
deriving Inhabited
protected def Arg.beq : Arg → Arg → Bool
| var x, var y => x == y
| irrelevant, irrelevant => true
| _, _ => false
instance : BEq Arg := ⟨Arg.beq⟩
@[export lean_ir_mk_var_arg] def mkVarArg (id : VarId) : Arg := Arg.var id
inductive LitVal where
| num (v : Nat)
| str (v : String)
def LitVal.beq : LitVal → LitVal → Bool
| num v₁, num v₂ => v₁ == v₂
| str v₁, str v₂ => v₁ == v₂
| _, _ => false
instance : BEq LitVal := ⟨LitVal.beq⟩
/-- Constructor information.
- `name` is the Name of the Constructor in Lean.
- `cidx` is the Constructor index (aka tag).
- `size` is the number of arguments of type `object/tobject`.
- `usize` is the number of arguments of type `usize`.
- `ssize` is the number of bytes used to store scalar values.
Recall that a Constructor object contains a header, then a sequence of
pointers to other Lean objects, a sequence of `USize` (i.e., `size_t`)
scalar values, and a sequence of other scalar values. -/
structure CtorInfo where
name : Name
cidx : Nat
size : Nat
usize : Nat
ssize : Nat
deriving Repr
def CtorInfo.beq : CtorInfo → CtorInfo → Bool
| ⟨n₁, cidx₁, size₁, usize₁, ssize₁⟩, ⟨n₂, cidx₂, size₂, usize₂, ssize₂⟩ =>
n₁ == n₂ && cidx₁ == cidx₂ && size₁ == size₂ && usize₁ == usize₂ && ssize₁ == ssize₂
instance : BEq CtorInfo := ⟨CtorInfo.beq⟩
def CtorInfo.isRef (info : CtorInfo) : Bool :=
info.size > 0 || info.usize > 0 || info.ssize > 0
def CtorInfo.isScalar (info : CtorInfo) : Bool :=
!info.isRef
inductive Expr where
/-- We use `ctor` mainly for constructing Lean object/tobject values `lean_ctor_object` in the runtime.
This instruction is also used to creat `struct` and `union` return values.
For `union`, only `i.cidx` is relevant. For `struct`, `i` is irrelevant. -/
| ctor (i : CtorInfo) (ys : Array Arg)
| reset (n : Nat) (x : VarId)
/-- `reuse x in ctor_i ys` instruction in the paper. -/
| reuse (x : VarId) (i : CtorInfo) (updtHeader : Bool) (ys : Array Arg)
/-- Extract the `tobject` value at Position `sizeof(void*)*i` from `x`.
We also use `proj` for extracting fields from `struct` return values, and casting `union` return values. -/
| proj (i : Nat) (x : VarId)
/-- Extract the `Usize` value at Position `sizeof(void*)*i` from `x`. -/
| uproj (i : Nat) (x : VarId)
/-- Extract the scalar value at Position `sizeof(void*)*n + offset` from `x`. -/
| sproj (n : Nat) (offset : Nat) (x : VarId)
/-- Full application. -/
| fap (c : FunId) (ys : Array Arg)
/-- Partial application that creates a `pap` value (aka closure in our nonstandard terminology). -/
| pap (c : FunId) (ys : Array Arg)
/-- Application. `x` must be a `pap` value. -/
| ap (x : VarId) (ys : Array Arg)
/-- Given `x : ty` where `ty` is a scalar type, this operation returns a value of Type `tobject`.
For small scalar values, the Result is a tagged pointer, and no memory allocation is performed. -/
| box (ty : IRType) (x : VarId)
/-- Given `x : [t]object`, obtain the scalar value. -/
| unbox (x : VarId)
| lit (v : LitVal)
/-- Return `1 : uint8` Iff `RC(x) > 1` -/
| isShared (x : VarId)
/-- Return `1 : uint8` Iff `x : tobject` is a tagged pointer (storing a scalar value). -/
| isTaggedPtr (x : VarId)
@[export lean_ir_mk_ctor_expr] def mkCtorExpr (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (ys : Array Arg) : Expr :=
Expr.ctor ⟨n, cidx, size, usize, ssize⟩ ys
@[export lean_ir_mk_proj_expr] def mkProjExpr (i : Nat) (x : VarId) : Expr := Expr.proj i x
@[export lean_ir_mk_uproj_expr] def mkUProjExpr (i : Nat) (x : VarId) : Expr := Expr.uproj i x
@[export lean_ir_mk_sproj_expr] def mkSProjExpr (n : Nat) (offset : Nat) (x : VarId) : Expr := Expr.sproj n offset x
@[export lean_ir_mk_fapp_expr] def mkFAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.fap c ys
@[export lean_ir_mk_papp_expr] def mkPAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.pap c ys
@[export lean_ir_mk_app_expr] def mkAppExpr (x : VarId) (ys : Array Arg) : Expr := Expr.ap x ys
@[export lean_ir_mk_num_expr] def mkNumExpr (v : Nat) : Expr := Expr.lit (LitVal.num v)
@[export lean_ir_mk_str_expr] def mkStrExpr (v : String) : Expr := Expr.lit (LitVal.str v)
structure Param where
x : VarId
borrow : Bool
ty : IRType
deriving Inhabited
@[export lean_ir_mk_param]
def mkParam (x : VarId) (borrow : Bool) (ty : IRType) : Param := ⟨x, borrow, ty⟩
inductive AltCore (FnBody : Type) : Type where
| ctor (info : CtorInfo) (b : FnBody) : AltCore FnBody
| default (b : FnBody) : AltCore FnBody
inductive FnBody where
/-- `let x : ty := e; b` -/
| vdecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody)
/-- Join point Declaration `block_j (xs) := e; b` -/
| jdecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody)
/-- Store `y` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1.
This operation is not part of λPure is only used during optimization. -/
| set (x : VarId) (i : Nat) (y : Arg) (b : FnBody)
| setTag (x : VarId) (cidx : Nat) (b : FnBody)
/-- Store `y : Usize` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. -/
| uset (x : VarId) (i : Nat) (y : VarId) (b : FnBody)
/-- Store `y : ty` at Position `sizeof(void*)*i + offset` in `x`. `x` must be a Constructor object and `RC(x)` must be 1.
`ty` must not be `object`, `tobject`, `irrelevant` nor `Usize`. -/
| sset (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody)
/-- RC increment for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not.
If `persistent == true` then `x` is statically known to be a persistent object. -/
| inc (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody)
/-- RC decrement for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not.
If `persistent == true` then `x` is statically known to be a persistent object. -/
| dec (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody)
| del (x : VarId) (b : FnBody)
| mdata (d : MData) (b : FnBody)
| case (tid : Name) (x : VarId) (xType : IRType) (cs : Array (AltCore FnBody))
| ret (x : Arg)
/-- Jump to join point `j` -/
| jmp (j : JoinPointId) (ys : Array Arg)
| unreachable
instance : Inhabited FnBody := ⟨FnBody.unreachable⟩
abbrev FnBody.nil := FnBody.unreachable
@[export lean_ir_mk_vdecl] def mkVDecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : FnBody := FnBody.vdecl x ty e b
@[export lean_ir_mk_jdecl] def mkJDecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) : FnBody := FnBody.jdecl j xs v b
@[export lean_ir_mk_uset] def mkUSet (x : VarId) (i : Nat) (y : VarId) (b : FnBody) : FnBody := FnBody.uset x i y b
@[export lean_ir_mk_sset] def mkSSet (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) : FnBody := FnBody.sset x i offset y ty b
@[export lean_ir_mk_case] def mkCase (tid : Name) (x : VarId) (cs : Array (AltCore FnBody)) : FnBody :=
-- Type field `xType` is set by `explicitBoxing` compiler pass.
FnBody.case tid x IRType.object cs
@[export lean_ir_mk_ret] def mkRet (x : Arg) : FnBody := FnBody.ret x
@[export lean_ir_mk_jmp] def mkJmp (j : JoinPointId) (ys : Array Arg) : FnBody := FnBody.jmp j ys
@[export lean_ir_mk_unreachable] def mkUnreachable : Unit → FnBody := fun _ => FnBody.unreachable
abbrev Alt := AltCore FnBody
@[match_pattern] abbrev Alt.ctor := @AltCore.ctor FnBody
@[match_pattern] abbrev Alt.default := @AltCore.default FnBody
instance : Inhabited Alt := ⟨Alt.default default⟩
def FnBody.isTerminal : FnBody → Bool
| FnBody.case _ _ _ _ => true
| FnBody.ret _ => true
| FnBody.jmp _ _ => true
| FnBody.unreachable => true
| _ => false
def FnBody.body : FnBody → FnBody
| FnBody.vdecl _ _ _ b => b
| FnBody.jdecl _ _ _ b => b
| FnBody.set _ _ _ b => b
| FnBody.uset _ _ _ b => b
| FnBody.sset _ _ _ _ _ b => b
| FnBody.setTag _ _ b => b
| FnBody.inc _ _ _ _ b => b
| FnBody.dec _ _ _ _ b => b
| FnBody.del _ b => b
| FnBody.mdata _ b => b
| other => other
def FnBody.setBody : FnBody → FnBody → FnBody
| FnBody.vdecl x t v _, b => FnBody.vdecl x t v b
| FnBody.jdecl j xs v _, b => FnBody.jdecl j xs v b
| FnBody.set x i y _, b => FnBody.set x i y b
| FnBody.uset x i y _, b => FnBody.uset x i y b
| FnBody.sset x i o y t _, b => FnBody.sset x i o y t b
| FnBody.setTag x i _, b => FnBody.setTag x i b
| FnBody.inc x n c p _, b => FnBody.inc x n c p b
| FnBody.dec x n c p _, b => FnBody.dec x n c p b
| FnBody.del x _, b => FnBody.del x b
| FnBody.mdata d _, b => FnBody.mdata d b
| other, _ => other
@[inline] def FnBody.resetBody (b : FnBody) : FnBody :=
b.setBody FnBody.nil
/-- If b is a non terminal, then return a pair `(c, b')` s.t. `b == c <;> b'`,
and c.body == FnBody.nil -/
@[inline] def FnBody.split (b : FnBody) : FnBody × FnBody :=
let b' := b.body
let c := b.resetBody
(c, b')
def AltCore.body : Alt → FnBody
| Alt.ctor _ b => b
| Alt.default b => b
def AltCore.setBody : Alt → FnBody → Alt
| Alt.ctor c _, b => Alt.ctor c b
| Alt.default _, b => Alt.default b
@[inline] def AltCore.modifyBody (f : FnBody → FnBody) : AltCore FnBody → Alt
| Alt.ctor c b => Alt.ctor c (f b)
| Alt.default b => Alt.default (f b)
@[inline] def AltCore.mmodifyBody {m : Type → Type} [Monad m] (f : FnBody → m FnBody) : AltCore FnBody → m Alt
| Alt.ctor c b => Alt.ctor c <$> f b
| Alt.default b => Alt.default <$> f b
def Alt.isDefault : Alt → Bool
| Alt.ctor _ _ => false
| Alt.default _ => true
def push (bs : Array FnBody) (b : FnBody) : Array FnBody :=
let b := b.resetBody
bs.push b
partial def flattenAux (b : FnBody) (r : Array FnBody) : (Array FnBody) × FnBody :=
if b.isTerminal then (r, b)
else flattenAux b.body (push r b)
def FnBody.flatten (b : FnBody) : (Array FnBody) × FnBody :=
flattenAux b #[]
partial def reshapeAux (a : Array FnBody) (i : Nat) (b : FnBody) : FnBody :=
if i == 0 then b
else
let i := i - 1
let (curr, a) := a.swapAt! i default
let b := curr.setBody b
reshapeAux a i b
def reshape (bs : Array FnBody) (term : FnBody) : FnBody :=
reshapeAux bs bs.size term
@[inline] def modifyJPs (bs : Array FnBody) (f : FnBody → FnBody) : Array FnBody :=
bs.map fun b => match b with
| FnBody.jdecl j xs v k => FnBody.jdecl j xs (f v) k
| other => other
@[inline] def mmodifyJPs {m : Type → Type} [Monad m] (bs : Array FnBody) (f : FnBody → m FnBody) : m (Array FnBody) :=
bs.mapM fun b => match b with
| FnBody.jdecl j xs v k => return FnBody.jdecl j xs (← f v) k
| other => return other
@[export lean_ir_mk_alt] def mkAlt (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (b : FnBody) : Alt :=
Alt.ctor ⟨n, cidx, size, usize, ssize⟩ b
/-- Extra information associated with a declaration. -/
structure DeclInfo where
/-- If `some <blame>`, then declaration depends on `<blame>` which uses a `sorry` axiom. -/
sorryDep? : Option Name := none
inductive Decl where
| fdecl (f : FunId) (xs : Array Param) (type : IRType) (body : FnBody) (info : DeclInfo)
| extern (f : FunId) (xs : Array Param) (type : IRType) (ext : ExternAttrData)
deriving Inhabited
namespace Decl
def name : Decl → FunId
| .fdecl f .. => f
| .extern f .. => f
def params : Decl → Array Param
| .fdecl (xs := xs) .. => xs
| .extern (xs := xs) .. => xs
def resultType : Decl → IRType
| .fdecl (type := t) .. => t
| .extern (type := t) .. => t
def isExtern : Decl → Bool
| .extern .. => true
| _ => false
def getInfo : Decl → DeclInfo
| .fdecl (info := info) .. => info
| _ => {}
def updateBody! (d : Decl) (bNew : FnBody) : Decl :=
match d with
| Decl.fdecl f xs t _ info => Decl.fdecl f xs t bNew info
| _ => panic! "expected definition"
end Decl
@[export lean_ir_mk_decl] def mkDecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) : Decl :=
Decl.fdecl f xs ty b {}
@[export lean_ir_mk_extern_decl] def mkExternDecl (f : FunId) (xs : Array Param) (ty : IRType) (e : ExternAttrData) : Decl :=
Decl.extern f xs ty e
-- Hack: we use this declaration as a stub for declarations annotated with `implemented_by` or `init`
@[export lean_ir_mk_dummy_extern_decl] def mkDummyExternDecl (f : FunId) (xs : Array Param) (ty : IRType) : Decl :=
Decl.fdecl f xs ty FnBody.unreachable {}
/-- Set of variable and join point names -/
abbrev IndexSet := RBTree Index compare
instance : Inhabited IndexSet := ⟨{}⟩
def mkIndexSet (idx : Index) : IndexSet :=
RBTree.empty.insert idx
inductive LocalContextEntry where
| param : IRType → LocalContextEntry
| localVar : IRType → Expr → LocalContextEntry
| joinPoint : Array Param → FnBody → LocalContextEntry
abbrev LocalContext := RBMap Index LocalContextEntry compare
def LocalContext.addLocal (ctx : LocalContext) (x : VarId) (t : IRType) (v : Expr) : LocalContext :=
ctx.insert x.idx (LocalContextEntry.localVar t v)
def LocalContext.addJP (ctx : LocalContext) (j : JoinPointId) (xs : Array Param) (b : FnBody) : LocalContext :=
ctx.insert j.idx (LocalContextEntry.joinPoint xs b)
def LocalContext.addParam (ctx : LocalContext) (p : Param) : LocalContext :=
ctx.insert p.x.idx (LocalContextEntry.param p.ty)
def LocalContext.addParams (ctx : LocalContext) (ps : Array Param) : LocalContext :=
ps.foldl LocalContext.addParam ctx
def LocalContext.isJP (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.joinPoint _ _) => true
| _ => false
def LocalContext.getJPBody (ctx : LocalContext) (j : JoinPointId) : Option FnBody :=
match ctx.find? j.idx with
| some (LocalContextEntry.joinPoint _ b) => some b
| _ => none
def LocalContext.getJPParams (ctx : LocalContext) (j : JoinPointId) : Option (Array Param) :=
match ctx.find? j.idx with
| some (LocalContextEntry.joinPoint ys _) => some ys
| _ => none
def LocalContext.isParam (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.param _) => true
| _ => false
def LocalContext.isLocalVar (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.localVar _ _) => true
| _ => false
def LocalContext.contains (ctx : LocalContext) (idx : Index) : Bool :=
RBMap.contains ctx idx
def LocalContext.eraseJoinPointDecl (ctx : LocalContext) (j : JoinPointId) : LocalContext :=
ctx.erase j.idx
def LocalContext.getType (ctx : LocalContext) (x : VarId) : Option IRType :=
match ctx.find? x.idx with
| some (LocalContextEntry.param t) => some t
| some (LocalContextEntry.localVar t _) => some t
| _ => none
def LocalContext.getValue (ctx : LocalContext) (x : VarId) : Option Expr :=
match ctx.find? x.idx with
| some (LocalContextEntry.localVar _ v) => some v
| _ => none
abbrev IndexRenaming := RBMap Index Index compare
class AlphaEqv (α : Type) where
aeqv : IndexRenaming → α → α → Bool
export AlphaEqv (aeqv)
def VarId.alphaEqv (ρ : IndexRenaming) (v₁ v₂ : VarId) : Bool :=
match ρ.find? v₁.idx with
| some v => v == v₂.idx
| none => v₁ == v₂
instance : AlphaEqv VarId := ⟨VarId.alphaEqv⟩
def Arg.alphaEqv (ρ : IndexRenaming) : Arg → Arg → Bool
| Arg.var v₁, Arg.var v₂ => aeqv ρ v₁ v₂
| Arg.irrelevant, Arg.irrelevant => true
| _, _ => false
instance : AlphaEqv Arg := ⟨Arg.alphaEqv⟩
def args.alphaEqv (ρ : IndexRenaming) (args₁ args₂ : Array Arg) : Bool :=
Array.isEqv args₁ args₂ (fun a b => aeqv ρ a b)
instance: AlphaEqv (Array Arg) := ⟨args.alphaEqv⟩
def Expr.alphaEqv (ρ : IndexRenaming) : Expr → Expr → Bool
| Expr.ctor i₁ ys₁, Expr.ctor i₂ ys₂ => i₁ == i₂ && aeqv ρ ys₁ ys₂
| Expr.reset n₁ x₁, Expr.reset n₂ x₂ => n₁ == n₂ && aeqv ρ x₁ x₂
| Expr.reuse x₁ i₁ u₁ ys₁, Expr.reuse x₂ i₂ u₂ ys₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && u₁ == u₂ && aeqv ρ ys₁ ys₂
| Expr.proj i₁ x₁, Expr.proj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂
| Expr.uproj i₁ x₁, Expr.uproj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂
| Expr.sproj n₁ o₁ x₁, Expr.sproj n₂ o₂ x₂ => n₁ == n₂ && o₁ == o₂ && aeqv ρ x₁ x₂
| Expr.fap c₁ ys₁, Expr.fap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂
| Expr.pap c₁ ys₁, Expr.pap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂
| Expr.ap x₁ ys₁, Expr.ap x₂ ys₂ => aeqv ρ x₁ x₂ && aeqv ρ ys₁ ys₂
| Expr.box ty₁ x₁, Expr.box ty₂ x₂ => ty₁ == ty₂ && aeqv ρ x₁ x₂
| Expr.unbox x₁, Expr.unbox x₂ => aeqv ρ x₁ x₂
| Expr.lit v₁, Expr.lit v₂ => v₁ == v₂
| Expr.isShared x₁, Expr.isShared x₂ => aeqv ρ x₁ x₂
| Expr.isTaggedPtr x₁, Expr.isTaggedPtr x₂ => aeqv ρ x₁ x₂
| _, _ => false
instance : AlphaEqv Expr:= ⟨Expr.alphaEqv⟩
def addVarRename (ρ : IndexRenaming) (x₁ x₂ : Nat) :=
if x₁ == x₂ then ρ else ρ.insert x₁ x₂
def addParamRename (ρ : IndexRenaming) (p₁ p₂ : Param) : Option IndexRenaming :=
if p₁.ty == p₂.ty && p₁.borrow = p₂.borrow then
some (addVarRename ρ p₁.x.idx p₂.x.idx)
else
none
def addParamsRename (ρ : IndexRenaming) (ps₁ ps₂ : Array Param) : Option IndexRenaming := do
if ps₁.size != ps₂.size then
failure
else
let mut ρ := ρ
for i in [:ps₁.size] do
ρ ← addParamRename ρ ps₁[i]! ps₂[i]!
pure ρ
partial def FnBody.alphaEqv : IndexRenaming → FnBody → FnBody → Bool
| ρ, FnBody.vdecl x₁ t₁ v₁ b₁, FnBody.vdecl x₂ t₂ v₂ b₂ => t₁ == t₂ && aeqv ρ v₁ v₂ && alphaEqv (addVarRename ρ x₁.idx x₂.idx) b₁ b₂
| ρ, FnBody.jdecl j₁ ys₁ v₁ b₁, FnBody.jdecl j₂ ys₂ v₂ b₂ => match addParamsRename ρ ys₁ ys₂ with
| some ρ' => alphaEqv ρ' v₁ v₂ && alphaEqv (addVarRename ρ j₁.idx j₂.idx) b₁ b₂
| none => false
| ρ, FnBody.set x₁ i₁ y₁ b₁, FnBody.set x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.uset x₁ i₁ y₁ b₁, FnBody.uset x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.sset x₁ i₁ o₁ y₁ t₁ b₁, FnBody.sset x₂ i₂ o₂ y₂ t₂ b₂ =>
aeqv ρ x₁ x₂ && i₁ = i₂ && o₁ = o₂ && aeqv ρ y₁ y₂ && t₁ == t₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.setTag x₁ i₁ b₁, FnBody.setTag x₂ i₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.inc x₁ n₁ c₁ p₁ b₁, FnBody.inc x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.dec x₁ n₁ c₁ p₁ b₁, FnBody.dec x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.del x₁ b₁, FnBody.del x₂ b₂ => aeqv ρ x₁ x₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.mdata m₁ b₁, FnBody.mdata m₂ b₂ => m₁ == m₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.case n₁ x₁ _ alts₁, FnBody.case n₂ x₂ _ alts₂ => n₁ == n₂ && aeqv ρ x₁ x₂ && Array.isEqv alts₁ alts₂ (fun alt₁ alt₂ =>
match alt₁, alt₂ with
| Alt.ctor i₁ b₁, Alt.ctor i₂ b₂ => i₁ == i₂ && alphaEqv ρ b₁ b₂
| Alt.default b₁, Alt.default b₂ => alphaEqv ρ b₁ b₂
| _, _ => false)
| ρ, FnBody.jmp j₁ ys₁, FnBody.jmp j₂ ys₂ => j₁ == j₂ && aeqv ρ ys₁ ys₂
| ρ, FnBody.ret x₁, FnBody.ret x₂ => aeqv ρ x₁ x₂
| _, FnBody.unreachable, FnBody.unreachable => true
| _, _, _ => false
def FnBody.beq (b₁ b₂ : FnBody) : Bool :=
FnBody.alphaEqv ∅ b₁ b₂
instance : BEq FnBody := ⟨FnBody.beq⟩
abbrev VarIdSet := RBTree VarId (fun x y => compare x.idx y.idx)
instance : Inhabited VarIdSet := ⟨{}⟩
def mkIf (x : VarId) (t e : FnBody) : FnBody :=
FnBody.case `Bool x IRType.uint8 #[
Alt.ctor {name := ``Bool.false, cidx := 0, size := 0, usize := 0, ssize := 0} e,
Alt.ctor {name := ``Bool.true, cidx := 1, size := 0, usize := 0, ssize := 0} t
]
end Lean.IR
|
0a6ed0f8489f415b335a2c1265292052dfb4c87c | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /tests/lean/run/unfold_crash.lean | a5b3ab0f2824de33adfa4d78e5c60c68818b1f95 | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 1,596 | lean | open tactic
-- TODO(Leo): remove the following command.
-- It has been added to avoid a crash in the code generator
noncomputable theory
inductive vector (A : Type) : nat → Type
| nil {} : vector 0
| cons : Π {n}, A -> vector n -> vector (nat.succ n)
definition vmap {A B : Type} (f : A -> B) : Π {n}, vector A n -> vector B n
| 0 vector.nil := vector.nil
| (n+1) (vector.cons x xs) := vector.cons (f x) (vmap xs)
noncomputable definition vappend {A} : Π {n m}, vector A n → vector A m → vector A (m + n)
| 0 0 vector.nil vector.nil := vector.nil
| 0 (m+1) vector.nil (vector.cons x xs) := vector.cons x xs
| (n+1) 0 (vector.cons x xs) vector.nil := vector.cons x (vappend xs vector.nil)
| (n+1) (m+1) (vector.cons x xs) (vector.cons y ys) := vector.cons x (vappend xs (vector.cons y ys))
axiom Sorry : ∀ A, A
theorem vappend_assoc :
Π {A : Type} {n m k : nat} (v1 : vector A n) (v2 : vector A m) (v3 : vector A k),
vappend (vappend v1 v2) v3 == vappend v1 (vappend v2 v3) :=
by do
intros,
v <- get_local `v1,
induction v,
v2 ← get_local `v2,
cases v2 [`m, `h2, `t2],
trace_state, trace "------",
-- unfold only the first occurrence (i.e., the one of the form (vappend nil nil)
dunfold_occs_of [1] `vappend,
trace_state, trace "------",
mk_const `Sorry >>= apply,
-- unfold only the first occurrence (i.e., the one of the form (vappend nil (cons ...))
dunfold_occs_of [1] `vappend,
trace_state, trace "------",
repeat $ mk_const `Sorry >>= apply
|
fbfbe7d41d2b2973d2102443b9ec9d239615ebcc | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/linear_algebra/affine_space/affine_equiv.lean | 91b890541417462c7b5af34e39d92f328c9acbad | [
"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 | 16,370 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import linear_algebra.affine_space.affine_map
import algebra.invertible
/-!
# Affine equivalences
In this file we define `affine_equiv k P₁ P₂` (notation: `P₁ ≃ᵃ[k] P₂`) to be the type of affine
equivalences between `P₁` and `P₂, i.e., equivalences such that both forward and inverse maps are
affine maps.
We define the following equivalences:
* `affine_equiv.refl k P`: the identity map as an `affine_equiv`;
* `e.symm`: the inverse map of an `affine_equiv` as an `affine_equiv`;
* `e.trans e'`: composition of two `affine_equiv`s; note that the order follows `mathlib`'s
`category_theory` convention (apply `e`, then `e'`), not the convention used in function
composition and compositions of bundled morphisms.
We equip `affine_equiv k P P` with a `group` structure with multiplication corresponding to
composition in `affine_equiv.group`.
## Tags
affine space, affine equivalence
-/
open function set
open_locale affine
/-- An affine equivalence is an equivalence between affine spaces such that both forward
and inverse maps are affine.
We define it using an `equiv` for the map and a `linear_equiv` for the linear part in order
to allow affine equivalences with good definitional equalities. -/
@[nolint has_inhabited_instance]
structure affine_equiv (k P₁ P₂ : Type*) {V₁ V₂ : Type*} [ring k]
[add_comm_group V₁] [module k V₁] [add_torsor V₁ P₁]
[add_comm_group V₂] [module k V₂] [add_torsor V₂ P₂] extends P₁ ≃ P₂ :=
(linear : V₁ ≃ₗ[k] V₂)
(map_vadd' : ∀ (p : P₁) (v : V₁), to_equiv (v +ᵥ p) = linear v +ᵥ to_equiv p)
notation P₁ ` ≃ᵃ[`:25 k:25 `] `:0 P₂:0 := affine_equiv k P₁ P₂
variables {k P₁ P₂ P₃ P₄ V₁ V₂ V₃ V₄ : Type*} [ring k]
[add_comm_group V₁] [module k V₁] [add_torsor V₁ P₁]
[add_comm_group V₂] [module k V₂] [add_torsor V₂ P₂]
[add_comm_group V₃] [module k V₃] [add_torsor V₃ P₃]
[add_comm_group V₄] [module k V₄] [add_torsor V₄ P₄]
namespace affine_equiv
include V₁ V₂
instance : has_coe_to_fun (P₁ ≃ᵃ[k] P₂) (λ _, P₁ → P₂) := ⟨λ e, e.to_fun⟩
instance : has_coe (P₁ ≃ᵃ[k] P₂) (P₁ ≃ P₂) := ⟨affine_equiv.to_equiv⟩
variables (k P₁)
omit V₂
/-- Identity map as an `affine_equiv`. -/
@[refl] def refl : P₁ ≃ᵃ[k] P₁ :=
{ to_equiv := equiv.refl P₁,
linear := linear_equiv.refl k V₁,
map_vadd' := λ _ _, rfl }
@[simp] lemma coe_refl : ⇑(refl k P₁) = id := rfl
lemma refl_apply (x : P₁) : refl k P₁ x = x := rfl
@[simp] lemma to_equiv_refl : (refl k P₁).to_equiv = equiv.refl P₁ := rfl
@[simp] lemma linear_refl : (refl k P₁).linear = linear_equiv.refl k V₁ := rfl
variables {k P₁}
include V₂
@[simp] lemma map_vadd (e : P₁ ≃ᵃ[k] P₂) (p : P₁) (v : V₁) : e (v +ᵥ p) = e.linear v +ᵥ e p :=
e.map_vadd' p v
@[simp] lemma coe_to_equiv (e : P₁ ≃ᵃ[k] P₂) : ⇑e.to_equiv = e := rfl
/-- Reinterpret an `affine_equiv` as an `affine_map`. -/
def to_affine_map (e : P₁ ≃ᵃ[k] P₂) : P₁ →ᵃ[k] P₂ := { to_fun := e, .. e }
instance : has_coe (P₁ ≃ᵃ[k] P₂) (P₁ →ᵃ[k] P₂) := ⟨to_affine_map⟩
@[simp] lemma coe_to_affine_map (e : P₁ ≃ᵃ[k] P₂) :
(e.to_affine_map : P₁ → P₂) = (e : P₁ → P₂) :=
rfl
@[simp] lemma to_affine_map_mk (f : P₁ ≃ P₂) (f' : V₁ ≃ₗ[k] V₂) (h) :
to_affine_map (mk f f' h) = ⟨f, f', h⟩ :=
rfl
@[norm_cast, simp] lemma coe_coe (e : P₁ ≃ᵃ[k] P₂) : ((e : P₁ →ᵃ[k] P₂) : P₁ → P₂) = e := rfl
@[simp] lemma linear_to_affine_map (e : P₁ ≃ᵃ[k] P₂) : e.to_affine_map.linear = e.linear := rfl
lemma to_affine_map_injective : injective (to_affine_map : (P₁ ≃ᵃ[k] P₂) → (P₁ →ᵃ[k] P₂)) :=
begin
rintros ⟨e, el, h⟩ ⟨e', el', h'⟩ H,
simp only [to_affine_map_mk, equiv.coe_inj, linear_equiv.to_linear_map_inj] at H,
congr,
exacts [H.1, H.2]
end
@[simp] lemma to_affine_map_inj {e e' : P₁ ≃ᵃ[k] P₂} :
e.to_affine_map = e'.to_affine_map ↔ e = e' :=
to_affine_map_injective.eq_iff
@[ext] lemma ext {e e' : P₁ ≃ᵃ[k] P₂} (h : ∀ x, e x = e' x) : e = e' :=
to_affine_map_injective $ affine_map.ext h
lemma coe_fn_injective : @injective (P₁ ≃ᵃ[k] P₂) (P₁ → P₂) coe_fn :=
λ e e' H, ext $ congr_fun H
@[simp, norm_cast] lemma coe_fn_inj {e e' : P₁ ≃ᵃ[k] P₂} : (e : P₁ → P₂) = e' ↔ e = e' :=
coe_fn_injective.eq_iff
lemma to_equiv_injective : injective (to_equiv : (P₁ ≃ᵃ[k] P₂) → (P₁ ≃ P₂)) :=
λ e e' H, ext $ equiv.ext_iff.1 H
@[simp] lemma to_equiv_inj {e e' : P₁ ≃ᵃ[k] P₂} : e.to_equiv = e'.to_equiv ↔ e = e' :=
to_equiv_injective.eq_iff
@[simp] lemma coe_mk (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (h) :
((⟨e, e', h⟩ : P₁ ≃ᵃ[k] P₂) : P₁ → P₂) = e :=
rfl
/-- Construct an affine equivalence by verifying the relation between the map and its linear part at
one base point. Namely, this function takes a map `e : P₁ → P₂`, a linear equivalence
`e' : V₁ ≃ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have
`e p' = e' (p' -ᵥ p) +ᵥ e p`. -/
def mk' (e : P₁ → P₂) (e' : V₁ ≃ₗ[k] V₂) (p : P₁) (h : ∀ p' : P₁, e p' = e' (p' -ᵥ p) +ᵥ e p) :
P₁ ≃ᵃ[k] P₂ :=
{ to_fun := e,
inv_fun := λ q' : P₂, e'.symm (q' -ᵥ e p) +ᵥ p,
left_inv := λ p', by simp [h p'],
right_inv := λ q', by simp [h (e'.symm (q' -ᵥ e p) +ᵥ p)],
linear := e',
map_vadd' := λ p' v, by { simp [h p', h (v +ᵥ p'), vadd_vsub_assoc, vadd_vadd] } }
@[simp] lemma coe_mk' (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (p h) : ⇑(mk' e e' p h) = e := rfl
@[simp] lemma linear_mk' (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (p h) :
(mk' e e' p h).linear = e' := rfl
/-- Inverse of an affine equivalence as an affine equivalence. -/
@[symm] def symm (e : P₁ ≃ᵃ[k] P₂) : P₂ ≃ᵃ[k] P₁ :=
{ to_equiv := e.to_equiv.symm,
linear := e.linear.symm,
map_vadd' := λ v p, e.to_equiv.symm.apply_eq_iff_eq_symm_apply.2 $
by simpa using (e.to_equiv.apply_symm_apply v).symm }
@[simp] lemma symm_to_equiv (e : P₁ ≃ᵃ[k] P₂) : e.to_equiv.symm = e.symm.to_equiv := rfl
@[simp] lemma symm_linear (e : P₁ ≃ᵃ[k] P₂) : e.linear.symm = e.symm.linear := rfl
/-- See Note [custom simps projection] -/
def simps.apply (e : P₁ ≃ᵃ[k] P₂) : P₁ → P₂ := e
/-- See Note [custom simps projection] -/
def simps.symm_apply (e : P₁ ≃ᵃ[k] P₂) : P₂ → P₁ := e.symm
initialize_simps_projections affine_equiv
(to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, linear → linear as_prefix, -to_equiv)
protected lemma bijective (e : P₁ ≃ᵃ[k] P₂) : bijective e := e.to_equiv.bijective
protected lemma surjective (e : P₁ ≃ᵃ[k] P₂) : surjective e := e.to_equiv.surjective
protected lemma injective (e : P₁ ≃ᵃ[k] P₂) : injective e := e.to_equiv.injective
@[simp] lemma range_eq (e : P₁ ≃ᵃ[k] P₂) : range e = univ := e.surjective.range_eq
@[simp] lemma apply_symm_apply (e : P₁ ≃ᵃ[k] P₂) (p : P₂) : e (e.symm p) = p :=
e.to_equiv.apply_symm_apply p
@[simp] lemma symm_apply_apply (e : P₁ ≃ᵃ[k] P₂) (p : P₁) : e.symm (e p) = p :=
e.to_equiv.symm_apply_apply p
lemma apply_eq_iff_eq_symm_apply (e : P₁ ≃ᵃ[k] P₂) {p₁ p₂} : e p₁ = p₂ ↔ p₁ = e.symm p₂ :=
e.to_equiv.apply_eq_iff_eq_symm_apply
@[simp] lemma apply_eq_iff_eq (e : P₁ ≃ᵃ[k] P₂) {p₁ p₂ : P₁} : e p₁ = e p₂ ↔ p₁ = p₂ :=
e.to_equiv.apply_eq_iff_eq
omit V₂
@[simp] lemma symm_refl : (refl k P₁).symm = refl k P₁ := rfl
include V₂ V₃
/-- Composition of two `affine_equiv`alences, applied left to right. -/
@[trans] def trans (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) : P₁ ≃ᵃ[k] P₃ :=
{ to_equiv := e.to_equiv.trans e'.to_equiv,
linear := e.linear.trans e'.linear,
map_vadd' := λ p v, by simp only [linear_equiv.trans_apply, coe_to_equiv, (∘),
equiv.coe_trans, map_vadd] }
@[simp] lemma coe_trans (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) : ⇑(e.trans e') = e' ∘ e := rfl
lemma trans_apply (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) (p : P₁) : e.trans e' p = e' (e p) := rfl
include V₄
lemma trans_assoc (e₁ : P₁ ≃ᵃ[k] P₂) (e₂ : P₂ ≃ᵃ[k] P₃) (e₃ : P₃ ≃ᵃ[k] P₄) :
(e₁.trans e₂).trans e₃ = e₁.trans (e₂.trans e₃) :=
ext $ λ _, rfl
omit V₃ V₄
@[simp] lemma trans_refl (e : P₁ ≃ᵃ[k] P₂) : e.trans (refl k P₂) = e :=
ext $ λ _, rfl
@[simp] lemma refl_trans (e : P₁ ≃ᵃ[k] P₂) : (refl k P₁).trans e = e :=
ext $ λ _, rfl
@[simp] lemma self_trans_symm (e : P₁ ≃ᵃ[k] P₂) : e.trans e.symm = refl k P₁ :=
ext e.symm_apply_apply
@[simp] lemma symm_trans_self (e : P₁ ≃ᵃ[k] P₂) : e.symm.trans e = refl k P₂ :=
ext e.apply_symm_apply
@[simp] lemma apply_line_map (e : P₁ ≃ᵃ[k] P₂) (a b : P₁) (c : k) :
e (affine_map.line_map a b c) = affine_map.line_map (e a) (e b) c :=
e.to_affine_map.apply_line_map a b c
omit V₂
instance : group (P₁ ≃ᵃ[k] P₁) :=
{ one := refl k P₁,
mul := λ e e', e'.trans e,
inv := symm,
mul_assoc := λ e₁ e₂ e₃, trans_assoc _ _ _,
one_mul := trans_refl,
mul_one := refl_trans,
mul_left_inv := self_trans_symm }
lemma one_def : (1 : P₁ ≃ᵃ[k] P₁) = refl k P₁ := rfl
@[simp] lemma coe_one : ⇑(1 : P₁ ≃ᵃ[k] P₁) = id := rfl
lemma mul_def (e e' : P₁ ≃ᵃ[k] P₁) : e * e' = e'.trans e := rfl
@[simp] lemma coe_mul (e e' : P₁ ≃ᵃ[k] P₁) : ⇑(e * e') = e ∘ e' := rfl
lemma inv_def (e : P₁ ≃ᵃ[k] P₁) : e⁻¹ = e.symm := rfl
/-- `affine_equiv.linear` on automorphisms is a `monoid_hom`. -/
@[simps] def linear_hom : (P₁ ≃ᵃ[k] P₁) →* (V₁ ≃ₗ[k] V₁) :=
{ to_fun := linear,
map_one' := rfl,
map_mul' := λ _ _, rfl }
/-- The group of `affine_equiv`s are equivalent to the group of units of `affine_map`.
This is the affine version of `linear_map.general_linear_group.general_linear_equiv`. -/
@[simps]
def equiv_units_affine_map : (P₁ ≃ᵃ[k] P₁) ≃* (P₁ →ᵃ[k] P₁)ˣ :=
{ to_fun := λ e, ⟨e, e.symm, congr_arg coe e.symm_trans_self, congr_arg coe e.self_trans_symm⟩,
inv_fun := λ u,
{ to_fun := (u : P₁ →ᵃ[k] P₁), inv_fun := (↑(u⁻¹) : P₁ →ᵃ[k] P₁),
left_inv := affine_map.congr_fun u.inv_mul,
right_inv := affine_map.congr_fun u.mul_inv,
linear := linear_map.general_linear_group.general_linear_equiv _ _ $
units.map (by exact affine_map.linear_hom) u,
map_vadd' := λ _ _, (u : P₁ →ᵃ[k] P₁).map_vadd _ _ },
left_inv := λ e, affine_equiv.ext $ λ x, rfl,
right_inv := λ u, units.ext $ affine_map.ext $ λ x, rfl,
map_mul' := λ e₁ e₂, rfl }
variable (k)
/-- The map `v ↦ v +ᵥ b` as an affine equivalence between a module `V` and an affine space `P` with
tangent space `V`. -/
@[simps]
def vadd_const (b : P₁) : V₁ ≃ᵃ[k] P₁ :=
{ to_equiv := equiv.vadd_const b,
linear := linear_equiv.refl _ _,
map_vadd' := λ p v, add_vadd _ _ _ }
/-- `p' ↦ p -ᵥ p'` as an equivalence. -/
def const_vsub (p : P₁) : P₁ ≃ᵃ[k] V₁ :=
{ to_equiv := equiv.const_vsub p,
linear := linear_equiv.neg k,
map_vadd' := λ p' v, by simp [vsub_vadd_eq_vsub_sub, neg_add_eq_sub] }
@[simp] lemma coe_const_vsub (p : P₁) : ⇑(const_vsub k p) = (-ᵥ) p := rfl
@[simp] lemma coe_const_vsub_symm (p : P₁) : ⇑(const_vsub k p).symm = λ v, -v +ᵥ p := rfl
variable (P₁)
/-- The map `p ↦ v +ᵥ p` as an affine automorphism of an affine space. -/
@[simps]
def const_vadd (v : V₁) : P₁ ≃ᵃ[k] P₁ :=
{ to_equiv := equiv.const_vadd P₁ v,
linear := linear_equiv.refl _ _,
map_vadd' := λ p w, vadd_comm _ _ _ }
section homothety
omit V₁
variables {R V P : Type*} [comm_ring R] [add_comm_group V] [module R V] [affine_space V P]
include V
/-- Fixing a point in affine space, homothety about this point gives a group homomorphism from (the
centre of) the units of the scalars into the group of affine equivalences. -/
def homothety_units_mul_hom (p : P) : Rˣ →* P ≃ᵃ[R] P :=
equiv_units_affine_map.symm.to_monoid_hom.comp $ units.map (affine_map.homothety_hom p)
@[simp] lemma coe_homothety_units_mul_hom_apply (p : P) (t : Rˣ) :
(homothety_units_mul_hom p t : P → P) = affine_map.homothety p (t : R) :=
rfl
@[simp] lemma coe_homothety_units_mul_hom_apply_symm (p : P) (t : Rˣ) :
((homothety_units_mul_hom p t).symm : P → P) = affine_map.homothety p (↑t⁻¹ : R) :=
rfl
@[simp] lemma coe_homothety_units_mul_hom_eq_homothety_hom_coe (p : P) :
(coe : (P ≃ᵃ[R] P) → P →ᵃ[R] P) ∘ homothety_units_mul_hom p =
(affine_map.homothety_hom p) ∘ (coe : Rˣ → R) :=
funext $ λ _, rfl
end homothety
variable {P₁}
open function
/-- Point reflection in `x` as a permutation. -/
def point_reflection (x : P₁) : P₁ ≃ᵃ[k] P₁ := (const_vsub k x).trans (vadd_const k x)
lemma point_reflection_apply (x y : P₁) : point_reflection k x y = x -ᵥ y +ᵥ x := rfl
@[simp] lemma point_reflection_symm (x : P₁) : (point_reflection k x).symm = point_reflection k x :=
to_equiv_injective $ equiv.point_reflection_symm x
@[simp] lemma to_equiv_point_reflection (x : P₁) :
(point_reflection k x).to_equiv = equiv.point_reflection x :=
rfl
@[simp] lemma point_reflection_self (x : P₁) : point_reflection k x x = x := vsub_vadd _ _
lemma point_reflection_involutive (x : P₁) : involutive (point_reflection k x : P₁ → P₁) :=
equiv.point_reflection_involutive x
/-- `x` is the only fixed point of `point_reflection x`. This lemma requires
`x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/
lemma point_reflection_fixed_iff_of_injective_bit0 {x y : P₁} (h : injective (bit0 : V₁ → V₁)) :
point_reflection k x y = y ↔ y = x :=
equiv.point_reflection_fixed_iff_of_injective_bit0 h
lemma injective_point_reflection_left_of_injective_bit0 (h : injective (bit0 : V₁ → V₁)) (y : P₁) :
injective (λ x : P₁, point_reflection k x y) :=
equiv.injective_point_reflection_left_of_injective_bit0 h y
lemma injective_point_reflection_left_of_module [invertible (2:k)]:
∀ y, injective (λ x : P₁, point_reflection k x y) :=
injective_point_reflection_left_of_injective_bit0 k $ λ x y h,
by rwa [bit0, bit0, ← two_smul k x, ← two_smul k y,
(is_unit_of_invertible (2:k)).smul_left_cancel] at h
lemma point_reflection_fixed_iff_of_module [invertible (2:k)] {x y : P₁} :
point_reflection k x y = y ↔ y = x :=
((injective_point_reflection_left_of_module k y).eq_iff' (point_reflection_self k y)).trans eq_comm
end affine_equiv
namespace linear_equiv
/-- Interpret a linear equivalence between modules as an affine equivalence. -/
def to_affine_equiv (e : V₁ ≃ₗ[k] V₂) : V₁ ≃ᵃ[k] V₂ :=
{ to_equiv := e.to_equiv,
linear := e,
map_vadd' := λ p v, e.map_add v p }
@[simp] lemma coe_to_affine_equiv (e : V₁ ≃ₗ[k] V₂) : ⇑e.to_affine_equiv = e := rfl
end linear_equiv
namespace affine_map
open affine_equiv
include V₁
lemma line_map_vadd (v v' : V₁) (p : P₁) (c : k) :
line_map v v' c +ᵥ p = line_map (v +ᵥ p) (v' +ᵥ p) c :=
(vadd_const k p).apply_line_map v v' c
lemma line_map_vsub (p₁ p₂ p₃ : P₁) (c : k) :
line_map p₁ p₂ c -ᵥ p₃ = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₃) c :=
(vadd_const k p₃).symm.apply_line_map p₁ p₂ c
lemma vsub_line_map (p₁ p₂ p₃ : P₁) (c : k) :
p₁ -ᵥ line_map p₂ p₃ c = line_map (p₁ -ᵥ p₂) (p₁ -ᵥ p₃) c :=
(const_vsub k p₁).apply_line_map p₂ p₃ c
lemma vadd_line_map (v : V₁) (p₁ p₂ : P₁) (c : k) :
v +ᵥ line_map p₁ p₂ c = line_map (v +ᵥ p₁) (v +ᵥ p₂) c :=
(const_vadd k P₁ v).apply_line_map p₁ p₂ c
variables {R' : Type*} [comm_ring R'] [module R' V₁]
lemma homothety_neg_one_apply (c p : P₁) :
homothety c (-1:R') p = point_reflection R' c p :=
by simp [homothety_apply, point_reflection_apply]
end affine_map
|
a96d462dc3264fdf4c0c7d140117bc7f1cfb8104 | 97c8e5d8aca4afeebb5b335f26a492c53680efc8 | /ground_zero/types/nat.lean | f627b33148ddf2e143555619df042f9ae9fe67f5 | [] | no_license | jfrancese/lean | cf32f0d8d5520b6f0e9d3987deb95841c553c53c | 06e7efaecce4093d97fb5ecc75479df2ef1dbbdb | refs/heads/master | 1,587,915,151,351 | 1,551,012,140,000 | 1,551,012,140,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,401 | lean | import ground_zero.types.coproduct ground_zero.HITs.colimit
open ground_zero.types
namespace ground_zero.types.nat
universes u v w
def encode : ℕ → ℕ + unit
| nat.zero := coproduct.inr unit.star
| (nat.succ n) := coproduct.inl n
def decode : ℕ + unit → ℕ
| (coproduct.inr _) := nat.zero
| (coproduct.inl n) := nat.succ n
theorem closed_nat : ℕ ≃ ℕ + unit := begin
existsi encode, split; existsi decode,
{ intro n, induction n with n ih,
{ simp [decode, encode] },
{ simp at ih, simp, simp [encode, decode] } },
{ intro n, simp, induction n,
{ simp [decode, encode] },
{ induction n, simp [encode, decode] } }
end
theorem equiv_addition {α : Type u} {β : Type v} (γ : Type w)
(e : α ≃ β) : α + γ ≃ β + γ := begin
induction e with f H,
have q := qinv.b2q f H,
cases q with g inv, cases inv with α' β',
simp [equiv.homotopy, function.comp] at α',
simp [equiv.homotopy, function.comp] at β',
let f : α + γ → β + γ := λ x, match x with
| coproduct.inl a := coproduct.inl (f a)
| coproduct.inr c := coproduct.inr c
end,
let g : β + γ → α + γ := λ x, match x with
| coproduct.inl b := coproduct.inl (g b)
| coproduct.inr c := coproduct.inr c
end,
existsi f, split; existsi g,
{ intro x, induction x,
{ simp [g, f],
rw [ground_zero.support.truncation (β' x)],
simp },
{ trivial } },
{ intro x, induction x,
{ simp [f, g],
rw [ground_zero.support.truncation (α' x)],
simp },
{ trivial } }
end
example : ℕ ≃ ℕ + unit + unit := begin
transitivity, exact closed_nat,
apply equiv_addition, exact closed_nat
end
def drop (α : Type) : ℕ → Type
| 0 := α
| (nat.succ n) := coproduct (drop n) unit
theorem nat_plus_unit (n : ℕ) : ℕ ≃ drop ℕ n := begin
induction n with n ih,
{ reflexivity },
{ transitivity,
exact closed_nat,
apply equiv_addition unit ih }
end
abbreviation lift_unit (n : ℕ) : drop unit n → drop unit (n + 1) :=
coproduct.inl
def lift_to_top (x : unit) : Π (n : ℕ), drop unit n
| 0 := x
| (n + 1) := coproduct.inl (lift_to_top n)
def iterated := ground_zero.HITs.colimit (drop unit) lift_unit
def iterated.encode : ℕ → iterated
| 0 := ground_zero.HITs.colimit.inclusion 0 unit.star
| (n + 1) := ground_zero.HITs.colimit.inclusion (n + 1) (coproduct.inr unit.star)
end ground_zero.types.nat |
1cf3d93cf6eb517707393b96a1a734ac040e0ec3 | 75c54c8946bb4203e0aaf196f918424a17b0de99 | /src/collapse.lean | f9650315c316f9aa171ae4ba8db7a30e2f96815f | [
"Apache-2.0"
] | permissive | urkud/flypitch | 261e2a45f1038130178575406df8aea78255ba77 | 2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c | refs/heads/master | 1,653,266,469,246 | 1,577,819,679,000 | 1,577,819,679,000 | 259,862,235 | 1 | 0 | Apache-2.0 | 1,588,147,244,000 | 1,588,147,244,000 | null | UTF-8 | Lean | false | false | 39,141 | lean | import .regular_open_algebra .pSet_ordinal
/-
Defining the collapsing poset/topology/boolean algebra and proving properties about them
-/
universe variables u v
lemma poset_yoneda_iff {β : Type*} [partial_order β] {a b : β} : (∀Γ : β, Γ ≤ a → Γ ≤ b) ↔ a ≤ b :=
⟨ lattice.poset_yoneda, λ h Γ, lattice.poset_yoneda_inv Γ h⟩
lemma poset_coyoneda_iff {β : Type*} [partial_order β] {a b : β} :
(∀Γ : β, a ≤ Γ → b ≤ Γ) ↔ b ≤ a :=
⟨λ h, h a (le_refl a), λ h Γ h', le_trans h h'⟩
namespace set
theorem subset_Inter_iff {α β} {t : set β} {s : α → set β} : t ⊆ (⋂ i, s i) ↔ ∀ i, t ⊆ s i :=
by { simp [subset_def], conv_rhs { rw [forall_swap] }, apply forall_congr, intro x, rw [forall_swap] }
end set
namespace subtype
definition val_eq_coe {α} {p : α → Prop} (x : subtype p) : x.val = x := by refl
end subtype
namespace cardinal -- todo: move
open cardinal set
theorem sum_const_lift (ι : Type u) (a : cardinal.{max u v}) :
sum (λ _:ι, a) = lift.{_ v} (mk ι) * a :=
quotient.induction_on a $ λ α, by simp; exact
quotient.sound ⟨(equiv.sigma_equiv_prod _ _).trans (equiv.prod_congr equiv.ulift.symm (by refl))⟩
theorem sum_le_sup_lift {ι : Type u} (f : ι → cardinal.{max u v}) :
sum f ≤ lift.{_ v} (mk ι) * sup f :=
by rw ← sum_const_lift; exact sum_le_sum _ _ (le_sup _)
-- TODO: replace mk_Union_le_sum_mk
theorem mk_Union_le_sum_mk' {ι : Type u} {α : Type (max u v)} {f : ι → set α} :
mk (set.Union f) ≤ sum (λ i, mk (f i)) :=
calc mk (set.Union f) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.surjective_sigma_to_Union f)
... = sum (λ i, mk (f i)) : (sum_mk _).symm
lemma mk_Union_le_lift {ι : Type u} {α : Type (max u v)} (f : ι → set α) :
mk (set.Union f) ≤ lift.{_ v} (mk ι) * cardinal.sup (λ i, mk (f i)) :=
le_trans mk_Union_le_sum_mk' (sum_le_sup_lift _)
end cardinal
namespace ordinal
open cardinal
theorem sup_lt_ord_lift {ι : Type u} (f : ι → ordinal.{max u v}) {c : ordinal}
(H1 : cardinal.lift.{_ v} (mk ι) < c.cof) (H2 : ∀ i, f i < c) : sup f < c :=
begin
apply lt_of_le_of_ne,
{ rw [sup_le], exact λ i, le_of_lt (H2 i) },
rintro h, apply not_le_of_lt H1,
simpa [sup_ord, H2, h] using cof_sup_le_lift.{u} f
end
theorem sup_lt_lift {ι : Type u} (f : ι → cardinal.{max u v}) {c : cardinal.{max u v}}
(H1 : cardinal.lift.{_ v} (cardinal.mk ι) < c.ord.cof)
(H2 : ∀ i, f i < c) : cardinal.sup f < c :=
by { rw [←ord_lt_ord, ←sup_ord], apply sup_lt_ord_lift _ H1, intro i, rw ord_lt_ord, apply H2 }
end ordinal
namespace topological_space
lemma mem_interior_of_is_topological_basis {α} [topological_space α] {B : set (set α)}
(hB : is_topological_basis B) {s : set α} {x : α} : x ∈ interior s ↔ ∃ t ⊆ s, t ∈ B ∧ x ∈ t :=
begin
rw [mem_interior], split,
{ rintro ⟨t, h1t, h2t, h3t⟩,
rcases mem_basis_subset_of_mem_open hB h3t h2t with ⟨u, h1u, h2u, h3u⟩,
exact ⟨u, set.subset.trans h3u h1t, h1u, h2u⟩ },
{ rintro ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h1t, is_open_of_is_topological_basis hB h2t, h3t⟩ }
end
end topological_space
open lattice topological_space cardinal pSet
noncomputable theory
local notation `ℵ₁` := (card_ex $ aleph 1 : pSet)
local infix ` ⟹ `:65 := lattice.imp
local infix ` ⇔ `:50 := lattice.biimp
local attribute [instance, priority 0] classical.prop_decidable
local prefix `#`:max := cardinal.mk
/- to_mathlib -/
@[simp] lemma iff_or_self_left {p q : Prop} : (p ↔ p ∨ q) ↔ (q → p) :=
⟨ λ h hq, h.2 (or.inr hq), λ h, ⟨or.inl, λ h', h'.elim id h⟩⟩
@[simp] lemma iff_or_self_right {p q : Prop} : (p ↔ q ∨ p) ↔ (q → p) :=
by simp [or.comm]
@[simp] lemma and_iff_self_right {p q : Prop} : (p ∧ q ↔ p) ↔ (p → q) :=
⟨ λ h hp, (h.mpr hp).2, λ h, ⟨and.left, λ hp, ⟨hp, h hp⟩⟩⟩
@[simp] lemma and_iff_self_left {p q : Prop} : (p ∧ q ↔ q) ↔ (q → p) :=
by { rw [and.comm], exact and_iff_self_right }
lemma and_or_and_not {p q r : Prop} : p ∧ (q ∨ (r ∧ ¬ p)) ↔ p ∧ q :=
by simp [and_or_distrib_left, and.comm, and.assoc.symm]
lemma or_and_iff_or {p q r : Prop} : (p ∨ (q ∧ r) ↔ p ∨ q) ↔ (q → p ∨ r) :=
⟨ λ h hq, (h.2 (or.inr hq)).imp id and.right,
λ h, ⟨λ h', h'.imp id and.left, λ h', h'.elim or.inl $ λ hq, (h hq).imp id $ λ hr, ⟨hq, hr⟩⟩⟩
lemma and_or_iff_and {p q r : Prop} : (p ∧ (q ∨ r) ↔ p ∧ r) ↔ (p → q → r) :=
⟨ λ h hp hq, (h.mp ⟨hp, or.inl hq⟩).2,
λ h, ⟨λ h', ⟨h'.1, h'.2.elim (h h'.1) id⟩, and.imp id or.inr⟩⟩
lemma or_not_iff (p q : Prop) [decidable q] : (p ∨ ¬ q) ↔ (q → p) :=
by { rw [imp_iff_not_or, or_comm] }
lemma eq_iff_eq_of_eq_left {α} {x y z : α} (h : x = y) : x = z ↔ y = z :=
by rw [h]
lemma eq_iff_eq_of_eq_right {α} {x y z : α} (h : x = y) : z = x ↔ z = y :=
by rw [h]
namespace roption
variables {α : Type*} {o₁ o₂ : roption α} {x : α}
/-- The intersection of two partial functions -/
def inter (o₁ o₂ : roption α) : roption α :=
⟨ ∃(x : α), x ∈ o₁ ∧ x ∈ o₂,
λ h, o₁.get $ dom_iff_mem.2 $ let ⟨x, h1x, h2x⟩ := h in ⟨x, h1x⟩⟩
instance : has_inter (roption α) := ⟨roption.inter⟩
lemma dom_inter : (o₁ ∩ o₂).dom ↔ ∃(x : α), x ∈ o₁ ∧ x ∈ o₂ := iff.refl _
lemma get_inter (h : ∃(x : α), x ∈ o₁ ∧ x ∈ o₂) :
∃(h' : o₁.dom), (o₁ ∩ o₂).get h = o₁.get h' := ⟨_, rfl⟩
@[simp] lemma mem_inter : x ∈ o₁ ∩ o₂ ↔ x ∈ o₁ ∧ x ∈ o₂ :=
begin
split,
{ intro h, rw [mem_eq] at h, rcases h with ⟨⟨x, h1x, h2x⟩, rfl⟩,
cases get_inter ⟨x, h1x, h2x⟩ with _h h2, rw [h2],
split, { apply get_mem },
rw [mem_eq] at h1x, rw [mem_eq] at h2x, cases h1x with _h2 h1x,
cases h2x with _h3 h2x, rw [h1x, ← h2x], apply get_mem },
{ rintro ⟨h1, h2⟩, use ⟨x, h1, h2⟩,
cases get_inter ⟨x, h1, h2⟩ with _h h3, rw [h3],
rw [mem_eq] at h1, cases h1 with _h2 h1, exact h1 }
end
end roption
namespace pfun
variables {ι : Sort*} {α : Type*} {β : Type*} {f f₁ f₂ : α →. β}
lemma mem_dom_iff_dom (f : α →. β) (x : α) : x ∈ dom f ↔ (f x).dom :=
by simp [dom, set.mem_def]
lemma mem_dom_of_mem {f : α →. β} {x : α} {y : β} (h : y ∈ f x) : x ∈ dom f :=
(mem_dom f x).2 ⟨y, h⟩
lemma some_fn {f : α →. β} {x : α} (h : x ∈ f.dom) : roption.some (f.fn x h) = f x :=
roption.some_get h
lemma fn_mem {f : α →. β} {x : α} (h : x ∈ f.dom) : f.fn x h ∈ f x :=
roption.get_mem h
lemma mem_iff_fn_eq {x : α} {y : β} : y ∈ f x ↔ ∃ h : x ∈ f.dom, f.fn x h = y :=
by refl
lemma fn_eq_iff_mem {x : α} {y : β} (h : x ∈ f.dom) : f.fn x h = y ↔ y ∈ f x :=
by simp [mem_iff_fn_eq, h]
lemma fn_eq_of_mem {x : α} {y : β} (h1 : y ∈ f x) (h2 : x ∈ f.dom) : f.fn x h2 = y :=
(fn_eq_iff_mem h2).2 h1
/- more on lift -/
lemma mem_lift {f : α → β} {x : α} {y : β} : y ∈ (f : α →. β) x ↔ f x = y :=
by simp [eq_comm]
lemma lift_eq_some_iff {f : α → β} {x : α} {y : β} : (f : α →. β) x = roption.some y ↔ f x = y :=
by simp
@[simp] lemma fn_lift (f : α → β) (x : α) : (f : α →. β).fn x trivial = f x :=
by simp [fn_eq_iff_mem]
/-- The empty partial function -/
def empty : α →. β := λ x, roption.none
@[simp] lemma dom_empty : (empty : α →. β).dom = ∅ := rfl
@[simp] lemma empty_def (x : α) : (empty : α →. β) x = none := rfl
lemma not_mem_empty (x : α) (y : β) : y ∉ (pfun.empty : α →. β) x := roption.not_mem_none _
/- Two partial functions are equal if their graphs are equal -/
lemma ext_graph {α β : Type*} (f g : α →. β) (h_graph : f.graph = g.graph) : f = g :=
pfun.ext $ λ _ _, iff_of_eq $ congr_fun h_graph (_,_)
lemma graph_empty_iff_dom_empty {α β : Type*} (f : α →. β) : f.graph = ∅ ↔ f.dom = ∅ :=
begin
have := dom_iff_graph f,
split; intro; ext; safe, exact this _ _ ‹_›
end
/-- A functional graph is a univalent graph -/
def functional {α β : Type*} (Γ : set (α × β)) : Prop :=
∀ a b₁ b₂, (a, b₁) ∈ Γ → (a, b₂) ∈ Γ → b₁ = b₂
lemma congr_arg {α β : Type*} (f : α →. β) : ∀ {x} {y} (h₁ : x ∈ f.dom) (h₂ : y ∈ f.dom)
(h_eq : x = y), fn f x h₁ = fn f y h₂ :=
by intros; congr; assumption
lemma functional_subset {α β : Type*} (Γ Γ': set (α × β)) (h_Γ' : Γ' ⊆ Γ) (h_Γ : functional Γ) : functional Γ' :=
λ _ _ _ _ _, by apply h_Γ; tidy
/-- The graph of a pfun is always functional -/
lemma graph_functional {α β : Type*} (f : α →. β) : functional f.graph := by tidy
/-- Given a partial functional relation, turn it into a pfun -/
noncomputable def of_graph {α β : Type*} (Γ : set (α × β)) (h_Γ : functional Γ) : α →. β :=
λ a, ⟨∃ c ∈ Γ, (prod.fst c) = a, λ h, @prod.snd α β $ (classical.indefinite_description _ h).val⟩
lemma of_graph_property {α β : Type*} (Γ : set $ α × β) (h_Γ : functional Γ) (a : α) (h : ∃ c ∈ Γ, (prod.fst c) = a) : ∃ (H : Γ (classical.indefinite_description _ h)), (classical.indefinite_description _ h).val.fst = a :=
by apply (classical.indefinite_description _ h).property
lemma of_graph_get {α β : Type*} (Γ : set $ α × β) (h_Γ : functional Γ) (a : α) : ∀ h,
(of_graph Γ h_Γ a).get h = (classical.indefinite_description _ h).val.snd :=
by intro; refl
lemma of_graph_val {α β : Type*} (Γ : set $ α × β) (h_Γ : functional Γ) (a : α) (h : ∃ c ∈ Γ, (prod.fst c) = a) (c' ∈ Γ) (h' : c'.1 = a) :
@prod.snd α β (classical.indefinite_description _ h).val = c'.snd :=
begin
let c'', swap, change (prod.snd c'' = c'.snd),
apply h_Γ a, swap, convert H, ext, rwa[h'], refl,
have := (classical.indefinite_description _ h).property,
cases this with this1 this2, rw [<-this2], convert this1, ext; refl
end
@[simp] lemma graph_of_graph {α β : Type*} (Γ : set $ α × β) (h_Γ : functional Γ) : (of_graph Γ h_Γ).graph = Γ :=
begin
ext, rcases x with ⟨a,b⟩, dsimp[graph],
split; intro H, {cases H, induction H_h, cases H_w, cases H_w_h, induction H_w_h_h,
convert H_w_h_w, ext, refl, rw [of_graph_get], apply of_graph_val; try{assumption}; refl},
fsplit, {tidy}, rw [of_graph_get], apply @of_graph_val _ _ Γ _ a _ (a,b) _;
try{assumption}; refl
end
@[simp] lemma of_graph_graph {α β : Type*} {f : α →. β} : of_graph (f.graph) (graph_functional f) = f :=
by apply ext_graph; rw [graph_of_graph]
@[simp] lemma dom_of_graph {α β : Type*} (Γ : set $ α × β) (h_Γ : functional Γ) : (of_graph Γ h_Γ).dom = (prod.fst '' Γ) :=
begin
ext, split; intros, {tidy},
{cases a, cases a_h, cases a_w, induction a_h_right, dsimp at *, fsplit,
work_on_goal 0 { fsplit }, work_on_goal 2 {fsplit,
work_on_goal 0 { assumption }, refl }}
end
@[simp] lemma dom_of_graph_union {α β : Type*} (Γ : set $ α × β) (p : α × β) (h_Γ : functional Γ) (h_Γ' : functional $ Γ ∪ {p}) : (of_graph (Γ ∪ {p}) h_Γ').dom = (of_graph Γ h_Γ).dom ∪ {p.fst} :=
by simp[dom_of_graph, set.image_insert_eq]
lemma in_dom_of_in_graph {α β : Type*} {f : α →. β} : ∀ {a} {b}, (a,b) ∈ f.graph → a ∈ f.dom :=
by {intros a b H, apply (pfun.dom_iff_graph _ a).mpr, exact ⟨b,H⟩}
lemma lift_graph' {α β : Type*} {f : α →. β} {a : α} {b : β} (h_a : a ∈ f.dom) : (a,b) ∈ f.graph ↔ pfun.fn f a h_a = b := by tidy
/-- The intersection of two partial functions -/
def inter (f₁ f₂ : α →. β) : α →. β :=
λ x, f₁ x ∩ f₂ x
instance : has_inter (α →. β) := ⟨pfun.inter⟩
@[simp] lemma mem_inter {x : α} {y : β} : y ∈ (f₁ ∩ f₂) x ↔ y ∈ f₁ x ∧ y ∈ f₂ x :=
roption.mem_inter
/-- f₁ is a subset, or subfunction of f₂: if `f₁ x = some y` then `f₂ x = some y` -/
def subfun (f₁ f₂ : α →. β) : Prop := ∀ x y, y ∈ f₁ x → y ∈ f₂ x
instance : partial_order (α →. β) :=
{ le := subfun,
le_refl := λ f x y hy, hy,
le_trans := λ f g h hfg hgh x y hy, hgh x y (hfg x y hy),
le_antisymm := λ f g h1 h2, pfun.ext $ λ x y, ⟨h1 x y, h2 x y⟩ }
instance : semilattice_inf_bot (α →. β) :=
{ le := subfun,
le_refl := λ f x y hy, hy,
le_trans := λ f g h hfg hgh x y hy, hgh x y (hfg x y hy),
le_antisymm := λ f g h1 h2, pfun.ext $ λ x y, ⟨h1 x y, h2 x y⟩,
bot := pfun.empty,
bot_le := λ f x y hy, false.elim $ roption.not_mem_none y hy,
inf := pfun.inter,
inf_le_left := λ f g x y hy, (mem_inter.1 hy).1,
inf_le_right := λ f g x y hy, (mem_inter.1 hy).2,
le_inf := λ f g h hfg hfh x y hf, mem_inter.2 ⟨hfg x y hf, hfh x y hf⟩ }
lemma le_def : f₁ ≤ f₂ ↔ ∀ x y, y ∈ f₁ x → y ∈ f₂ x := by refl
lemma dom_subset_dom_of_le (h : f₁ ≤ f₂) : f₁.dom ⊆ f₂.dom :=
λ x hx, mem_dom_of_mem (h x (f₁.fn x hx) (fn_mem hx))
lemma eq_some_of_subfun (h : f₁ ≤ f₂) {x : α} {y : β} (h1 : f₁ x = roption.some y) :
f₂ x = roption.some y :=
by { rw [roption.eq_some_iff] at h1 ⊢, exact h x y h1 }
lemma fn_eq_of_subfun (h : f₁ ≤ f₂) {x : α} {y : β} (h1 : x ∈ f₁.dom)
(h2 : f₁.fn x h1 = y) (h3 : x ∈ f₂.dom) : f₂.fn x h3 = y :=
by { apply fn_eq_of_mem, apply h, rw [mem_iff_fn_eq], exact ⟨h1, h2⟩ }
lemma le_lift {f : α →. β} {g : α → β} : f ≤ (g : α →. β) ↔ ∀ x y, y ∈ f x → g x = y :=
by simp [le_def, eq_comm]
/-- Two functions are compatible if they agree on the intersection of their domains. -/
def compatible (f₁ f₂ : α →. β) : Prop :=
∀(x : α), x ∈ f₁.dom → x ∈ f₂.dom → f₁ x = f₂ x
lemma compatible_def : compatible f₁ f₂ ↔ ∀(x : α), x ∈ f₁.dom → x ∈ f₂.dom → f₁ x = f₂ x :=
by refl
lemma mem_of_compatible (h : compatible f₁ f₂) {x : α} {y : β} (h1 : y ∈ f₁ x) (h2 : x ∈ f₂.dom) :
y ∈ f₂ x :=
by { convert h1, symmetry, exact h x (mem_dom_of_mem h1) h2 }
@[refl] lemma compatible_refl : compatible f f := λ x h1x h2x, rfl
lemma compatible_comm : compatible f₁ f₂ ↔ compatible f₂ f₁ :=
by { simp [compatible_def, eq_comm, imp.swap] }
lemma compatible_of_le (h : f₁ ≤ f₂) : compatible f₁ f₂ :=
begin
intros x h1x h2x, apply roption.ext, intro y, split; intro hy, exact h x y hy,
have := h x (f₁.fn x h1x) (fn_mem h1x),
convert fn_mem h1x,
rw [← roption.some_inj, ← roption.eq_some_iff.2 hy, ← roption.eq_some_iff.2 this]
end
/-- The sup of two functions f₁ and f₂. Corresponds to the set-theoretic union of f₁ and f₂ as
long as f₁ and f₂ are compatible. If they are not compatible, the values of f₁ are chosen when
both functions are defined. We use classical logic, so that we can define a has_sup instance
(otherwise we would need to assume that `f₁.dom` is decidable). -/
def sup (f₁ f₂ : α →. β) : α →. β :=
λ a, if a ∈ f₁.dom then f₁ a else f₂ a
instance : has_sup (α →. β) := ⟨pfun.sup⟩
@[simp] lemma sup_eq_of_mem {x : α} (h : x ∈ f₁.dom) : (f₁ ⊔ f₂) x = f₁ x :=
by { dsimp [pfun.lattice.has_sup, pfun.sup], simp [h] }
@[simp] lemma sup_eq_of_nmem {x : α} (h : x ∉ f₁.dom) : (f₁ ⊔ f₂) x = f₂ x :=
by { dsimp [pfun.lattice.has_sup, pfun.sup], simp [h] }
@[simp] lemma dom_sup (f₁ f₂ : α →. β) : (f₁ ⊔ f₂).dom = f₁.dom ∪ f₂.dom :=
by { ext x, by_cases hx : x ∈ f₁.dom; simp [mem_dom_iff_dom] at hx; simp [mem_dom_iff_dom, hx] }
lemma subset_dom_sup_left (f₁ f₂ : α →. β) : f₁.dom ⊆ (f₁ ⊔ f₂).dom := by simp
lemma subset_dom_sup_right (f₁ f₂ : α →. β) : f₂.dom ⊆ (f₁ ⊔ f₂).dom := by simp
lemma mem_sup {x : α} {y : β} : y ∈ (f₁ ⊔ f₂) x ↔ y ∈ f₁ x ∨ (y ∈ f₂ x ∧ x ∉ f₁.dom) :=
begin
by_cases hx : x ∈ f₁.dom, { simp [hx] },
have := hx, rw [mem_dom] at this, push_neg at this, simp [hx, this]
end
lemma mem_sup_of_compatible {x : α} {y : β} (h : compatible f₁ f₂) :
y ∈ (f₁ ⊔ f₂) x ↔ y ∈ f₁ x ∨ y ∈ f₂ x :=
begin
rw [mem_sup, or_and_iff_or, or_not_iff],
intros hy hx, convert hy, exact h x hx (mem_dom_of_mem hy),
end
lemma sup_restrict_left {f₁ f₂ : α →. β} :
(f₁ ⊔ f₂).restrict (subset_dom_sup_left f₁ f₂) = f₁ :=
begin
apply pfun.ext, intros x y, simp [mem_sup, and_or_and_not],
show y ∈ f₁ x → x ∈ dom f₁, rw [mem_dom], intro hy, exact ⟨y, hy⟩
end
lemma sup_restrict_right {f₁ f₂ : α →. β} (h : compatible f₁ f₂) :
(f₁ ⊔ f₂).restrict (subset_dom_sup_right f₁ f₂) = f₂ :=
begin
apply pfun.ext, intros x y, simp [mem_sup_of_compatible h],
rw [and_or_iff_and.2, and_iff_self_left], apply mem_dom_of_mem,
intros hx hy, convert hy, symmetry, exact h x (mem_dom_of_mem hy) hx
end
lemma le_sup_left (f₁ f₂ : α →. β) : f₁ ≤ f₁ ⊔ f₂ :=
by { intros x y hy, rw [mem_sup], exact or.inl hy }
lemma le_sup_right (h : compatible f₁ f₂) : f₂ ≤ f₁ ⊔ f₂ :=
by { intros x y hy, rw [mem_sup_of_compatible h], exact or.inr hy }
/-- The indexed sup of a family of partial functions. This corresponds to the set-theoretic union
if the functions are pairwise compatible. Otherwise, the value of a function will be chosen using
classical.some. -/
def Sup (f : ι → α →. β) : α →. β :=
λ x, if h : ∃ i, x ∈ dom (f i) then f (classical.some h) x else roption.none
-- TODO: define Sup instance
lemma Sup_helper {f : ι → α →. β} {x : α} :
(∃i, x ∈ (f i).dom) ↔ (∃i, x ∈ (f i).dom ∧ Sup f x = f i x) :=
⟨λ h, ⟨classical.some h, classical.some_spec h, dif_pos h⟩, λ⟨i, h, _⟩, ⟨i, h⟩⟩
lemma Sup_helper2 {f : ι → α →. β} {x : α} :
(∃i, x ∈ (f i).dom) ↔ (∃i (h : x ∈ (f i).dom), Sup f x = roption.some ((f i).fn x h)) :=
begin
rw [Sup_helper], apply exists_congr, intro i,
rw [← exists_prop], apply exists_congr, intro hi,
apply eq_iff_eq_of_eq_right, rw [some_fn hi]
end
@[simp] lemma dom_Sup (f : ι → α →. β) : (Sup f).dom = set.Union (λ (i : ι), (f i).dom) :=
begin
ext x, rw [set.mem_Union], by_cases hx : ∃i, x ∈ (f i).dom,
{ simp only [hx, iff_true], rw [Sup_helper2] at hx, rcases hx with ⟨i, hx, h⟩,
rw [mem_dom_iff_dom, h], trivial },
{ simp only [hx, iff_false], rw [mem_dom_iff_dom], dsimp [Sup], rw [dif_neg hx], exact id }
end
lemma subset_dom_Sup (f : ι → α →. β) (i : ι) : (f i).dom ⊆ (Sup f).dom :=
by { rw [dom_Sup], apply set.subset_Union (λ i, (f i).dom) }
lemma Sup_eq_of_mem {f : ι → α →. β} {x : α} {i : ι} (hf : ∀i j, compatible (f i) (f j))
(h : x ∈ (f i).dom) : Sup f x = f i x :=
begin
have : ∃ i, x ∈ (f i).dom := ⟨i, h⟩, rw [Sup_helper] at this, rcases this with ⟨j, hj, h2j⟩,
rw [h2j], exact hf j i x hj h
end
lemma Sup_eq_of_nmem {f : ι → α →. β} {x : α} (h : ∀ i, x ∉ (f i).dom) :
Sup f x = roption.none :=
by { dsimp [pfun.Sup], simp [h] }
lemma mem_Sup {f : ι → α →. β} {x : α} {y : β} (hf : ∀i j, compatible (f i) (f j)) :
y ∈ Sup f x ↔ ∃ i, y ∈ f i x :=
begin
split,
{ intro hy, have := mem_dom_of_mem hy, rw [dom_Sup, set.mem_Union] at this,
cases this with i hi, use i, rwa [Sup_eq_of_mem hf hi] at hy },
{ rintro ⟨i, hi⟩, rwa [Sup_eq_of_mem hf (mem_dom_of_mem hi)] }
end
lemma Sup_restrict {f : ι → α →. β} (hf : ∀i j, compatible (f i) (f j)) (i : ι) :
(Sup f).restrict (subset_dom_Sup f i) = f i :=
begin
apply pfun.ext, intros x y, simp [mem_Sup hf],
split,
{ rintro ⟨hx, j, hj⟩, exact mem_of_compatible (hf j i) hj hx },
{ intro hy, exact ⟨mem_dom_of_mem hy, i, hy⟩ }
end
lemma le_Sup {f : ι → α →. β} (hf : ∀i j, compatible (f i) (f j)) (i : ι) : f i ≤ Sup f :=
by { intros x y hy, rw [mem_Sup hf], exact ⟨i, hy⟩ }
lemma Sup_le {f : ι → α →. β} (hf : ∀i j, compatible (f i) (f j))
{g : α →. β} : Sup f ≤ g ↔ ∀i, f i ≤ g :=
begin
simp only [le_def, mem_Sup hf, exists_imp_distrib],
conv_rhs { rw [forall_swap] }, apply forall_congr, intro x, rw [forall_swap]
end
lemma fn_mem_ran {X Y} {f : X →. Y} {x : X} {Hx : x ∈ f.dom} :
(fn f x Hx) ∈ f.ran :=
by use x; tidy
lemma mk_ran_le_mk_dom {α β : Type u} (f : α →. β) : # f.ran ≤ # f.dom :=
begin
refine mk_le_of_surjective _,
{ exact λ ⟨x,H⟩, ⟨fn f x H, by apply fn_mem_ran⟩},
{ intros y, by_contra, push_neg at a,
/- `tidy` says -/ cases y, cases y_property, cases y_property_h,
induction y_property_h_h, simp at *, dsimp at *,
specialize a ‹_› ‹_›, finish }
end
/-- A partial function with one element in its domain.
Note, this is a component of `pequiv.single` in a newer version of mathlib
-/
def singleton (x : α) (y : β) : α →. β :=
λ a, { dom := a = x, get := λ _, y }
@[simp] lemma fn_singleton {x x' : α} {y : β} (H_a : x' = x) :
fn (singleton x y) x' H_a = y := by refl
@[simp] lemma mem_singleton {x x' : α} {y y' : β} :
y' ∈ singleton x y x' ↔ x = x' ∧ y = y' :=
begin
split,
{ intro h, rw [roption.mem_eq] at h, rcases h with ⟨h, rfl⟩, exact ⟨h.symm, rfl⟩ },
{ rintro ⟨rfl, rfl⟩, exact ⟨rfl, rfl⟩ }
end
@[simp] lemma singleton_eq_some {x : α} {y : β} : singleton x y x = roption.some y :=
by simp [roption.eq_some_iff]
@[simp] lemma dom_singleton {x : α} {y : β} : (singleton x y).dom = {x} :=
by { ext x', simp [singleton, mem_dom_iff_dom] }
lemma mk_dom_singleton {x : α} {y : β} : # (singleton x y).dom = 1 := by simp
/-- Extend `f` using `g` for all values where `f` is undefined -/
noncomputable def extend_via (f : α →. β) (g : α → β) : α → β :=
λ x, if hx : x ∈ f.dom then f.fn x hx else g x
lemma extend_via_pos {f : α →. β} {g : α → β} {x : α} (h : x ∈ f.dom) :
extend_via f g x = f.fn x h :=
by simp [h, extend_via]
lemma extend_via_neg {f : α →. β} {g : α → β} {x : α} (h : x ∉ f.dom) :
extend_via f g x = g x :=
by simp [h, extend_via]
lemma le_extend_via (f : α →. β) (g : α → β) : f ≤ ↑(extend_via f g) :=
λ x y hy, by { simp [mem_dom_of_mem hy, extend_via], symmetry, rwa [fn_eq_iff_mem] }
/--
Given a partial function f : X →. Y and a point y : Y, define an extension g of f to X such that g(x) = y whenever x ∉ f.dom
-/
noncomputable def trivial_extension (f : α →. β) (y : β) : α → β :=
extend_via f (λ _, y)
lemma trivial_extension_pos {f : α →. β} {y : β} {x : α} (h : x ∈ f.dom) :
trivial_extension f y x = f.fn x h :=
extend_via_pos h
lemma trivial_extension_neg {f : α →. β} {y : β} {x : α} (h : x ∉ f.dom) :
trivial_extension f y x = y :=
extend_via_neg h
lemma le_trivial_extension (f : α →. β) (y : β) : f ≤ ↑(trivial_extension f y) :=
le_extend_via _ _
end pfun
section collapse_poset
structure collapse_poset (X Y : Type u) (κ : cardinal.{u}) : Type u :=
(f : X →. Y)
(Hc : #f.dom < κ)
def collapse_poset.empty {α β : Type u} {κ : cardinal} (h : 0 < κ) : collapse_poset α β κ :=
{ f := pfun.empty,
Hc := by simp [h] }
open pfun
variables {X Y : Type u} {κ : cardinal.{u}}
lemma collapse_poset.mk_ran_lt (p : collapse_poset X Y κ) : # p.f.ran < κ :=
lt_of_le_of_lt (mk_ran_le_mk_dom p.f) p.Hc
def collapse_poset.inter (p₁ p₂ : collapse_poset X Y κ) : collapse_poset X Y κ :=
{ f := p₁.f ⊓ p₂.f,
Hc := lt_of_le_of_lt (mk_le_mk_of_subset $ dom_subset_dom_of_le inf_le_left) p₁.Hc }
noncomputable def collapse_poset.union (p₁ p₂ : collapse_poset X Y κ) (h : omega ≤ κ) :
collapse_poset X Y κ :=
{ f := p₁.f ⊔ p₂.f,
Hc := by { rw [dom_sup],
exact lt_of_le_of_lt cardinal.mk_union_le (cardinal.add_lt_of_lt h p₁.Hc p₂.Hc) } }
lemma exists_mem_compl_dom_of_unctbl (p : collapse_poset X Y κ) (H_card : κ ≤ #X) :
∃ x : X, x ∉ p.f.dom :=
exists_mem_compl_of_mk_lt_mk _ $ lt_of_lt_of_le p.Hc H_card
lemma exists_mem_compl_ran_of_unctbl (p : collapse_poset X Y κ) (H_card : κ ≤ #Y) :
∃ y : Y, y ∉ p.f.ran :=
exists_mem_compl_of_mk_lt_mk _ $ lt_of_lt_of_le (collapse_poset.mk_ran_lt p) H_card
def collapse_poset.principal_open (p : collapse_poset X Y κ) : set (X → Y) :=
{f | p.f ≤ (f : X →. Y)}
@[simp] lemma collapse_poset.principal_open_empty (h : 0 < κ) :
collapse_poset.principal_open (collapse_poset.empty h : collapse_poset X Y κ) = set.univ :=
begin
ext f, split; intro H,
{ trivial },
{ tidy }
end
lemma mem_principal_open_iff {p : collapse_poset X Y κ} {f : X → Y} :
f ∈ collapse_poset.principal_open p ↔ ∀ x y, y ∈ p.f x → f x = y :=
le_lift
lemma mem_principal_open_iff' {p : collapse_poset X Y κ} {f : X → Y} :
f ∈ collapse_poset.principal_open p ↔ ∀ (x : X) (H_x : x ∈ p.f.dom), f x = fn p.f x H_x :=
begin
rw [mem_principal_open_iff], apply forall_congr, intro x,
split,
{ intros H Hx, apply H, apply fn_mem },
{ intros H y hy, rw [H $ mem_dom_of_mem hy], apply fn_eq_of_mem hy }
end
lemma mem_compl_principal_open_iff {p : collapse_poset X Y κ} {f : X → Y} :
f ∈ - collapse_poset.principal_open p ↔ ∃x (H_x : x ∈ p.f.dom), f x ≠ fn p.f x H_x :=
by { rw [set.mem_compl_iff, mem_principal_open_iff'], push_neg }
@[simp] lemma mem_ran_of_mem_dom {p : collapse_poset X Y κ} {f : X → Y} {x : X}
(H : f ∈ collapse_poset.principal_open p) : x ∈ p.f.dom → f x ∈ p.f.ran :=
by { intro H_mem, rw [mem_principal_open_iff] at H,
use x, rw [H x (p.f.fn x H_mem) (fn_mem _)], exact roption.get_mem H_mem }
def collapse_poset.Sup {ι : Type u} (p : ι → collapse_poset X Y κ) (h : #ι < (ord κ).cof)
(hκ : cardinal.omega ≤ κ) : collapse_poset X Y κ :=
⟨Sup $ λ i, (p i).f,
begin
rw [dom_Sup], apply lt_of_le_of_lt (mk_Union_le _) _,
apply mul_lt_of_lt hκ (lt_of_lt_of_le h (ordinal.cof_ord_le κ)),
exact ordinal.sup_lt _ h (λ i, collapse_poset.Hc _)
end⟩
def collapse_poset.Sup_lift {ι : Type u} {X Y : Type (max u v)} {κ : cardinal.{max u v}}
(p : ι → collapse_poset X Y κ)
(h : cardinal.lift.{_ v} #ι < (ord κ).cof)
(hκ : cardinal.omega ≤ κ) : collapse_poset X Y κ :=
⟨Sup $ λ i, (p i).f,
begin
rw [dom_Sup], apply lt_of_le_of_lt (mk_Union_le_lift.{u v} _) _,
apply mul_lt_of_lt hκ (lt_of_lt_of_le h (ordinal.cof_ord_le κ)),
refine ordinal.sup_lt_lift _ h (λ i, collapse_poset.Hc _)
end⟩
def collapse_space : topological_space (X → Y) :=
generate_from $
(collapse_poset.principal_open : collapse_poset X Y cardinal.omega.succ → set (X → Y)) '' set.univ
local attribute [instance, priority 9001, reducible] collapse_space
@[simp] lemma collapse_poset.principal_open_is_open {p : collapse_poset X Y cardinal.omega.succ} :
is_open (collapse_poset.principal_open p) :=
generate_open.basic _ $ set.mem_image_of_mem _ trivial
lemma one_lt_omega_succ : 1 < cardinal.omega.succ :=
lt_trans one_lt_omega (cardinal.lt_succ_self _)
lemma zero_lt_omega_succ : 0 < cardinal.omega.succ :=
lt_trans cardinal.zero_lt_one one_lt_omega_succ
open collapse_poset
def singleton_collapse_poset (x : X) (y : Y) (hκ : 1 < κ) : collapse_poset X Y κ :=
{ f := singleton x y,
Hc := by simp [hκ] }
@[simp] lemma singleton_collapse_poset_principal_open {x : X} {y : Y} {hκ : 1 < κ} :
principal_open (singleton_collapse_poset x y hκ) = {g : X → Y | g x = y} :=
begin
ext f, refine ⟨_,_⟩; intro H,
{ rw mem_principal_open_iff at H,
apply H, finish[singleton_collapse_poset] },
{ tidy }
end
lemma collapse_poset.compl_principal_open_is_Union (hκ : 1 < κ) (p : collapse_poset X Y κ) :
∃ {ι : Type u} (s : ι → collapse_poset X Y κ),
set.Union (λ i : ι, principal_open $ s i) = - principal_open p :=
begin
use {pr : X × Y // ∃ H_mem : pr.1 ∈ p.f.dom, pr.2 ≠ fn p.f pr.1 H_mem },
use (λ s, singleton_collapse_poset s.1.1 s.1.2 hκ),
ext f, split; intro H,
{ intro H_mem,
rcases H with ⟨P, ⟨⟨⟨x',y'⟩, ⟨H_mem₁, H_neq⟩⟩, rfl⟩, H_mem₂⟩,
dsimp at H_neq H_mem₂,
apply H_neq,
rw [← show f x' = y', by simpa using H_mem₂],
rw mem_principal_open_iff'.mp H_mem _ _ },
{ rw [mem_compl_principal_open_iff] at H, rcases H with ⟨x, Hx, H_neq⟩,
suffices this : ∃ (a : X) (H_mem : (a, f a).fst ∈ dom (p.f)), ¬f a = fn (p.f) a H_mem,
{ simp [this] },
exact ⟨_, by use ‹_›⟩ }
end
@[simp] lemma collapse_poset.principal_open_is_closed {p : collapse_poset X Y cardinal.omega.succ} :
is_closed (collapse_poset.principal_open p) :=
by { rcases collapse_poset.compl_principal_open_is_Union one_lt_omega_succ p with ⟨ι, ⟨s, Hu⟩⟩,
rw [is_closed, ← Hu], simp [is_open_Union] }
@[simp] lemma collapse_poset.is_regular_principal_open
(p : collapse_poset X Y cardinal.omega.succ) : is_regular (collapse_poset.principal_open p) :=
by simp [is_clopen]
lemma inter_principal_open (hκ : omega ≤ κ) {p₁ p₂ : collapse_poset X Y κ}
(H : compatible p₁.f p₂.f) :
principal_open p₁ ∩ principal_open p₂ = principal_open (p₁.union p₂ hκ) :=
begin
ext f,
simp [mem_principal_open_iff],
rw [← forall_and_distrib], apply forall_congr, intro x,
rw [← forall_and_distrib], apply forall_congr, intro y,
rw [union, mem_sup_of_compatible H, or_imp_distrib]
end
variables (X Y)
def collapse_space_basis : set $ set (X → Y) :=
insert (∅ : set (X → Y))
(collapse_poset.principal_open '' (set.univ : set (collapse_poset X Y cardinal.omega.succ)))
variables {X Y}
def collapse_space_basis_spec : is_topological_basis (collapse_space_basis X Y) :=
begin
refine ⟨λ P HP P' HP' f H_mem_inter, _,_,_⟩,
{ rw [collapse_space_basis] at HP HP',
cases HP; cases HP',
{ suffices this : f ∈ (∅ : set $ X → Y),
by {cases this}, substs HP, cases H_mem_inter, exact ‹_› },
{ suffices this : f ∈ (∅ : set $ X → Y),
by {cases this}, substs HP, cases H_mem_inter, exact ‹_› },
{ suffices this : f ∈ (∅ : set $ X → Y),
by {cases this}, substs HP', cases H_mem_inter, exact ‹_› },
simp only [set.image_univ, set.mem_range] at HP HP',
cases HP with y Hy; cases HP' with y' Hy',
substs Hy Hy', use (principal_open y ∩ principal_open y'),
refine ⟨_,⟨‹_›,(by refl)⟩⟩,
{ by_cases H_compat : compatible y.f y'.f,
{ right, refine ⟨_,⟨trivial, _⟩⟩, exact y.union y' (le_of_lt (lt_succ_self _)),
rwa [inter_principal_open] },
{ suffices this : principal_open y ∩ principal_open y' = ∅,
by {rw [this], exact or.inl rfl },
ext g; split; intro H,
{ exfalso, cases H with H₁ H₂, rw [mem_principal_open_iff] at H₁ H₂,
rw [compatible] at H_compat,
push_neg at H_compat, rcases H_compat with ⟨x, Hx₁, Hx₂, Hx₃⟩,
apply Hx₃, rw [← some_fn Hx₁, ← some_fn Hx₂],
rw [← H₁ x _ (fn_mem Hx₁), ← H₂ x _ (fn_mem Hx₂)] },
{ cases H }}}},
{ refine le_antisymm (λ _ _, trivial) _,
intros f _a, refine ⟨_,_⟩,
{ exact (principal_open (collapse_poset.empty zero_lt_omega_succ)) },
{ refine ⟨by {rw [collapse_space_basis], right, exact set.mem_image_univ},_⟩, simp }},
{ unfold collapse_space_basis collapse_space, refine le_antisymm _ _,
{ intros T HT, induction HT,
{ cases HT_H, subst HT_H, exact is_open_empty, constructor, exact ‹_› },
{ exact is_open_univ },
{ apply generate_open.inter, exact ‹_›, exact ‹_› },
{ apply generate_open.sUnion, intros S HS, solve_by_elim }},
{ refine generate_from_mono _, exact λ _ _, or.inr ‹_› }}
end
@[simp] lemma is_regular_singleton_regular_open {x : X} {y : Y} :
is_regular (principal_open (singleton_collapse_poset x y one_lt_omega_succ)) :=
collapse_poset.is_regular_principal_open _
@[simp] lemma is_regular_singleton_regular_open' {x : X} {y : Y} :
is_regular {g : X → Y | g x = y} :=
by {rw [<-singleton_collapse_poset_principal_open], exact is_regular_singleton_regular_open}
lemma trivial_extension_mem_principal_open {p : collapse_poset X Y κ} {y : Y}
: (trivial_extension p.f y) ∈ collapse_poset.principal_open p :=
by { rw [mem_principal_open_iff],
intros x y hy, simp [trivial_extension_pos, mem_dom_of_mem hy, fn_eq_of_mem hy] }
end collapse_poset
section omega_closed_dense_subset
variables {α : Type*} [nontrivial_complete_boolean_algebra α]
-- any ω-indexed downward chain in D has an intersection in D
def omega_closed (D : set α) : Prop :=
∀ (s : ℕ → α) (s_sub_D : ∀n, s n ∈ D) (H_nonzero : ∀ n, ⊥ < s n) (H_chain : ∀ n, s (n+1) ≤ s n), (⨅n, s n) ∈ D
def dense_subset {α : Type*} [order_bot α] (D : set α) : Prop :=
⊥ ∉ D ∧ ∀x, ⊥ < x → ∃ y ∈ D, y ≤ x
@[reducible]def dense_omega_closed_subset (D : set α) : Prop :=
dense_subset D ∧ omega_closed D
variable (α)
def has_dense_omega_closed_subset : Prop :=
∃ D : set α, dense_omega_closed_subset D
variable {α}
lemma nonzero_of_mem_dense_omega_closed_subset {x : α} {D : set α} (H : dense_omega_closed_subset D) (H_mem : x ∈ D) : ⊥ < x :=
by {have := H.left.left, by_contra H', finish [le_bot_iff_not_bot_lt]}
lemma nonzero_infi_of_mem_dense_omega_closed_subset {s : ℕ → α} {D : set α} (H : dense_omega_closed_subset D) (H_chain : ∀ n, s (n + 1) ≤ s n) (H_mem : ∀ n, s n ∈ D) : ⊥ < ⨅ n, s n :=
begin
apply nonzero_of_mem_dense_omega_closed_subset H, refine H.right s ‹_› _ ‹_›,
intro n, specialize H_mem n, from nonzero_of_mem_dense_omega_closed_subset H ‹_›
end
end omega_closed_dense_subset
local attribute [instance, priority 9000] collapse_space
section collapse_algebra
variables X Y : Type u
def collapse_algebra : Type* := @regular_opens (X → Y) collapse_space
variables {X Y}
@[instance, priority 9001] def collapse_algebra_boolean_algebra [nonempty (X → Y)] : nontrivial_complete_boolean_algebra (collapse_algebra X Y) :=
regular_open_algebra
end collapse_algebra
section collapse_poset_dense
variables {X Y : Type u}
def collapse_poset.inclusion (p : collapse_poset X Y cardinal.omega.succ) :
collapse_algebra X Y :=
⟨collapse_poset.principal_open p, collapse_poset.is_regular_principal_open p⟩
local notation `ι`:65 := collapse_poset.inclusion
lemma collapse_poset_dense_basis : ∀ T ∈ collapse_space_basis X Y,
∀ h_nonempty : T ≠ ∅, ∃ p : collapse_poset X Y cardinal.omega.succ, (ι p).val ⊆ T :=
begin
intros T H_mem_basis _,
refine or.elim H_mem_basis (λ _, (false.elim (absurd ‹T = ∅› ‹_›))) (λ H, _),
rcases H with ⟨_,⟨_,H₂⟩⟩, exact ⟨‹_›, by simp[H₂, collapse_poset.inclusion]⟩
end
lemma collapse_poset_dense [nonempty (X → Y)] {b : collapse_algebra X Y}
(H : ⊥ < b) : ∃ p : collapse_poset X Y cardinal.omega.succ, ι p ≤ b :=
begin
cases (classical.choice (classical.nonempty_of_not_empty _ H.right.symm)) with S_wit H_wit,
change ∃ p, (ι p).val ⊆ b.val,
have := mem_basis_subset_of_mem_open collapse_space_basis_spec H_wit (is_open_of_is_regular b.property),
rcases (mem_basis_subset_of_mem_open
collapse_space_basis_spec H_wit (is_open_of_is_regular b.property))
with ⟨v, Hv₁, Hv₂, Hv₃⟩,
have : v ≠ ∅, by {intro H, rw [H] at Hv₂, cases Hv₂},
cases (collapse_poset_dense_basis ‹_› ‹_› ‹_›) with p H_p, exact ⟨p, set.subset.trans H_p ‹_›⟩
end
/- note: the hypothesis in this lemma almost always implies that q.f ≤ p.f, except when `Y` is a singleton -/
def compatible_of_inclusion_le_inclusion [nonempty $ X → Y]
{p q : collapse_poset X Y cardinal.omega.succ} (h : ι p ≤ ι q) : p.f.compatible q.f :=
begin
simp [collapse_poset.inclusion, le_iff_subset, collapse_poset.principal_open] at h,
intros x px qx,
have := h _ (pfun.le_trivial_extension p.f (p.f.fn x px)) x (q.f.fn x qx) (pfun.fn_mem _),
simp [pfun.trivial_extension_pos px] at this,
rw [← pfun.some_fn px, ← pfun.some_fn qx, this]
end
local postfix `ᵖ`:80 := perp
lemma principal_open_eq_infi_of_eq_inter [nonempty $ X → Y] {I : Type*} {s : I → collapse_algebra X Y}
{s_infty : collapse_algebra X Y} (H_eq_inter: s_infty.val = ⋂n, (s n).val)
: s_infty = ⨅ n, s n :=
begin
rw subtype.ext, rw fst_infi',
have s_infty_p_p : s_infty.val = s_infty.valᵖᵖ,
by {rw is_regular_eq_p_p, exact s_infty.property},
rw s_infty_p_p, simp*
end
lemma principal_opens_dense_omega_closed [nonempty $ X → Y] :
dense_omega_closed_subset (set.range ι : set (collapse_algebra X Y)) :=
begin
refine ⟨⟨_, _⟩, _⟩,
{ rintro ⟨p, hp⟩, have := congr_arg subtype.val hp,
simp [collapse_poset.inclusion, collapse_poset.principal_open] at this,
erw [set.eq_empty_iff_forall_not_mem] at this,
have := _inst_1, cases this with g,
exact this (p.f.extend_via g) (p.f.le_extend_via g) },
{ intros o ho,
have h2o : o.1 ≠ ∅ := ho.2.symm,
rcases nonempty_basis_subset collapse_space_basis_spec h2o (is_open_of_is_regular o.2)
with ⟨u, hu, h2u, h3u⟩,
rcases or.resolve_left hu h2u with ⟨u', hu', rfl⟩,
refine ⟨ι u', set.mem_range_self u', h3u⟩ },
{ intros f hf h2f h3f, choose g hg using hf,
simp only [(hg _).symm] at h3f h2f ⊢, clear hg f,
let P : collapse_poset X Y _,
{ refine collapse_poset.Sup_lift g _ _,
{ simp [(succ_is_regular (by refl)).2],
simp only [cardinal.omega, (lift_succ _).symm, lift_lt, lt_succ_self] },
{ apply le_of_lt (lt_succ_self _) } },
refine ⟨P, _⟩,
have : ∀ {{i j : ℕ}}, i ≤ j → ι (g j) ≤ ι (g i),
{ intros i j h, induction h, exact le_refl _, exact le_trans (h3f _) h_ih },
have : ∀ (i j : ℕ), pfun.compatible ((g i).f) ((g j).f),
{ intros, cases le_total i j with h h, rw [pfun.compatible_comm],
apply compatible_of_inclusion_le_inclusion (this h),
apply compatible_of_inclusion_le_inclusion (this h) },
simp [collapse_poset.inclusion, subtype.val_eq_coe],
apply principal_open_eq_infi_of_eq_inter, ext f,
refine ⟨_,_⟩; intro H,
{ rw set.mem_Inter, intro k,
rw mem_principal_open_iff at H ⊢, intros x y Hy,
apply H, dsimp[P, collapse_poset.Sup_lift],
rw (pfun.mem_Sup ‹_›), use k, from ‹_›},
{ rw mem_principal_open_iff, dsimp[P, collapse_poset.Sup_lift],
intros x y H_mem, rw set.mem_Inter at H, rw (pfun.mem_Sup ‹_›) at H_mem,
simp only [mem_principal_open_iff] at H, finish }}
end
end collapse_poset_dense
local notation `𝔹` := collapse_algebra ((ℵ₁ : pSet).type) (powerset omega : pSet).type
instance nonempty_aleph_one_powerset_omega : nonempty $ ((ℵ₁).type) → (powerset omega).type :=
⟨λ _, by {unfold pSet.omega, exact λ _, false}⟩
def collapse_boolean_algebra : nontrivial_complete_boolean_algebra 𝔹 :=
by apply_instance
|
9fab8150f36643255a8a00c8fd7917a434e4b87c | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/hint.lean | b2e58b97b707aa47c0b968cb36149c3ca4af097f | [
"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,953 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import tactic.solve_by_elim
import tactic.interactive
namespace tactic
namespace hint
/-- An attribute marking a `tactic unit` or `tactic string` which should be used by the `hint`
tactic. -/
@[user_attribute] meta def hint_tactic_attribute : user_attribute :=
{ name := `hint_tactic,
descr := "A tactic that should be tried by `hint`." }
add_tactic_doc
{ name := "hint_tactic",
category := doc_category.attr,
decl_names := [`tactic.hint.hint_tactic_attribute],
tags := ["rewrite", "search"] }
setup_tactic_parser
private meta def add_tactic_hint (n : name) (t : expr) : tactic unit :=
do
add_decl $ declaration.defn n [] `(tactic string) t reducibility_hints.opaque ff,
hint_tactic_attribute.set n () tt
/--
`add_hint_tactic t` runs the tactic `t` whenever `hint` is invoked.
The typical use case is `add_hint_tactic "foo"` for some interactive tactic `foo`.
-/
@[user_command] meta def add_hint_tactic (_ : parse (tk "add_hint_tactic")) : parser unit :=
do n ← parser.pexpr,
e ← to_expr n,
s ← eval_expr string e,
let t := "`[" ++ s ++ "]",
(t, _) ← with_input parser.pexpr t,
of_tactic $ do
let h := s <.> "_hint",
t ← to_expr ``(do %%t, pure %%n),
add_tactic_hint h t.
add_tactic_doc
{ name := "add_hint_tactic",
category := doc_category.cmd,
decl_names := [`tactic.hint.add_hint_tactic],
tags := ["search"] }
add_hint_tactic "refl"
add_hint_tactic "exact dec_trivial"
add_hint_tactic "assumption"
-- tidy does something better here: it suggests the actual "intros X Y f" string.
-- perhaps add a wrapper?
add_hint_tactic "intro"
add_hint_tactic "apply_auto_param"
add_hint_tactic "dsimp at *"
add_hint_tactic "simp at *" -- TODO hook up to squeeze_simp?
add_hint_tactic "fconstructor"
add_hint_tactic "injections_and_clear"
add_hint_tactic "solve_by_elim"
add_hint_tactic "unfold_coes"
add_hint_tactic "unfold_aux"
end hint
/--
Report a list of tactics that can make progress against the current goal,
and for each such tactic, the number of remaining goals afterwards.
-/
meta def hint : tactic (list (string × ℕ)) :=
do
names ← attribute.get_instances `hint_tactic,
focus1 $ try_all_sorted (names.reverse.map name_to_tactic)
namespace interactive
/--
Report a list of tactics that can make progress against the current goal.
-/
meta def hint : tactic unit :=
do
hints ← tactic.hint,
if hints.length = 0 then
fail "no hints available"
else do
t ← hints.nth 0,
if t.2 = 0 then do
trace "the following tactics solve the goal:\n----",
(hints.filter (λ p : string × ℕ, p.2 = 0)).mmap' (λ p, tactic.trace format!"Try this: {p.1}")
else do
trace "the following tactics make progress:\n----",
hints.mmap' (λ p, tactic.trace format!"Try this: {p.1}")
/--
`hint` lists possible tactics which will make progress (that is, not fail) against the current goal.
```lean
example {P Q : Prop} (p : P) (h : P → Q) : Q :=
begin
hint,
/- the following tactics make progress:
----
Try this: solve_by_elim
Try this: finish
Try this: tauto
-/
solve_by_elim,
end
```
You can add a tactic to the list that `hint` tries by either using
1. `attribute [hint_tactic] my_tactic`, if `my_tactic` is already of type `tactic string`
(`tactic unit` is allowed too, in which case the printed string will be the name of the
tactic), or
2. `add_hint_tactic "my_tactic"`, specifying a string which works as an interactive tactic.
-/
add_tactic_doc
{ name := "hint",
category := doc_category.tactic,
decl_names := [`tactic.interactive.hint],
tags := ["search", "Try this"] }
end interactive
end tactic
|
6ecf0c44be92ef217ac5e222efc57d3c22db72d5 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/monotonicity/lemmas.lean | 4c7cb0fb7988695461a34c33c68f29b0594ce480 | [
"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 | 2,635 | lean | /-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import tactic.monotonicity.basic
import algebra.ordered_ring
import data.set.lattice
import order.bounds
variables {α : Type*}
@[mono]
lemma mul_mono_nonneg {x y z : α} [ordered_semiring α]
(h' : 0 ≤ z)
(h : x ≤ y)
: x * z ≤ y * z :=
by apply mul_le_mul_of_nonneg_right; assumption
lemma lt_of_mul_lt_mul_neg_right {a b c : α} [linear_ordered_ring α]
(h : a * c < b * c) (hc : c ≤ 0) : b < a :=
have nhc : -c ≥ 0, from neg_nonneg_of_nonpos hc,
have h2 : -(b * c) < -(a * c), from neg_lt_neg h,
have h3 : b * (-c) < a * (-c), from calc
b * (-c) = - (b * c) : by rewrite neg_mul_eq_mul_neg
... < - (a * c) : h2
... = a * (-c) : by rewrite neg_mul_eq_mul_neg,
lt_of_mul_lt_mul_right h3 nhc
@[mono]
lemma mul_mono_nonpos {x y z : α} [linear_ordered_ring α]
(h' : z ≤ 0) (h : y ≤ x) : x * z ≤ y * z :=
begin
classical,
by_contradiction h'',
revert h,
apply not_le_of_lt,
apply lt_of_mul_lt_mul_neg_right _ h',
apply lt_of_not_ge h''
end
@[mono]
lemma nat.sub_mono_left_strict {x y z : ℕ}
(h' : z ≤ x)
(h : x < y)
: x - z < y - z :=
begin
have : z ≤ y,
{ transitivity, assumption, apply le_of_lt h, },
apply @nat.lt_of_add_lt_add_left z,
rw [nat.add_sub_of_le,nat.add_sub_of_le];
solve_by_elim
end
@[mono]
lemma nat.sub_mono_right_strict {x y z : ℕ}
(h' : x ≤ z)
(h : y < x)
: z - x < z - y :=
begin
have h'' : y ≤ z,
{ transitivity, apply le_of_lt h, assumption },
apply @nat.lt_of_add_lt_add_right _ x,
rw [nat.sub_add_cancel h'],
apply @lt_of_le_of_lt _ _ _ (z - y + y),
rw [nat.sub_add_cancel h''],
apply nat.add_lt_add_left h
end
open set
attribute [mono] inter_subset_inter union_subset_union
sUnion_mono bUnion_mono sInter_subset_sInter bInter_mono
image_subset preimage_mono prod_mono monotone_prod seq_mono
image2_subset order_embedding.monotone
attribute [mono] upper_bounds_mono_set lower_bounds_mono_set
upper_bounds_mono_mem lower_bounds_mono_mem
upper_bounds_mono lower_bounds_mono
bdd_above.mono bdd_below.mono
attribute [mono] add_le_add mul_le_mul neg_le_neg
mul_lt_mul_of_pos_left mul_lt_mul_of_pos_right
imp_imp_imp le_implies_le_of_le_of_le
sub_le_sub abs_le_abs sup_le_sup
inf_le_inf
attribute [mono left] add_lt_add_of_le_of_lt mul_lt_mul'
attribute [mono right] add_lt_add_of_lt_of_le mul_lt_mul
|
05ffba6a67b7ec7e8284f6ce3df5f7684196ecdc | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /logic/relator.lean | f4a9c12e8daf2b7cae7ff1acd386f17ffad09757 | [
"Apache-2.0"
] | permissive | kckennylau/mathlib | 21fb810b701b10d6606d9002a4004f7672262e83 | 47b3477e20ffb5a06588dd3abb01fe0fe3205646 | refs/heads/master | 1,634,976,409,281 | 1,542,042,832,000 | 1,542,319,733,000 | 109,560,458 | 0 | 0 | Apache-2.0 | 1,542,369,208,000 | 1,509,867,494,000 | Lean | UTF-8 | Lean | false | false | 1,116 | 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
This is an extension of `init/relator.lean`
-/
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables {r : α → β → Prop} {p : β → γ → Prop} {q : γ → δ → Prop}
namespace relator
def bi_unique (r : α → β → Prop) : Prop := left_unique r ∧ right_unique r
lemma left_unique_flip (h : left_unique r) : right_unique (flip r)
| a b c h₁ h₂ := h h₁ h₂
lemma rel_and : ((↔) ⇒ (↔) ⇒ (↔)) (∧) (∧) :=
assume a b h₁ c d h₂, and_congr h₁ h₂
lemma rel_or : ((↔) ⇒ (↔) ⇒ (↔)) (∨) (∨) :=
assume a b h₁ c d h₂, or_congr h₁ h₂
lemma rel_iff : ((↔) ⇒ (↔) ⇒ (↔)) (↔) (↔) :=
assume a b h₁ c d h₂, iff_congr h₁ h₂
lemma rel_eq {r : α → β → Prop} (hr : bi_unique r) : (r ⇒ r ⇒ (↔)) (=) (=) :=
assume a b h₁ c d h₂,
iff.intro
begin intro h, subst h, exact hr.right h₁ h₂ end
begin intro h, subst h, exact hr.left h₁ h₂ end
end relator
|
94fae8e3fabf08e363ec86465892bfa648572b1e | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/ring_theory/ideal/local_ring.lean | a59ffbda206f5f1ee59d170518d1a3a3e543089c | [
"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 | 9,437 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Chris Hughes, Mario Carneiro
-/
import ring_theory.ideal.operations
import algebra.algebra.basic
import algebra.category.CommRing.basic
/-!
# Local rings
Define local rings as commutative rings having a unique maximal ideal.
## Main definitions
* `local_ring`: A predicate on commutative rings, stating that every element `a` is either a unit
or `1 - a` is a unit. This is shown to be equivalent to the condition that there exists a unique
maximal ideal.
* `local_ring.maximal_ideal`: The unique maximal ideal for a local rings. Its carrier set is the set
of non units.
* `is_local_ring_hom`: A predicate on semiring homomorphisms, requiring that it maps nonunits
to nonunits. For local rings, this means that the image of the unique maximal ideal is again
contained in the unique maximal ideal.
* `local_ring.residue_field`: The quotient of a local ring by its maximal ideal.
-/
universes u v w
/-- A commutative ring is local if it has a unique maximal ideal. Note that
`local_ring` is a predicate. -/
class local_ring (R : Type u) [comm_ring R] extends nontrivial R : Prop :=
(is_local : ∀ (a : R), (is_unit a) ∨ (is_unit (1 - a)))
namespace local_ring
variables {R : Type u} [comm_ring R] [local_ring R]
lemma is_unit_or_is_unit_one_sub_self (a : R) :
(is_unit a) ∨ (is_unit (1 - a)) :=
is_local a
lemma is_unit_of_mem_nonunits_one_sub_self (a : R) (h : (1 - a) ∈ nonunits R) :
is_unit a :=
or_iff_not_imp_right.1 (is_local a) h
lemma is_unit_one_sub_self_of_mem_nonunits (a : R) (h : a ∈ nonunits R) :
is_unit (1 - a) :=
or_iff_not_imp_left.1 (is_local a) h
lemma nonunits_add {x y} (hx : x ∈ nonunits R) (hy : y ∈ nonunits R) :
x + y ∈ nonunits R :=
begin
rintros ⟨u, hu⟩,
apply hy,
suffices : is_unit ((↑u⁻¹ : R) * y),
{ rcases this with ⟨s, hs⟩,
use u * s,
convert congr_arg (λ z, (u : R) * z) hs,
rw ← mul_assoc, simp },
rw show (↑u⁻¹ * y) = (1 - ↑u⁻¹ * x),
{ rw eq_sub_iff_add_eq,
replace hu := congr_arg (λ z, (↑u⁻¹ : R) * z) hu.symm,
simpa [mul_add, add_comm] using hu },
apply is_unit_one_sub_self_of_mem_nonunits,
exact mul_mem_nonunits_right hx
end
variable (R)
/-- The ideal of elements that are not units. -/
def maximal_ideal : ideal R :=
{ carrier := nonunits R,
zero_mem' := zero_mem_nonunits.2 $ zero_ne_one,
add_mem' := λ x y hx hy, nonunits_add hx hy,
smul_mem' := λ a x, mul_mem_nonunits_right }
instance maximal_ideal.is_maximal : (maximal_ideal R).is_maximal :=
begin
rw ideal.is_maximal_iff,
split,
{ intro h, apply h, exact is_unit_one },
{ intros I x hI hx H,
erw not_not at hx,
rcases hx with ⟨u,rfl⟩,
simpa using I.mul_mem_left ↑u⁻¹ H }
end
lemma maximal_ideal_unique :
∃! I : ideal R, I.is_maximal :=
⟨maximal_ideal R, maximal_ideal.is_maximal R,
λ I hI, hI.eq_of_le (maximal_ideal.is_maximal R).1.1 $
λ x hx, hI.1.1 ∘ I.eq_top_of_is_unit_mem hx⟩
variable {R}
lemma eq_maximal_ideal {I : ideal R} (hI : I.is_maximal) : I = maximal_ideal R :=
unique_of_exists_unique (maximal_ideal_unique R) hI $ maximal_ideal.is_maximal R
lemma le_maximal_ideal {J : ideal R} (hJ : J ≠ ⊤) : J ≤ maximal_ideal R :=
begin
rcases ideal.exists_le_maximal J hJ with ⟨M, hM1, hM2⟩,
rwa ←eq_maximal_ideal hM1
end
@[simp] lemma mem_maximal_ideal (x) :
x ∈ maximal_ideal R ↔ x ∈ nonunits R := iff.rfl
end local_ring
variables {R : Type u} {S : Type v} {T : Type w}
lemma local_of_nonunits_ideal [comm_ring R] (hnze : (0:R) ≠ 1)
(h : ∀ x y ∈ nonunits R, x + y ∈ nonunits R) : local_ring R :=
{ exists_pair_ne := ⟨0, 1, hnze⟩,
is_local := λ x, or_iff_not_imp_left.mpr $ λ hx,
begin
by_contra H,
apply h _ _ hx H,
simp [-sub_eq_add_neg, add_sub_cancel'_right]
end }
lemma local_of_unique_max_ideal [comm_ring R] (h : ∃! I : ideal R, I.is_maximal) :
local_ring R :=
local_of_nonunits_ideal
(let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.1.1 $ I.eq_top_iff_one.2 $ H ▸ I.zero_mem))
$ λ x y hx hy H,
let ⟨I, Imax, Iuniq⟩ := h in
let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx in
let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy in
have xmemI : x ∈ I, from ((Iuniq Ix Ixmax) ▸ Hx),
have ymemI : y ∈ I, from ((Iuniq Iy Iymax) ▸ Hy),
Imax.1.1 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H
lemma local_of_unique_nonzero_prime (R : Type u) [comm_ring R]
(h : ∃! P : ideal R, P ≠ ⊥ ∧ ideal.is_prime P) : local_ring R :=
local_of_unique_max_ideal begin
rcases h with ⟨P, ⟨hPnonzero, hPnot_top, _⟩, hPunique⟩,
refine ⟨P, ⟨⟨hPnot_top, _⟩⟩, λ M hM, hPunique _ ⟨_, ideal.is_maximal.is_prime hM⟩⟩,
{ refine ideal.maximal_of_no_maximal (λ M hPM hM, ne_of_lt hPM _),
exact (hPunique _ ⟨ne_bot_of_gt hPM, ideal.is_maximal.is_prime hM⟩).symm },
{ rintro rfl,
exact hPnot_top (hM.1.2 P (bot_lt_iff_ne_bot.2 hPnonzero)) },
end
lemma local_of_surjective [comm_ring R] [local_ring R] [comm_ring S] [nontrivial S]
(f : R →+* S) (hf : function.surjective f) :
local_ring S :=
{ is_local :=
begin
intros b,
obtain ⟨a, rfl⟩ := hf b,
apply (local_ring.is_unit_or_is_unit_one_sub_self a).imp f.is_unit_map _,
rw [← f.map_one, ← f.map_sub],
apply f.is_unit_map,
end,
.. ‹nontrivial S› }
/-- A local ring homomorphism is a homomorphism between local rings
such that the image of the maximal ideal of the source is contained within
the maximal ideal of the target. -/
class is_local_ring_hom [semiring R] [semiring S] (f : R →+* S) : Prop :=
(map_nonunit : ∀ a, is_unit (f a) → is_unit a)
instance is_local_ring_hom_id (R : Type*) [semiring R] : is_local_ring_hom (ring_hom.id R) :=
{ map_nonunit := λ a, id }
@[simp] lemma is_unit_map_iff [semiring R] [semiring S] (f : R →+* S)
[is_local_ring_hom f] (a) :
is_unit (f a) ↔ is_unit a :=
⟨is_local_ring_hom.map_nonunit a, f.is_unit_map⟩
instance is_local_ring_hom_comp [semiring R] [semiring S] [semiring T]
(g : S →+* T) (f : R →+* S) [is_local_ring_hom g] [is_local_ring_hom f] :
is_local_ring_hom (g.comp f) :=
{ map_nonunit := λ a, is_local_ring_hom.map_nonunit a ∘ is_local_ring_hom.map_nonunit (f a) }
instance is_local_ring_hom_equiv [semiring R] [semiring S] (f : R ≃+* S) :
is_local_ring_hom f.to_ring_hom :=
{ map_nonunit := λ a ha,
begin
convert f.symm.to_ring_hom.is_unit_map ha,
rw ring_equiv.symm_to_ring_hom_apply_to_ring_hom_apply,
end }
@[simp] lemma is_unit_of_map_unit [semiring R] [semiring S] (f : R →+* S) [is_local_ring_hom f]
(a) (h : is_unit (f a)) : is_unit a :=
is_local_ring_hom.map_nonunit a h
theorem of_irreducible_map [semiring R] [semiring S] (f : R →+* S) [h : is_local_ring_hom f] {x : R}
(hfx : irreducible (f x)) : irreducible x :=
⟨λ h, hfx.not_unit $ is_unit.map f.to_monoid_hom h, λ p q hx, let ⟨H⟩ := h in
or.imp (H p) (H q) $ hfx.is_unit_or_is_unit $ f.map_mul p q ▸ congr_arg f hx⟩
section
open category_theory
lemma is_local_ring_hom_of_iso {R S : CommRing} (f : R ≅ S) : is_local_ring_hom f.hom :=
{ map_nonunit := λ a ha,
begin
convert f.inv.is_unit_map ha,
rw category_theory.coe_hom_inv_id,
end }
@[priority 100] -- see Note [lower instance priority]
instance is_local_ring_hom_of_is_iso {R S : CommRing} (f : R ⟶ S) [is_iso f] :
is_local_ring_hom f :=
is_local_ring_hom_of_iso (as_iso f)
end
section
open local_ring
variables [comm_ring R] [local_ring R] [comm_ring S] [local_ring S]
variables (f : R →+* S) [is_local_ring_hom f]
lemma map_nonunit (a : R) (h : a ∈ maximal_ideal R) : f a ∈ maximal_ideal S :=
λ H, h $ is_unit_of_map_unit f a H
end
namespace local_ring
variables [comm_ring R] [local_ring R] [comm_ring S] [local_ring S]
variable (R)
/-- The residue field of a local ring is the quotient of the ring by its maximal ideal. -/
def residue_field := (maximal_ideal R).quotient
noncomputable instance residue_field.field : field (residue_field R) :=
ideal.quotient.field (maximal_ideal R)
noncomputable instance : inhabited (residue_field R) := ⟨37⟩
/-- The quotient map from a local ring to its residue field. -/
def residue : R →+* (residue_field R) :=
ideal.quotient.mk _
noncomputable instance residue_field.algebra : algebra R (residue_field R) := (residue R).to_algebra
namespace residue_field
variables {R S}
/-- The map on residue fields induced by a local homomorphism between local rings -/
noncomputable def map (f : R →+* S) [is_local_ring_hom f] :
residue_field R →+* residue_field S :=
ideal.quotient.lift (maximal_ideal R) ((ideal.quotient.mk _).comp f) $
λ a ha,
begin
erw ideal.quotient.eq_zero_iff_mem,
exact map_nonunit f a ha
end
end residue_field
variables {R}
lemma ker_eq_maximal_ideal {K : Type*} [field K]
(φ : R →+* K) (hφ : function.surjective φ) : φ.ker = maximal_ideal R :=
local_ring.eq_maximal_ideal $ φ.ker_is_maximal_of_surjective hφ
end local_ring
namespace field
variables [field R]
open_locale classical
@[priority 100] -- see Note [lower instance priority]
instance : local_ring R :=
{ is_local := λ a,
if h : a = 0
then or.inr (by rw [h, sub_zero]; exact is_unit_one)
else or.inl $ is_unit.mk0 a h }
end field
|
1fbfc875fe18307c31ace606be5ba008fe9838ab | bb31430994044506fa42fd667e2d556327e18dfe | /src/topology/subset_properties.lean | 205223f8efb924db6af01d072b39cc387b800b4e | [
"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 | 89,148 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov
-/
import order.filter.pi
import topology.bases
import data.finset.order
import data.set.accumulate
import data.set.bool_indicator
import topology.bornology.basic
import order.minimal
/-!
# Properties of subsets of topological spaces
In this file we define various properties of subsets of a topological space, and some classes on
topological spaces.
## Main definitions
We define the following properties for sets in a topological space:
* `is_compact`: each open cover has a finite subcover. This is defined in mathlib using filters.
The main property of a compact set is `is_compact.elim_finite_subcover`.
* `is_clopen`: a set that is both open and closed.
* `is_irreducible`: a nonempty set that has contains no non-trivial pair of disjoint opens.
See also the section below in the module doc.
For each of these definitions (except for `is_clopen`), we also have a class stating that the whole
space satisfies that property:
`compact_space`, `irreducible_space`
Furthermore, we have three more classes:
* `locally_compact_space`: for every point `x`, every open neighborhood of `x` contains a compact
neighborhood of `x`. The definition is formulated in terms of the neighborhood filter.
* `sigma_compact_space`: a space that is the union of a countably many compact subspaces;
* `noncompact_space`: a space that is not a compact space.
## On the definition of irreducible and connected sets/spaces
In informal mathematics, irreducible spaces are assumed to be nonempty.
We formalise the predicate without that assumption as `is_preirreducible`.
In other words, the only difference is whether the empty space counts as irreducible.
There are good reasons to consider the empty space to be “too simple to be simple”
See also https://ncatlab.org/nlab/show/too+simple+to+be+simple,
and in particular
https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions.
-/
open set filter classical topological_space
open_locale classical topological_space filter
universes u v
variables {α : Type u} {β : Type v} {ι : Type*} {π : ι → Type*}
variables [topological_space α] [topological_space β] {s t : set α}
/- compact sets -/
section compact
/-- A set `s` is compact if for every nontrivial filter `f` that contains `s`,
there exists `a ∈ s` such that every set of `f` meets every neighborhood of `a`. -/
def is_compact (s : set α) := ∀ ⦃f⦄ [ne_bot f], f ≤ 𝓟 s → ∃ a ∈ s, cluster_pt a f
/-- The complement to a compact set belongs to a filter `f` if it belongs to each filter
`𝓝 a ⊓ f`, `a ∈ s`. -/
lemma is_compact.compl_mem_sets (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, sᶜ ∈ 𝓝 a ⊓ f) :
sᶜ ∈ f :=
begin
contrapose! hf,
simp only [not_mem_iff_inf_principal_compl, compl_compl, inf_assoc, ← exists_prop] at hf ⊢,
exact @hs _ hf inf_le_right
end
/-- The complement to a compact set belongs to a filter `f` if each `a ∈ s` has a neighborhood `t`
within `s` such that `tᶜ` belongs to `f`. -/
lemma is_compact.compl_mem_sets_of_nhds_within (hs : is_compact s) {f : filter α}
(hf : ∀ a ∈ s, ∃ t ∈ 𝓝[s] a, tᶜ ∈ f) :
sᶜ ∈ f :=
begin
refine hs.compl_mem_sets (λ a ha, _),
rcases hf a ha with ⟨t, ht, hst⟩,
replace ht := mem_inf_principal.1 ht,
apply mem_inf_of_inter ht hst,
rintros x ⟨h₁, h₂⟩ hs,
exact h₂ (h₁ hs)
end
/-- If `p : set α → Prop` is stable under restriction and union, and each point `x`
of a compact set `s` has a neighborhood `t` within `s` such that `p t`, then `p s` holds. -/
@[elab_as_eliminator]
lemma is_compact.induction_on {s : set α} (hs : is_compact s) {p : set α → Prop} (he : p ∅)
(hmono : ∀ ⦃s t⦄, s ⊆ t → p t → p s) (hunion : ∀ ⦃s t⦄, p s → p t → p (s ∪ t))
(hnhds : ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, p t) :
p s :=
let f : filter α :=
{ sets := {t | p tᶜ},
univ_sets := by simpa,
sets_of_superset := λ t₁ t₂ ht₁ ht, hmono (compl_subset_compl.2 ht) ht₁,
inter_sets := λ t₁ t₂ ht₁ ht₂, by simp [compl_inter, hunion ht₁ ht₂] } in
have sᶜ ∈ f, from hs.compl_mem_sets_of_nhds_within (by simpa using hnhds),
by simpa
/-- The intersection of a compact set and a closed set is a compact set. -/
lemma is_compact.inter_right (hs : is_compact s) (ht : is_closed t) :
is_compact (s ∩ t) :=
begin
introsI f hnf hstf,
obtain ⟨a, hsa, ha⟩ : ∃ a ∈ s, cluster_pt a f :=
hs (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))),
have : a ∈ t :=
(ht.mem_of_nhds_within_ne_bot $ ha.mono $
le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))),
exact ⟨a, ⟨hsa, this⟩, ha⟩
end
/-- The intersection of a closed set and a compact set is a compact set. -/
lemma is_compact.inter_left (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) :=
inter_comm t s ▸ ht.inter_right hs
/-- The set difference of a compact set and an open set is a compact set. -/
lemma is_compact.diff (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) :=
hs.inter_right (is_closed_compl_iff.mpr ht)
/-- A closed subset of a compact set is a compact set. -/
lemma is_compact_of_is_closed_subset (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) :
is_compact t :=
inter_eq_self_of_subset_right h ▸ hs.inter_right ht
lemma is_compact.image_of_continuous_on {f : α → β} (hs : is_compact s) (hf : continuous_on f s) :
is_compact (f '' s) :=
begin
intros l lne ls,
have : ne_bot (l.comap f ⊓ 𝓟 s) :=
comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls),
obtain ⟨a, has, ha⟩ : ∃ a ∈ s, cluster_pt a (l.comap f ⊓ 𝓟 s) := @@hs this inf_le_right,
use [f a, mem_image_of_mem f has],
have : tendsto f (𝓝 a ⊓ (comap f l ⊓ 𝓟 s)) (𝓝 (f a) ⊓ l),
{ convert (hf a has).inf (@tendsto_comap _ _ f l) using 1,
rw nhds_within,
ac_refl },
exact @@tendsto.ne_bot _ this ha,
end
lemma is_compact.image {f : α → β} (hs : is_compact s) (hf : continuous f) :
is_compact (f '' s) :=
hs.image_of_continuous_on hf.continuous_on
lemma is_compact.adherence_nhdset {f : filter α}
(hs : is_compact s) (hf₂ : f ≤ 𝓟 s) (ht₁ : is_open t) (ht₂ : ∀ a ∈ s, cluster_pt a f → a ∈ t) :
t ∈ f :=
classical.by_cases mem_of_eq_bot $
assume : f ⊓ 𝓟 tᶜ ≠ ⊥,
let ⟨a, ha, (hfa : cluster_pt a $ f ⊓ 𝓟 tᶜ)⟩ := @@hs ⟨this⟩ $ inf_le_of_left_le hf₂ in
have a ∈ t,
from ht₂ a ha (hfa.of_inf_left),
have tᶜ ∩ t ∈ 𝓝[tᶜ] a,
from inter_mem_nhds_within _ (is_open.mem_nhds ht₁ this),
have A : 𝓝[tᶜ] a = ⊥,
from empty_mem_iff_bot.1 $ compl_inter_self t ▸ this,
have 𝓝[tᶜ] a ≠ ⊥,
from hfa.of_inf_right.ne,
absurd A this
lemma is_compact_iff_ultrafilter_le_nhds :
is_compact s ↔ (∀ f : ultrafilter α, ↑f ≤ 𝓟 s → ∃ a ∈ s, ↑f ≤ 𝓝 a) :=
begin
refine (forall_ne_bot_le_iff _).trans _,
{ rintro f g hle ⟨a, has, haf⟩,
exact ⟨a, has, haf.mono hle⟩ },
{ simp only [ultrafilter.cluster_pt_iff] }
end
alias is_compact_iff_ultrafilter_le_nhds ↔ is_compact.ultrafilter_le_nhds _
/-- For every open directed cover of a compact set, there exists a single element of the
cover which itself includes the set. -/
lemma is_compact.elim_directed_cover {ι : Type v} [hι : nonempty ι] (hs : is_compact s)
(U : ι → set α) (hUo : ∀ i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) (hdU : directed (⊆) U) :
∃ i, s ⊆ U i :=
hι.elim $ λ i₀, is_compact.induction_on hs ⟨i₀, empty_subset _⟩
(λ s₁ s₂ hs ⟨i, hi⟩, ⟨i, subset.trans hs hi⟩)
(λ s₁ s₂ ⟨i, hi⟩ ⟨j, hj⟩, let ⟨k, hki, hkj⟩ := hdU i j in
⟨k, union_subset (subset.trans hi hki) (subset.trans hj hkj)⟩)
(λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hsU hx) in
⟨U i, mem_nhds_within_of_mem_nhds (is_open.mem_nhds (hUo i) hi), i, subset.refl _⟩)
/-- For every open cover of a compact set, there exists a finite subcover. -/
lemma is_compact.elim_finite_subcover {ι : Type v} (hs : is_compact s)
(U : ι → set α) (hUo : ∀ i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) :
∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i :=
hs.elim_directed_cover _ (λ t, is_open_bUnion $ λ i _, hUo i) (Union_eq_Union_finset U ▸ hsU)
(directed_of_sup $ λ t₁ t₂ h, bUnion_subset_bUnion_left h)
lemma is_compact.elim_nhds_subcover' (hs : is_compact s) (U : Π x ∈ s, set α)
(hU : ∀ x ∈ s, U x ‹x ∈ s› ∈ 𝓝 x) :
∃ t : finset s, s ⊆ ⋃ x ∈ t, U (x : s) x.2 :=
(hs.elim_finite_subcover (λ x : s, interior (U x x.2)) (λ x, is_open_interior)
(λ x hx, mem_Union.2 ⟨⟨x, hx⟩, mem_interior_iff_mem_nhds.2 $ hU _ _⟩)).imp $ λ t ht,
subset.trans ht $ Union₂_mono $ λ _ _, interior_subset
lemma is_compact.elim_nhds_subcover (hs : is_compact s) (U : α → set α) (hU : ∀ x ∈ s, U x ∈ 𝓝 x) :
∃ t : finset α, (∀ x ∈ t, x ∈ s) ∧ s ⊆ ⋃ x ∈ t, U x :=
let ⟨t, ht⟩ := hs.elim_nhds_subcover' (λ x _, U x) hU
in ⟨t.image coe, λ x hx, let ⟨y, hyt, hyx⟩ := finset.mem_image.1 hx in hyx ▸ y.2,
by rwa finset.set_bUnion_finset_image⟩
/-- The neighborhood filter of a compact set is disjoint with a filter `l` if and only if the
neighborhood filter of each point of this set is disjoint with `l`. -/
lemma is_compact.disjoint_nhds_set_left {l : filter α} (hs : is_compact s) :
disjoint (𝓝ˢ s) l ↔ ∀ x ∈ s, disjoint (𝓝 x) l :=
begin
refine ⟨λ h x hx, h.mono_left $ nhds_le_nhds_set hx, λ H, _⟩,
choose! U hxU hUl using λ x hx, (nhds_basis_opens x).disjoint_iff_left.1 (H x hx),
choose hxU hUo using hxU,
rcases hs.elim_nhds_subcover U (λ x hx, (hUo x hx).mem_nhds (hxU x hx)) with ⟨t, hts, hst⟩,
refine (has_basis_nhds_set _).disjoint_iff_left.2
⟨⋃ x ∈ t, U x, ⟨is_open_bUnion $ λ x hx, hUo x (hts x hx), hst⟩, _⟩,
rw [compl_Union₂, bInter_finset_mem],
exact λ x hx, hUl x (hts x hx)
end
/-- A filter `l` is disjoint with the neighborhood filter of a compact set if and only if it is
disjoint with the neighborhood filter of each point of this set. -/
lemma is_compact.disjoint_nhds_set_right {l : filter α} (hs : is_compact s) :
disjoint l (𝓝ˢ s) ↔ ∀ x ∈ s, disjoint l (𝓝 x) :=
by simpa only [disjoint.comm] using hs.disjoint_nhds_set_left
/-- For every family of closed sets whose intersection avoids a compact set,
there exists a finite subfamily whose intersection avoids this compact set. -/
lemma is_compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : is_compact s)
(Z : ι → set α) (hZc : ∀ i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) :
∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ :=
let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, (Z i)ᶜ) (λ i, (hZc i).is_open_compl)
(by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_iff, not_and, iff_self, mem_Inter, mem_compl_iff] using hsZ)
in
⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_iff, not_and, iff_self, mem_Inter, mem_compl_iff] using ht⟩
/-- If `s` is a compact set in a topological space `α` and `f : ι → set α` is a locally finite
family of sets, then `f i ∩ s` is nonempty only for a finitely many `i`. -/
lemma locally_finite.finite_nonempty_inter_compact {ι : Type*} {f : ι → set α}
(hf : locally_finite f) {s : set α} (hs : is_compact s) :
{i | (f i ∩ s).nonempty}.finite :=
begin
choose U hxU hUf using hf,
rcases hs.elim_nhds_subcover U (λ x _, hxU x) with ⟨t, -, hsU⟩,
refine (t.finite_to_set.bUnion (λ x _, hUf x)).subset _,
rintro i ⟨x, hx⟩,
rcases mem_Union₂.1 (hsU hx.2) with ⟨c, hct, hcx⟩,
exact mem_bUnion hct ⟨x, hx.1, hcx⟩
end
/-- To show that a compact set intersects the intersection of a family of closed sets,
it is sufficient to show that it intersects every finite subfamily. -/
lemma is_compact.inter_Inter_nonempty {s : set α} {ι : Type v} (hs : is_compact s)
(Z : ι → set α) (hZc : ∀ i, is_closed (Z i)) (hsZ : ∀ t : finset ι, (s ∩ ⋂ i ∈ t, Z i).nonempty) :
(s ∩ ⋂ i, Z i).nonempty :=
begin
simp only [nonempty_iff_ne_empty] at hsZ ⊢,
apply mt (hs.elim_finite_subfamily_closed Z hZc), push_neg, exact hsZ
end
/-- Cantor's intersection theorem:
the intersection of a directed family of nonempty compact closed sets is nonempty. -/
lemma is_compact.nonempty_Inter_of_directed_nonempty_compact_closed
{ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z)
(hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, is_compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) :
(⋂ i, Z i).nonempty :=
begin
apply hι.elim,
intro i₀,
let Z' := λ i, Z i ∩ Z i₀,
suffices : (⋂ i, Z' i).nonempty,
{ exact this.mono (Inter_mono $ λ i, inter_subset_left (Z i) (Z i₀)) },
rw nonempty_iff_ne_empty,
intro H,
obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅,
from (hZc i₀).elim_finite_subfamily_closed Z'
(assume i, is_closed.inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]),
obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i,
{ rcases directed.finset_le hZd t with ⟨i, hi⟩,
rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩,
use [i₁, hi₁₀],
intros j hj,
exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ },
suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty,
{ rw nonempty_iff_ne_empty at this, contradiction },
exact (hZn i₁).mono (subset_inter hi₁.left $ subset_Inter₂ hi₁.right),
end
/-- Cantor's intersection theorem for sequences indexed by `ℕ`:
the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/
lemma is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed
(Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i)
(hZn : ∀ i, (Z i).nonempty) (hZ0 : is_compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) :
(⋂ i, Z i).nonempty :=
have Zmono : antitone Z := antitone_nat_of_succ_le hZd,
have hZd : directed (⊇) Z, from directed_of_sup Zmono,
have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i,
have hZc : ∀ i, is_compact (Z i),
from assume i, is_compact_of_is_closed_subset hZ0 (hZcl i) (this i),
is_compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl
/-- For every open cover of a compact set, there exists a finite subcover. -/
lemma is_compact.elim_finite_subcover_image {b : set ι} {c : ι → set α}
(hs : is_compact s) (hc₁ : ∀ i ∈ b, is_open (c i)) (hc₂ : s ⊆ ⋃ i ∈ b, c i) :
∃ b' ⊆ b, set.finite b' ∧ s ⊆ ⋃ i ∈ b', c i :=
begin
rcases hs.elim_finite_subcover (λ i, c i : b → set α) _ _ with ⟨d, hd⟩;
[skip, simpa using hc₁, simpa using hc₂],
refine ⟨↑(d.image coe), _, finset.finite_to_set _, _⟩,
{ simp },
{ rwa [finset.coe_image, bUnion_image] }
end
/-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`,
there exists a finite subfamily whose intersection avoids `s`. -/
theorem is_compact_of_finite_subfamily_closed
(h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) :
is_compact s :=
assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃ x ∈ s, cluster_pt x f),
have hf : ∀ x ∈ s, 𝓝 x ⊓ f = ⊥,
by simpa only [cluster_pt, not_exists, not_not, ne_bot_iff],
have ¬ ∃ x ∈ s, ∀ t ∈ f.sets, x ∈ closure t,
from assume ⟨x, hxs, hx⟩,
have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_mem_iff_bot, hf x hxs],
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_iff] at this; exact this in
have ∅ ∈ 𝓝[t₂] x,
by { rw [ht, inter_comm], exact inter_mem_nhds_within _ ht₁ },
have 𝓝[t₂] x = ⊥,
by rwa [empty_mem_iff_bot] at this,
by simp only [closure_eq_cluster_pts] at hx; exact (hx t₂ ht₂).ne this,
let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure)
(by simpa [eq_empty_iff_forall_not_mem, not_exists]) in
have (⋂ i ∈ t, subtype.val i) ∈ f,
from t.Inter_mem_sets.2 $ assume i hi, i.2,
have s ∩ (⋂ i ∈ t, subtype.val i) ∈ f,
from inter_mem (le_principal_iff.1 hfs) this,
have ∅ ∈ f,
from mem_of_superset this $ assume x ⟨hxs, hx⟩,
let ⟨i, hit, hxi⟩ := (show ∃ i ∈ t, x ∉ closure (subtype.val i),
by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in
have x ∈ closure i.val, from subset_closure (by { rw mem_Inter₂ at hx, exact hx i hit }),
show false, from hxi this,
hfn.ne $ by rwa [empty_mem_iff_bot] at this
/-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/
lemma is_compact_of_finite_subcover
(h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) →
s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) :
is_compact s :=
is_compact_of_finite_subfamily_closed $
assume ι Z hZc hsZ,
let ⟨t, ht⟩ := h (λ i, (Z i)ᶜ) (assume i, is_open_compl_iff.mpr $ hZc i)
(by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_iff, not_and, iff_self, mem_Inter, mem_compl_iff] using hsZ)
in
⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_iff, not_and, iff_self, mem_Inter, mem_compl_iff] using ht⟩
/-- A set `s` is compact if and only if
for every open cover of `s`, there exists a finite subcover. -/
lemma is_compact_iff_finite_subcover :
is_compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) →
s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) :=
⟨assume hs ι, hs.elim_finite_subcover, is_compact_of_finite_subcover⟩
/-- A set `s` is compact if and only if
for every family of closed sets whose intersection avoids `s`,
there exists a finite subfamily whose intersection avoids `s`. -/
theorem is_compact_iff_finite_subfamily_closed :
is_compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) :=
⟨assume hs ι, hs.elim_finite_subfamily_closed, is_compact_of_finite_subfamily_closed⟩
/--
To show that `∀ y ∈ K, P x y` holds for `x` close enough to `x₀` when `K` is compact,
it is sufficient to show that for all `y₀ ∈ K` there `P x y` holds for `(x, y)` close enough
to `(x₀, y₀)`.
-/
lemma is_compact.eventually_forall_of_forall_eventually {x₀ : α} {K : set β} (hK : is_compact K)
{P : α → β → Prop} (hP : ∀ y ∈ K, ∀ᶠ (z : α × β) in 𝓝 (x₀, y), P z.1 z.2):
∀ᶠ x in 𝓝 x₀, ∀ y ∈ K, P x y :=
begin
refine hK.induction_on _ _ _ _,
{ exact eventually_of_forall (λ x y, false.elim) },
{ intros s t hst ht, refine ht.mono (λ x h y hys, h y $ hst hys) },
{ intros s t hs ht, filter_upwards [hs, ht], rintro x h1 h2 y (hys|hyt),
exacts [h1 y hys, h2 y hyt] },
{ intros y hyK,
specialize hP y hyK,
rw [nhds_prod_eq, eventually_prod_iff] at hP,
rcases hP with ⟨p, hp, q, hq, hpq⟩,
exact ⟨{y | q y}, mem_nhds_within_of_mem_nhds hq, eventually_of_mem hp @hpq⟩ }
end
@[simp]
lemma is_compact_empty : is_compact (∅ : set α) :=
assume f hnf hsf, not.elim hnf.ne $
empty_mem_iff_bot.1 $ le_principal_iff.1 hsf
@[simp]
lemma is_compact_singleton {a : α} : is_compact ({a} : set α) :=
λ f hf hfa, ⟨a, rfl, cluster_pt.of_le_nhds'
(hfa.trans $ by simpa only [principal_singleton] using pure_le_nhds a) hf⟩
lemma set.subsingleton.is_compact {s : set α} (hs : s.subsingleton) : is_compact s :=
subsingleton.induction_on hs is_compact_empty $ λ x, is_compact_singleton
lemma set.finite.is_compact_bUnion {s : set ι} {f : ι → set α} (hs : s.finite)
(hf : ∀ i ∈ s, is_compact (f i)) :
is_compact (⋃ i ∈ s, f i) :=
is_compact_of_finite_subcover $ assume ι U hUo hsU,
have ∀ i : subtype s, ∃ t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from
assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo
(calc f i ⊆ ⋃ i ∈ s, f i : subset_bUnion_of_mem hi
... ⊆ ⋃ j, U j : hsU),
let ⟨finite_subcovers, h⟩ := axiom_of_choice this in
by haveI : fintype (subtype s) := hs.fintype; exact
let t := finset.bUnion finset.univ finite_subcovers in
have (⋃ i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from Union₂_subset $
assume i hi, calc
f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩)
... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $
assume j hj, finset.mem_bUnion.mpr ⟨_, finset.mem_univ _, hj⟩,
⟨t, this⟩
lemma finset.is_compact_bUnion (s : finset ι) {f : ι → set α} (hf : ∀ i ∈ s, is_compact (f i)) :
is_compact (⋃ i ∈ s, f i) :=
s.finite_to_set.is_compact_bUnion hf
lemma is_compact_accumulate {K : ℕ → set α} (hK : ∀ n, is_compact (K n)) (n : ℕ) :
is_compact (accumulate K n) :=
(finite_le_nat n).is_compact_bUnion $ λ k _, hK k
lemma is_compact_Union {f : ι → set α} [finite ι] (h : ∀ i, is_compact (f i)) :
is_compact (⋃ i, f i) :=
by rw ← bUnion_univ; exact finite_univ.is_compact_bUnion (λ i _, h i)
lemma set.finite.is_compact (hs : s.finite) : is_compact s :=
bUnion_of_singleton s ▸ hs.is_compact_bUnion (λ _ _, is_compact_singleton)
lemma is_compact.finite_of_discrete [discrete_topology α] {s : set α} (hs : is_compact s) :
s.finite :=
begin
have : ∀ x : α, ({x} : set α) ∈ 𝓝 x, by simp [nhds_discrete],
rcases hs.elim_nhds_subcover (λ x, {x}) (λ x hx, this x) with ⟨t, hts, hst⟩,
simp only [← t.set_bUnion_coe, bUnion_of_singleton] at hst,
exact t.finite_to_set.subset hst
end
lemma is_compact_iff_finite [discrete_topology α] {s : set α} : is_compact s ↔ s.finite :=
⟨λ h, h.finite_of_discrete, λ h, h.is_compact⟩
lemma is_compact.union (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) :=
by rw union_eq_Union; exact is_compact_Union (λ b, by cases b; assumption)
lemma is_compact.insert (hs : is_compact s) (a) : is_compact (insert a s) :=
is_compact_singleton.union hs
/-- If `V : ι → set α` is a decreasing family of closed compact sets then any neighborhood of
`⋂ i, V i` contains some `V i`. We assume each `V i` is compact *and* closed because `α` is
not assumed to be Hausdorff. See `exists_subset_nhd_of_compact` for version assuming this. -/
lemma exists_subset_nhds_of_is_compact' {ι : Type*} [nonempty ι]
{V : ι → set α} (hV : directed (⊇) V)
(hV_cpct : ∀ i, is_compact (V i)) (hV_closed : ∀ i, is_closed (V i))
{U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U :=
begin
obtain ⟨W, hsubW, W_op, hWU⟩ := exists_open_set_nhds hU,
rsuffices ⟨i, hi⟩ : ∃ i, V i ⊆ W,
{ exact ⟨i, hi.trans hWU⟩ },
by_contra' H,
replace H : ∀ i, (V i ∩ Wᶜ).nonempty := λ i, set.inter_compl_nonempty_iff.mpr (H i),
have : (⋂ i, V i ∩ Wᶜ).nonempty,
{ refine is_compact.nonempty_Inter_of_directed_nonempty_compact_closed _ (λ i j, _) H
(λ i, (hV_cpct i).inter_right W_op.is_closed_compl)
(λ i, (hV_closed i).inter W_op.is_closed_compl),
rcases hV i j with ⟨k, hki, hkj⟩,
refine ⟨k, ⟨λ x, _, λ x, _⟩⟩ ; simp only [and_imp, mem_inter_iff, mem_compl_iff] ; tauto },
have : ¬ (⋂ (i : ι), V i) ⊆ W, by simpa [← Inter_inter, inter_compl_nonempty_iff],
contradiction
end
/-- If `α` has a basis consisting of compact opens, then an open set in `α` is compact open iff
it is a finite union of some elements in the basis -/
lemma is_compact_open_iff_eq_finite_Union_of_is_topological_basis (b : ι → set α)
(hb : is_topological_basis (set.range b))
(hb' : ∀ i, is_compact (b i)) (U : set α) :
is_compact U ∧ is_open U ↔ ∃ (s : set ι), s.finite ∧ U = ⋃ i ∈ s, b i :=
begin
classical,
split,
{ rintro ⟨h₁, h₂⟩,
obtain ⟨β, f, e, hf⟩ := hb.open_eq_Union h₂,
choose f' hf' using hf,
have : b ∘ f' = f := funext hf', subst this,
obtain ⟨t, ht⟩ := h₁.elim_finite_subcover (b ∘ f')
(λ i, hb.is_open (set.mem_range_self _)) (by rw e),
refine ⟨t.image f', set.finite.intro infer_instance, le_antisymm _ _⟩,
{ refine set.subset.trans ht _,
simp only [set.Union_subset_iff, coe_coe],
intros i hi,
erw ← set.Union_subtype (λ x : ι, x ∈ t.image f') (λ i, b i.1),
exact set.subset_Union (λ i : t.image f', b i) ⟨_, finset.mem_image_of_mem _ hi⟩ },
{ apply set.Union₂_subset,
rintro i hi,
obtain ⟨j, hj, rfl⟩ := finset.mem_image.mp hi,
rw e,
exact set.subset_Union (b ∘ f') j } },
{ rintro ⟨s, hs, rfl⟩,
split,
{ exact hs.is_compact_bUnion (λ i _, hb' i) },
{ apply is_open_bUnion, intros i hi, exact hb.is_open (set.mem_range_self _) } },
end
namespace filter
/-- `filter.cocompact` is the filter generated by complements to compact sets. -/
def cocompact (α : Type*) [topological_space α] : filter α :=
⨅ (s : set α) (hs : is_compact s), 𝓟 (sᶜ)
lemma has_basis_cocompact : (cocompact α).has_basis is_compact compl :=
has_basis_binfi_principal'
(λ s hs t ht, ⟨s ∪ t, hs.union ht, compl_subset_compl.2 (subset_union_left s t),
compl_subset_compl.2 (subset_union_right s t)⟩)
⟨∅, is_compact_empty⟩
lemma mem_cocompact : s ∈ cocompact α ↔ ∃ t, is_compact t ∧ tᶜ ⊆ s :=
has_basis_cocompact.mem_iff.trans $ exists_congr $ λ t, exists_prop
lemma mem_cocompact' : s ∈ cocompact α ↔ ∃ t, is_compact t ∧ sᶜ ⊆ t :=
mem_cocompact.trans $ exists_congr $ λ t, and_congr_right $ λ ht, compl_subset_comm
lemma _root_.is_compact.compl_mem_cocompact (hs : is_compact s) : sᶜ ∈ filter.cocompact α :=
has_basis_cocompact.mem_of_mem hs
lemma cocompact_le_cofinite : cocompact α ≤ cofinite :=
λ s hs, compl_compl s ▸ hs.is_compact.compl_mem_cocompact
lemma cocompact_eq_cofinite (α : Type*) [topological_space α] [discrete_topology α] :
cocompact α = cofinite :=
has_basis_cocompact.eq_of_same_basis $
by { convert has_basis_cofinite, ext s, exact is_compact_iff_finite }
@[simp] lemma _root_.nat.cocompact_eq : cocompact ℕ = at_top :=
(cocompact_eq_cofinite ℕ).trans nat.cofinite_eq_at_top
lemma tendsto.is_compact_insert_range_of_cocompact {f : α → β} {b}
(hf : tendsto f (cocompact α) (𝓝 b)) (hfc : continuous f) :
is_compact (insert b (range f)) :=
begin
introsI l hne hle,
by_cases hb : cluster_pt b l, { exact ⟨b, or.inl rfl, hb⟩ },
simp only [cluster_pt_iff, not_forall, ← not_disjoint_iff_nonempty_inter, not_not] at hb,
rcases hb with ⟨s, hsb, t, htl, hd⟩,
rcases mem_cocompact.1 (hf hsb) with ⟨K, hKc, hKs⟩,
have : f '' K ∈ l,
{ filter_upwards [htl, le_principal_iff.1 hle] with y hyt hyf,
rcases hyf with (rfl|⟨x, rfl⟩),
exacts [(hd.le_bot ⟨mem_of_mem_nhds hsb, hyt⟩).elim,
mem_image_of_mem _ (not_not.1 $ λ hxK, hd.le_bot ⟨hKs hxK, hyt⟩)] },
rcases hKc.image hfc (le_principal_iff.2 this) with ⟨y, hy, hyl⟩,
exact ⟨y, or.inr $ image_subset_range _ _ hy, hyl⟩
end
lemma tendsto.is_compact_insert_range_of_cofinite {f : ι → α} {a}
(hf : tendsto f cofinite (𝓝 a)) :
is_compact (insert a (range f)) :=
begin
letI : topological_space ι := ⊥, haveI : discrete_topology ι := ⟨rfl⟩,
rw ← cocompact_eq_cofinite at hf,
exact hf.is_compact_insert_range_of_cocompact continuous_of_discrete_topology
end
lemma tendsto.is_compact_insert_range {f : ℕ → α} {a} (hf : tendsto f at_top (𝓝 a)) :
is_compact (insert a (range f)) :=
filter.tendsto.is_compact_insert_range_of_cofinite $ nat.cofinite_eq_at_top.symm ▸ hf
/-- `filter.coclosed_compact` is the filter generated by complements to closed compact sets.
In a Hausdorff space, this is the same as `filter.cocompact`. -/
def coclosed_compact (α : Type*) [topological_space α] : filter α :=
⨅ (s : set α) (h₁ : is_closed s) (h₂ : is_compact s), 𝓟 (sᶜ)
lemma has_basis_coclosed_compact :
(filter.coclosed_compact α).has_basis (λ s, is_closed s ∧ is_compact s) compl :=
begin
simp only [filter.coclosed_compact, infi_and'],
refine has_basis_binfi_principal' _ ⟨∅, is_closed_empty, is_compact_empty⟩,
rintro s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩,
exact ⟨s ∪ t, ⟨⟨hs₁.union ht₁, hs₂.union ht₂⟩, compl_subset_compl.2 (subset_union_left _ _),
compl_subset_compl.2 (subset_union_right _ _)⟩⟩
end
lemma mem_coclosed_compact : s ∈ coclosed_compact α ↔ ∃ t, is_closed t ∧ is_compact t ∧ tᶜ ⊆ s :=
by simp [has_basis_coclosed_compact.mem_iff, and_assoc]
lemma mem_coclosed_compact' : s ∈ coclosed_compact α ↔ ∃ t, is_closed t ∧ is_compact t ∧ sᶜ ⊆ t :=
by simp only [mem_coclosed_compact, compl_subset_comm]
lemma cocompact_le_coclosed_compact : cocompact α ≤ coclosed_compact α :=
infi_mono $ λ s, le_infi $ λ _, le_rfl
lemma _root_.is_compact.compl_mem_coclosed_compact_of_is_closed (hs : is_compact s)
(hs' : is_closed s) :
sᶜ ∈ filter.coclosed_compact α :=
has_basis_coclosed_compact.mem_of_mem ⟨hs', hs⟩
end filter
namespace bornology
variable (α)
/-- Sets that are contained in a compact set form a bornology. Its `cobounded` filter is
`filter.cocompact`. See also `bornology.relatively_compact` the bornology of sets with compact
closure. -/
def in_compact : bornology α :=
{ cobounded := filter.cocompact α,
le_cofinite := filter.cocompact_le_cofinite }
variable {α}
lemma in_compact.is_bounded_iff : @is_bounded _ (in_compact α) s ↔ ∃ t, is_compact t ∧ s ⊆ t :=
begin
change sᶜ ∈ filter.cocompact α ↔ _,
rw filter.mem_cocompact,
simp
end
end bornology
section tube_lemma
/-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes
a product of an open neighborhood of `s` by an open neighborhood of `t`. -/
def nhds_contain_boxes (s : set α) (t : set β) : Prop :=
∀ (n : set (α × β)) (hn : is_open n) (hp : s ×ˢ t ⊆ n),
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ×ˢ v ⊆ n
lemma nhds_contain_boxes.symm {s : set α} {t : set β} :
nhds_contain_boxes s t → nhds_contain_boxes t s :=
assume H n hn hp,
let ⟨u, v, uo, vo, su, tv, p⟩ :=
H (prod.swap ⁻¹' n)
(hn.preimage continuous_swap)
(by rwa [←image_subset_iff, image_swap_prod]) in
⟨v, u, vo, uo, tv, su,
by rwa [←image_subset_iff, image_swap_prod] at p⟩
lemma nhds_contain_boxes.comm {s : set α} {t : set β} :
nhds_contain_boxes s t ↔ nhds_contain_boxes t s :=
iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm
lemma nhds_contain_boxes_of_singleton {x : α} {y : β} :
nhds_contain_boxes ({x} : set α) ({y} : set β) :=
assume n hn hp,
let ⟨u, v, uo, vo, xu, yv, hp'⟩ :=
is_open_prod_iff.mp hn x y (hp $ by simp) in
⟨u, v, uo, vo, by simpa, by simpa, hp'⟩
lemma nhds_contain_boxes_of_compact {s : set α} (hs : is_compact s) (t : set β)
(H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t :=
assume n hn hp,
have ∀ x : s, ∃ uv : set α × set β,
is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ uv.1 ×ˢ uv.2 ⊆ n,
from assume ⟨x, hx⟩,
have ({x} : set α) ×ˢ t ⊆ n, from
subset.trans (prod_mono (by simpa) subset.rfl) hp,
let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩,
let ⟨uvs, h⟩ := classical.axiom_of_choice this in
have us_cover : s ⊆ ⋃ i, (uvs i).1, from
assume x hx, subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1),
let ⟨s0, s0_cover⟩ :=
hs.elim_finite_subcover _ (λi, (h i).1) us_cover in
let u := ⋃(i ∈ s0), (uvs i).1 in
let v := ⋂(i ∈ s0), (uvs i).2 in
have is_open u, from is_open_bUnion (λi _, (h i).1),
have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1),
have t ⊆ v, from subset_Inter₂ (λi _, (h i).2.2.2.1),
have u ×ˢ v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩,
have ∃ i ∈ s0, x' ∈ (uvs i).1, by simpa using hx',
let ⟨i,is0,hi⟩ := this in
(h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩,
⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹u ×ˢ v ⊆ n›⟩
/-- If `s` and `t` are compact sets and `n` is an open neighborhood of `s × t`, then there exist
open neighborhoods `u ⊇ s` and `v ⊇ t` such that `u × v ⊆ n`. -/
lemma generalized_tube_lemma {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t)
{n : set (α × β)} (hn : is_open n) (hp : s ×ˢ t ⊆ n) :
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ×ˢ v ⊆ n :=
have _, from
nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $
nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton,
this n hn hp
end tube_lemma
/-- Type class for compact spaces. Separation is sometimes included in the definition, especially
in the French literature, but we do not include it here. -/
class compact_space (α : Type*) [topological_space α] : Prop :=
(is_compact_univ : is_compact (univ : set α))
@[priority 10] -- see Note [lower instance priority]
instance subsingleton.compact_space [subsingleton α] : compact_space α :=
⟨subsingleton_univ.is_compact⟩
lemma is_compact_univ_iff : is_compact (univ : set α) ↔ compact_space α := ⟨λ h, ⟨h⟩, λ h, h.1⟩
lemma is_compact_univ [h : compact_space α] : is_compact (univ : set α) := h.is_compact_univ
lemma cluster_point_of_compact [compact_space α] (f : filter α) [ne_bot f] :
∃ x, cluster_pt x f :=
by simpa using is_compact_univ (show f ≤ 𝓟 univ, by simp)
lemma compact_space.elim_nhds_subcover [compact_space α]
(U : α → set α) (hU : ∀ x, U x ∈ 𝓝 x) :
∃ t : finset α, (⋃ x ∈ t, U x) = ⊤ :=
begin
obtain ⟨t, -, s⟩ := is_compact.elim_nhds_subcover is_compact_univ U (λ x m, hU x),
exact ⟨t, by { rw eq_top_iff, exact s }⟩,
end
theorem compact_space_of_finite_subfamily_closed
(h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
(⋂ i, Z i) = ∅ → ∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅) :
compact_space α :=
{ is_compact_univ :=
begin
apply is_compact_of_finite_subfamily_closed,
intros ι Z, specialize h Z,
simpa using h
end }
lemma is_closed.is_compact [compact_space α] {s : set α} (h : is_closed s) :
is_compact s :=
is_compact_of_is_closed_subset is_compact_univ h (subset_univ _)
/-- `α` is a noncompact topological space if it not a compact space. -/
class noncompact_space (α : Type*) [topological_space α] : Prop :=
(noncompact_univ [] : ¬is_compact (univ : set α))
export noncompact_space (noncompact_univ)
lemma is_compact.ne_univ [noncompact_space α] {s : set α} (hs : is_compact s) : s ≠ univ :=
λ h, noncompact_univ α (h ▸ hs)
instance [noncompact_space α] : ne_bot (filter.cocompact α) :=
begin
refine filter.has_basis_cocompact.ne_bot_iff.2 (λ s hs, _),
contrapose hs, rw [not_nonempty_iff_eq_empty, compl_empty_iff] at hs,
rw hs, exact noncompact_univ α
end
@[simp]
lemma filter.cocompact_eq_bot [compact_space α] : filter.cocompact α = ⊥ :=
filter.has_basis_cocompact.eq_bot_iff.mpr ⟨set.univ, is_compact_univ, set.compl_univ⟩
instance [noncompact_space α] : ne_bot (filter.coclosed_compact α) :=
ne_bot_of_le filter.cocompact_le_coclosed_compact
lemma noncompact_space_of_ne_bot (h : ne_bot (filter.cocompact α)) : noncompact_space α :=
⟨λ h', (filter.nonempty_of_mem h'.compl_mem_cocompact).ne_empty compl_univ⟩
lemma filter.cocompact_ne_bot_iff : ne_bot (filter.cocompact α) ↔ noncompact_space α :=
⟨noncompact_space_of_ne_bot, @filter.cocompact.filter.ne_bot _ _⟩
lemma not_compact_space_iff : ¬compact_space α ↔ noncompact_space α :=
⟨λ h₁, ⟨λ h₂, h₁ ⟨h₂⟩⟩, λ ⟨h₁⟩ ⟨h₂⟩, h₁ h₂⟩
instance : noncompact_space ℤ :=
noncompact_space_of_ne_bot $ by simp only [filter.cocompact_eq_cofinite, filter.cofinite_ne_bot]
-- Note: We can't make this into an instance because it loops with `finite.compact_space`.
/-- A compact discrete space is finite. -/
lemma finite_of_compact_of_discrete [compact_space α] [discrete_topology α] : finite α :=
finite.of_finite_univ $ is_compact_univ.finite_of_discrete
lemma exists_nhds_ne_ne_bot (α : Type*) [topological_space α] [compact_space α] [infinite α] :
∃ z : α, (𝓝[≠] z).ne_bot :=
begin
by_contra' H,
simp_rw not_ne_bot at H,
haveI := discrete_topology_iff_nhds_ne.mpr H,
exact infinite.not_finite (finite_of_compact_of_discrete : finite α),
end
lemma finite_cover_nhds_interior [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) :
∃ t : finset α, (⋃ x ∈ t, interior (U x)) = univ :=
let ⟨t, ht⟩ := is_compact_univ.elim_finite_subcover (λ x, interior (U x)) (λ x, is_open_interior)
(λ x _, mem_Union.2 ⟨x, mem_interior_iff_mem_nhds.2 (hU x)⟩)
in ⟨t, univ_subset_iff.1 ht⟩
lemma finite_cover_nhds [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) :
∃ t : finset α, (⋃ x ∈ t, U x) = univ :=
let ⟨t, ht⟩ := finite_cover_nhds_interior hU in ⟨t, univ_subset_iff.1 $ ht.symm.subset.trans $
Union₂_mono $ λ x hx, interior_subset⟩
/-- If `α` is a compact space, then a locally finite family of sets of `α` can have only finitely
many nonempty elements. -/
lemma locally_finite.finite_nonempty_of_compact {ι : Type*} [compact_space α] {f : ι → set α}
(hf : locally_finite f) :
{i | (f i).nonempty}.finite :=
by simpa only [inter_univ] using hf.finite_nonempty_inter_compact is_compact_univ
/-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only
finitely many elements, `set.finite` version. -/
lemma locally_finite.finite_of_compact {ι : Type*} [compact_space α] {f : ι → set α}
(hf : locally_finite f) (hne : ∀ i, (f i).nonempty) :
(univ : set ι).finite :=
by simpa only [hne] using hf.finite_nonempty_of_compact
/-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only
finitely many elements, `fintype` version. -/
noncomputable def locally_finite.fintype_of_compact {ι : Type*} [compact_space α] {f : ι → set α}
(hf : locally_finite f) (hne : ∀ i, (f i).nonempty) :
fintype ι :=
fintype_of_finite_univ (hf.finite_of_compact hne)
/-- The comap of the cocompact filter on `β` by a continuous function `f : α → β` is less than or
equal to the cocompact filter on `α`.
This is a reformulation of the fact that images of compact sets are compact. -/
lemma filter.comap_cocompact_le {f : α → β} (hf : continuous f) :
(filter.cocompact β).comap f ≤ filter.cocompact α :=
begin
rw (filter.has_basis_cocompact.comap f).le_basis_iff filter.has_basis_cocompact,
intros t ht,
refine ⟨f '' t, ht.image hf, _⟩,
simpa using t.subset_preimage_image f
end
lemma is_compact_range [compact_space α] {f : α → β} (hf : continuous f) :
is_compact (range f) :=
by rw ← image_univ; exact is_compact_univ.image hf
lemma is_compact_diagonal [compact_space α] : is_compact (diagonal α) :=
@range_diag α ▸ is_compact_range (continuous_id.prod_mk continuous_id)
/-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/
theorem is_closed_proj_of_is_compact
{X : Type*} [topological_space X] [compact_space X]
{Y : Type*} [topological_space Y] :
is_closed_map (prod.snd : X × Y → Y) :=
begin
set πX := (prod.fst : X × Y → X),
set πY := (prod.snd : X × Y → Y),
assume C (hC : is_closed C),
rw is_closed_iff_cluster_pt at hC ⊢,
assume y (y_closure : cluster_pt y $ 𝓟 (πY '' C)),
haveI : ne_bot (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)),
{ suffices : ne_bot (map πY (comap πY (𝓝 y) ⊓ 𝓟 C)),
by simpa only [map_ne_bot_iff],
convert y_closure,
calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) =
𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _
... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal },
obtain ⟨x, hx⟩ : ∃ x, cluster_pt x (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)),
from cluster_point_of_compact _,
refine ⟨⟨x, y⟩, _, by simp [πY]⟩,
apply hC,
rw [cluster_pt, ← filter.map_ne_bot_iff πX],
convert hx,
calc map πX (𝓝 (x, y) ⊓ 𝓟 C)
= map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod]
... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl
... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull
... = 𝓝 x ⊓ map πX (comap πY (𝓝 y) ⊓ 𝓟 C) : by rw inf_comm
end
lemma exists_subset_nhds_of_compact_space [compact_space α] {ι : Type*} [nonempty ι]
{V : ι → set α} (hV : directed (⊇) V) (hV_closed : ∀ i, is_closed (V i))
{U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U :=
exists_subset_nhds_of_is_compact' hV (λ i, (hV_closed i).is_compact) hV_closed hU
/-- If `f : α → β` is an `inducing` map, then the image `f '' s` of a set `s` is compact if and only
if the set `s` is closed. -/
lemma inducing.is_compact_iff {f : α → β} (hf : inducing f) {s : set α} :
is_compact (f '' s) ↔ is_compact s :=
begin
refine ⟨_, λ hs, hs.image hf.continuous⟩,
introsI hs F F_ne_bot F_le,
obtain ⟨_, ⟨x, x_in : x ∈ s, rfl⟩, hx : cluster_pt (f x) (map f F)⟩ :=
hs (calc map f F ≤ map f (𝓟 s) : map_mono F_le
... = 𝓟 (f '' s) : map_principal),
use [x, x_in],
suffices : (map f (𝓝 x ⊓ F)).ne_bot, by simpa [filter.map_ne_bot_iff],
rwa calc map f (𝓝 x ⊓ F) = map f ((comap f $ 𝓝 $ f x) ⊓ F) : by rw hf.nhds_eq_comap
... = 𝓝 (f x) ⊓ map f F : filter.push_pull' _ _ _
end
/-- If `f : α → β` is an `embedding` (or more generally, an `inducing` map, see
`inducing.is_compact_iff`), then the image `f '' s` of a set `s` is compact if and only if the set
`s` is closed. -/
lemma embedding.is_compact_iff_is_compact_image {f : α → β} (hf : embedding f) :
is_compact s ↔ is_compact (f '' s) :=
hf.to_inducing.is_compact_iff.symm
/-- The preimage of a compact set under a closed embedding is a compact set. -/
lemma closed_embedding.is_compact_preimage {f : α → β} (hf : closed_embedding f) {K : set β}
(hK : is_compact K) : is_compact (f ⁻¹' K) :=
begin
replace hK := hK.inter_right hf.closed_range,
rwa [← hf.to_inducing.is_compact_iff, image_preimage_eq_inter_range]
end
/-- A closed embedding is proper, ie, inverse images of compact sets are contained in compacts.
Moreover, the preimage of a compact set is compact, see `closed_embedding.is_compact_preimage`. -/
lemma closed_embedding.tendsto_cocompact
{f : α → β} (hf : closed_embedding f) : tendsto f (filter.cocompact α) (filter.cocompact β) :=
filter.has_basis_cocompact.tendsto_right_iff.mpr $ λ K hK,
(hf.is_compact_preimage hK).compl_mem_cocompact
lemma is_compact_iff_is_compact_in_subtype {p : α → Prop} {s : set {a // p a}} :
is_compact s ↔ is_compact ((coe : _ → α) '' s) :=
embedding_subtype_coe.is_compact_iff_is_compact_image
lemma is_compact_iff_is_compact_univ {s : set α} : is_compact s ↔ is_compact (univ : set s) :=
by rw [is_compact_iff_is_compact_in_subtype, image_univ, subtype.range_coe]; refl
lemma is_compact_iff_compact_space {s : set α} : is_compact s ↔ compact_space s :=
is_compact_iff_is_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.is_compact_univ _ _⟩
lemma is_compact.finite {s : set α} (hs : is_compact s) (hs' : discrete_topology s) : s.finite :=
finite_coe_iff.mp (@finite_of_compact_of_discrete _ _ (is_compact_iff_compact_space.mp hs) hs')
lemma exists_nhds_ne_inf_principal_ne_bot {s : set α} (hs : is_compact s) (hs' : s.infinite) :
∃ z ∈ s, (𝓝[≠] z ⊓ 𝓟 s).ne_bot :=
begin
by_contra' H,
simp_rw not_ne_bot at H,
exact hs' (hs.finite $ discrete_topology_subtype_iff.mpr H),
end
protected lemma closed_embedding.noncompact_space [noncompact_space α] {f : α → β}
(hf : closed_embedding f) : noncompact_space β :=
noncompact_space_of_ne_bot hf.tendsto_cocompact.ne_bot
protected lemma closed_embedding.compact_space [h : compact_space β] {f : α → β}
(hf : closed_embedding f) : compact_space α :=
by { unfreezingI { contrapose! h, rw not_compact_space_iff at h ⊢ }, exact hf.noncompact_space }
lemma is_compact.prod {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) :
is_compact (s ×ˢ t) :=
begin
rw is_compact_iff_ultrafilter_le_nhds at hs ht ⊢,
intros f hfs,
rw le_principal_iff at hfs,
obtain ⟨a : α, sa : a ∈ s, ha : map prod.fst ↑f ≤ 𝓝 a⟩ :=
hs (f.map prod.fst) (le_principal_iff.2 $ mem_map.2 $ mem_of_superset hfs (λ x, and.left)),
obtain ⟨b : β, tb : b ∈ t, hb : map prod.snd ↑f ≤ 𝓝 b⟩ :=
ht (f.map prod.snd) (le_principal_iff.2 $ mem_map.2 $
mem_of_superset hfs (λ x, and.right)),
rw map_le_iff_le_comap at ha hb,
refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩,
rw nhds_prod_eq, exact le_inf ha hb
end
/-- Finite topological spaces are compact. -/
@[priority 100] instance finite.compact_space [finite α] : compact_space α :=
{ is_compact_univ := finite_univ.is_compact }
/-- The product of two compact spaces is compact. -/
instance [compact_space α] [compact_space β] : compact_space (α × β) :=
⟨by { rw ← univ_prod_univ, exact is_compact_univ.prod is_compact_univ }⟩
/-- The disjoint union of two compact spaces is compact. -/
instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) :=
⟨begin
rw ← range_inl_union_range_inr,
exact (is_compact_range continuous_inl).union (is_compact_range continuous_inr)
end⟩
instance [finite ι] [Π i, topological_space (π i)] [∀ i, compact_space (π i)] :
compact_space (Σ i, π i) :=
begin
refine ⟨_⟩,
rw sigma.univ,
exact is_compact_Union (λ i, is_compact_range continuous_sigma_mk),
end
/-- The coproduct of the cocompact filters on two topological spaces is the cocompact filter on
their product. -/
lemma filter.coprod_cocompact :
(filter.cocompact α).coprod (filter.cocompact β) = filter.cocompact (α × β) :=
begin
ext S,
simp only [mem_coprod_iff, exists_prop, mem_comap, filter.mem_cocompact],
split,
{ rintro ⟨⟨A, ⟨t, ht, hAt⟩, hAS⟩, B, ⟨t', ht', hBt'⟩, hBS⟩,
refine ⟨t ×ˢ t', ht.prod ht', _⟩,
refine subset.trans _ (union_subset hAS hBS),
rw compl_subset_comm at ⊢ hAt hBt',
refine subset.trans _ (set.prod_mono hAt hBt'),
intros x,
simp only [compl_union, mem_inter_iff, mem_prod, mem_preimage, mem_compl_iff],
tauto },
{ rintros ⟨t, ht, htS⟩,
refine ⟨⟨(prod.fst '' t)ᶜ, _, _⟩, ⟨(prod.snd '' t)ᶜ, _, _⟩⟩,
{ exact ⟨prod.fst '' t, ht.image continuous_fst, subset.rfl⟩ },
{ rw preimage_compl,
rw compl_subset_comm at ⊢ htS,
exact subset.trans htS (subset_preimage_image prod.fst _) },
{ exact ⟨prod.snd '' t, ht.image continuous_snd, subset.rfl⟩ },
{ rw preimage_compl,
rw compl_subset_comm at ⊢ htS,
exact subset.trans htS (subset_preimage_image prod.snd _) } }
end
lemma prod.noncompact_space_iff :
noncompact_space (α × β) ↔ noncompact_space α ∧ nonempty β ∨ nonempty α ∧ noncompact_space β :=
by simp [← filter.cocompact_ne_bot_iff, ← filter.coprod_cocompact, filter.coprod_ne_bot_iff]
@[priority 100] -- See Note [lower instance priority]
instance prod.noncompact_space_left [noncompact_space α] [nonempty β] : noncompact_space (α × β) :=
prod.noncompact_space_iff.2 (or.inl ⟨‹_›, ‹_›⟩)
@[priority 100] -- See Note [lower instance priority]
instance prod.noncompact_space_right [nonempty α] [noncompact_space β] : noncompact_space (α × β) :=
prod.noncompact_space_iff.2 (or.inr ⟨‹_›, ‹_›⟩)
section tychonoff
variables [Π i, topological_space (π i)]
/-- **Tychonoff's theorem**: product of compact sets is compact. -/
lemma is_compact_pi_infinite {s : Π i, set (π i)} :
(∀ i, is_compact (s i)) → is_compact {x : Π i, π i | ∀ i, x i ∈ s i} :=
begin
simp only [is_compact_iff_ultrafilter_le_nhds, nhds_pi, filter.pi, exists_prop, mem_set_of_eq,
le_infi_iff, le_principal_iff],
intros h f hfs,
have : ∀ i:ι, ∃ a, a ∈ s i ∧ tendsto (λx:Πi:ι, π i, x i) f (𝓝 a),
{ refine λ i, h i (f.map _) (mem_map.2 _),
exact mem_of_superset hfs (λ x hx, hx i) },
choose a ha,
exact ⟨a, assume i, (ha i).left, assume i, (ha i).right.le_comap⟩
end
/-- **Tychonoff's theorem** formulated using `set.pi`: product of compact sets is compact. -/
lemma is_compact_univ_pi {s : Π i, set (π i)} (h : ∀ i, is_compact (s i)) :
is_compact (pi univ s) :=
by { convert is_compact_pi_infinite h, simp only [← mem_univ_pi, set_of_mem_eq] }
instance pi.compact_space [∀ i, compact_space (π i)] : compact_space (Πi, π i) :=
⟨by { rw [← pi_univ univ], exact is_compact_univ_pi (λ i, is_compact_univ) }⟩
/-- **Tychonoff's theorem** formulated in terms of filters: `filter.cocompact` on an indexed product
type `Π d, κ d` the `filter.Coprod` of filters `filter.cocompact` on `κ d`. -/
lemma filter.Coprod_cocompact {δ : Type*} {κ : δ → Type*} [Π d, topological_space (κ d)] :
filter.Coprod (λ d, filter.cocompact (κ d)) = filter.cocompact (Π d, κ d) :=
begin
refine le_antisymm (supr_le $ λ i, filter.comap_cocompact_le (continuous_apply i)) _,
refine compl_surjective.forall.2 (λ s H, _),
simp only [compl_mem_Coprod, filter.mem_cocompact, compl_subset_compl, image_subset_iff] at H ⊢,
choose K hKc htK using H,
exact ⟨set.pi univ K, is_compact_univ_pi hKc, λ f hf i hi, htK i hf⟩
end
end tychonoff
instance quot.compact_space {r : α → α → Prop} [compact_space α] :
compact_space (quot r) :=
⟨by { rw ← range_quot_mk, exact is_compact_range continuous_quot_mk }⟩
instance quotient.compact_space {s : setoid α} [compact_space α] :
compact_space (quotient s) :=
quot.compact_space
/-- There are various definitions of "locally compact space" in the literature, which agree for
Hausdorff spaces but not in general. This one is the precise condition on X needed for the
evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the
compact-open topology. -/
class locally_compact_space (α : Type*) [topological_space α] : Prop :=
(local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s)
lemma compact_basis_nhds [locally_compact_space α] (x : α) :
(𝓝 x).has_basis (λ s, s ∈ 𝓝 x ∧ is_compact s) (λ s, s) :=
has_basis_self.2 $ by simpa only [and_comm] using locally_compact_space.local_compact_nhds x
lemma local_compact_nhds [locally_compact_space α] {x : α} {n : set α} (h : n ∈ 𝓝 x) :
∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s :=
locally_compact_space.local_compact_nhds _ _ h
lemma locally_compact_space_of_has_basis {ι : α → Type*} {p : Π x, ι x → Prop}
{s : Π x, ι x → set α} (h : ∀ x, (𝓝 x).has_basis (p x) (s x))
(hc : ∀ x i, p x i → is_compact (s x i)) :
locally_compact_space α :=
⟨λ x t ht, let ⟨i, hp, ht⟩ := (h x).mem_iff.1 ht in ⟨s x i, (h x).mem_of_mem hp, ht, hc x i hp⟩⟩
instance locally_compact_space.prod (α : Type*) (β : Type*) [topological_space α]
[topological_space β] [locally_compact_space α] [locally_compact_space β] :
locally_compact_space (α × β) :=
have _ := λ x : α × β, (compact_basis_nhds x.1).prod_nhds' (compact_basis_nhds x.2),
locally_compact_space_of_has_basis this $ λ x s ⟨⟨_, h₁⟩, _, h₂⟩, h₁.prod h₂
section pi
variables [Π i, topological_space (π i)] [∀ i, locally_compact_space (π i)]
/--In general it suffices that all but finitely many of the spaces are compact,
but that's not straightforward to state and use. -/
instance locally_compact_space.pi_finite [finite ι] : locally_compact_space (Π i, π i) :=
⟨λ t n hn, begin
rw [nhds_pi, filter.mem_pi] at hn,
obtain ⟨s, hs, n', hn', hsub⟩ := hn,
choose n'' hn'' hsub' hc using λ i, locally_compact_space.local_compact_nhds (t i) (n' i) (hn' i),
refine ⟨(set.univ : set ι).pi n'', _, subset_trans (λ _ h, _) hsub, is_compact_univ_pi hc⟩,
{ exact (set_pi_mem_nhds_iff (@set.finite_univ ι _) _).mpr (λ i hi, hn'' i), },
{ exact λ i hi, hsub' i (h i trivial), },
end⟩
/-- For spaces that are not Hausdorff. -/
instance locally_compact_space.pi [∀ i, compact_space (π i)] : locally_compact_space (Π i, π i) :=
⟨λ t n hn, begin
rw [nhds_pi, filter.mem_pi] at hn,
obtain ⟨s, hs, n', hn', hsub⟩ := hn,
choose n'' hn'' hsub' hc using λ i, locally_compact_space.local_compact_nhds (t i) (n' i) (hn' i),
refine ⟨s.pi n'', _, subset_trans (λ _, _) hsub, _⟩,
{ exact (set_pi_mem_nhds_iff hs _).mpr (λ i _, hn'' i), },
{ exact forall₂_imp (λ i hi hi', hsub' i hi'), },
{ rw ← set.univ_pi_ite,
refine is_compact_univ_pi (λ i, _),
by_cases i ∈ s,
{ rw if_pos h, exact hc i, },
{ rw if_neg h, exact compact_space.is_compact_univ, } },
end⟩
end pi
/-- A reformulation of the definition of locally compact space: In a locally compact space,
every open set containing `x` has a compact subset containing `x` in its interior. -/
lemma exists_compact_subset [locally_compact_space α] {x : α} {U : set α}
(hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U :=
begin
rcases locally_compact_space.local_compact_nhds x U (hU.mem_nhds hx) with ⟨K, h1K, h2K, h3K⟩,
exact ⟨K, h3K, mem_interior_iff_mem_nhds.2 h1K, h2K⟩,
end
/-- In a locally compact space every point has a compact neighborhood. -/
lemma exists_compact_mem_nhds [locally_compact_space α] (x : α) :
∃ K, is_compact K ∧ K ∈ 𝓝 x :=
let ⟨K, hKc, hx, H⟩ := exists_compact_subset is_open_univ (mem_univ x)
in ⟨K, hKc, mem_interior_iff_mem_nhds.1 hx⟩
/-- In a locally compact space, for every containement `K ⊆ U` of a compact set `K` in an open
set `U`, there is a compact neighborhood `L` such that `K ⊆ L ⊆ U`: equivalently, there is a
compact `L` such that `K ⊆ interior L` and `L ⊆ U`. -/
lemma exists_compact_between [hα : locally_compact_space α] {K U : set α} (hK : is_compact K)
(hU : is_open U) (h_KU : K ⊆ U) : ∃ L, is_compact L ∧ K ⊆ interior L ∧ L ⊆ U :=
begin
choose V hVc hxV hKV using λ x : K, exists_compact_subset hU (h_KU x.2),
have : K ⊆ ⋃ x, interior (V x), from λ x hx, mem_Union.2 ⟨⟨x, hx⟩, hxV _⟩,
rcases hK.elim_finite_subcover _ (λ x, @is_open_interior α _ (V x)) this with ⟨t, ht⟩,
refine ⟨_, t.is_compact_bUnion (λ x _, hVc x), λ x hx, _, set.Union₂_subset (λ i _, hKV i)⟩,
rcases mem_Union₂.1 (ht hx) with ⟨y, hyt, hy⟩,
exact interior_mono (subset_bUnion_of_mem hyt) hy,
end
/-- In a locally compact space, every compact set is contained in the interior of a compact set. -/
lemma exists_compact_superset [locally_compact_space α] {K : set α} (hK : is_compact K) :
∃ K', is_compact K' ∧ K ⊆ interior K' :=
let ⟨L, hLc, hKL, _⟩ := exists_compact_between hK is_open_univ K.subset_univ in ⟨L, hLc, hKL⟩
protected lemma closed_embedding.locally_compact_space [locally_compact_space β] {f : α → β}
(hf : closed_embedding f) : locally_compact_space α :=
begin
have : ∀ x : α, (𝓝 x).has_basis (λ s, s ∈ 𝓝 (f x) ∧ is_compact s) (λ s, f ⁻¹' s),
{ intro x,
rw hf.to_embedding.to_inducing.nhds_eq_comap,
exact (compact_basis_nhds _).comap _ },
exact locally_compact_space_of_has_basis this (λ x s hs, hf.is_compact_preimage hs.2)
end
protected lemma is_closed.locally_compact_space [locally_compact_space α] {s : set α}
(hs : is_closed s) : locally_compact_space s :=
(closed_embedding_subtype_coe hs).locally_compact_space
protected lemma open_embedding.locally_compact_space [locally_compact_space β] {f : α → β}
(hf : open_embedding f) : locally_compact_space α :=
begin
have : ∀ x : α, (𝓝 x).has_basis (λ s, (s ∈ 𝓝 (f x) ∧ is_compact s) ∧ s ⊆ range f) (λ s, f ⁻¹' s),
{ intro x,
rw hf.to_embedding.to_inducing.nhds_eq_comap,
exact ((compact_basis_nhds _).restrict_subset $
hf.open_range.mem_nhds $ mem_range_self _).comap _ },
refine locally_compact_space_of_has_basis this (λ x s hs, _),
rw [← hf.to_inducing.is_compact_iff, image_preimage_eq_of_subset hs.2],
exact hs.1.2
end
protected lemma is_open.locally_compact_space [locally_compact_space α] {s : set α}
(hs : is_open s) : locally_compact_space s :=
hs.open_embedding_subtype_coe.locally_compact_space
lemma ultrafilter.le_nhds_Lim [compact_space α] (F : ultrafilter α) :
↑F ≤ 𝓝 (@Lim _ _ (F : filter α).nonempty_of_ne_bot F) :=
begin
rcases is_compact_univ.ultrafilter_le_nhds F (by simp) with ⟨x, -, h⟩,
exact le_nhds_Lim ⟨x,h⟩,
end
theorem is_closed.exists_minimal_nonempty_closed_subset [compact_space α]
{S : set α} (hS : is_closed S) (hne : S.nonempty) :
∃ (V : set α),
V ⊆ S ∧ V.nonempty ∧ is_closed V ∧
(∀ (V' : set α), V' ⊆ V → V'.nonempty → is_closed V' → V' = V) :=
begin
let opens := {U : set α | Sᶜ ⊆ U ∧ is_open U ∧ Uᶜ.nonempty},
obtain ⟨U, ⟨Uc, Uo, Ucne⟩, h⟩ := zorn_subset opens (λ c hc hz, begin
by_cases hcne : c.nonempty,
{ obtain ⟨U₀, hU₀⟩ := hcne,
haveI : nonempty {U // U ∈ c} := ⟨⟨U₀, hU₀⟩⟩,
obtain ⟨U₀compl, U₀opn, U₀ne⟩ := hc hU₀,
use ⋃₀ c,
refine ⟨⟨_, _, _⟩, λ U hU a ha, ⟨U, hU, ha⟩⟩,
{ exact λ a ha, ⟨U₀, hU₀, U₀compl ha⟩ },
{ exact is_open_sUnion (λ _ h, (hc h).2.1) },
{ convert_to (⋂(U : {U // U ∈ c}), U.1ᶜ).nonempty,
{ ext,
simp only [not_exists, exists_prop, not_and, set.mem_Inter, subtype.forall, mem_set_of_eq,
mem_compl_iff, mem_sUnion] },
apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed,
{ rintros ⟨U, hU⟩ ⟨U', hU'⟩,
obtain ⟨V, hVc, hVU, hVU'⟩ := hz.directed_on U hU U' hU',
exact ⟨⟨V, hVc⟩, set.compl_subset_compl.mpr hVU, set.compl_subset_compl.mpr hVU'⟩, },
{ exact λ U, (hc U.2).2.2, },
{ exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1).is_compact, },
{ exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1), } } },
{ use Sᶜ,
refine ⟨⟨set.subset.refl _, is_open_compl_iff.mpr hS, _⟩, λ U Uc, (hcne ⟨U, Uc⟩).elim⟩,
rw compl_compl,
exact hne, }
end),
refine ⟨Uᶜ, set.compl_subset_comm.mp Uc, Ucne, is_closed_compl_iff.mpr Uo, _⟩,
intros V' V'sub V'ne V'cls,
have : V'ᶜ = U,
{ refine h V'ᶜ ⟨_, is_open_compl_iff.mpr V'cls, _⟩ (set.subset_compl_comm.mp V'sub),
exact set.subset.trans Uc (set.subset_compl_comm.mp V'sub),
simp only [compl_compl, V'ne], },
rw [←this, compl_compl],
end
/-- A σ-compact space is a space that is the union of a countable collection of compact subspaces.
Note that a locally compact separable T₂ space need not be σ-compact.
The sequence can be extracted using `topological_space.compact_covering`. -/
class sigma_compact_space (α : Type*) [topological_space α] : Prop :=
(exists_compact_covering : ∃ K : ℕ → set α, (∀ n, is_compact (K n)) ∧ (⋃ n, K n) = univ)
@[priority 200] -- see Note [lower instance priority]
instance compact_space.sigma_compact [compact_space α] : sigma_compact_space α :=
⟨⟨λ _, univ, λ _, is_compact_univ, Union_const _⟩⟩
lemma sigma_compact_space.of_countable (S : set (set α)) (Hc : S.countable)
(Hcomp : ∀ s ∈ S, is_compact s) (HU : ⋃₀ S = univ) : sigma_compact_space α :=
⟨(exists_seq_cover_iff_countable ⟨_, is_compact_empty⟩).2 ⟨S, Hc, Hcomp, HU⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance sigma_compact_space_of_locally_compact_second_countable [locally_compact_space α]
[second_countable_topology α] : sigma_compact_space α :=
begin
choose K hKc hxK using λ x : α, exists_compact_mem_nhds x,
rcases countable_cover_nhds hxK with ⟨s, hsc, hsU⟩,
refine sigma_compact_space.of_countable _ (hsc.image K) (ball_image_iff.2 $ λ x _, hKc x) _,
rwa sUnion_image
end
variables (α) [sigma_compact_space α]
open sigma_compact_space
/-- A choice of compact covering for a `σ`-compact space, chosen to be monotone. -/
def compact_covering : ℕ → set α :=
accumulate exists_compact_covering.some
lemma is_compact_compact_covering (n : ℕ) : is_compact (compact_covering α n) :=
is_compact_accumulate (classical.some_spec sigma_compact_space.exists_compact_covering).1 n
lemma Union_compact_covering : (⋃ n, compact_covering α n) = univ :=
begin
rw [compact_covering, Union_accumulate],
exact (classical.some_spec sigma_compact_space.exists_compact_covering).2
end
@[mono] lemma compact_covering_subset ⦃m n : ℕ⦄ (h : m ≤ n) :
compact_covering α m ⊆ compact_covering α n :=
monotone_accumulate h
variable {α}
lemma exists_mem_compact_covering (x : α) : ∃ n, x ∈ compact_covering α n :=
Union_eq_univ_iff.mp (Union_compact_covering α) x
/-- If `α` is a `σ`-compact space, then a locally finite family of nonempty sets of `α` can have
only countably many elements, `set.countable` version. -/
protected lemma locally_finite.countable_univ {ι : Type*} {f : ι → set α} (hf : locally_finite f)
(hne : ∀ i, (f i).nonempty) :
(univ : set ι).countable :=
begin
have := λ n, hf.finite_nonempty_inter_compact (is_compact_compact_covering α n),
refine (countable_Union (λ n, (this n).countable)).mono (λ i hi, _),
rcases hne i with ⟨x, hx⟩,
rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩,
exact mem_Union.2 ⟨n, x, hx, hn⟩
end
/-- If `f : ι → set α` is a locally finite covering of a σ-compact topological space by nonempty
sets, then the index type `ι` is encodable. -/
protected noncomputable def locally_finite.encodable {ι : Type*} {f : ι → set α}
(hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : encodable ι :=
@encodable.of_equiv _ _ (hf.countable_univ hne).to_encodable (equiv.set.univ _).symm
/-- In a topological space with sigma compact topology, if `f` is a function that sends each point
`x` of a closed set `s` to a neighborhood of `x` within `s`, then for some countable set `t ⊆ s`,
the neighborhoods `f x`, `x ∈ t`, cover the whole set `s`. -/
lemma countable_cover_nhds_within_of_sigma_compact {f : α → set α} {s : set α} (hs : is_closed s)
(hf : ∀ x ∈ s, f x ∈ 𝓝[s] x) : ∃ t ⊆ s, t.countable ∧ s ⊆ ⋃ x ∈ t, f x :=
begin
simp only [nhds_within, mem_inf_principal] at hf,
choose t ht hsub using λ n, ((is_compact_compact_covering α n).inter_right hs).elim_nhds_subcover
_ (λ x hx, hf x hx.right),
refine ⟨⋃ n, (t n : set α), Union_subset $ λ n x hx, (ht n x hx).2,
countable_Union $ λ n, (t n).countable_to_set, λ x hx, mem_Union₂.2 _⟩,
rcases exists_mem_compact_covering x with ⟨n, hn⟩,
rcases mem_Union₂.1 (hsub n ⟨hn, hx⟩) with ⟨y, hyt : y ∈ t n, hyf : x ∈ s → x ∈ f y⟩,
exact ⟨y, mem_Union.2 ⟨n, hyt⟩, hyf hx⟩
end
/-- In a topological space with sigma compact topology, if `f` is a function that sends each
point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`,
`x ∈ s`, cover the whole space. -/
lemma countable_cover_nhds_of_sigma_compact {f : α → set α}
(hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : set α, s.countable ∧ (⋃ x ∈ s, f x) = univ :=
begin
simp only [← nhds_within_univ] at hf,
rcases countable_cover_nhds_within_of_sigma_compact is_closed_univ (λ x _, hf x)
with ⟨s, -, hsc, hsU⟩,
exact ⟨s, hsc, univ_subset_iff.1 hsU⟩
end
end compact
/-- An [exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets) of a
topological space is a sequence of compact sets `K n` such that `K n ⊆ interior (K (n + 1))` and
`(⋃ n, K n) = univ`.
If `X` is a locally compact sigma compact space, then `compact_exhaustion.choice X` provides
a choice of an exhaustion by compact sets. This choice is also available as
`(default : compact_exhaustion X)`. -/
structure compact_exhaustion (X : Type*) [topological_space X] :=
(to_fun : ℕ → set X)
(is_compact' : ∀ n, is_compact (to_fun n))
(subset_interior_succ' : ∀ n, to_fun n ⊆ interior (to_fun (n + 1)))
(Union_eq' : (⋃ n, to_fun n) = univ)
namespace compact_exhaustion
instance : has_coe_to_fun (compact_exhaustion α) (λ _, ℕ → set α) := ⟨to_fun⟩
variables {α} (K : compact_exhaustion α)
protected lemma is_compact (n : ℕ) : is_compact (K n) := K.is_compact' n
lemma subset_interior_succ (n : ℕ) : K n ⊆ interior (K (n + 1)) :=
K.subset_interior_succ' n
lemma subset_succ (n : ℕ) : K n ⊆ K (n + 1) :=
subset.trans (K.subset_interior_succ n) interior_subset
@[mono] protected lemma subset ⦃m n : ℕ⦄ (h : m ≤ n) : K m ⊆ K n :=
show K m ≤ K n, from monotone_nat_of_le_succ K.subset_succ h
lemma subset_interior ⦃m n : ℕ⦄ (h : m < n) : K m ⊆ interior (K n) :=
subset.trans (K.subset_interior_succ m) $ interior_mono $ K.subset h
lemma Union_eq : (⋃ n, K n) = univ := K.Union_eq'
lemma exists_mem (x : α) : ∃ n, x ∈ K n := Union_eq_univ_iff.1 K.Union_eq x
/-- The minimal `n` such that `x ∈ K n`. -/
protected noncomputable def find (x : α) : ℕ := nat.find (K.exists_mem x)
lemma mem_find (x : α) : x ∈ K (K.find x) := nat.find_spec (K.exists_mem x)
lemma mem_iff_find_le {x : α} {n : ℕ} : x ∈ K n ↔ K.find x ≤ n :=
⟨λ h, nat.find_min' (K.exists_mem x) h, λ h, K.subset h $ K.mem_find x⟩
/-- Prepend the empty set to a compact exhaustion `K n`. -/
def shiftr : compact_exhaustion α :=
{ to_fun := λ n, nat.cases_on n ∅ K,
is_compact' := λ n, nat.cases_on n is_compact_empty K.is_compact,
subset_interior_succ' := λ n, nat.cases_on n (empty_subset _) K.subset_interior_succ,
Union_eq' := Union_eq_univ_iff.2 $ λ x, ⟨K.find x + 1, K.mem_find x⟩ }
@[simp] lemma find_shiftr (x : α) : K.shiftr.find x = K.find x + 1 :=
nat.find_comp_succ _ _ (not_mem_empty _)
lemma mem_diff_shiftr_find (x : α) : x ∈ K.shiftr (K.find x + 1) \ K.shiftr (K.find x) :=
⟨K.mem_find _, mt K.shiftr.mem_iff_find_le.1 $
by simp only [find_shiftr, not_le, nat.lt_succ_self]⟩
/-- A choice of an
[exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets)
of a locally compact sigma compact space. -/
noncomputable def choice (X : Type*) [topological_space X] [locally_compact_space X]
[sigma_compact_space X] : compact_exhaustion X :=
begin
apply classical.choice,
let K : ℕ → {s : set X // is_compact s} :=
λ n, nat.rec_on n ⟨∅, is_compact_empty⟩
(λ n s, ⟨(exists_compact_superset s.2).some ∪ compact_covering X n,
(exists_compact_superset s.2).some_spec.1.union (is_compact_compact_covering _ _)⟩),
refine ⟨⟨λ n, K n, λ n, (K n).2, λ n, _, _⟩⟩,
{ exact subset.trans (exists_compact_superset (K n).2).some_spec.2
(interior_mono $ subset_union_left _ _) },
{ refine univ_subset_iff.1 (Union_compact_covering X ▸ _),
exact Union_mono' (λ n, ⟨n + 1, subset_union_right _ _⟩) }
end
noncomputable instance [locally_compact_space α] [sigma_compact_space α] :
inhabited (compact_exhaustion α) :=
⟨compact_exhaustion.choice α⟩
end compact_exhaustion
section clopen
/-- A set is clopen if it is both open and closed. -/
def is_clopen (s : set α) : Prop :=
is_open s ∧ is_closed s
protected lemma is_clopen.is_open (hs : is_clopen s) : is_open s := hs.1
protected lemma is_clopen.is_closed (hs : is_clopen s) : is_closed s := hs.2
lemma is_clopen_iff_frontier_eq_empty {s : set α} : is_clopen s ↔ frontier s = ∅ :=
begin
rw [is_clopen, ← closure_eq_iff_is_closed, ← interior_eq_iff_is_open, frontier, diff_eq_empty],
refine ⟨λ h, (h.2.trans h.1.symm).subset, λ h, _⟩,
exact ⟨interior_subset.antisymm (subset_closure.trans h),
(h.trans interior_subset).antisymm subset_closure⟩
end
alias is_clopen_iff_frontier_eq_empty ↔ is_clopen.frontier_eq _
theorem is_clopen.union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) :=
⟨hs.1.union ht.1, hs.2.union ht.2⟩
theorem is_clopen.inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) :=
⟨hs.1.inter ht.1, hs.2.inter ht.2⟩
@[simp] theorem is_clopen_empty : is_clopen (∅ : set α) :=
⟨is_open_empty, is_closed_empty⟩
@[simp] theorem is_clopen_univ : is_clopen (univ : set α) :=
⟨is_open_univ, is_closed_univ⟩
theorem is_clopen.compl {s : set α} (hs : is_clopen s) : is_clopen sᶜ :=
⟨hs.2.is_open_compl, hs.1.is_closed_compl⟩
@[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen sᶜ ↔ is_clopen s :=
⟨λ h, compl_compl s ▸ is_clopen.compl h, is_clopen.compl⟩
theorem is_clopen.diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) :=
hs.inter ht.compl
lemma is_clopen.prod {s : set α} {t : set β} (hs : is_clopen s) (ht : is_clopen t) :
is_clopen (s ×ˢ t) :=
⟨hs.1.prod ht.1, hs.2.prod ht.2⟩
lemma is_clopen_Union {β : Type*} [finite β] {s : β → set α} (h : ∀ i, is_clopen (s i)) :
is_clopen (⋃ i, s i) :=
⟨is_open_Union (forall_and_distrib.1 h).1, is_closed_Union (forall_and_distrib.1 h).2⟩
lemma is_clopen_bUnion {β : Type*} {s : set β} {f : β → set α} (hs : s.finite)
(h : ∀ i ∈ s, is_clopen $ f i) :
is_clopen (⋃ i ∈ s, f i) :=
⟨is_open_bUnion (λ i hi, (h i hi).1), is_closed_bUnion hs (λ i hi, (h i hi).2)⟩
lemma is_clopen_bUnion_finset {β : Type*} {s : finset β} {f : β → set α}
(h : ∀ i ∈ s, is_clopen $ f i) :
is_clopen (⋃ i ∈ s, f i) :=
is_clopen_bUnion s.finite_to_set h
lemma is_clopen_Inter {β : Type*} [finite β] {s : β → set α} (h : ∀ i, is_clopen (s i)) :
is_clopen (⋂ i, s i) :=
⟨(is_open_Inter (forall_and_distrib.1 h).1), (is_closed_Inter (forall_and_distrib.1 h).2)⟩
lemma is_clopen_bInter {β : Type*} {s : set β} (hs : s.finite) {f : β → set α}
(h : ∀ i ∈ s, is_clopen (f i)) :
is_clopen (⋂ i ∈ s, f i) :=
⟨is_open_bInter hs (λ i hi, (h i hi).1), is_closed_bInter (λ i hi, (h i hi).2)⟩
lemma is_clopen_bInter_finset {β : Type*} {s : finset β} {f : β → set α}
(h : ∀ i ∈ s, is_clopen (f i)) :
is_clopen (⋂ i ∈ s, f i) :=
is_clopen_bInter s.finite_to_set h
lemma is_clopen.preimage {s : set β} (h : is_clopen s) {f : α → β} (hf : continuous f) :
is_clopen (f ⁻¹' s) :=
⟨h.1.preimage hf, h.2.preimage hf⟩
lemma continuous_on.preimage_clopen_of_clopen
{f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_clopen s)
(ht : is_clopen t) : is_clopen (s ∩ f⁻¹' t) :=
⟨continuous_on.preimage_open_of_open hf hs.1 ht.1,
continuous_on.preimage_closed_of_closed hf hs.2 ht.2⟩
/-- The intersection of a disjoint covering by two open sets of a clopen set will be clopen. -/
theorem is_clopen_inter_of_disjoint_cover_clopen {Z a b : set α} (h : is_clopen Z)
(cover : Z ⊆ a ∪ b) (ha : is_open a) (hb : is_open b) (hab : disjoint a b) : is_clopen (Z ∩ a) :=
begin
refine ⟨is_open.inter h.1 ha, _⟩,
have : is_closed (Z ∩ bᶜ) := is_closed.inter h.2 (is_closed_compl_iff.2 hb),
convert this using 1,
refine (inter_subset_inter_right Z hab.subset_compl_right).antisymm _,
rintro x ⟨hx₁, hx₂⟩,
exact ⟨hx₁, by simpa [not_mem_of_mem_compl hx₂] using cover hx₁⟩,
end
@[simp] lemma is_clopen_discrete [discrete_topology α] (x : set α) : is_clopen x :=
⟨is_open_discrete _, is_closed_discrete _⟩
lemma clopen_range_sigma_mk {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] {i : ι} :
is_clopen (set.range (@sigma.mk ι σ i)) :=
⟨open_embedding_sigma_mk.open_range, closed_embedding_sigma_mk.closed_range⟩
protected lemma quotient_map.is_clopen_preimage {f : α → β}
(hf : quotient_map f) {s : set β} : is_clopen (f ⁻¹' s) ↔ is_clopen s :=
and_congr hf.is_open_preimage hf.is_closed_preimage
variables {X : Type*} [topological_space X]
lemma continuous_bool_indicator_iff_clopen (U : set X) :
continuous U.bool_indicator ↔ is_clopen U :=
begin
split,
{ intros hc,
rw ← U.preimage_bool_indicator_tt,
exact
⟨hc.is_open_preimage _ trivial, continuous_iff_is_closed.mp hc _ (is_closed_discrete _)⟩ },
{ refine λ hU, ⟨λ s hs, _⟩,
rcases U.preimage_bool_indicator s with (h|h|h|h) ; rw h,
exacts [is_open_univ, hU.1, hU.2.is_open_compl, is_open_empty] },
end
lemma continuous_on_indicator_iff_clopen (s U : set X) :
continuous_on U.bool_indicator s ↔ is_clopen ((coe : s → X) ⁻¹' U) :=
begin
rw [continuous_on_iff_continuous_restrict, ← continuous_bool_indicator_iff_clopen],
refl
end
end clopen
section preirreducible
/-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/
def is_preirreducible (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v →
(s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty
/-- An irreducible set `s` is one that is nonempty and
where there is no non-trivial pair of disjoint opens on `s`. -/
def is_irreducible (s : set α) : Prop :=
s.nonempty ∧ is_preirreducible s
lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) :
s.nonempty := h.1
lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) :
is_preirreducible s := h.2
theorem is_preirreducible_empty : is_preirreducible (∅ : set α) :=
λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim
lemma set.subsingleton.is_preirreducible {s : set α} (hs : s.subsingleton) :
is_preirreducible s :=
λ u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩, ⟨y, hys, hs hxs hys ▸ hxu, hyv⟩
theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) :=
⟨singleton_nonempty x, subsingleton_singleton.is_preirreducible⟩
theorem is_preirreducible_iff_closure {s : set α} :
is_preirreducible (closure s) ↔ is_preirreducible s :=
forall₄_congr $ λ u v hu hv,
by { iterate 3 { rw closure_inter_open_nonempty_iff }, exacts [hu.inter hv, hv, hu] }
theorem is_irreducible_iff_closure {s : set α} :
is_irreducible (closure s) ↔ is_irreducible s :=
and_congr closure_nonempty_iff is_preirreducible_iff_closure
alias is_preirreducible_iff_closure ↔ _ is_preirreducible.closure
alias is_irreducible_iff_closure ↔ _ is_irreducible.closure
theorem exists_preirreducible (s : set α) (H : is_preirreducible s) :
∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t :=
let ⟨m, hm, hsm, hmm⟩ := zorn_subset_nonempty {t : set α | is_preirreducible t}
(λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in
⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩,
let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy,
⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in
or.cases_on (hcc.total hpc hqc)
(assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv
⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩)
(assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv
⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩),
λ x hxc, subset_sUnion_of_mem hxc⟩) s H in
⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩
/-- The set of irreducible components of a topological space. -/
def irreducible_components (α : Type*) [topological_space α] : set (set α) :=
maximals (≤) { s : set α | is_irreducible s }
lemma is_closed_of_mem_irreducible_components (s ∈ irreducible_components α) :
is_closed s :=
begin
rw [← closure_eq_iff_is_closed, eq_comm],
exact subset_closure.antisymm (H.2 H.1.closure subset_closure),
end
lemma irreducible_components_eq_maximals_closed (α : Type*) [topological_space α] :
irreducible_components α = maximals (≤) { s : set α | is_closed s ∧ is_irreducible s } :=
begin
ext s,
split,
{ intro H, exact ⟨⟨is_closed_of_mem_irreducible_components _ H, H.1⟩, λ x h e, H.2 h.2 e⟩ },
{ intro H, refine ⟨H.1.2, λ x h e, _⟩,
have : closure x ≤ s,
{ exact H.2 ⟨is_closed_closure, h.closure⟩ (e.trans subset_closure) },
exact le_trans subset_closure this }
end
/-- A maximal irreducible set that contains a given point. -/
def irreducible_component (x : α) : set α :=
classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible)
lemma irreducible_component_property (x : α) :
is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧
∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) :=
classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible)
theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x :=
singleton_subset_iff.1 (irreducible_component_property x).2.1
theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) :=
⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩
theorem eq_irreducible_component {x : α} :
∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x :=
(irreducible_component_property x).2.2
lemma irreducible_component_mem_irreducible_components (x : α) :
irreducible_component x ∈ irreducible_components α :=
⟨is_irreducible_irreducible_component, λ s h₁ h₂,(eq_irreducible_component h₁.2 h₂).le⟩
theorem is_closed_irreducible_component {x : α} :
is_closed (irreducible_component x) :=
is_closed_of_mem_irreducible_components _ (irreducible_component_mem_irreducible_components x)
/-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/
class preirreducible_space (α : Type u) [topological_space α] : Prop :=
(is_preirreducible_univ [] : is_preirreducible (univ : set α))
/-- An irreducible space is one that is nonempty
and where there is no non-trivial pair of disjoint opens. -/
class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop :=
(to_nonempty [] : nonempty α)
-- see Note [lower instance priority]
attribute [instance, priority 50] irreducible_space.to_nonempty
lemma irreducible_space.is_irreducible_univ (α : Type u) [topological_space α]
[irreducible_space α] : is_irreducible (⊤ : set α) :=
⟨by simp, preirreducible_space.is_preirreducible_univ α⟩
lemma irreducible_space_def (α : Type u) [topological_space α] :
irreducible_space α ↔ is_irreducible (⊤ : set α) :=
⟨@@irreducible_space.is_irreducible_univ α _,
λ h, by { haveI : preirreducible_space α := ⟨h.2⟩, exact ⟨⟨h.1.some⟩⟩ }⟩
theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} :
is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty :=
by simpa only [univ_inter, univ_subset_iff] using
@preirreducible_space.is_preirreducible_univ α _ _ s t
/-- In a (pre)irreducible space, a nonempty open set is dense. -/
protected theorem is_open.dense [preirreducible_space α] {s : set α} (ho : is_open s)
(hne : s.nonempty) : dense s :=
dense_iff_inter_open.2 $ λ t hto htne, nonempty_preirreducible_inter hto ho htne hne
theorem is_preirreducible.image {s : set α} (H : is_preirreducible s)
(f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) :=
begin
rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩,
rw ← mem_preimage at hxu hyv,
rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩,
rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩,
have := H u' v' hu' hv',
rw [inter_comm s u', ← u'_eq] at this,
rw [inter_comm s v', ← v'_eq] at this,
rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩,
refine ⟨f z, mem_image_of_mem f hzs, _, _⟩,
all_goals
{ rw ← mem_preimage,
apply mem_of_mem_inter_left,
show z ∈ _ ∩ s,
simp [*] }
end
theorem is_irreducible.image {s : set α} (H : is_irreducible s)
(f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) :=
⟨H.nonempty.image _, H.is_preirreducible.image f hf⟩
lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) :
preirreducible_space s :=
{ is_preirreducible_univ :=
begin
intros u v hu hv hsu hsv,
rw is_open_induced_iff at hu hv,
rcases hu with ⟨u, hu, rfl⟩,
rcases hv with ⟨v, hv, rfl⟩,
rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩,
rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩,
rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩,
exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩
end }
lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) :
irreducible_space s :=
{ is_preirreducible_univ :=
(subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ,
to_nonempty := h.nonempty.to_subtype }
/-- An infinite type with cofinite topology is an irreducible topological space. -/
@[priority 100] instance {α} [infinite α] : irreducible_space (cofinite_topology α) :=
{ is_preirreducible_univ := λ u v,
begin
haveI : infinite (cofinite_topology α) := ‹_›,
simp only [cofinite_topology.is_open_iff, univ_inter],
intros hu hv hu' hv',
simpa only [compl_union, compl_compl] using ((hu hu').union (hv hv')).infinite_compl.nonempty
end,
to_nonempty := (infer_instance : nonempty α) }
/-- A set `s` is irreducible if and only if
for every finite collection of open sets all of whose members intersect `s`,
`s` also intersects the intersection of the entire collection
(i.e., there is an element of `s` contained in every member of the collection). -/
lemma is_irreducible_iff_sInter {s : set α} :
is_irreducible s ↔
∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty),
(s ∩ ⋂₀ ↑U).nonempty :=
begin
split; intro h,
{ intro U, apply finset.induction_on U,
{ intros, simpa using h.nonempty },
{ intros u U hu IH hU H,
rw [finset.coe_insert, sInter_insert],
apply h.2,
{ solve_by_elim [finset.mem_insert_self] },
{ apply is_open_sInter (finset.finite_to_set U),
intros, solve_by_elim [finset.mem_insert_of_mem] },
{ solve_by_elim [finset.mem_insert_self] },
{ apply IH,
all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } },
{ split,
{ simpa using h ∅ _ _; intro u; simp },
intros u v hu hv hu' hv',
simpa using h {u,v} _ _,
all_goals
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption } }
end
/-- A set is preirreducible if and only if
for every cover by two closed sets, it is contained in one of the two covering sets. -/
lemma is_preirreducible_iff_closed_union_closed {s : set α} :
is_preirreducible s ↔
∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ :=
begin
split,
all_goals
{ intros h t₁ t₂ ht₁ ht₂,
specialize h t₁ᶜ t₂ᶜ,
simp only [is_open_compl_iff, is_closed_compl_iff] at h,
specialize h ht₁ ht₂ },
{ contrapose!, simp only [not_subset],
rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩,
rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩,
rw ← compl_union at hz',
exact ⟨z, hz, hz'⟩ },
{ rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩,
rw ← compl_inter at h,
delta set.nonempty,
rw imp_iff_not_or at h,
contrapose! h,
split,
{ intros z hz hz', exact h z ⟨hz, hz'⟩ },
{ split; intro H; refine H _ ‹_›; assumption } }
end
/-- A set is irreducible if and only if
for every cover by a finite collection of closed sets,
it is contained in one of the members of the collection. -/
lemma is_irreducible_iff_sUnion_closed {s : set α} :
is_irreducible s ↔
∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z),
∃ z ∈ Z, s ⊆ z :=
begin
rw [is_irreducible, is_preirreducible_iff_closed_union_closed],
split; intro h,
{ intro Z, apply finset.induction_on Z,
{ intros, rw [finset.coe_empty, sUnion_empty] at H,
rcases h.1 with ⟨x, hx⟩,
exfalso, tauto },
{ intros z Z hz IH hZ H,
cases h.2 z (⋃₀ ↑Z) _ _ _
with h' h',
{ exact ⟨z, finset.mem_insert_self _ _, h'⟩ },
{ rcases IH _ h' with ⟨z', hz', hsz'⟩,
{ exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ },
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ solve_by_elim [finset.mem_insert_self] },
{ rw sUnion_eq_bUnion,
apply is_closed_bUnion (finset.finite_to_set Z),
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ simpa using H } } },
{ split,
{ by_contradiction hs,
simpa using h ∅ _ _,
{ intro z, simp },
{ simpa [set.nonempty] using hs } },
intros z₁ z₂ hz₁ hz₂ H,
have := h {z₁, z₂} _ _,
simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this,
{ rcases this with ⟨z, rfl|rfl, hz⟩; tauto },
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption },
{ simpa using H } }
end
/-- A nonemtpy open subset of a preirreducible subspace is dense in the subspace. -/
lemma subset_closure_inter_of_is_preirreducible_of_is_open {S U : set α}
(hS : is_preirreducible S) (hU : is_open U) (h : (S ∩ U).nonempty) : S ⊆ closure (S ∩ U) :=
begin
by_contra h',
obtain ⟨x, h₁, h₂, h₃⟩ := hS _ (closure (S ∩ U))ᶜ hU (is_open_compl_iff.mpr is_closed_closure) h
(set.inter_compl_nonempty_iff.mpr h'),
exact h₃ (subset_closure ⟨h₁, h₂⟩)
end
/-- If `∅ ≠ U ⊆ S ⊆ Z` such that `U` is open and `Z` is preirreducible, then `S` is irreducible. -/
lemma is_preirreducible.subset_irreducible {S U Z : set α}
(hZ : is_preirreducible Z) (hU : U.nonempty) (hU' : is_open U)
(h₁ : U ⊆ S) (h₂ : S ⊆ Z) : is_irreducible S :=
begin
classical,
obtain ⟨z, hz⟩ := hU,
replace hZ : is_irreducible Z := ⟨⟨z, h₂ (h₁ hz)⟩, hZ⟩,
refine ⟨⟨z, h₁ hz⟩, _⟩,
rintros u v hu hv ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩,
obtain ⟨a, -, ha'⟩ := is_irreducible_iff_sInter.mp hZ {U, u, v} (by tidy) _,
replace ha' : a ∈ U ∧ a ∈ u ∧ a ∈ v := by simpa using ha',
exact ⟨a, h₁ ha'.1, ha'.2⟩,
{ intros U H,
simp only [finset.mem_insert, finset.mem_singleton] at H,
rcases H with (rfl|rfl|rfl),
exacts [⟨z, h₂ (h₁ hz), hz⟩, ⟨x, h₂ hx, hx'⟩, ⟨y, h₂ hy, hy'⟩] }
end
lemma is_preirreducible.open_subset {Z U : set α} (hZ : is_preirreducible Z)
(hU : is_open U) (hU' : U ⊆ Z) :
is_preirreducible U :=
U.eq_empty_or_nonempty.elim (λ h, h.symm ▸ is_preirreducible_empty)
(λ h, (hZ.subset_irreducible h hU (λ _, id) hU').2)
lemma is_preirreducible.interior {Z : set α} (hZ : is_preirreducible Z) :
is_preirreducible (interior Z) :=
hZ.open_subset is_open_interior interior_subset
lemma is_preirreducible.preimage {Z : set α} (hZ : is_preirreducible Z)
{f : β → α} (hf : open_embedding f) :
is_preirreducible (f ⁻¹' Z) :=
begin
rintros U V hU hV ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩,
obtain ⟨_, h₁, ⟨z, h₂, rfl⟩, ⟨z', h₃, h₄⟩⟩ := hZ _ _ (hf.is_open_map _ hU) (hf.is_open_map _ hV)
⟨f x, hx, set.mem_image_of_mem f hx'⟩ ⟨f y, hy, set.mem_image_of_mem f hy'⟩,
cases hf.inj h₄,
exact ⟨z, h₁, h₂, h₃⟩
end
end preirreducible
|
13b8f07ad8da82fb101383706784f51f132eddbf | 761fea1362b10b4c588c2dfc0ae90c70b119e35d | /src/extract_consts.lean | c5ee74217c8909bf4849373c63c753e6826f1621 | [] | no_license | holtzermann17/mm-lean | 382a29fca5245f97cf488c525ed0c9594917f73b | a9130d71ed448f62df28d4128043b707bad85ccd | refs/heads/master | 1,588,477,413,982 | 1,553,885,046,000 | 1,553,885,046,000 | 178,404,617 | 0 | 0 | null | 1,553,863,829,000 | 1,553,863,828,000 | null | UTF-8 | Lean | false | false | 6,094 | lean | import data.set.basic
open tactic expr
/-
meta def expr.mfold' {α : Type} : Π (e : expr) (a : α) (f : expr → α → tactic α), tactic α
| (var e) a f := f (var e) a
| (sort l) a f := f (sort l) a
| (const nm l) a f := f (const nm l) a
| (mvar nm ppnm tp) a f:= (f (mvar nm ppnm tp) a) >>= λ a', expr.mfold' tp a' f
| (local_const nm ppnm bi tp) a f := (f (local_const nm ppnm bi tp) a) >>= λ a', expr.mfold' tp a' f
| (app e1 e2) a f := do v1 ← (f (app e1 e2) a) >>= λ a', expr.mfold' e1 a' f, expr.mfold' e2 v1 f
| (lam nm bi e1 e2) a f :=
do v1 ← (f (lam nm bi e1 e2) a) >>= λ a', expr.mfold' e1 a' f,
lc ← mk_local' nm bi e1,
e2' ← return $ e2.instantiate_var lc,
expr.mfold' e2' v1 f
| (pi nm bi e1 e2) a f :=
do v1 ← (f (pi nm bi e1 e2) a) >>= λ a', expr.mfold' e1 a' f,
lc ← mk_local' nm bi e1,
e2' ← return $ e2.instantiate_var lc,
expr.mfold' e2' v1 f
| (elet n e1 e2 e3) a f := do v1 ← (f (elet n e1 e2 e3) a) >>= λ a', expr.mfold' e1 a' f, v2 ← expr.mfold' e2 v1 f, expr.mfold' e3 v2 f
| (macro c b) a f := f (macro c b) a
meta def prop_subterms (e : expr) : tactic (rb_set expr) :=
e.mfold' mk_rb_set
(λ e s,
do ip ← is_proof e,
return $ if ip then s.insert e else s)
meta def is_forall : expr → tactic bool
| (pi nm bi tp bd) := do sort l ← infer_type tp, return $ bnot (l = level.zero)
| _ := return ff
meta def lemmas_used (e : expr) : tactic (list expr) :=
do pst ← prop_subterms e,
pst.to_list.mmap infer_type >>= mfilter (λ x, bnot <$> is_forall x)
/-#check list.filter
run_cmd
do dcl ← get_decl `add_le_add,
pst ← prop_subterms dcl.value,
-- trace pst,
pst.to_list.mmap infer_type >>= mfilter (λ x, bnot <$> is_forall x) >>= trace
-- (pst.to_list.mfilter (λ x, bnot <$> (is_forall x))) >>= mmap infer_type >>= trace-/
-/
meta def is_prop_concl_tp : expr → tactic bool
--| `(Prop) := tt
| `(Π _ : %%T, %%b) := do m ← mk_meta_var T, is_prop_concl_tp (b.instantiate_var m)
| t := do tp ← infer_type t, return $ tp = `(Prop)
meta def is_prop_concl (e : expr) : tactic unit :=
do tp ← infer_type e,
b ← is_prop_concl_tp tp,
if b then skip else failed
run_cmd is_prop_concl `(nat.mod_lt)
meta def list_prop_consts : expr → tactic (list name)
| (var _) := return []
| (sort _) := return []
| (const nm l) := (is_prop_concl (const nm l) >> return [nm]) <|> return []
| (mvar _ _ tp) := list_prop_consts tp
| (local_const _ _ _ tp) := list_prop_consts tp
| (app e1 e2) := do l1 ← list_prop_consts e1, l2 ← list_prop_consts e2, return $ l1 ++ l2
| (lam _ _ e1 e2) := do l1 ← list_prop_consts e1, l2 ← list_prop_consts e2, return $ l1 ++ l2
| (pi _ _ e1 e2) := do l1 ← list_prop_consts e1, l2 ← list_prop_consts e2, return $ l1 ++ l2
| (elet _ e1 e2 e3) := do l1 ← list_prop_consts e1, l2 ← list_prop_consts e2, l3 ← list_prop_consts e3, return $ l1 ++ l2 ++ l3
| (macro _ _) := return []
meta def is_app_of_int_const (ics : name_set) : expr → bool
| (const nm _) := ics.contains nm
| (app e1 e2) := is_app_of_int_const e1
| _ := ff
meta def apps_of_interesting_consts (ics : name_set) : expr → tactic (list expr)
| (var _) := return []
| (sort _) := return []
| (const nm l) := return []
| (mvar _ _ tp) := apps_of_interesting_consts tp
| (local_const _ _ _ tp) := apps_of_interesting_consts tp
| (app e1 e2) := if is_app_of_int_const ics e1 then do l1 ← apps_of_interesting_consts e2, rv ← whnf $ app e1 e2, return $ [rv] ++ l1 else do l1 ← apps_of_interesting_consts e1, l2 ← apps_of_interesting_consts e2, return $ l1 ++ l2
| (lam nm bi e1 e2) := do l1 ← apps_of_interesting_consts e1, l2 ← apps_of_interesting_consts (e2.instantiate_var (local_const nm nm binder_info.default e1)), return $ l1 ++ l2
| (pi _ _ e1 e2) := do l1 ← apps_of_interesting_consts e1, l2 ← apps_of_interesting_consts e2, return $ l1 ++ l2
| (elet _ e1 e2 e3) :=do l1 ← apps_of_interesting_consts e1, l2 ← apps_of_interesting_consts e2, l3 ← apps_of_interesting_consts e3, return $ l1 ++ l2 ++ l3
| (macro _ _) := return []
section
open name
meta def is_recursor : name → bool
| (mk_string "rec" n) := tt
| (mk_string "rec_on" n) := tt
| (mk_string "cases_on" n) := tt
| (mk_string "case_strong_induction_on" n) := tt
| _ := ff
private meta def boring_consts : name_set :=
name_set.of_list [`id_locked, `congr, `forall_congr_eq, `congr_arg, `propext, `forall_const, `eq_self_iff_true]
meta def is_boring : name → bool
| (mk_string _ (mk_string "eq" _)) := tt
| (mk_string _ (mk_string "or" _)) := tt
| (mk_string _ (mk_string "and" _)) := tt
| (mk_string _ (mk_string "decidable" _)) := tt
| (mk_string _ (mk_string "iff" _)) := tt
| (mk_string _ (mk_string "not" _)) := tt
| n := boring_consts.contains n
end
meta def is_interesting (n : name) : bool :=
bnot (is_recursor n || is_boring n)
meta def get_interesting_consts (e : expr) : tactic name_set :=
do ns ← name_set.of_list <$> list_prop_consts e,
return $ ns.filter is_interesting
meta def get_interesting_lemmas_used (e : expr) : tactic (list (name × expr)) :=
do ns ← get_interesting_consts e,
ns.mfold [] (λ n l, do tp ← mk_const n >>= infer_type, return ((n, tp)::l))
meta def print_name_type_list (exs : list (name × expr)) : tactic string :=
string.join <$> exs.mmap (λ s, do pps ← pp s.2, return $ s.1.to_string ++ " : " ++ pps.to_string ++ "\n")
meta def print_lemmas_used (e : expr) : tactic string :=
do exs ← get_interesting_lemmas_used e,
--pex ← exs.mmap pp,
print_name_type_list exs
/-
run_cmd
do l ← get_decl `nat.mod_lt,
ns ← name_set.of_list <$> list_prop_consts l.value,
trace $ (ns.filter is_interesting),
print_lemmas_used l.value >>= trace
run_cmd
do l ← get_decl `nat.mod_lt,
nms ← name_set.of_list <$> (list_prop_consts l.value),
exps ← apps_of_interesting_consts nms l.value,
exps.mmap infer_type >>= trace
-/
|
b1ead3f63cd57ab8ec57bafa6fca617543b3286f | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/logic/function/conjugate.lean | 85946719b7a8df0ef5cb01a6ec4b838eb9f94492 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 5,055 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import logic.function.basic
/-!
# Semiconjugate and commuting maps
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define the following predicates:
* `function.semiconj`: `f : α → β` semiconjugates `ga : α → α` to `gb : β → β` if `f ∘ ga = gb ∘ f`;
* `function.semiconj₂: `f : α → β` semiconjugates a binary operation `ga : α → α → α`
to `gb : β → β → β` if `f (ga x y) = gb (f x) (f y)`;
* `f : α → α` commutes with `g : α → α` if `f ∘ g = g ∘ f`, or equivalently `semiconj f g g`.
-/
namespace function
variables {α : Type*} {β : Type*} {γ : Type*}
/-- We say that `f : α → β` semiconjugates `ga : α → α` to `gb : β → β` if `f ∘ ga = gb ∘ f`.
We use `∀ x, f (ga x) = gb (f x)` as the definition, so given `h : function.semiconj f ga gb` and
`a : α`, we have `h a : f (ga a) = gb (f a)` and `h.comp_eq : f ∘ ga = gb ∘ f`. -/
def semiconj (f : α → β) (ga : α → α) (gb : β → β) : Prop := ∀ x, f (ga x) = gb (f x)
namespace semiconj
variables {f fab : α → β} {fbc : β → γ} {ga ga' : α → α} {gb gb' : β → β} {gc gc' : γ → γ}
protected lemma comp_eq (h : semiconj f ga gb) : f ∘ ga = gb ∘ f := funext h
protected lemma eq (h : semiconj f ga gb) (x : α) : f (ga x) = gb (f x) := h x
lemma comp_right (h : semiconj f ga gb) (h' : semiconj f ga' gb') :
semiconj f (ga ∘ ga') (gb ∘ gb') :=
λ x, by rw [comp_app, h.eq, h'.eq]
lemma comp_left (hab : semiconj fab ga gb) (hbc : semiconj fbc gb gc) :
semiconj (fbc ∘ fab) ga gc :=
λ x, by simp only [comp_app, hab.eq, hbc.eq]
lemma id_right : semiconj f id id := λ _, rfl
lemma id_left : semiconj id ga ga := λ _, rfl
lemma inverses_right (h : semiconj f ga gb) (ha : right_inverse ga' ga)
(hb : left_inverse gb' gb) :
semiconj f ga' gb' :=
λ x, by rw [← hb (f (ga' x)), ← h.eq, ha x]
lemma option_map {f : α → β} {ga : α → α} {gb : β → β} (h : semiconj f ga gb) :
semiconj (option.map f) (option.map ga) (option.map gb)
| none := rfl
| (some a) := congr_arg some $ h _
end semiconj
/-- Two maps `f g : α → α` commute if `f (g x) = g (f x)` for all `x : α`.
Given `h : function.commute f g` and `a : α`, we have `h a : f (g a) = g (f a)` and
`h.comp_eq : f ∘ g = g ∘ f`. -/
def commute (f g : α → α) : Prop := semiconj f g g
lemma semiconj.commute {f g : α → α} (h : semiconj f g g) : commute f g := h
namespace commute
variables {f f' g g' : α → α}
@[refl] lemma refl (f : α → α) : commute f f := λ _, eq.refl _
@[symm] lemma symm (h : commute f g) : commute g f := λ x, (h x).symm
lemma comp_right (h : commute f g) (h' : commute f g') : commute f (g ∘ g') :=
h.comp_right h'
lemma comp_left (h : commute f g) (h' : commute f' g) : commute (f ∘ f') g :=
(h.symm.comp_right h'.symm).symm
lemma id_right : commute f id := semiconj.id_right
lemma id_left : commute id f := semiconj.id_left
lemma option_map {f g : α → α} : commute f g → commute (option.map f) (option.map g) :=
semiconj.option_map
end commute
/-- A map `f` semiconjugates a binary operation `ga` to a binary operation `gb` if
for all `x`, `y` we have `f (ga x y) = gb (f x) (f y)`. E.g., a `monoid_hom`
semiconjugates `(*)` to `(*)`. -/
def semiconj₂ (f : α → β) (ga : α → α → α) (gb : β → β → β) : Prop :=
∀ x y, f (ga x y) = gb (f x) (f y)
namespace semiconj₂
variables {f : α → β} {ga : α → α → α} {gb : β → β → β}
protected lemma eq (h : semiconj₂ f ga gb) (x y : α) : f (ga x y) = gb (f x) (f y) := h x y
protected lemma comp_eq (h : semiconj₂ f ga gb) :
bicompr f ga = bicompl gb f f :=
funext $ λ x, funext $ h x
lemma id_left (op : α → α → α) : semiconj₂ id op op := λ _ _, rfl
lemma comp {f' : β → γ} {gc : γ → γ → γ} (hf' : semiconj₂ f' gb gc) (hf : semiconj₂ f ga gb) :
semiconj₂ (f' ∘ f) ga gc :=
λ x y, by simp only [hf'.eq, hf.eq, comp_app]
lemma is_associative_right [is_associative α ga] (h : semiconj₂ f ga gb) (h_surj : surjective f) :
is_associative β gb :=
⟨h_surj.forall₃.2 $ λ x₁ x₂ x₃, by simp only [← h.eq, @is_associative.assoc _ ga]⟩
lemma is_associative_left [is_associative β gb] (h : semiconj₂ f ga gb) (h_inj : injective f) :
is_associative α ga :=
⟨λ x₁ x₂ x₃, h_inj $ by simp only [h.eq, @is_associative.assoc _ gb]⟩
lemma is_idempotent_right [is_idempotent α ga] (h : semiconj₂ f ga gb) (h_surj : surjective f) :
is_idempotent β gb :=
⟨h_surj.forall.2 $ λ x, by simp only [← h.eq, @is_idempotent.idempotent _ ga]⟩
lemma is_idempotent_left [is_idempotent β gb] (h : semiconj₂ f ga gb) (h_inj : injective f) :
is_idempotent α ga :=
⟨λ x, h_inj $ by rw [h.eq, @is_idempotent.idempotent _ gb]⟩
end semiconj₂
end function
|
c41d90101cb2e6a27ed3a50e6e71b3adbe272c91 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/multiset/basic.lean | 338fc366f9c34cb1ef38a415dc9c483b5b61a268 | [
"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 | 84,777 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.list.perm
import algebra.group_power
/-!
# Multisets
These are implemented as the quotient of a list by permutations.
-/
open list subtype nat
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `multiset α` is the quotient of `list α` by list permutation. The result
is a type of finite sets with duplicates allowed. -/
def {u} multiset (α : Type u) : Type u :=
quotient (list.is_setoid α)
namespace multiset
instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩
@[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl
@[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl
@[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl
@[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq
instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α)
| s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂,
decidable_of_iff' _ quotient.eq
/-- defines a size for a multiset by referring to the size of the underlying list -/
protected def sizeof [has_sizeof α] (s : multiset α) : ℕ :=
quot.lift_on s sizeof $ λ l₁ l₂, perm.sizeof_eq_sizeof
instance has_sizeof [has_sizeof α] : has_sizeof (multiset α) := ⟨multiset.sizeof⟩
/- empty multiset -/
/-- `0 : multiset α` is the empty set -/
protected def zero : multiset α := @nil α
instance : has_zero (multiset α) := ⟨multiset.zero⟩
instance : has_emptyc (multiset α) := ⟨0⟩
instance : inhabited (multiset α) := ⟨0⟩
@[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl
@[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl
theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] :=
iff.trans coe_eq_coe perm_nil
/- cons -/
/-- `cons a s` is the multiset which contains `s` plus one more
instance of `a`. -/
def cons (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (a :: l : multiset α))
(λ l₁ l₂ p, quot.sound (p.cons a))
notation a :: b := cons a b
instance : has_insert α (multiset α) := ⟨cons⟩
@[simp] theorem insert_eq_cons (a : α) (s : multiset α) :
insert a s = a::s := rfl
@[simp] theorem cons_coe (a : α) (l : list α) :
(a::l : multiset α) = (a::l : list α) := rfl
theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl
@[simp] theorem cons_inj_left {a b : α} (s : multiset α) :
a::s = b::s ↔ a = b :=
⟨quot.induction_on s $ λ l e,
have [a] ++ l ~ [b] ++ l, from quotient.exact e,
singleton_perm_singleton.1 $ (perm_append_right_iff _).1 this, congr_arg _⟩
@[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t :=
by rintros ⟨l₁⟩ ⟨l₂⟩; simp
@[recursor 5] protected theorem induction {p : multiset α → Prop}
(h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s :=
by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih]
@[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop}
(s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s :=
multiset.induction h₁ h₂ s
theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s :=
quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _
section rec
variables {C : multiset α → Sort*}
/-- Dependent recursor on multisets.
TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack
overflow in `whnf`.
-/
protected def rec
(C_0 : C 0)
(C_cons : Πa m, C m → C (a::m))
(C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b))
(m : multiset α) : C m :=
quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $
assume l l' h,
h.rec_heq
(assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc)
(assume a a' l, C_cons_heq a a' ⟦l⟧)
@[elab_as_eliminator]
protected def rec_on (m : multiset α)
(C_0 : C 0)
(C_cons : Πa m, C m → C (a::m))
(C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) :
C m :=
multiset.rec C_0 C_cons C_cons_heq m
variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)}
{C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)}
@[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 :=
rfl
@[simp] lemma rec_on_cons (a : α) (m : multiset α) :
(a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) :=
quotient.induction_on m $ assume l, rfl
end rec
section mem
/-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/
def mem (a : α) (s : multiset α) : Prop :=
quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ e.mem_iff)
instance : has_mem α (multiset α) := ⟨mem⟩
@[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl
instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) :=
quot.rec_on_subsingleton s $ list.decidable_mem a
@[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, iff.rfl
lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s :=
mem_cons.2 $ or.inr h
@[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s :=
mem_cons.2 (or.inl rfl)
theorem forall_mem_cons {p : α → Prop} {a : α} {s : multiset α} :
(∀ x ∈ (a :: s), p x) ↔ p a ∧ ∀ x ∈ s, p x :=
quotient.induction_on' s $ λ L, list.forall_mem_cons
theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t :=
quot.induction_on s $ λ l (h : a ∈ l),
let ⟨l₁, l₂, e⟩ := mem_split h in
e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩
@[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id
theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 :=
quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl
theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s :=
⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩
theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s :=
quot.induction_on s $ assume l hl,
match l, hl with
| [] := assume h, false.elim $ h rfl
| (a :: l) := assume _, ⟨a, by simp⟩
end
@[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m :=
assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this
@[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm
lemma cons_eq_cons {a b : α} {as bs : multiset α} :
a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) :=
begin
haveI : decidable_eq α := classical.dec_eq α,
split,
{ assume eq,
by_cases a = b,
{ subst h, simp * at * },
{ have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _,
have : a ∈ bs, by simpa [h],
rcases exists_cons_of_mem this with ⟨cs, hcs⟩,
simp [h, hcs],
have : a :: as = b :: a :: cs, by simp [eq, hcs],
have : a :: as = a :: b :: cs, by rwa [cons_swap],
simpa using this } },
{ assume h,
rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ simp * },
{ simp [*, cons_swap a b] } }
end
end mem
/- subset -/
section subset
/-- `s ⊆ t` is the lift of the list subset relation. It means that any
element with nonzero multiplicity in `s` has nonzero multiplicity in `t`,
but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`;
see `s ≤ t` for this relation. -/
protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t
instance : has_subset (multiset α) := ⟨multiset.subset⟩
@[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl
@[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h
theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u :=
λ h₁ h₂ a m, h₂ (h₁ m)
theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl
theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _
@[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s :=
λ a, (not_mem_nil a).elim
@[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp [subset_iff, or_imp_distrib, forall_and_distrib]
theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 :=
eq_zero_of_forall_not_mem h
theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 :=
⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩
end subset
section to_list
/-- Produces a list of the elements in the multiset using choice. -/
@[reducible] noncomputable def to_list {α : Type*} (s : multiset α) :=
classical.some (quotient.exists_rep s)
@[simp] lemma to_list_zero {α : Type*} : (multiset.to_list 0 : list α) = [] :=
(multiset.coe_eq_zero _).1 (classical.some_spec (quotient.exists_rep multiset.zero))
lemma coe_to_list {α : Type*} (s : multiset α) : (s.to_list : multiset α) = s :=
classical.some_spec (quotient.exists_rep _)
lemma mem_to_list {α : Type*} (a : α) (s : multiset α) : a ∈ s.to_list ↔ a ∈ s :=
by rw [←multiset.mem_coe, multiset.coe_to_list]
end to_list
/- multiset order -/
/-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation).
Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/
protected def le (s t : multiset α) : Prop :=
quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
propext (p₂.subperm_left.trans p₁.subperm_right)
instance : partial_order (multiset α) :=
{ le := multiset.le,
le_refl := by rintros ⟨l⟩; exact subperm.refl _,
le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _,
le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) }
theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm.subset
theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t :=
mem_of_subset (subset_of_le h)
@[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl
@[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop}
{s t : multiset α} (h : s ≤ t)
(H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t :=
quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩,
(show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h
theorem zero_le (s : multiset α) : 0 ≤ s :=
quot.induction_on s $ λ l, (nil_sublist l).subperm
theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 :=
⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩
theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s :=
quot.induction_on s $ λ l,
suffices l <+~ a :: l ∧ (¬l ~ a :: l),
by simpa [lt_iff_le_and_ne],
⟨(sublist_cons _ _).subperm,
λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩
theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s :=
le_of_lt $ lt_cons_self _ _
theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a
theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t :=
(cons_le_cons_iff a).2
theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t :=
begin
refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩,
suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t',
{ exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) },
introv h, revert m, refine le_induction_on h _,
introv s m₁ m₂,
rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩,
exact perm_middle.subperm_left.2 ((subperm_cons _).2 $
((sublist_or_mem_of_sublist s).resolve_right m₁).subperm)
end
/- cardinality -/
/-- The cardinality of a multiset is the sum of the multiplicities
of all its elements, or simply the length of the underlying list. -/
def card (s : multiset α) : ℕ :=
quot.lift_on s length $ λ l₁ l₂, perm.length_eq
@[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl
@[simp] theorem card_zero : @card α 0 = 0 := rfl
@[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 :=
quot.induction_on s $ λ l, rfl
@[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp
theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t :=
le_induction_on h $ λ l₁ l₂, length_le_of_sublist
theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t :=
le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂
theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t :=
lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂
theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t :=
⟨quotient.induction_on₂ s t $ λ l₁ l₂ h,
subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h),
λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩
@[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 :=
⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩
theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s :=
quot.induction_on s $ λ l, length_pos_iff_exists_mem
@[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} :
∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s
| s := λ ih, ih s $ λ t h,
have card t < card s, from card_lt_of_lt h,
strong_induction_on t ih
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]}
theorem strong_induction_eq {p : multiset α → Sort*}
(s : multiset α) (H) : @strong_induction_on _ p s H =
H s (λ t h, @strong_induction_on _ p t H) :=
by rw [strong_induction_on]
@[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop}
(s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s :=
multiset.strong_induction_on s $ assume s,
multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $
λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _
/- singleton -/
instance : has_singleton α (multiset α) := ⟨λ a, a::0⟩
instance : is_lawful_singleton α (multiset α) := ⟨λ a, rfl⟩
@[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp
theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _
theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _
@[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 :=
ne_of_gt (lt_cons_self _ _)
@[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s :=
⟨λ h, mem_of_le h (mem_singleton_self _),
λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩
theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 :=
⟨quot.induction_on s $ λ l h,
(list.length_eq_one.1 h).imp $ λ a, congr_arg coe,
λ ⟨a, e⟩, e.symm ▸ rfl⟩
/- add -/
/-- The sum of two multisets is the lift of the list append operation.
This adds the multiplicities of each element,
i.e. `count a (s + t) = count a s + count a t`. -/
protected def add (s₁ s₂ : multiset α) : multiset α :=
quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $
λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.append p₂
instance : has_add (multiset α) := ⟨multiset.add⟩
@[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl
protected theorem add_comm (s t : multiset α) : s + t = t + s :=
quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_append_comm
protected theorem zero_add (s : multiset α) : 0 + s = s :=
quot.induction_on s $ λ l, rfl
theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl
protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u :=
quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_append_left _
protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u :=
le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h))
((multiset.add_le_add_left _).1 (le_of_eq h.symm))
instance : ordered_cancel_add_comm_monoid (multiset α) :=
{ zero := 0,
add := (+),
add_comm := multiset.add_comm,
add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃,
congr_arg coe $ append_assoc l₁ l₂ l₃,
zero_add := multiset.zero_add,
add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add],
add_left_cancel := multiset.add_left_cancel,
add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $
by simpa [multiset.add_comm] using h,
add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h,
le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1,
..@multiset.partial_order α }
@[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) :=
by rw [← singleton_add, ← singleton_add, add_assoc]
@[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) :=
by rw [add_comm, cons_add, add_comm]
theorem le_add_right (s t : multiset α) : s ≤ s + t :=
by simpa using add_le_add_left (zero_le t) s
theorem le_add_left (s t : multiset α) : s ≤ t + s :=
by simpa using add_le_add_right (zero_le t) s
@[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t :=
quotient.induction_on₂ s t length_append
lemma card_smul (s : multiset α) (n : ℕ) :
(n •ℕ s).card = n * s.card :=
by induction n; simp [succ_nsmul, *, nat.succ_mul]; cc
@[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, mem_append
theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u :=
⟨λ h, le_induction_on h $ λ l₁ l₂ s,
let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩,
λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩
instance : canonically_ordered_add_monoid (multiset α) :=
{ lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _,
le_iff_exists_add := @le_iff_exists_add _,
bot := 0,
bot_le := multiset.zero_le,
..multiset.ordered_cancel_add_comm_monoid }
/- repeat -/
/-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/
def repeat (a : α) (n : ℕ) : multiset α := repeat a n
@[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl
@[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat]
@[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp
@[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat
theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat
theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
(perm_repeat.1 $ (quotient.exact h)), congr_arg coe⟩ eq_repeat'
theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card :=
eq_repeat'.2
theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a :=
⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton
theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l :=
⟨λ ⟨l', p, s⟩, (perm_repeat.1 p) ▸ s, sublist.subperm⟩
/- erase -/
section erase
variables [decidable_eq α] {s t : multiset α} {a b : α}
/-- `erase s a` is the multiset that subtracts 1 from the
multiplicity of `a`. -/
def erase (s : multiset α) (a : α) : multiset α :=
quot.lift_on s (λ l, (l.erase a : multiset α))
(λ l₁ l₂ p, quot.sound (p.erase a))
@[simp] theorem coe_erase (l : list α) (a : α) :
erase (l : multiset α) a = l.erase a := rfl
@[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl
@[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l
@[simp, priority 990]
theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h
@[simp, priority 980]
theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s :=
quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h
@[simp, priority 980]
theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s :=
quot.induction_on s $ λ l h, quot.sound (perm_cons_erase h).symm
theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a :=
if h : a ∈ s then le_of_eq (cons_erase h).symm
else by rw erase_of_not_mem h; apply le_cons_self
theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h
theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) :
(s + t).erase a = s + t.erase a :=
by rw [add_comm, erase_add_left_pos s h, add_comm]
theorem erase_add_right_neg {a : α} {s : multiset α} (t) :
a ∉ s → (s + t).erase a = s + t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h
theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) :
(s + t).erase a = s.erase a + t :=
by rw [add_comm, erase_add_right_neg s h, add_comm]
theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s :=
quot.induction_on s $ λ l, (erase_sublist a l).subperm
@[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s :=
⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h),
λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩
theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s :=
subset_of_le (erase_le a s)
theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s :=
quot.induction_on s $ λ l, list.mem_erase_of_ne ab
theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s :=
mem_of_subset (erase_subset _ _)
theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a :=
quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b
theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a :=
le_induction_on h $ λ l₁ l₂ h, (h.erase _).subperm
theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t :=
⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h),
λ h, if m : a ∈ s
then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h
else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩
@[simp] theorem card_erase_of_mem {a : α} {s : multiset α} :
a ∈ s → card (s.erase a) = pred (card s) :=
quot.induction_on s $ λ l, length_erase_of_mem
theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s :=
λ h, card_lt_of_lt (erase_lt.mpr h)
theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s :=
card_le_of_le (erase_le a s)
end erase
@[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l :=
quot.sound $ reverse_perm _
/- map -/
/-- `map f s` is the lift of the list `map` operation. The multiplicity
of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity)
such that `f a = b`. -/
def map (f : α → β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l : list α, (l.map f : multiset β))
(λ l₁ l₂ p, quot.sound (p.map f))
theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : multiset α} :
(∀ y ∈ s.map f, p y) ↔ (∀ x ∈ s, p (f x)) :=
quotient.induction_on' s $ λ L, list.forall_mem_map_iff
@[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl
@[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl
@[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s :=
quot.induction_on s $ λ l, rfl
lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl
theorem map_repeat (f : α → β) (a : α) (k : ℕ) : (repeat a k).map f = repeat (f a) k := by
{ induction k, simp, simpa }
@[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _
instance (f : α → β) : is_add_monoid_hom (map f) :=
{ map_add := map_add _, map_zero := map_zero _ }
@[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} :
b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b :=
quot.induction_on s $ λ l, mem_map
@[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s :=
quot.induction_on s $ λ l, length_map _ _
@[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 :=
by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero]
theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s :=
mem_map.2 ⟨_, h, rfl⟩
theorem mem_map_of_injective {f : α → β} (H : function.injective f) {a : α} {s : multiset α} :
f a ∈ map f s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_map_of_injective H
@[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _
theorem map_id (s : multiset α) : map id s = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_id _
@[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s
@[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card :=
quot.induction_on s $ λ l, congr_arg coe $ map_const _ _
@[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s :=
quot.induction_on s $ λ l H, congr_arg coe $ map_congr H
lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m :=
begin subst h, simp at hf, simp [map_congr hf] end
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
eq_of_mem_repeat $ by rwa map_const at h
@[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t :=
le_induction_on h $ λ l₁ l₂ h, (h.map f).subperm
@[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t :=
λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩
/- fold -/
/-- `foldl f H b s` is the lift of the list operation `foldl f b l`,
which folds `f` over the multiset. It is well defined when `f` is right-commutative,
that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/
def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldl f b l)
(λ l₁ l₂ p, p.foldl_eq H b)
@[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl
@[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _
/-- `foldr f H b s` is the lift of the list operation `foldr f b l`,
which folds `f` over the multiset. It is well defined when `f` is left-commutative,
that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/
def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldr f b l)
(λ l₁ l₂ p, p.foldr_eq H b)
@[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _
@[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldr f b := rfl
@[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) :
foldl f H b l = l.foldl f b := rfl
theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldl (λ x y, f y x) b :=
(congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _
theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) :
foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _
theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) :
foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
(foldr_swap _ _ _ _).symm
/-- Product of a multiset given a commutative monoid structure on `α`.
`prod {a, b, c} = a * b * c` -/
@[to_additive]
def prod [comm_monoid α] : multiset α → α :=
foldr (*) (λ x y z, by simp [mul_left_comm]) 1
@[to_additive]
theorem prod_eq_foldr [comm_monoid α] (s : multiset α) :
prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl
@[to_additive]
theorem prod_eq_foldl [comm_monoid α] (s : multiset α) :
prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s :=
(foldr_swap _ _ _ _).trans (by simp [mul_comm])
@[simp, to_additive]
theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod :=
prod_eq_foldl _
@[simp, to_additive]
theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl
@[simp, to_additive]
theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s :=
foldr_cons _ _ _ _ _
@[to_additive]
theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp
@[simp, to_additive]
theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t :=
quotient.induction_on₂ s t $ λ l₁ l₂, by simp
instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) :=
{ map_add := sum_add, map_zero := sum_zero }
lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) :
∀n, (n •ℕ m).prod = m.prod ^ n
| 0 := rfl
| (n + 1) :=
by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_smul n]
@[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n :=
by simp [repeat, list.prod_repeat]
@[simp] theorem sum_repeat [add_comm_monoid α] :
∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n •ℕ a :=
@prod_repeat (multiplicative α) _
attribute [to_additive] prod_repeat
lemma prod_map_one [comm_monoid γ] {m : multiset α} :
prod (m.map (λa, (1 : γ))) = (1 : γ) :=
by simp
lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} :
sum (m.map (λa, (0 : γ))) = (0 : γ) :=
by simp
attribute [to_additive] prod_map_one
@[simp, to_additive]
lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} :
prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc)
lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} :
prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih])
lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ},
sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) :=
@prod_map_prod_map _ _ (multiplicative γ) _
attribute [to_additive] prod_map_prod_map
lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, b * f a)) = b * sum (s.map f) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add])
lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, f a * b)) = sum (s.map f) * b :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul])
theorem prod_ne_zero {R : Type*} [integral_domain R] {m : multiset R} :
(∀ x ∈ m, (x : _) ≠ 0) → m.prod ≠ 0 :=
multiset.induction_on m (λ _, one_ne_zero) $ λ hd tl ih H,
by { rw forall_mem_cons at H, rw prod_cons, exact mul_ne_zero H.1 (ih H.2) }
lemma prod_eq_zero {α : Type*} [comm_semiring α] {s : multiset α} (h : (0 : α) ∈ s) :
multiset.prod s = 0 :=
begin
rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩,
simp [hs', multiset.prod_cons]
end
@[to_additive]
lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (f : α →* β) :
(s.map f).prod = f s.prod :=
quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod]
@[to_additive]
theorem prod_hom_rel [comm_monoid β] [comm_monoid γ] (s : multiset α) {r : β → γ → Prop}
{f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) :
r (s.map f).prod (s.map g).prod :=
quotient.induction_on s $ λ l,
by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod]
lemma dvd_prod [comm_monoid α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod :=
quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a
theorem prod_eq_zero_iff [comm_cancel_monoid_with_zero α] [nontrivial α]
{s : multiset α} :
s.prod = 0 ↔ (0 : α) ∈ s :=
multiset.induction_on s (by simp) $
assume a s, by simp [mul_eq_zero, @eq_comm _ 0 a] {contextual := tt}
lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β]
(f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) :
f s.sum ≤ (s.map f).sum :=
multiset.induction_on s (le_of_eq h_zero) $
assume a s ih, by rw [sum_cons, map_cons, sum_cons];
from le_trans (h_add a s.sum) (add_le_add_left ih _)
lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {s : multiset α} :
abs s.sum ≤ (s.map abs).sum :=
le_sum_of_subadditive _ abs_zero abs_add s
theorem dvd_sum [comm_semiring α] {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum :=
multiset.induction_on s (λ _, dvd_zero _)
(λ x s ih h, by rw sum_cons; exact dvd_add
(h _ (mem_cons_self _ _)) (ih (λ y hy, h _ (mem_cons.2 (or.inr hy)))))
/- join -/
/-- `join S`, where `S` is a multiset of multisets, is the lift of the list join
operation, that is, the union of all the sets.
join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/
def join : multiset (multiset α) → multiset α := sum
theorem coe_join : ∀ L : list (list α),
join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join
| [] := rfl
| (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L)
@[simp] theorem join_zero : @join α 0 = 0 := rfl
@[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S :=
sum_cons _ _
@[simp] theorem join_add (S T) : @join α (S + T) = join S + join T :=
sum_add _ _
@[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s :=
multiset.induction_on S (by simp) $
by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt}
@[simp] theorem card_join (S) : card (@join α S) = sum (map card S) :=
multiset.induction_on S (by simp) (by simp)
/- bind -/
/-- `bind s f` is the monad bind operation, defined as `join (map f s)`.
It is the union of `f a` as `a` ranges over `s`. -/
def bind (s : multiset α) (f : α → multiset β) : multiset β :=
join (map f s)
@[simp] theorem coe_bind (l : list α) (f : α → list β) :
@bind α β l (λ a, f a) = l.bind f :=
by rw [list.bind, ← coe_join, list.map_map]; refl
@[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl
@[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f :=
by simp [bind]
@[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f :=
by simp [bind]
@[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 :=
by simp [bind, join]
@[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) :
bind s (λa, f a + g a) = bind s f + bind s g :=
by simp [bind, join]
@[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) :
bind s (λa, f a :: g a) = map f s + bind s g :=
multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt})
@[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a :=
by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm];
rw exists_swap; simp [and_assoc]
@[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) :=
by simp [bind]
lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g :=
by simp [bind] {contextual := tt}
lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' :=
begin subst h, simp at hf, simp [bind_congr hf] end
lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) :
map f (bind m n) = bind m (λa, map f (n a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) :
bind (map f m) n = bind m (λa, n (f a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} :
(s.bind f).bind g = s.bind (λa, (f a).bind g) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} :
(bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} :
(bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
@[simp, to_additive]
lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) :
prod (bind s t) = prod (s.map $ λa, prod (t a)) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind])
/- product -/
/-- The multiplicity of `(a, b)` in `product s t` is
the product of the multiplicity of `a` in `s` and `b` in `t`. -/
def product (s : multiset α) (t : multiset β) : multiset (α × β) :=
s.bind $ λ a, t.map $ prod.mk a
@[simp] theorem coe_product (l₁ : list α) (l₂ : list β) :
@product α β l₁ l₂ = l₁.product l₂ :=
by rw [product, list.product, ← coe_bind]; simp
@[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl
@[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) :
product (a :: s) t = map (prod.mk a) t + product s t :=
by simp [product]
@[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl
@[simp] theorem add_product (s t : multiset α) (u : multiset β) :
product (s + t) u = product s u + product t u :=
by simp [product]
@[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β,
product s (t + u) = product s t + product s u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_product, IH]; simp; cc
@[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t
| (a, b) := by simp [product, and.left_comm]
@[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t :=
by simp [product, repeat, (∘), mul_comm]
/- sigma -/
section
variable {σ : α → Type*}
/-- `sigma s t` is the dependent version of `product`. It is the sum of
`(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/
protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) :=
s.bind $ λ a, (t a).map $ sigma.mk a
@[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
@multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ :=
by rw [multiset.sigma, list.sigma, ← coe_bind]; simp
@[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl
@[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) :
(a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t :=
by simp [multiset.sigma]
@[simp] theorem sigma_singleton (a : α) (b : α → β) :
(a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl
@[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) :
(s + t).sigma u = s.sigma u + t.sigma u :=
by simp [multiset.sigma]
@[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a),
s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_sigma, IH]; simp; cc
@[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a},
p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1
| ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm]
@[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) :
card (s.sigma t) = sum (map (λ a, card (t a)) s) :=
by simp [multiset.sigma, (∘)]
end
/- map for partial functions -/
/-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset
`s` whose elements are all in the domain of `f`. -/
def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β :=
quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂),
funext $ λ (H₂ : ∀ a ∈ l₂, p a),
have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a (pp.subset h),
have ∀ {s₂ e H}, @eq.rec (multiset α) l₁
(λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁))
s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e,
this.trans $ quot.sound $ pp.pmap f
@[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β)
(l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl
@[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) :
pmap f 0 h = 0 := rfl
@[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) :
∀(h : ∀b∈a::m, p b), pmap f (a :: m) h =
f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) :=
quotient.induction_on m $ assume l h, rfl
/-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce
a multiset on `{x // x ∈ s}`. -/
def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id)
@[simp] theorem coe_attach (l : list α) :
@eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl
theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : multiset α} (hx : x ∈ s) :
sizeof x < sizeof s := by
{ induction s with l a b, exact list.sizeof_lt_sizeof_of_mem hx, refl }
theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) :
∀ H, @pmap _ _ p (λ a _, f a) s H = map f s :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f s H₁ = pmap g s H₂ :=
quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H :=
quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H
theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s :=
quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l
@[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach :=
quot.induction_on s $ λ l, mem_attach _
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b :=
quot.induction_on s (λ l H, mem_pmap) H
@[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β)
(s H) : card (pmap f s H) = card s :=
quot.induction_on s (λ l H, length_pmap) H
@[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _
@[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl
lemma attach_cons (a : α) (m : multiset α) :
(a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) :=
quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $
by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl)
section decidable_pi_exists
variables {m : multiset α}
protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] :
decidable (∀a∈m, p a) :=
quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp)
instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∀a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _))
/-- decidable equality for functions whose domain is bounded by multisets -/
instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈m, β a) :=
assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff])
def decidable_exists_multiset {p : α → Prop} [decidable_pred p] :
decidable (∃ x ∈ m, p x) :=
quotient.rec_on_subsingleton m list.decidable_exists_mem
instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∃a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩)
(λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩))
end decidable_pi_exists
/- subtraction -/
section
variables [decidable_eq α] {s t u : multiset α} {a b : α}
/-- `s - t` is the multiset such that
`count a (s - t) = count a s - count a t` for all `a`. -/
protected def sub (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ p₁.diff p₂
instance : has_sub (multiset α) := ⟨multiset.sub⟩
@[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl
theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂,
by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) }
@[simp] theorem sub_zero (s : multiset α) : s - 0 = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _
theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t :=
begin
revert t,
refine multiset.induction_on s (by simp) (λ a s IH t h, _),
have := cons_erase (mem_of_le h (mem_cons_self _ _)),
rw [cons_add, sub_cons, IH, this],
exact (cons_le_cons_iff a).1 (this.symm ▸ h)
end
theorem sub_add' : s - (t + u) = s - t - u :=
quotient.induction_on₃ s t u $
λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _
theorem sub_add_cancel (h : t ≤ s) : s - t + t = s :=
by rw [add_comm, add_sub_of_le h]
@[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t :=
multiset.induction_on s (by simp)
(λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH])
@[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s :=
by rw [add_comm, add_sub_cancel_left]
theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u :=
by revert s t h; exact
multiset.induction_on u (by simp {contextual := tt})
(λ a u IH s t h, by simp [IH, erase_le_erase a h])
theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s :=
le_induction_on h $ λ l₁ l₂ h, begin
induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u,
{ refl },
{ rw [← cons_coe, sub_cons],
exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) },
{ rw [← cons_coe, sub_cons, ← cons_coe, sub_cons],
exact IH _ }
end
theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t :=
by revert s; exact
multiset.induction_on t (by simp)
(λ a t IH s, by simp [IH, erase_le_iff_le_cons])
theorem le_sub_add (s t : multiset α) : s ≤ s - t + t :=
sub_le_iff_le_add.1 (le_refl _)
theorem sub_le_self (s t : multiset α) : s - t ≤ s :=
sub_le_iff_le_add.2 (le_add_right _ _)
@[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t :=
(nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm
/- union -/
/-- `s ∪ t` is the lattice join operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum
of the multiplicities in `s` and `t`. -/
def union (s t : multiset α) : multiset α := s - t + t
instance : has_union (multiset α) := ⟨union⟩
theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl
theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _
theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _
theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel
theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u :=
add_le_add_right (sub_le_sub_right h _) u
theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u :=
by rw ← eq_union_left h₂; exact union_le_union_right h₁ t
@[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t :=
⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _),
or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩
@[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} :
map f (s ∪ t) = map f s ∪ map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
congr_arg coe (by rw [list.map_append f, list.map_diff finj])
/- inter -/
/-- `s ∩ t` is the lattice meet operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum
of the multiplicities in `s` and `t`. -/
def inter (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ p₁.bag_inter p₂
instance : has_inter (multiset α) := ⟨inter⟩
@[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil
@[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter
@[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} :
a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_pos _ h
@[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} :
a ∉ t → (a :: s) ∩ t = s ∩ t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_neg _ h
theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s :=
quotient.induction_on₂ s t $ λ l₁ l₂,
(bag_inter_sublist_left _ _).subperm
theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t :=
multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $
λ a s IH t, if h : a ∈ t
then by simpa [h] using cons_le_cons a (IH (t.erase a))
else by simp [h, IH]
theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u :=
begin
revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros,
{ simp [h₁] },
by_cases a ∈ u,
{ rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons],
exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) },
{ rw cons_inter_of_neg _ h,
exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ }
end
@[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t :=
⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩,
λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩
instance : lattice (multiset α) :=
{ sup := (∪),
sup_le := @union_le _ _,
le_sup_left := le_union_left,
le_sup_right := le_union_right,
inf := (∩),
le_inf := @le_inter _ _,
inf_le_left := inter_le_left,
inf_le_right := inter_le_right,
..@multiset.partial_order α }
@[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl
@[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff
@[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff
instance : semilattice_inf_bot (multiset α) :=
{ bot := 0, bot_le := zero_le, ..multiset.lattice }
theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm
theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm
theorem eq_union_right (h : s ≤ t) : s ∪ t = t :=
by rw [union_comm, eq_union_left h]
theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t :=
sup_le_sup_left h _
theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t :=
union_le (le_add_right _ _) (le_add_left _ _)
theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) :=
by simpa [(∪), union, eq_comm, add_assoc] using show s + u - (t + u) = s - t,
by rw [add_comm t, sub_add', add_sub_cancel]
theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) :=
by rw [add_comm, union_add_distrib, add_comm s, add_comm s]
theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) :=
by simpa using add_union_distrib (a::0) s t
theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) :=
begin
by_contra h,
cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter
(add_le_add_right (inter_le_left s t) u)
(add_le_add_right (inter_le_right s t) u)) h) with a hl,
rw ← cons_add at hl,
exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter
(le_of_add_le_add_right (le_trans hl (inter_le_left _ _)))
(le_of_add_le_add_right (le_trans hl (inter_le_right _ _))))
end
theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) :=
by rw [add_comm, inter_add_distrib, add_comm s, add_comm s]
theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) :=
by simp
theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t :=
begin
apply le_antisymm,
{ rw union_add_distrib,
refine union_le (add_le_add_left (inter_le_right _ _) _) _,
rw add_comm, exact add_le_add_right (inter_le_left _ _) _ },
{ rw [add_comm, add_inter_distrib],
refine le_inter (add_le_add_right (le_union_right _ _) _) _,
rw add_comm, exact add_le_add_right (le_union_left _ _) _ }
end
theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s :=
begin
rw [inter_comm],
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
by_cases a ∈ s,
{ rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] },
{ rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] }
end
theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t :=
add_right_cancel $
by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)]
end
/- filter -/
section
variables {p : α → Prop} [decidable_pred p]
/-- `filter p s` returns the elements in `s` (with the same multiplicities)
which satisfy `p`, and removes the rest. -/
def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (filter p l : multiset α))
(λ l₁ l₂ h, quot.sound $ h.filter p)
@[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p]
(l : list α) : filter p (↑l) = l.filter p := rfl
@[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl
@[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h
@[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s :=
quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
{s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h
@[simp] theorem filter_add (s t : multiset α) :
filter p (s + t) = filter p s + filter p t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _
@[simp] theorem filter_le (s : multiset α) : filter p s ≤ s :=
quot.induction_on s $ λ l, (filter_sublist _).subperm
@[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s :=
subset_of_le $ filter_le _
@[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a :=
quot.induction_on s $ λ l, mem_filter
theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a :=
(mem_filter.1 h).2
theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s :=
(mem_filter.1 h).1
theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l :=
mem_filter.2 ⟨m, h⟩
theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_self
theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_nil
theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t :=
le_induction_on h $ λ l₁ l₂ h, (filter_sublist_filter h).subperm
theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a :=
⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩,
λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩
@[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) :
filter p (s - t) = filter p s - filter p t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
rw [sub_cons, IH],
by_cases p a,
{ rw [filter_cons_of_pos _ h, sub_cons], congr,
by_cases m : a ∈ s,
{ rw [← cons_inj_right a, ← filter_cons_of_pos _ h,
cons_erase (mem_filter_of_mem m h), cons_erase m] },
{ rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } },
{ rw [filter_cons_of_neg _ h],
by_cases m : a ∈ s,
{ rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)),
cons_erase m] },
{ rw [erase_of_not_mem m] } }
end
@[simp] theorem filter_union [decidable_eq α] (s t : multiset α) :
filter p (s ∪ t) = filter p s ∪ filter p t :=
by simp [(∪), union]
@[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) :
filter p (s ∩ t) = filter p s ∩ filter p t :=
le_antisymm (le_inter
(filter_le_filter $ inter_le_left _ _)
(filter_le_filter $ inter_le_right _ _)) $ le_filter.2
⟨inf_le_inf (filter_le _) (filter_le _),
λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩
@[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) :
filter p (filter q s) = filter (λ a, p a ∧ q a) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter l
theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) :
filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s :=
multiset.induction_on s rfl $ λ a s IH,
by by_cases p a; by_cases q a; simp *
theorem filter_add_not (s : multiset α) :
filter p s + filter (λ a, ¬ p a) s = s :=
by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em]
/- filter_map -/
/-- `filter_map f s` is a combination filter/map operation on `s`.
The function `f : α → option β` is applied to each element of `s`;
if `f a` is `some b` then `b` is added to the result, otherwise
`a` is removed from the resulting multiset. -/
def filter_map (f : α → option β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l, (filter_map f l : multiset β))
(λ l₁ l₂ h, quot.sound $ h.filter_map f)
@[simp] theorem coe_filter_map (f : α → option β) (l : list α) :
filter_map f l = l.filter_map f := rfl
@[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) :
filter_map f (a :: s) = filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (s : multiset α) {b : β} (h : f a = some b) :
filter_map f (a :: s) = b :: filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) :
filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l
theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) :
map g (filter_map f s) = filter_map (λ x, (f x).map g) s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l
theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) :
filter_map g (map f s) = filter_map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) :
filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) :
filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l
@[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l
@[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} :
b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b :=
quot.induction_on s $ λ l, mem_filter_map f l
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (s : multiset α) :
map g (filter_map f s) = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l
theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α}
(h : s ≤ t) : filter_map f s ≤ filter_map f t :=
le_induction_on h $ λ l₁ l₂ h, (h.filter_map _).subperm
/-! ### countp -/
/-- `countp p s` counts the number of elements of `s` (with multiplicity) that
satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ :=
quot.lift_on s (countp p) (λ l₁ l₂, perm.countp_eq p)
@[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl
@[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 :=
quot.induction_on s countp_cons_of_pos
@[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s :=
quot.induction_on s countp_cons_of_neg
theorem countp_eq_card_filter (s) : countp p s = card (filter p s) :=
quot.induction_on s $ λ l, countp_eq_length_filter _
@[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t :=
by simp [countp_eq_card_filter]
instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) :=
{ map_add := countp_add, map_zero := countp_zero _ }
theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a :=
by simp [countp_eq_card_filter, card_pos_iff_exists_mem]
@[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) :
countp p (s - t) = countp p s - countp p t :=
by simp [countp_eq_card_filter, h, filter_le_filter]
theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s :=
countp_pos.2 ⟨_, h, pa⟩
theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t :=
by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h)
@[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) :
countp p (filter q s) = countp (λ a, p a ∧ q a) s :=
by simp [countp_eq_card_filter]
end
/- count -/
section
variable [decidable_eq α]
/-- `count a s` is the multiplicity of `a` in `s`. -/
def count (a : α) : multiset α → ℕ := countp (eq a)
@[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _
@[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl
@[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) :=
countp_cons_of_pos _ rfl
@[simp, priority 990]
theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s :=
countp_cons_of_neg _ h
theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t :=
countp_le_of_le
theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) :=
count_le_of_le _ (le_cons_self _ _)
theorem count_singleton (a : α) : count a (a::0) = 1 :=
by simp
@[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t :=
countp_add
instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) :=
countp.is_add_monoid_hom
@[simp] theorem count_smul (a : α) (n s) : count a (n •ℕ s) = n * count a s :=
by induction n; simp [*, succ_nsmul', succ_mul]
theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s :=
by simp [count, countp_pos]
@[simp, priority 980]
theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s :=
iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero
theorem count_ne_zero {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s :=
by simp [ne.def, count_eq_zero]
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by simp [repeat]
@[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) :=
begin
by_cases a ∈ s,
{ rw [(by rw cons_erase h : count a s = count a (a::erase s a)),
count_cons_self]; refl },
{ rw [erase_of_not_mem h, count_eq_zero.2 h]; refl }
end
@[simp, priority 980]
theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s :=
begin
by_cases b ∈ s,
{ rw [← count_cons_of_ne ab, cons_erase h] },
{ rw [erase_of_not_mem h] }
end
@[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _),
rw [sub_cons, IH],
by_cases ab : a = b,
{ subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] },
{ rw [count_erase_of_ne ab, count_cons_of_ne ab] }
end
@[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) :=
by simp [(∪), union, sub_add_eq_max, -add_comm]
@[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) :=
begin
apply @nat.add_left_cancel (count a (s - t)),
rw [← count_add, sub_add_inter, count_sub, sub_add_min],
end
lemma count_sum {m : multiset β} {f : β → multiset α} {a : α} :
count a (map f m).sum = sum (m.map $ λb, count a $ f b) :=
multiset.induction_on m (by simp) ( by simp)
lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} :
count a (bind m f) = sum (m.map $ λb, count a $ f b) := count_sum
theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s :=
quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {s : multiset α} (h : p a) : count a (filter p s) = count a s :=
quot.induction_on s $ λ l, count_filter h
theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t :=
quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count
@[ext]
theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t :=
ext.2
@[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) :=
by ext; simp
theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t :=
⟨λ h a, count_le_of_le a h, λ al,
by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t);
apply le_union_left⟩
instance : distrib_lattice (multiset α) :=
{ le_sup_inf := λ s t u, le_of_eq $ eq.symm $
ext.2 $ λ a, by simp only [max_min_distrib_left,
multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter],
..multiset.lattice }
instance : semilattice_sup_bot (multiset α) :=
{ bot := 0,
bot_le := zero_le,
..multiset.lattice }
end
/- relator -/
section rel
/-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`,
s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/
inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop
| zero : rel 0 0
| cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs)
mk_iff_of_inductive_prop multiset.rel multiset.rel_iff
variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s :=
rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih)
lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s :=
⟨rel_flip_aux, rel_flip_aux⟩
lemma rel_eq_refl {s : multiset α} : rel (=) s s :=
multiset.induction_on s rel.zero (assume a s, rel.cons rfl)
lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t :=
begin
split,
{ assume h, induction h; simp * },
{ assume h, subst h, exact rel_eq_refl }
end
lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t :=
begin
induction hst,
case rel.zero { exact rel.zero },
case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) }
end
lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) :=
begin
induction hst,
case rel.zero { simpa using huv },
case rel.cons : a b s t hab hst ih { simpa using ih.cons hab }
end
lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t :=
show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm]
@[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 :=
by rw [rel_iff]; simp
@[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 :=
by rw [rel_iff]; simp
lemma rel_cons_left {a as bs} :
rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') :=
begin
split,
{ generalize hm : a :: as = m,
assume h,
induction h generalizing as,
case rel.zero { simp at hm, contradiction },
case rel.cons : a' b as' bs ha'b h ih {
rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ },
{ rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩,
exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ }
} },
{ exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h }
end
lemma rel_cons_right {as b bs} :
rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') :=
begin
rw [← rel_flip, rel_cons_left],
apply exists_congr, assume a,
apply exists_congr, assume as',
rw [rel_flip, flip]
end
lemma rel_add_left {as₀ as₁} :
∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) :=
multiset.induction_on as₀ (by simp)
begin
assume a s ih bs,
simp only [ih, cons_add, rel_cons_left],
split,
{ assume h,
rcases h with ⟨b, bs', hab, h, rfl⟩,
rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩,
exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ },
{ assume h,
rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩,
rcases h with ⟨b, bs, hab, h₀, rfl⟩,
exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ }
end
lemma rel_add_right {as bs₀ bs₁} :
rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) :=
by rw [← rel_flip, rel_add_left]; simp [rel_flip]
lemma rel_map_left {s : multiset γ} {f : γ → α} :
∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t :=
multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt})
lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} :
rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t :=
by rw [← rel_flip, rel_map_left, ← rel_flip]; refl
lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join :=
begin
induction h,
case rel.zero { simp },
case rel.cons : a b s t hab hst ih { simpa using hab.add ih }
end
lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) :
rel p (s.map f) (t.map g) :=
by rw [rel_map_left, rel_map_right]; exact hst.mono h
lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ}
(h : (r ⇒ rel p) f g) (hst : rel r s t) :
rel p (s.bind f) (t.bind g) :=
by apply rel_join; apply rel_map; assumption
lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
card s = card t :=
by induction h; simp [*]
lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b :=
begin
induction h with x y s t hxy hst ih,
{ simp },
{ assume a ha,
cases mem_cons.1 ha with ha ha,
{ exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ },
{ rcases ih ha with ⟨b, hbt, hab⟩,
exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } }
end
end rel
section map
theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} :
s.map f = t.map f ↔ s = t :=
by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff]
theorem map_injective {f : α → β} (hf : function.injective f) :
function.injective (multiset.map f) :=
assume x y, (map_eq_map hf).1
end map
section quot
theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) :
s.map (quot.mk r) = t.map (quot.mk r) :=
rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab]
theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) :
∃t:multiset α, s = t.map (quot.mk r) :=
multiset.induction_on s ⟨0, rfl⟩ $
assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩
theorem induction_on_multiset_quot
{r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) :
(∀s:multiset α, p (s.map (quot.mk r))) → p s :=
match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end
end quot
/- disjoint -/
/-- `disjoint s t` means that `s` and `t` have no elements in common. -/
def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false
@[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl
theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s
| a i₂ i₁ := d i₁ i₂
theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl
theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
disjoint_comm
theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t
| x m₁ := d (h m₁)
theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t
| x m m₁ := d m (h m₁)
theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t :=
disjoint_of_subset_left (subset_of_le h)
theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t :=
disjoint_of_subset_right (subset_of_le h)
@[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l
| a := (not_mem_nil a).elim
@[simp, priority 1100]
theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l :=
by simp [disjoint]; refl
@[simp, priority 1100]
theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l :=
by rw disjoint_comm; simp
@[simp] theorem disjoint_add_left {s t u : multiset α} :
disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_add_right {s t u : multiset α} :
disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u :=
by rw [disjoint_comm, disjoint_add_left]; tauto
@[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} :
disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t :=
(@disjoint_add_left _ (a::0) s t).trans $ by simp
@[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} :
disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t :=
by rw [disjoint_comm, disjoint_cons_left]; tauto
theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
@[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} :
disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) :=
begin
simp [disjoint],
split,
from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm,
from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁)
end
/-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/
def pairwise (r : α → α → Prop) (m : multiset α) : Prop :=
∃l:list α, m = l ∧ l.pairwise r
lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} :
multiset.pairwise r l ↔ l.pairwise r :=
iff.intro
(assume ⟨l', eq, h⟩, ((quotient.exact eq).pairwise_iff hr).2 h)
(assume h, ⟨l, rfl, h⟩)
end multiset
namespace multiset
section choose
variables (p : α → Prop) [decidable_pred p] (l : multiset α)
/-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns
that `a`. -/
def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } :=
quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin
intros,
funext hp,
suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y,
{ apply all_equal },
{ rintros ⟨x, px⟩ ⟨y, py⟩,
rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩,
congr,
calc x = z : z_unique x px
... = y : (z_unique y py).symm }
end
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
variable (α)
/-- The equivalence between lists and multisets of a subsingleton type. -/
def subsingleton_equiv [subsingleton α] : list α ≃ multiset α :=
{ to_fun := coe,
inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b),
list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _,
left_inv := λ l, rfl,
right_inv := λ m, quot.induction_on m $ λ l, rfl }
end multiset
@[to_additive]
theorem monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) :
f s.prod = (s.map f).prod :=
(s.prod_hom f).symm
|
f5d7b2cf7421b55eed549a6460a19eaa57f86a2e | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Lean/Compiler/IR/Basic.lean | 97d4760a172983e165512b9e6e52557e61b8f7bb | [
"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",
"Apache-2.0",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | gebner/lean4 | d51c4922640a52a6f7426536ea669ef18a1d9af5 | 8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f | refs/heads/master | 1,685,732,780,391 | 1,672,962,627,000 | 1,673,459,398,000 | 373,307,283 | 0 | 0 | Apache-2.0 | 1,691,316,730,000 | 1,622,669,271,000 | Lean | UTF-8 | Lean | false | false | 26,659 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.KVMap
import Lean.Data.Name
import Lean.Data.Format
import Lean.Compiler.ExternAttr
/-!
Implements (extended) λPure and λRc proposed in the article
"Counting Immutable Beans", Sebastian Ullrich and Leonardo de Moura.
The Lean to IR transformation produces λPure code, and
this part is implemented in C++. The procedures described in the paper
above are implemented in Lean.
-/
namespace Lean.IR
/-- Function identifier -/
abbrev FunId := Name
abbrev Index := Nat
/-- Variable identifier -/
structure VarId where
idx : Index
deriving Inhabited
/-- Join point identifier -/
structure JoinPointId where
idx : Index
deriving Inhabited
abbrev Index.lt (a b : Index) : Bool := a < b
instance : BEq VarId := ⟨fun a b => a.idx == b.idx⟩
instance : ToString VarId := ⟨fun a => "x_" ++ toString a.idx⟩
instance : ToFormat VarId := ⟨fun a => toString a⟩
instance : Hashable VarId := ⟨fun a => hash a.idx⟩
instance : BEq JoinPointId := ⟨fun a b => a.idx == b.idx⟩
instance : ToString JoinPointId := ⟨fun a => "block_" ++ toString a.idx⟩
instance : ToFormat JoinPointId := ⟨fun a => toString a⟩
instance : Hashable JoinPointId := ⟨fun a => hash a.idx⟩
abbrev MData := KVMap
abbrev MData.empty : MData := {}
/-- Low Level IR types. Most are self explanatory.
- `usize` represents the C++ `size_t` Type. We have it here
because it is 32-bit in 32-bit machines, and 64-bit in 64-bit machines,
and we want the C++ backend for our Compiler to generate platform independent code.
- `irrelevant` for Lean types, propositions and proofs.
- `object` a pointer to a value in the heap.
- `tobject` a pointer to a value in the heap or tagged pointer
(i.e., the least significant bit is 1) storing a scalar value.
- `struct` and `union` are used to return small values (e.g., `Option`, `Prod`, `Except`)
on the stack.
Remark: the RC operations for `tobject` are slightly more expensive because we
first need to test whether the `tobject` is really a pointer or not.
Remark: the Lean runtime assumes that sizeof(void*) == sizeof(sizeT).
Lean cannot be compiled on old platforms where this is not True.
Since values of type `struct` and `union` are only used to return values,
We assume they must be used/consumed "linearly". We use the term "linear" here
to mean "exactly once" in each execution. That is, given `x : S`, where `S` is a struct,
then one of the following must hold in each (execution) branch.
1- `x` occurs only at a single `ret x` instruction. That is, it is being consumed by being returned.
2- `x` occurs only at a single `ctor`. That is, it is being "consumed" by being stored into another `struct/union`.
3- We extract (aka project) every single field of `x` exactly once. That is, we are consuming `x` by consuming each
of one of its components. Minor refinement: we don't need to consume scalar fields or struct/union
fields that do not contain object fields.
-/
inductive IRType where
| float | uint8 | uint16 | uint32 | uint64 | usize
| irrelevant | object | tobject
| struct (leanTypeName : Option Name) (types : Array IRType) : IRType
| union (leanTypeName : Name) (types : Array IRType) : IRType
deriving Inhabited
namespace IRType
partial def beq : IRType → IRType → Bool
| float, float => true
| uint8, uint8 => true
| uint16, uint16 => true
| uint32, uint32 => true
| uint64, uint64 => true
| usize, usize => true
| irrelevant, irrelevant => true
| object, object => true
| tobject, tobject => true
| struct n₁ tys₁, struct n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq
| union n₁ tys₁, union n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq
| _, _ => false
instance : BEq IRType := ⟨beq⟩
def isScalar : IRType → Bool
| float => true
| uint8 => true
| uint16 => true
| uint32 => true
| uint64 => true
| usize => true
| _ => false
def isObj : IRType → Bool
| object => true
| tobject => true
| _ => false
def isIrrelevant : IRType → Bool
| irrelevant => true
| _ => false
def isStruct : IRType → Bool
| struct _ _ => true
| _ => false
def isUnion : IRType → Bool
| union _ _ => true
| _ => false
end IRType
/-- Arguments to applications, constructors, etc.
We use `irrelevant` for Lean types, propositions and proofs that have been erased.
Recall that for a Function `f`, we also generate `f._rarg` which does not take
`irrelevant` arguments. However, `f._rarg` is only safe to be used in full applications. -/
inductive Arg where
| var (id : VarId)
| irrelevant
deriving Inhabited
protected def Arg.beq : Arg → Arg → Bool
| var x, var y => x == y
| irrelevant, irrelevant => true
| _, _ => false
instance : BEq Arg := ⟨Arg.beq⟩
@[export lean_ir_mk_var_arg] def mkVarArg (id : VarId) : Arg := Arg.var id
inductive LitVal where
| num (v : Nat)
| str (v : String)
def LitVal.beq : LitVal → LitVal → Bool
| num v₁, num v₂ => v₁ == v₂
| str v₁, str v₂ => v₁ == v₂
| _, _ => false
instance : BEq LitVal := ⟨LitVal.beq⟩
/-- Constructor information.
- `name` is the Name of the Constructor in Lean.
- `cidx` is the Constructor index (aka tag).
- `size` is the number of arguments of type `object/tobject`.
- `usize` is the number of arguments of type `usize`.
- `ssize` is the number of bytes used to store scalar values.
Recall that a Constructor object contains a header, then a sequence of
pointers to other Lean objects, a sequence of `USize` (i.e., `size_t`)
scalar values, and a sequence of other scalar values. -/
structure CtorInfo where
name : Name
cidx : Nat
size : Nat
usize : Nat
ssize : Nat
deriving Repr
def CtorInfo.beq : CtorInfo → CtorInfo → Bool
| ⟨n₁, cidx₁, size₁, usize₁, ssize₁⟩, ⟨n₂, cidx₂, size₂, usize₂, ssize₂⟩ =>
n₁ == n₂ && cidx₁ == cidx₂ && size₁ == size₂ && usize₁ == usize₂ && ssize₁ == ssize₂
instance : BEq CtorInfo := ⟨CtorInfo.beq⟩
def CtorInfo.isRef (info : CtorInfo) : Bool :=
info.size > 0 || info.usize > 0 || info.ssize > 0
def CtorInfo.isScalar (info : CtorInfo) : Bool :=
!info.isRef
inductive Expr where
/-- We use `ctor` mainly for constructing Lean object/tobject values `lean_ctor_object` in the runtime.
This instruction is also used to creat `struct` and `union` return values.
For `union`, only `i.cidx` is relevant. For `struct`, `i` is irrelevant. -/
| ctor (i : CtorInfo) (ys : Array Arg)
| reset (n : Nat) (x : VarId)
/-- `reuse x in ctor_i ys` instruction in the paper. -/
| reuse (x : VarId) (i : CtorInfo) (updtHeader : Bool) (ys : Array Arg)
/-- Extract the `tobject` value at Position `sizeof(void*)*i` from `x`.
We also use `proj` for extracting fields from `struct` return values, and casting `union` return values. -/
| proj (i : Nat) (x : VarId)
/-- Extract the `Usize` value at Position `sizeof(void*)*i` from `x`. -/
| uproj (i : Nat) (x : VarId)
/-- Extract the scalar value at Position `sizeof(void*)*n + offset` from `x`. -/
| sproj (n : Nat) (offset : Nat) (x : VarId)
/-- Full application. -/
| fap (c : FunId) (ys : Array Arg)
/-- Partial application that creates a `pap` value (aka closure in our nonstandard terminology). -/
| pap (c : FunId) (ys : Array Arg)
/-- Application. `x` must be a `pap` value. -/
| ap (x : VarId) (ys : Array Arg)
/-- Given `x : ty` where `ty` is a scalar type, this operation returns a value of Type `tobject`.
For small scalar values, the Result is a tagged pointer, and no memory allocation is performed. -/
| box (ty : IRType) (x : VarId)
/-- Given `x : [t]object`, obtain the scalar value. -/
| unbox (x : VarId)
| lit (v : LitVal)
/-- Return `1 : uint8` Iff `RC(x) > 1` -/
| isShared (x : VarId)
/-- Return `1 : uint8` Iff `x : tobject` is a tagged pointer (storing a scalar value). -/
| isTaggedPtr (x : VarId)
@[export lean_ir_mk_ctor_expr] def mkCtorExpr (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (ys : Array Arg) : Expr :=
Expr.ctor ⟨n, cidx, size, usize, ssize⟩ ys
@[export lean_ir_mk_proj_expr] def mkProjExpr (i : Nat) (x : VarId) : Expr := Expr.proj i x
@[export lean_ir_mk_uproj_expr] def mkUProjExpr (i : Nat) (x : VarId) : Expr := Expr.uproj i x
@[export lean_ir_mk_sproj_expr] def mkSProjExpr (n : Nat) (offset : Nat) (x : VarId) : Expr := Expr.sproj n offset x
@[export lean_ir_mk_fapp_expr] def mkFAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.fap c ys
@[export lean_ir_mk_papp_expr] def mkPAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.pap c ys
@[export lean_ir_mk_app_expr] def mkAppExpr (x : VarId) (ys : Array Arg) : Expr := Expr.ap x ys
@[export lean_ir_mk_num_expr] def mkNumExpr (v : Nat) : Expr := Expr.lit (LitVal.num v)
@[export lean_ir_mk_str_expr] def mkStrExpr (v : String) : Expr := Expr.lit (LitVal.str v)
structure Param where
x : VarId
borrow : Bool
ty : IRType
deriving Inhabited
@[export lean_ir_mk_param]
def mkParam (x : VarId) (borrow : Bool) (ty : IRType) : Param := ⟨x, borrow, ty⟩
inductive AltCore (FnBody : Type) : Type where
| ctor (info : CtorInfo) (b : FnBody) : AltCore FnBody
| default (b : FnBody) : AltCore FnBody
inductive FnBody where
/-- `let x : ty := e; b` -/
| vdecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody)
/-- Join point Declaration `block_j (xs) := e; b` -/
| jdecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody)
/-- Store `y` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1.
This operation is not part of λPure is only used during optimization. -/
| set (x : VarId) (i : Nat) (y : Arg) (b : FnBody)
| setTag (x : VarId) (cidx : Nat) (b : FnBody)
/-- Store `y : Usize` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. -/
| uset (x : VarId) (i : Nat) (y : VarId) (b : FnBody)
/-- Store `y : ty` at Position `sizeof(void*)*i + offset` in `x`. `x` must be a Constructor object and `RC(x)` must be 1.
`ty` must not be `object`, `tobject`, `irrelevant` nor `Usize`. -/
| sset (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody)
/-- RC increment for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not.
If `persistent == true` then `x` is statically known to be a persistent object. -/
| inc (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody)
/-- RC decrement for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not.
If `persistent == true` then `x` is statically known to be a persistent object. -/
| dec (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody)
| del (x : VarId) (b : FnBody)
| mdata (d : MData) (b : FnBody)
| case (tid : Name) (x : VarId) (xType : IRType) (cs : Array (AltCore FnBody))
| ret (x : Arg)
/-- Jump to join point `j` -/
| jmp (j : JoinPointId) (ys : Array Arg)
| unreachable
instance : Inhabited FnBody := ⟨FnBody.unreachable⟩
abbrev FnBody.nil := FnBody.unreachable
@[export lean_ir_mk_vdecl] def mkVDecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : FnBody := FnBody.vdecl x ty e b
@[export lean_ir_mk_jdecl] def mkJDecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) : FnBody := FnBody.jdecl j xs v b
@[export lean_ir_mk_uset] def mkUSet (x : VarId) (i : Nat) (y : VarId) (b : FnBody) : FnBody := FnBody.uset x i y b
@[export lean_ir_mk_sset] def mkSSet (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) : FnBody := FnBody.sset x i offset y ty b
@[export lean_ir_mk_case] def mkCase (tid : Name) (x : VarId) (cs : Array (AltCore FnBody)) : FnBody :=
-- Type field `xType` is set by `explicitBoxing` compiler pass.
FnBody.case tid x IRType.object cs
@[export lean_ir_mk_ret] def mkRet (x : Arg) : FnBody := FnBody.ret x
@[export lean_ir_mk_jmp] def mkJmp (j : JoinPointId) (ys : Array Arg) : FnBody := FnBody.jmp j ys
@[export lean_ir_mk_unreachable] def mkUnreachable : Unit → FnBody := fun _ => FnBody.unreachable
abbrev Alt := AltCore FnBody
@[match_pattern] abbrev Alt.ctor := @AltCore.ctor FnBody
@[match_pattern] abbrev Alt.default := @AltCore.default FnBody
instance : Inhabited Alt := ⟨Alt.default default⟩
def FnBody.isTerminal : FnBody → Bool
| FnBody.case _ _ _ _ => true
| FnBody.ret _ => true
| FnBody.jmp _ _ => true
| FnBody.unreachable => true
| _ => false
def FnBody.body : FnBody → FnBody
| FnBody.vdecl _ _ _ b => b
| FnBody.jdecl _ _ _ b => b
| FnBody.set _ _ _ b => b
| FnBody.uset _ _ _ b => b
| FnBody.sset _ _ _ _ _ b => b
| FnBody.setTag _ _ b => b
| FnBody.inc _ _ _ _ b => b
| FnBody.dec _ _ _ _ b => b
| FnBody.del _ b => b
| FnBody.mdata _ b => b
| other => other
def FnBody.setBody : FnBody → FnBody → FnBody
| FnBody.vdecl x t v _, b => FnBody.vdecl x t v b
| FnBody.jdecl j xs v _, b => FnBody.jdecl j xs v b
| FnBody.set x i y _, b => FnBody.set x i y b
| FnBody.uset x i y _, b => FnBody.uset x i y b
| FnBody.sset x i o y t _, b => FnBody.sset x i o y t b
| FnBody.setTag x i _, b => FnBody.setTag x i b
| FnBody.inc x n c p _, b => FnBody.inc x n c p b
| FnBody.dec x n c p _, b => FnBody.dec x n c p b
| FnBody.del x _, b => FnBody.del x b
| FnBody.mdata d _, b => FnBody.mdata d b
| other, _ => other
@[inline] def FnBody.resetBody (b : FnBody) : FnBody :=
b.setBody FnBody.nil
/-- If b is a non terminal, then return a pair `(c, b')` s.t. `b == c <;> b'`,
and c.body == FnBody.nil -/
@[inline] def FnBody.split (b : FnBody) : FnBody × FnBody :=
let b' := b.body
let c := b.resetBody
(c, b')
def AltCore.body : Alt → FnBody
| Alt.ctor _ b => b
| Alt.default b => b
def AltCore.setBody : Alt → FnBody → Alt
| Alt.ctor c _, b => Alt.ctor c b
| Alt.default _, b => Alt.default b
@[inline] def AltCore.modifyBody (f : FnBody → FnBody) : AltCore FnBody → Alt
| Alt.ctor c b => Alt.ctor c (f b)
| Alt.default b => Alt.default (f b)
@[inline] def AltCore.mmodifyBody {m : Type → Type} [Monad m] (f : FnBody → m FnBody) : AltCore FnBody → m Alt
| Alt.ctor c b => Alt.ctor c <$> f b
| Alt.default b => Alt.default <$> f b
def Alt.isDefault : Alt → Bool
| Alt.ctor _ _ => false
| Alt.default _ => true
def push (bs : Array FnBody) (b : FnBody) : Array FnBody :=
let b := b.resetBody
bs.push b
partial def flattenAux (b : FnBody) (r : Array FnBody) : (Array FnBody) × FnBody :=
if b.isTerminal then (r, b)
else flattenAux b.body (push r b)
def FnBody.flatten (b : FnBody) : (Array FnBody) × FnBody :=
flattenAux b #[]
partial def reshapeAux (a : Array FnBody) (i : Nat) (b : FnBody) : FnBody :=
if i == 0 then b
else
let i := i - 1
let (curr, a) := a.swapAt! i default
let b := curr.setBody b
reshapeAux a i b
def reshape (bs : Array FnBody) (term : FnBody) : FnBody :=
reshapeAux bs bs.size term
@[inline] def modifyJPs (bs : Array FnBody) (f : FnBody → FnBody) : Array FnBody :=
bs.map fun b => match b with
| FnBody.jdecl j xs v k => FnBody.jdecl j xs (f v) k
| other => other
@[inline] def mmodifyJPs {m : Type → Type} [Monad m] (bs : Array FnBody) (f : FnBody → m FnBody) : m (Array FnBody) :=
bs.mapM fun b => match b with
| FnBody.jdecl j xs v k => return FnBody.jdecl j xs (← f v) k
| other => return other
@[export lean_ir_mk_alt] def mkAlt (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (b : FnBody) : Alt :=
Alt.ctor ⟨n, cidx, size, usize, ssize⟩ b
/-- Extra information associated with a declaration. -/
structure DeclInfo where
/-- If `some <blame>`, then declaration depends on `<blame>` which uses a `sorry` axiom. -/
sorryDep? : Option Name := none
inductive Decl where
| fdecl (f : FunId) (xs : Array Param) (type : IRType) (body : FnBody) (info : DeclInfo)
| extern (f : FunId) (xs : Array Param) (type : IRType) (ext : ExternAttrData)
deriving Inhabited
namespace Decl
def name : Decl → FunId
| .fdecl f .. => f
| .extern f .. => f
def params : Decl → Array Param
| .fdecl (xs := xs) .. => xs
| .extern (xs := xs) .. => xs
def resultType : Decl → IRType
| .fdecl (type := t) .. => t
| .extern (type := t) .. => t
def isExtern : Decl → Bool
| .extern .. => true
| _ => false
def getInfo : Decl → DeclInfo
| .fdecl (info := info) .. => info
| _ => {}
def updateBody! (d : Decl) (bNew : FnBody) : Decl :=
match d with
| Decl.fdecl f xs t _ info => Decl.fdecl f xs t bNew info
| _ => panic! "expected definition"
end Decl
@[export lean_ir_mk_decl] def mkDecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) : Decl :=
Decl.fdecl f xs ty b {}
@[export lean_ir_mk_extern_decl] def mkExternDecl (f : FunId) (xs : Array Param) (ty : IRType) (e : ExternAttrData) : Decl :=
Decl.extern f xs ty e
-- Hack: we use this declaration as a stub for declarations annotated with `implemented_by` or `init`
@[export lean_ir_mk_dummy_extern_decl] def mkDummyExternDecl (f : FunId) (xs : Array Param) (ty : IRType) : Decl :=
Decl.fdecl f xs ty FnBody.unreachable {}
/-- Set of variable and join point names -/
abbrev IndexSet := RBTree Index compare
instance : Inhabited IndexSet := ⟨{}⟩
def mkIndexSet (idx : Index) : IndexSet :=
RBTree.empty.insert idx
inductive LocalContextEntry where
| param : IRType → LocalContextEntry
| localVar : IRType → Expr → LocalContextEntry
| joinPoint : Array Param → FnBody → LocalContextEntry
abbrev LocalContext := RBMap Index LocalContextEntry compare
def LocalContext.addLocal (ctx : LocalContext) (x : VarId) (t : IRType) (v : Expr) : LocalContext :=
ctx.insert x.idx (LocalContextEntry.localVar t v)
def LocalContext.addJP (ctx : LocalContext) (j : JoinPointId) (xs : Array Param) (b : FnBody) : LocalContext :=
ctx.insert j.idx (LocalContextEntry.joinPoint xs b)
def LocalContext.addParam (ctx : LocalContext) (p : Param) : LocalContext :=
ctx.insert p.x.idx (LocalContextEntry.param p.ty)
def LocalContext.addParams (ctx : LocalContext) (ps : Array Param) : LocalContext :=
ps.foldl LocalContext.addParam ctx
def LocalContext.isJP (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.joinPoint _ _) => true
| _ => false
def LocalContext.getJPBody (ctx : LocalContext) (j : JoinPointId) : Option FnBody :=
match ctx.find? j.idx with
| some (LocalContextEntry.joinPoint _ b) => some b
| _ => none
def LocalContext.getJPParams (ctx : LocalContext) (j : JoinPointId) : Option (Array Param) :=
match ctx.find? j.idx with
| some (LocalContextEntry.joinPoint ys _) => some ys
| _ => none
def LocalContext.isParam (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.param _) => true
| _ => false
def LocalContext.isLocalVar (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.localVar _ _) => true
| _ => false
def LocalContext.contains (ctx : LocalContext) (idx : Index) : Bool :=
RBMap.contains ctx idx
def LocalContext.eraseJoinPointDecl (ctx : LocalContext) (j : JoinPointId) : LocalContext :=
ctx.erase j.idx
def LocalContext.getType (ctx : LocalContext) (x : VarId) : Option IRType :=
match ctx.find? x.idx with
| some (LocalContextEntry.param t) => some t
| some (LocalContextEntry.localVar t _) => some t
| _ => none
def LocalContext.getValue (ctx : LocalContext) (x : VarId) : Option Expr :=
match ctx.find? x.idx with
| some (LocalContextEntry.localVar _ v) => some v
| _ => none
abbrev IndexRenaming := RBMap Index Index compare
class AlphaEqv (α : Type) where
aeqv : IndexRenaming → α → α → Bool
export AlphaEqv (aeqv)
def VarId.alphaEqv (ρ : IndexRenaming) (v₁ v₂ : VarId) : Bool :=
match ρ.find? v₁.idx with
| some v => v == v₂.idx
| none => v₁ == v₂
instance : AlphaEqv VarId := ⟨VarId.alphaEqv⟩
def Arg.alphaEqv (ρ : IndexRenaming) : Arg → Arg → Bool
| Arg.var v₁, Arg.var v₂ => aeqv ρ v₁ v₂
| Arg.irrelevant, Arg.irrelevant => true
| _, _ => false
instance : AlphaEqv Arg := ⟨Arg.alphaEqv⟩
def args.alphaEqv (ρ : IndexRenaming) (args₁ args₂ : Array Arg) : Bool :=
Array.isEqv args₁ args₂ (fun a b => aeqv ρ a b)
instance: AlphaEqv (Array Arg) := ⟨args.alphaEqv⟩
def Expr.alphaEqv (ρ : IndexRenaming) : Expr → Expr → Bool
| Expr.ctor i₁ ys₁, Expr.ctor i₂ ys₂ => i₁ == i₂ && aeqv ρ ys₁ ys₂
| Expr.reset n₁ x₁, Expr.reset n₂ x₂ => n₁ == n₂ && aeqv ρ x₁ x₂
| Expr.reuse x₁ i₁ u₁ ys₁, Expr.reuse x₂ i₂ u₂ ys₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && u₁ == u₂ && aeqv ρ ys₁ ys₂
| Expr.proj i₁ x₁, Expr.proj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂
| Expr.uproj i₁ x₁, Expr.uproj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂
| Expr.sproj n₁ o₁ x₁, Expr.sproj n₂ o₂ x₂ => n₁ == n₂ && o₁ == o₂ && aeqv ρ x₁ x₂
| Expr.fap c₁ ys₁, Expr.fap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂
| Expr.pap c₁ ys₁, Expr.pap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂
| Expr.ap x₁ ys₁, Expr.ap x₂ ys₂ => aeqv ρ x₁ x₂ && aeqv ρ ys₁ ys₂
| Expr.box ty₁ x₁, Expr.box ty₂ x₂ => ty₁ == ty₂ && aeqv ρ x₁ x₂
| Expr.unbox x₁, Expr.unbox x₂ => aeqv ρ x₁ x₂
| Expr.lit v₁, Expr.lit v₂ => v₁ == v₂
| Expr.isShared x₁, Expr.isShared x₂ => aeqv ρ x₁ x₂
| Expr.isTaggedPtr x₁, Expr.isTaggedPtr x₂ => aeqv ρ x₁ x₂
| _, _ => false
instance : AlphaEqv Expr:= ⟨Expr.alphaEqv⟩
def addVarRename (ρ : IndexRenaming) (x₁ x₂ : Nat) :=
if x₁ == x₂ then ρ else ρ.insert x₁ x₂
def addParamRename (ρ : IndexRenaming) (p₁ p₂ : Param) : Option IndexRenaming :=
if p₁.ty == p₂.ty && p₁.borrow = p₂.borrow then
some (addVarRename ρ p₁.x.idx p₂.x.idx)
else
none
def addParamsRename (ρ : IndexRenaming) (ps₁ ps₂ : Array Param) : Option IndexRenaming := do
if ps₁.size != ps₂.size then
failure
else
let mut ρ := ρ
for i in [:ps₁.size] do
ρ ← addParamRename ρ ps₁[i]! ps₂[i]!
pure ρ
partial def FnBody.alphaEqv : IndexRenaming → FnBody → FnBody → Bool
| ρ, FnBody.vdecl x₁ t₁ v₁ b₁, FnBody.vdecl x₂ t₂ v₂ b₂ => t₁ == t₂ && aeqv ρ v₁ v₂ && alphaEqv (addVarRename ρ x₁.idx x₂.idx) b₁ b₂
| ρ, FnBody.jdecl j₁ ys₁ v₁ b₁, FnBody.jdecl j₂ ys₂ v₂ b₂ => match addParamsRename ρ ys₁ ys₂ with
| some ρ' => alphaEqv ρ' v₁ v₂ && alphaEqv (addVarRename ρ j₁.idx j₂.idx) b₁ b₂
| none => false
| ρ, FnBody.set x₁ i₁ y₁ b₁, FnBody.set x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.uset x₁ i₁ y₁ b₁, FnBody.uset x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.sset x₁ i₁ o₁ y₁ t₁ b₁, FnBody.sset x₂ i₂ o₂ y₂ t₂ b₂ =>
aeqv ρ x₁ x₂ && i₁ = i₂ && o₁ = o₂ && aeqv ρ y₁ y₂ && t₁ == t₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.setTag x₁ i₁ b₁, FnBody.setTag x₂ i₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.inc x₁ n₁ c₁ p₁ b₁, FnBody.inc x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.dec x₁ n₁ c₁ p₁ b₁, FnBody.dec x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.del x₁ b₁, FnBody.del x₂ b₂ => aeqv ρ x₁ x₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.mdata m₁ b₁, FnBody.mdata m₂ b₂ => m₁ == m₂ && alphaEqv ρ b₁ b₂
| ρ, FnBody.case n₁ x₁ _ alts₁, FnBody.case n₂ x₂ _ alts₂ => n₁ == n₂ && aeqv ρ x₁ x₂ && Array.isEqv alts₁ alts₂ (fun alt₁ alt₂ =>
match alt₁, alt₂ with
| Alt.ctor i₁ b₁, Alt.ctor i₂ b₂ => i₁ == i₂ && alphaEqv ρ b₁ b₂
| Alt.default b₁, Alt.default b₂ => alphaEqv ρ b₁ b₂
| _, _ => false)
| ρ, FnBody.jmp j₁ ys₁, FnBody.jmp j₂ ys₂ => j₁ == j₂ && aeqv ρ ys₁ ys₂
| ρ, FnBody.ret x₁, FnBody.ret x₂ => aeqv ρ x₁ x₂
| _, FnBody.unreachable, FnBody.unreachable => true
| _, _, _ => false
def FnBody.beq (b₁ b₂ : FnBody) : Bool :=
FnBody.alphaEqv ∅ b₁ b₂
instance : BEq FnBody := ⟨FnBody.beq⟩
abbrev VarIdSet := RBTree VarId (fun x y => compare x.idx y.idx)
instance : Inhabited VarIdSet := ⟨{}⟩
def mkIf (x : VarId) (t e : FnBody) : FnBody :=
FnBody.case `Bool x IRType.uint8 #[
Alt.ctor {name := ``Bool.false, cidx := 0, size := 0, usize := 0, ssize := 0} e,
Alt.ctor {name := ``Bool.true, cidx := 1, size := 0, usize := 0, ssize := 0} t
]
def getUnboxOpName (t : IRType) : String :=
match t with
| IRType.usize => "lean_unbox_usize"
| IRType.uint32 => "lean_unbox_uint32"
| IRType.uint64 => "lean_unbox_uint64"
| IRType.float => "lean_unbox_float"
| _ => "lean_unbox"
end Lean.IR
|
597c7d24a194c3830fdd7829a9a30b4d67a4ea3a | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/measure_theory/group/measure.lean | 2ade894b17f6192601da7bddfc9c13b5fe432b14 | [
"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 | 24,352 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import dynamics.ergodic.measure_preserving
import measure_theory.measure.regular
import measure_theory.group.measurable_equiv
import measure_theory.measure.open_pos
import measure_theory.constructions.prod
/-!
# Measures on Groups
We develop some properties of measures on (topological) groups
* We define properties on measures: measures that are left or right invariant w.r.t. multiplication.
* We define the measure `μ.inv : A ↦ μ(A⁻¹)` and show that it is right invariant iff
`μ` is left invariant.
* We define a class `is_haar_measure μ`, requiring that the measure `μ` is left-invariant, finite
on compact sets, and positive on open sets.
We also give analogues of all these notions in the additive world.
-/
noncomputable theory
open_locale ennreal pointwise big_operators
open has_inv set function measure_theory.measure
variables {G : Type*} [measurable_space G]
namespace measure_theory
namespace measure
/-- A measure `μ` on a measurable additive group is left invariant
if the measure of left translations of a set are equal to the measure of the set itself. -/
class is_add_left_invariant [has_add G] (μ : measure G) : Prop :=
(map_add_left_eq_self : ∀ g : G, map ((+) g) μ = μ)
/-- A measure `μ` on a measurable group is left invariant
if the measure of left translations of a set are equal to the measure of the set itself. -/
@[to_additive] class is_mul_left_invariant [has_mul G] (μ : measure G) : Prop :=
(map_mul_left_eq_self : ∀ g : G, map ((*) g) μ = μ)
/-- A measure `μ` on a measurable additive group is right invariant
if the measure of right translations of a set are equal to the measure of the set itself. -/
class is_add_right_invariant [has_add G] (μ : measure G) : Prop :=
(map_add_right_eq_self : ∀ g : G, map (+ g) μ = μ)
/-- A measure `μ` on a measurable group is right invariant
if the measure of right translations of a set are equal to the measure of the set itself. -/
@[to_additive] class is_mul_right_invariant [has_mul G] (μ : measure G) : Prop :=
(map_mul_right_eq_self : ∀ g : G, map (* g) μ = μ)
end measure
open measure
section mul
variables [has_mul G] {μ : measure G}
@[to_additive]
lemma map_mul_left_eq_self (μ : measure G) [is_mul_left_invariant μ] (g : G) : map ((*) g) μ = μ :=
is_mul_left_invariant.map_mul_left_eq_self g
@[to_additive]
lemma map_mul_right_eq_self (μ : measure G) [is_mul_right_invariant μ] (g : G) : map (* g) μ = μ :=
is_mul_right_invariant.map_mul_right_eq_self g
@[to_additive]
instance [is_mul_left_invariant μ] (c : ℝ≥0∞) : is_mul_left_invariant (c • μ) :=
⟨λ g, by rw [measure.map_smul, map_mul_left_eq_self]⟩
@[to_additive]
instance [is_mul_right_invariant μ] (c : ℝ≥0∞) : is_mul_right_invariant (c • μ) :=
⟨λ g, by rw [measure.map_smul, map_mul_right_eq_self]⟩
section has_measurable_mul
variables [has_measurable_mul G]
@[to_additive]
lemma measure_preserving_mul_left (μ : measure G) [is_mul_left_invariant μ] (g : G) :
measure_preserving ((*) g) μ μ :=
⟨measurable_const_mul g, map_mul_left_eq_self μ g⟩
@[to_additive]
lemma measure_preserving_mul_right (μ : measure G) [is_mul_right_invariant μ] (g : G) :
measure_preserving (* g) μ μ :=
⟨measurable_mul_const g, map_mul_right_eq_self μ g⟩
/-- An alternative way to prove that `μ` is left invariant under multiplication. -/
@[to_additive /-" An alternative way to prove that `μ` is left invariant under addition. "-/]
lemma forall_measure_preimage_mul_iff (μ : measure G) :
(∀ (g : G) (A : set G), measurable_set A → μ ((λ h, g * h) ⁻¹' A) = μ A) ↔
is_mul_left_invariant μ :=
begin
transitivity ∀ g, map ((*) g) μ = μ,
{ simp_rw [measure.ext_iff],
refine forall_congr (λ g, forall_congr $ λ A, forall_congr $ λ hA, _),
rw [map_apply (measurable_const_mul g) hA] },
exact ⟨λ h, ⟨h⟩, λ h, h.1⟩
end
/-- An alternative way to prove that `μ` is right invariant under multiplication. -/
@[to_additive /-" An alternative way to prove that `μ` is right invariant under addition. "-/]
lemma forall_measure_preimage_mul_right_iff (μ : measure G) :
(∀ (g : G) (A : set G), measurable_set A → μ ((λ h, h * g) ⁻¹' A) = μ A) ↔
is_mul_right_invariant μ :=
begin
transitivity ∀ g, map (* g) μ = μ,
{ simp_rw [measure.ext_iff],
refine forall_congr (λ g, forall_congr $ λ A, forall_congr $ λ hA, _),
rw [map_apply (measurable_mul_const g) hA] },
exact ⟨λ h, ⟨h⟩, λ h, h.1⟩
end
@[to_additive]
instance [is_mul_left_invariant μ] [sigma_finite μ] {H : Type*} [has_mul H]
{mH : measurable_space H} {ν : measure H} [has_measurable_mul H]
[is_mul_left_invariant ν] [sigma_finite ν] :
is_mul_left_invariant (μ.prod ν) :=
begin
constructor,
rintros ⟨g, h⟩,
change map (prod.map ((*) g) ((*) h)) (μ.prod ν) = μ.prod ν,
rw [← map_prod_map _ _ (measurable_const_mul g) (measurable_const_mul h),
map_mul_left_eq_self μ g, map_mul_left_eq_self ν h],
{ rw map_mul_left_eq_self μ g, apply_instance },
{ rw map_mul_left_eq_self ν h, apply_instance },
end
@[to_additive]
instance [is_mul_right_invariant μ] [sigma_finite μ] {H : Type*} [has_mul H]
{mH : measurable_space H} {ν : measure H} [has_measurable_mul H]
[is_mul_right_invariant ν] [sigma_finite ν] :
is_mul_right_invariant (μ.prod ν) :=
begin
constructor,
rintros ⟨g, h⟩,
change map (prod.map (* g) (* h)) (μ.prod ν) = μ.prod ν,
rw [← map_prod_map _ _ (measurable_mul_const g) (measurable_mul_const h),
map_mul_right_eq_self μ g, map_mul_right_eq_self ν h],
{ rw map_mul_right_eq_self μ g, apply_instance },
{ rw map_mul_right_eq_self ν h, apply_instance },
end
end has_measurable_mul
end mul
section group
variables [group G]
@[to_additive]
lemma map_div_right_eq_self (μ : measure G) [is_mul_right_invariant μ] (g : G) :
map (/ g) μ = μ :=
by simp_rw [div_eq_mul_inv, map_mul_right_eq_self μ g⁻¹]
variables [has_measurable_mul G]
/-- We shorten this from `measure_preimage_mul_left`, since left invariant is the preferred option
for measures in this formalization. -/
@[simp, to_additive "We shorten this from `measure_preimage_add_left`, since left invariant is the
preferred option for measures in this formalization."]
lemma measure_preimage_mul (μ : measure G) [is_mul_left_invariant μ] (g : G) (A : set G) :
μ ((λ h, g * h) ⁻¹' A) = μ A :=
calc μ ((λ h, g * h) ⁻¹' A) = map (λ h, g * h) μ A :
((measurable_equiv.mul_left g).map_apply A).symm
... = μ A : by rw map_mul_left_eq_self μ g
@[simp, to_additive]
lemma measure_preimage_mul_right (μ : measure G) [is_mul_right_invariant μ] (g : G) (A : set G) :
μ ((λ h, h * g) ⁻¹' A) = μ A :=
calc μ ((λ h, h * g) ⁻¹' A) = map (λ h, h * g) μ A :
((measurable_equiv.mul_right g).map_apply A).symm
... = μ A : by rw map_mul_right_eq_self μ g
@[to_additive]
lemma map_mul_left_ae (μ : measure G) [is_mul_left_invariant μ] (x : G) :
filter.map (λ h, x * h) μ.ae = μ.ae :=
((measurable_equiv.mul_left x).map_ae μ).trans $ congr_arg ae $ map_mul_left_eq_self μ x
@[to_additive]
lemma map_mul_right_ae (μ : measure G) [is_mul_right_invariant μ] (x : G) :
filter.map (λ h, h * x) μ.ae = μ.ae :=
((measurable_equiv.mul_right x).map_ae μ).trans $ congr_arg ae $ map_mul_right_eq_self μ x
@[to_additive]
lemma map_div_right_ae (μ : measure G) [is_mul_right_invariant μ] (x : G) :
filter.map (λ t, t / x) μ.ae = μ.ae :=
((measurable_equiv.div_right x).map_ae μ).trans $ congr_arg ae $ map_div_right_eq_self μ x
end group
namespace measure
/-- The measure `A ↦ μ (A⁻¹)`, where `A⁻¹` is the pointwise inverse of `A`. -/
@[to_additive "The measure `A ↦ μ (- A)`, where `- A` is the pointwise negation of `A`."]
protected def inv [has_inv G] (μ : measure G) : measure G :=
measure.map inv μ
/-- A measure is invariant under negation if `- μ = μ`. Equivalently, this means that for all
measurable `A` we have `μ (- A) = μ A`, where `- A` is the pointwise negation of `A`. -/
class is_neg_invariant [has_neg G] (μ : measure G) : Prop :=
(neg_eq_self : μ.neg = μ)
/-- A measure is invariant under inversion if `μ⁻¹ = μ`. Equivalently, this means that for all
measurable `A` we have `μ (A⁻¹) = μ A`, where `A⁻¹` is the pointwise inverse of `A`. -/
@[to_additive] class is_inv_invariant [has_inv G] (μ : measure G) : Prop :=
(inv_eq_self : μ.inv = μ)
section inv
variables [has_inv G]
@[simp, to_additive]
lemma inv_eq_self (μ : measure G) [is_inv_invariant μ] : μ.inv = μ :=
is_inv_invariant.inv_eq_self
@[simp, to_additive]
lemma map_inv_eq_self (μ : measure G) [is_inv_invariant μ] : map has_inv.inv μ = μ :=
is_inv_invariant.inv_eq_self
end inv
section has_involutive_inv
variables [has_involutive_inv G] [has_measurable_inv G]
@[simp, to_additive]
lemma inv_apply (μ : measure G) (s : set G) : μ.inv s = μ s⁻¹ :=
(measurable_equiv.inv G).map_apply s
@[simp, to_additive]
protected lemma inv_inv (μ : measure G) : μ.inv.inv = μ :=
(measurable_equiv.inv G).map_symm_map
@[simp, to_additive]
lemma measure_inv (μ : measure G) [is_inv_invariant μ] (A : set G) : μ A⁻¹ = μ A :=
by rw [← inv_apply, inv_eq_self]
@[to_additive]
lemma measure_preimage_inv (μ : measure G) [is_inv_invariant μ] (A : set G) :
μ (has_inv.inv ⁻¹' A) = μ A :=
μ.measure_inv A
@[to_additive]
instance (μ : measure G) [sigma_finite μ] : sigma_finite μ.inv :=
(measurable_equiv.inv G).sigma_finite_map ‹_›
end has_involutive_inv
section mul_inv
variables [group G] [has_measurable_mul G] [has_measurable_inv G] {μ : measure G}
@[to_additive]
instance [is_mul_left_invariant μ] : is_mul_right_invariant μ.inv :=
begin
constructor,
intro g,
conv_rhs { rw [← map_mul_left_eq_self μ g⁻¹] },
simp_rw [measure.inv, map_map (measurable_mul_const g) measurable_inv,
map_map measurable_inv (measurable_const_mul g⁻¹), function.comp, mul_inv_rev, inv_inv]
end
@[to_additive]
instance [is_mul_right_invariant μ] : is_mul_left_invariant μ.inv :=
begin
constructor,
intro g,
conv_rhs { rw [← map_mul_right_eq_self μ g⁻¹] },
simp_rw [measure.inv, map_map (measurable_const_mul g) measurable_inv,
map_map measurable_inv (measurable_mul_const g⁻¹), function.comp, mul_inv_rev, inv_inv]
end
@[to_additive]
lemma map_div_left_eq_self (μ : measure G) [is_inv_invariant μ] [is_mul_left_invariant μ] (g : G) :
map (λ t, g / t) μ = μ :=
begin
simp_rw [div_eq_mul_inv],
conv_rhs { rw [← map_mul_left_eq_self μ g, ← map_inv_eq_self μ] },
exact (map_map (measurable_const_mul g) measurable_inv).symm
end
@[to_additive]
lemma map_mul_right_inv_eq_self (μ : measure G) [is_inv_invariant μ] [is_mul_left_invariant μ]
(g : G) : map (λ t, (g * t)⁻¹) μ = μ :=
begin
conv_rhs { rw [← map_inv_eq_self μ, ← map_mul_left_eq_self μ g] },
exact (map_map measurable_inv (measurable_const_mul g)).symm
end
@[to_additive]
lemma map_div_left_ae (μ : measure G) [is_mul_left_invariant μ] [is_inv_invariant μ] (x : G) :
filter.map (λ t, x / t) μ.ae = μ.ae :=
((measurable_equiv.div_left x).map_ae μ).trans $ congr_arg ae $ map_div_left_eq_self μ x
end mul_inv
end measure
section topological_group
variables [topological_space G] [borel_space G] {μ : measure G}
variables [group G] [topological_group G]
@[to_additive]
instance measure.regular.inv [t2_space G] [regular μ] : regular μ.inv :=
regular.map (homeomorph.inv G)
@[to_additive]
lemma regular_inv_iff [t2_space G] : μ.inv.regular ↔ μ.regular :=
begin
split,
{ introI h, rw ← μ.inv_inv, exact measure.regular.inv },
{ introI h, exact measure.regular.inv }
end
variables [is_mul_left_invariant μ]
/-- If a left-invariant measure gives positive mass to a compact set, then it gives positive mass to
any open set. -/
@[to_additive "If a left-invariant measure gives positive mass to a compact set, then it gives
positive mass to any open set."]
lemma is_open_pos_measure_of_mul_left_invariant_of_compact
(K : set G) (hK : is_compact K) (h : μ K ≠ 0) :
is_open_pos_measure μ :=
begin
refine ⟨λ U hU hne, _⟩,
contrapose! h,
rw ← nonpos_iff_eq_zero,
rw ← hU.interior_eq at hne,
obtain ⟨t, hKt⟩ : ∃ (t : finset G), K ⊆ ⋃ (g : G) (H : g ∈ t), (λ (h : G), g * h) ⁻¹' U :=
compact_covered_by_mul_left_translates hK hne,
calc μ K ≤ μ (⋃ (g : G) (H : g ∈ t), (λ (h : G), g * h) ⁻¹' U) : measure_mono hKt
... ≤ ∑ g in t, μ ((λ (h : G), g * h) ⁻¹' U) : measure_bUnion_finset_le _ _
... = 0 : by simp [measure_preimage_mul, h]
end
/-- A nonzero left-invariant regular measure gives positive mass to any open set. -/
@[to_additive "A nonzero left-invariant regular measure gives positive mass to any open set."]
lemma is_open_pos_measure_of_mul_left_invariant_of_regular [regular μ] (h₀ : μ ≠ 0) :
is_open_pos_measure μ :=
let ⟨K, hK, h2K⟩ := regular.exists_compact_not_null.mpr h₀
in is_open_pos_measure_of_mul_left_invariant_of_compact K hK h2K
@[to_additive]
lemma null_iff_of_is_mul_left_invariant [regular μ]
{s : set G} (hs : is_open s) :
μ s = 0 ↔ s = ∅ ∨ μ = 0 :=
begin
by_cases h3μ : μ = 0, { simp [h3μ] },
{ haveI := is_open_pos_measure_of_mul_left_invariant_of_regular h3μ,
simp only [h3μ, or_false, hs.measure_eq_zero_iff μ] },
end
@[to_additive]
lemma measure_ne_zero_iff_nonempty_of_is_mul_left_invariant [regular μ]
(hμ : μ ≠ 0) {s : set G} (hs : is_open s) :
μ s ≠ 0 ↔ s.nonempty :=
by simpa [null_iff_of_is_mul_left_invariant hs, hμ] using ne_empty_iff_nonempty
@[to_additive]
lemma measure_pos_iff_nonempty_of_is_mul_left_invariant [regular μ]
(h3μ : μ ≠ 0) {s : set G} (hs : is_open s) :
0 < μ s ↔ s.nonempty :=
pos_iff_ne_zero.trans $ measure_ne_zero_iff_nonempty_of_is_mul_left_invariant h3μ hs
/-- If a left-invariant measure gives finite mass to a nonempty open set, then it gives finite mass
to any compact set. -/
@[to_additive "If a left-invariant measure gives finite mass to a nonempty open set, then it gives
finite mass to any compact set."]
lemma measure_lt_top_of_is_compact_of_is_mul_left_invariant
(U : set G) (hU : is_open U) (h'U : U.nonempty) (h : μ U ≠ ∞) {K : set G} (hK : is_compact K) :
μ K < ∞ :=
begin
rw ← hU.interior_eq at h'U,
obtain ⟨t, hKt⟩ : ∃ (t : finset G), K ⊆ ⋃ (g : G) (H : g ∈ t), (λ (h : G), g * h) ⁻¹' U :=
compact_covered_by_mul_left_translates hK h'U,
calc μ K ≤ μ (⋃ (g : G) (H : g ∈ t), (λ (h : G), g * h) ⁻¹' U) : measure_mono hKt
... ≤ ∑ g in t, μ ((λ (h : G), g * h) ⁻¹' U) : measure_bUnion_finset_le _ _
... = finset.card t * μ U : by simp only [measure_preimage_mul, finset.sum_const, nsmul_eq_mul]
... < ∞ : ennreal.mul_lt_top (ennreal.nat_ne_top _) h
end
/-- If a left-invariant measure gives finite mass to a set with nonempty interior, then
it gives finite mass to any compact set. -/
@[to_additive "If a left-invariant measure gives finite mass to a set with nonempty interior, then
it gives finite mass to any compact set."]
lemma measure_lt_top_of_is_compact_of_is_mul_left_invariant'
{U : set G} (hU : (interior U).nonempty) (h : μ U ≠ ∞) {K : set G} (hK : is_compact K) :
μ K < ∞ :=
measure_lt_top_of_is_compact_of_is_mul_left_invariant (interior U) is_open_interior hU
((measure_mono (interior_subset)).trans_lt (lt_top_iff_ne_top.2 h)).ne hK
end topological_group
section comm_group
variables [comm_group G]
/-- In an abelian group every left invariant measure is also right-invariant.
We don't declare the converse as an instance, since that would loop type-class inference, and
we use `is_mul_left_invariant` as default hypotheses in abelian groups. -/
@[priority 100, to_additive "In an abelian additive group every left invariant measure is also
right-invariant. We don't declare the converse as an instance, since that would loop type-class
inference, and we use `is_add_left_invariant` as default hypotheses in abelian groups."]
instance is_mul_left_invariant.is_mul_right_invariant {μ : measure G} [is_mul_left_invariant μ] :
is_mul_right_invariant μ :=
⟨λ g, by simp_rw [mul_comm, map_mul_left_eq_self]⟩
end comm_group
section haar
namespace measure
/-- A measure on an additive group is an additive Haar measure if it is left-invariant, and gives
finite mass to compact sets and positive mass to open sets. -/
class is_add_haar_measure {G : Type*} [add_group G] [topological_space G] [measurable_space G]
(μ : measure G)
extends is_finite_measure_on_compacts μ, is_add_left_invariant μ, is_open_pos_measure μ : Prop
/-- A measure on a group is a Haar measure if it is left-invariant, and gives finite mass to compact
sets and positive mass to open sets. -/
@[to_additive]
class is_haar_measure {G : Type*} [group G] [topological_space G] [measurable_space G]
(μ : measure G)
extends is_finite_measure_on_compacts μ, is_mul_left_invariant μ, is_open_pos_measure μ : Prop
/-- Record that a Haar measure on a locally compact space is locally finite. This is needed as the
fact that a measure which is finite on compacts is locally finite is not registered as an instance,
to avoid an instance loop.
See Note [lower instance priority]. -/
@[priority 100, to_additive "Record that an additive Haar measure on a locally compact space is
locally finite. This is needed as the fact that a measure which is finite on compacts is locally
finite is not registered as an instance, to avoid an instance loop.
See Note [lower instance priority]"]
instance is_locally_finite_measure_of_is_haar_measure {G : Type*}
[group G] [measurable_space G] [topological_space G] [locally_compact_space G]
(μ : measure G) [is_haar_measure μ] :
is_locally_finite_measure μ :=
is_locally_finite_measure_of_is_finite_measure_on_compacts
section
variables [group G] [topological_space G] (μ : measure G) [is_haar_measure μ]
@[simp, to_additive]
lemma haar_singleton [topological_group G] [borel_space G] (g : G) :
μ {g} = μ {(1 : G)} :=
begin
convert measure_preimage_mul μ (g⁻¹) _,
simp only [mul_one, preimage_mul_left_singleton, inv_inv],
end
@[to_additive measure_theory.measure.is_add_haar_measure.smul]
lemma is_haar_measure.smul {c : ℝ≥0∞} (cpos : c ≠ 0) (ctop : c ≠ ∞) :
is_haar_measure (c • μ) :=
{ lt_top_of_is_compact := λ K hK, ennreal.mul_lt_top ctop hK.measure_lt_top.ne,
to_is_open_pos_measure := is_open_pos_measure_smul μ cpos }
/-- If a left-invariant measure gives positive mass to some compact set with nonempty interior, then
it is a Haar measure. -/
@[to_additive "If a left-invariant measure gives positive mass to some compact set with nonempty
interior, then it is an additive Haar measure."]
lemma is_haar_measure_of_is_compact_nonempty_interior [topological_group G] [borel_space G]
(μ : measure G) [is_mul_left_invariant μ]
(K : set G) (hK : is_compact K) (h'K : (interior K).nonempty) (h : μ K ≠ 0) (h' : μ K ≠ ∞) :
is_haar_measure μ :=
{ lt_top_of_is_compact :=
λ L hL, measure_lt_top_of_is_compact_of_is_mul_left_invariant' h'K h' hL,
to_is_open_pos_measure := is_open_pos_measure_of_mul_left_invariant_of_compact K hK h }
/-- The image of a Haar measure under a group homomorphism which is also a homeomorphism is again
a Haar measure. -/
@[to_additive "The image of an additive Haar measure under an additive group homomorphism which is
also a homeomorphism is again an additive Haar measure."]
lemma is_haar_measure_map [borel_space G] [topological_group G] {H : Type*} [group H]
[topological_space H] [measurable_space H] [borel_space H] [t2_space H] [topological_group H]
(f : G ≃* H) (hf : continuous f) (hfsymm : continuous f.symm) :
is_haar_measure (measure.map f μ) :=
{ to_is_mul_left_invariant := begin
constructor,
assume h,
rw map_map (continuous_mul_left h).measurable hf.measurable,
conv_rhs { rw ← map_mul_left_eq_self μ (f.symm h) },
rw map_map hf.measurable (continuous_mul_left _).measurable,
congr' 2,
ext y,
simp only [mul_equiv.apply_symm_apply, comp_app, mul_equiv.map_mul],
end,
lt_top_of_is_compact := begin
assume K hK,
rw map_apply hf.measurable hK.measurable_set,
have : f.symm '' K = f ⁻¹' K := equiv.image_eq_preimage _ _,
rw ← this,
exact is_compact.measure_lt_top (hK.image hfsymm)
end,
to_is_open_pos_measure := hf.is_open_pos_measure_map f.surjective }
/-- A Haar measure on a σ-compact space is σ-finite.
See Note [lower instance priority] -/
@[priority 100, to_additive "A Haar measure on a σ-compact space is σ-finite.
See Note [lower instance priority]"]
instance is_haar_measure.sigma_finite [sigma_compact_space G] : sigma_finite μ :=
⟨⟨{ set := compact_covering G,
set_mem := λ n, mem_univ _,
finite := λ n, is_compact.measure_lt_top $ is_compact_compact_covering G n,
spanning := Union_compact_covering G }⟩⟩
@[to_additive]
instance {G : Type*} [group G] [topological_space G] {mG : measurable_space G}
{H : Type*} [group H] [topological_space H] {mH : measurable_space H}
(μ : measure G) (ν : measure H) [is_haar_measure μ] [is_haar_measure ν]
[sigma_finite μ] [sigma_finite ν]
[has_measurable_mul G] [has_measurable_mul H] :
is_haar_measure (μ.prod ν) := {}
open_locale topological_space
open filter
/-- If the neutral element of a group is not isolated, then a Haar measure on this group has
no atoms.
The additive version of this instance applies in particular to show that an additive Haar measure on
a nontrivial finite-dimensional real vector space has no atom. -/
@[priority 100, to_additive "If the zero element of an additive group is not isolated, then an
additive Haar measure on this group has no atoms.
This applies in particular to show that an additive Haar measure on a nontrivial finite-dimensional
real vector space has no atom."]
instance is_haar_measure.has_no_atoms [topological_group G] [borel_space G]
[t1_space G] [locally_compact_space G] [(𝓝[≠] (1 : G)).ne_bot]
(μ : measure G) [μ.is_haar_measure] :
has_no_atoms μ :=
begin
suffices H : μ {(1 : G)} ≤ 0, by { constructor, simp [le_bot_iff.1 H] },
obtain ⟨K, K_compact, K_int⟩ : ∃ (K : set G), is_compact K ∧ (1 : G) ∈ interior K,
{ rcases exists_compact_subset is_open_univ (mem_univ (1 : G)) with ⟨K, hK⟩,
exact ⟨K, hK.1, hK.2.1⟩ },
have K_inf : set.infinite K := infinite_of_mem_nhds (1 : G) (mem_interior_iff_mem_nhds.1 K_int),
have μKlt : μ K ≠ ∞ := K_compact.measure_lt_top.ne,
have I : ∀ (n : ℕ), μ {(1 : G)} ≤ μ K / n,
{ assume n,
obtain ⟨t, tK, tn⟩ : ∃ (t : finset G), ↑t ⊆ K ∧ t.card = n := K_inf.exists_subset_card_eq n,
have A : μ t ≤ μ K := measure_mono tK,
have B : μ t = n * μ {(1 : G)},
{ rw ← bUnion_of_singleton ↑t,
change μ (⋃ (x ∈ t), {x}) = n * μ {1},
rw @measure_bUnion_finset G G _ μ t (λ i, {i}),
{ simp only [tn, finset.sum_const, nsmul_eq_mul, haar_singleton] },
{ assume x hx y hy xy,
simp only [on_fun, xy.symm, mem_singleton_iff, not_false_iff, disjoint_singleton_right] },
{ assume b hb, exact measurable_set_singleton b } },
rw B at A,
rwa [ennreal.le_div_iff_mul_le _ (or.inr μKlt), mul_comm],
right,
apply (measure_pos_of_nonempty_interior μ ⟨_, K_int⟩).ne' },
have J : tendsto (λ (n : ℕ), μ K / n) at_top (𝓝 (μ K / ∞)) :=
ennreal.tendsto.const_div ennreal.tendsto_nat_nhds_top (or.inr μKlt),
simp only [ennreal.div_top] at J,
exact ge_of_tendsto' J I,
end
/- The above instance applies in particular to show that an additive Haar measure on a nontrivial
finite-dimensional real vector space has no atom. -/
example {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [nontrivial E]
[finite_dimensional ℝ E] [measurable_space E] [borel_space E] (μ : measure E)
[is_add_haar_measure μ] :
has_no_atoms μ := by apply_instance
end
end measure
end haar
end measure_theory
|
5fe2b420eeec26cc7ce17000716d3b8cc4cf7c85 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/nat/choose/cast.lean | 907dc455792bb45aa62b836aab76ca835f4836a6 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 1,489 | lean | /-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.nat.choose.basic
import data.nat.factorial.cast
/-!
# Cast of binomial coefficients
This file allows calculating the binomial coefficient `a.choose b` as an element of a division ring
of characteristic `0`.
-/
open_locale nat
variables (K : Type*) [division_ring K] [char_zero K]
namespace nat
lemma cast_choose {a b : ℕ} (h : a ≤ b) :
(b.choose a : K) = b! / (a! * (b - a)!) :=
begin
have : ∀ {n : ℕ}, (n! : K) ≠ 0 := λ n, nat.cast_ne_zero.2 (factorial_ne_zero _),
rw eq_div_iff_mul_eq (mul_ne_zero this this),
rw_mod_cast [← mul_assoc, choose_mul_factorial_mul_factorial h],
end
lemma cast_add_choose {a b : ℕ} :
((a + b).choose a : K) = (a + b)! / (a! * b!) :=
by rw [cast_choose K (le_add_right le_rfl), add_tsub_cancel_left]
lemma cast_choose_eq_pochhammer_div (a b : ℕ) :
(a.choose b : K) = (pochhammer K b).eval (a - (b - 1) : ℕ) / b! :=
by rw [eq_div_iff_mul_eq (nat.cast_ne_zero.2 b.factorial_ne_zero : (b! : K) ≠ 0),
←nat.cast_mul, mul_comm, ←nat.desc_factorial_eq_factorial_mul_choose, ←cast_desc_factorial]
lemma cast_choose_two (a : ℕ) :
(a.choose 2 : K) = a * (a - 1) / 2 :=
by rw [←cast_desc_factorial_two, desc_factorial_eq_factorial_mul_choose, factorial_two, mul_comm,
cast_mul, cast_two, eq_div_iff_mul_eq (two_ne_zero : (2 : K) ≠ 0)]
end nat
|
1e5bd57dbd3a2528f34d869ca3952bad5e53b1b6 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/number_theory/number_field/norm.lean | 8476cfc5dff863db30e9a1e36bd72a60fd12faba | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 4,789 | lean | /-
Copyright (c) 2022 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca, Eric Rodriguez
-/
import number_theory.number_field.basic
import ring_theory.norm
/-!
# Norm in number fields
Given a finite extension of number fields, we define the norm morphism as a function between the
rings of integers.
## Main definitions
* `ring_of_integers.norm K` : `algebra.norm` as a morphism `(𝓞 L) →* (𝓞 K)`.
## Main results
* `algebra.dvd_norm` : if `L/K` is a finite Galois extension of fields, then, for all `(x : 𝓞 L)`
we have that `x ∣ algebra_map (𝓞 K) (𝓞 L) (norm K x)`.
-/
open_locale number_field big_operators
open finset number_field algebra finite_dimensional
namespace ring_of_integers
variables {L : Type*} (K : Type*) [field K] [field L] [algebra K L] [finite_dimensional K L]
/-- `algebra.norm` as a morphism betwen the rings of integers. -/
@[simps] noncomputable def norm [is_separable K L] : (𝓞 L) →* (𝓞 K) :=
((algebra.norm K).restrict (𝓞 L)).cod_restrict (𝓞 K) (λ x, is_integral_norm K x.2)
local attribute [instance] number_field.ring_of_integers_algebra
lemma coe_algebra_map_norm [is_separable K L] (x : 𝓞 L) :
(algebra_map (𝓞 K) (𝓞 L) (norm K x) : L) = algebra_map K L (algebra.norm K (x : L)) := rfl
lemma coe_norm_algebra_map [is_separable K L] (x : 𝓞 K) :
(norm K (algebra_map (𝓞 K) (𝓞 L) x) : K) = algebra.norm K (algebra_map K L x) := rfl
lemma norm_algebra_map [is_separable K L] (x : 𝓞 K) :
norm K (algebra_map (𝓞 K) (𝓞 L) x) = x ^ finrank K L :=
by rw [← subtype.coe_inj, ring_of_integers.coe_norm_algebra_map, algebra.norm_algebra_map,
subsemiring_class.coe_pow]
lemma is_unit_norm_of_is_galois [is_galois K L] {x : 𝓞 L} :
is_unit (norm K x) ↔ is_unit x :=
begin
classical,
refine ⟨λ hx, _, is_unit.map _⟩,
replace hx : is_unit (algebra_map (𝓞 K) (𝓞 L) $ norm K x) := hx.map (algebra_map (𝓞 K) $ 𝓞 L),
refine @is_unit_of_mul_is_unit_right (𝓞 L) _
⟨(univ \ { alg_equiv.refl }).prod (λ (σ : L ≃ₐ[K] L), σ x),
prod_mem (λ σ hσ, map_is_integral (σ : L →+* L).to_int_alg_hom x.2)⟩ _ _,
convert hx using 1,
ext,
push_cast,
convert_to (univ \ { alg_equiv.refl }).prod (λ (σ : L ≃ₐ[K] L), σ x) * (∏ (σ : L ≃ₐ[K] L) in
{alg_equiv.refl}, σ (x : L)) = _,
{ rw [prod_singleton, alg_equiv.coe_refl, id] },
{ rw [prod_sdiff $ subset_univ _, ←norm_eq_prod_automorphisms, coe_algebra_map_norm] }
end
/-- If `L/K` is a finite Galois extension of fields, then, for all `(x : 𝓞 L)` we have that
`x ∣ algebra_map (𝓞 K) (𝓞 L) (norm K x)`. -/
lemma dvd_norm [is_galois K L] (x : 𝓞 L) : x ∣ algebra_map (𝓞 K) (𝓞 L) (norm K x) :=
begin
classical,
have hint : (∏ (σ : L ≃ₐ[K] L) in univ.erase alg_equiv.refl, σ x) ∈ 𝓞 L :=
subalgebra.prod_mem _ (λ σ hσ, (mem_ring_of_integers _ _).2
(map_is_integral σ (ring_of_integers.is_integral_coe x))),
refine ⟨⟨_, hint⟩, subtype.ext _⟩,
rw [coe_algebra_map_norm K x, norm_eq_prod_automorphisms],
simp [← finset.mul_prod_erase _ _ (mem_univ alg_equiv.refl)]
end
variables (F : Type*) [field F] [algebra K F] [is_separable K F] [finite_dimensional K F]
lemma norm_norm [is_separable K L] [algebra F L] [is_separable F L] [finite_dimensional F L]
[is_scalar_tower K F L] (x : 𝓞 L) : norm K (norm F x) = norm K x :=
by rw [← subtype.coe_inj, norm_apply_coe, norm_apply_coe, norm_apply_coe, algebra.norm_norm]
variable {F}
lemma is_unit_norm [char_zero K] {x : 𝓞 F} :
is_unit (norm K x) ↔ is_unit x :=
begin
letI : algebra K (algebraic_closure K) := algebraic_closure.algebra K,
let L := normal_closure K F (algebraic_closure F),
haveI : finite_dimensional F L := finite_dimensional.right K F L,
haveI : is_alg_closure K (algebraic_closure F) :=
is_alg_closure.of_algebraic K F (algebraic_closure F) (algebra.is_algebraic_of_finite K F),
haveI : is_galois F L := is_galois.tower_top_of_is_galois K F L,
calc
is_unit (norm K x) ↔ is_unit ((norm K) x ^ finrank F L) :
(is_unit_pow_iff (pos_iff_ne_zero.mp finrank_pos)).symm
... ↔ is_unit (norm K (algebra_map (𝓞 F) (𝓞 L) x)) :
by rw [← norm_norm K F (algebra_map (𝓞 F) (𝓞 L) x), norm_algebra_map F _, map_pow]
... ↔ is_unit (algebra_map (𝓞 F) (𝓞 L) x) : is_unit_norm_of_is_galois K
... ↔ is_unit (norm F (algebra_map (𝓞 F) (𝓞 L) x)) : (is_unit_norm_of_is_galois F).symm
... ↔ is_unit (x ^ finrank F L) : (congr_arg is_unit (norm_algebra_map F _)).to_iff
... ↔ is_unit x : is_unit_pow_iff (pos_iff_ne_zero.mp finrank_pos),
end
end ring_of_integers
|
90d3de3c94355b0db411a4c6a42cff58000c5dac | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/algebra/gcd_monoid/finset.lean | a93814e0c632f9dd5231e556b5c06c9e5848f364 | [
"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 | 6,886 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import data.finset.fold
import algebra.gcd_monoid.multiset
/-!
# GCD and LCM operations on finsets
## Main definitions
- `finset.gcd` - the greatest common denominator of a `finset` of elements of a `gcd_monoid`
- `finset.lcm` - the least common multiple of a `finset` of elements of a `gcd_monoid`
## Implementation notes
Many of the proofs use the lemmas `gcd.def` and `lcm.def`, which relate `finset.gcd`
and `finset.lcm` to `multiset.gcd` and `multiset.lcm`.
TODO: simplify with a tactic and `data.finset.lattice`
## Tags
finset, gcd
-/
variables {α β γ : Type*}
namespace finset
open multiset
variables [comm_cancel_monoid_with_zero α] [normalized_gcd_monoid α]
/-! ### lcm -/
section lcm
/-- Least common multiple of a finite set -/
def lcm (s : finset β) (f : β → α) : α := s.fold gcd_monoid.lcm 1 f
variables {s s₁ s₂ : finset β} {f : β → α}
lemma lcm_def : s.lcm f = (s.1.map f).lcm := rfl
@[simp] lemma lcm_empty : (∅ : finset β).lcm f = 1 :=
fold_empty
@[simp] lemma lcm_dvd_iff {a : α} : s.lcm f ∣ a ↔ (∀b ∈ s, f b ∣ a) :=
begin
apply iff.trans multiset.lcm_dvd,
simp only [multiset.mem_map, and_imp, exists_imp_distrib],
exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩,
end
lemma lcm_dvd {a : α} : (∀b ∈ s, f b ∣ a) → s.lcm f ∣ a :=
lcm_dvd_iff.2
lemma dvd_lcm {b : β} (hb : b ∈ s) : f b ∣ s.lcm f :=
lcm_dvd_iff.1 dvd_rfl _ hb
@[simp] lemma lcm_insert [decidable_eq β] {b : β} :
(insert b s : finset β).lcm f = gcd_monoid.lcm (f b) (s.lcm f) :=
begin
by_cases h : b ∈ s,
{ rw [insert_eq_of_mem h,
(lcm_eq_right_iff (f b) (s.lcm f) (multiset.normalize_lcm (s.1.map f))).2 (dvd_lcm h)] },
apply fold_insert h,
end
@[simp] lemma lcm_singleton {b : β} : ({b} : finset β).lcm f = normalize (f b) :=
multiset.lcm_singleton
@[simp] lemma normalize_lcm : normalize (s.lcm f) = s.lcm f := by simp [lcm_def]
lemma lcm_union [decidable_eq β] : (s₁ ∪ s₂).lcm f = gcd_monoid.lcm (s₁.lcm f) (s₂.lcm f) :=
finset.induction_on s₁ (by rw [empty_union, lcm_empty, lcm_one_left, normalize_lcm]) $ λ a s has ih,
by rw [insert_union, lcm_insert, lcm_insert, ih, lcm_assoc]
theorem lcm_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a ∈ s₂, f a = g a) :
s₁.lcm f = s₂.lcm g :=
by { subst hs, exact finset.fold_congr hfg }
lemma lcm_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ∣ g b) : s.lcm f ∣ s.lcm g :=
lcm_dvd (λ b hb, (h b hb).trans (dvd_lcm hb))
lemma lcm_mono (h : s₁ ⊆ s₂) : s₁.lcm f ∣ s₂.lcm f :=
lcm_dvd $ assume b hb, dvd_lcm (h hb)
end lcm
/-! ### gcd -/
section gcd
/-- Greatest common divisor of a finite set -/
def gcd (s : finset β) (f : β → α) : α := s.fold gcd_monoid.gcd 0 f
variables {s s₁ s₂ : finset β} {f : β → α}
lemma gcd_def : s.gcd f = (s.1.map f).gcd := rfl
@[simp] lemma gcd_empty : (∅ : finset β).gcd f = 0 :=
fold_empty
lemma dvd_gcd_iff {a : α} : a ∣ s.gcd f ↔ ∀b ∈ s, a ∣ f b :=
begin
apply iff.trans multiset.dvd_gcd,
simp only [multiset.mem_map, and_imp, exists_imp_distrib],
exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩,
end
lemma gcd_dvd {b : β} (hb : b ∈ s) : s.gcd f ∣ f b :=
dvd_gcd_iff.1 dvd_rfl _ hb
lemma dvd_gcd {a : α} : (∀b ∈ s, a ∣ f b) → a ∣ s.gcd f :=
dvd_gcd_iff.2
@[simp] lemma gcd_insert [decidable_eq β] {b : β} :
(insert b s : finset β).gcd f = gcd_monoid.gcd (f b) (s.gcd f) :=
begin
by_cases h : b ∈ s,
{ rw [insert_eq_of_mem h,
(gcd_eq_right_iff (f b) (s.gcd f) (multiset.normalize_gcd (s.1.map f))).2 (gcd_dvd h)] ,},
apply fold_insert h,
end
@[simp] lemma gcd_singleton {b : β} : ({b} : finset β).gcd f = normalize (f b) :=
multiset.gcd_singleton
@[simp] lemma normalize_gcd : normalize (s.gcd f) = s.gcd f := by simp [gcd_def]
lemma gcd_union [decidable_eq β] : (s₁ ∪ s₂).gcd f = gcd_monoid.gcd (s₁.gcd f) (s₂.gcd f) :=
finset.induction_on s₁ (by rw [empty_union, gcd_empty, gcd_zero_left, normalize_gcd]) $
λ a s has ih, by rw [insert_union, gcd_insert, gcd_insert, ih, gcd_assoc]
theorem gcd_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a ∈ s₂, f a = g a) :
s₁.gcd f = s₂.gcd g :=
by { subst hs, exact finset.fold_congr hfg }
lemma gcd_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ∣ g b) : s.gcd f ∣ s.gcd g :=
dvd_gcd (λ b hb, (gcd_dvd hb).trans (h b hb))
lemma gcd_mono (h : s₁ ⊆ s₂) : s₂.gcd f ∣ s₁.gcd f :=
dvd_gcd $ assume b hb, gcd_dvd (h hb)
theorem gcd_eq_zero_iff : s.gcd f = 0 ↔ ∀ (x : β), x ∈ s → f x = 0 :=
begin
rw [gcd_def, multiset.gcd_eq_zero_iff],
split; intro h,
{ intros b bs,
apply h (f b),
simp only [multiset.mem_map, mem_def.1 bs],
use b,
simp [mem_def.1 bs] },
{ intros a as,
rw multiset.mem_map at as,
rcases as with ⟨b, ⟨bs, rfl⟩⟩,
apply h b (mem_def.1 bs) }
end
lemma gcd_eq_gcd_filter_ne_zero [decidable_pred (λ (x : β), f x = 0)] :
s.gcd f = (s.filter (λ x, f x ≠ 0)).gcd f :=
begin
classical,
transitivity ((s.filter (λ x, f x = 0)) ∪ (s.filter (λ x, f x ≠ 0))).gcd f,
{ rw filter_union_filter_neg_eq },
rw gcd_union,
transitivity gcd_monoid.gcd (0 : α) _,
{ refine congr (congr rfl _) rfl,
apply s.induction_on, { simp },
intros a s has h,
rw filter_insert,
split_ifs with h1; simp [h, h1], },
simp [gcd_zero_left, normalize_gcd],
end
lemma gcd_mul_left {a : α} : s.gcd (λ x, a * f x) = normalize a * s.gcd f :=
begin
classical,
apply s.induction_on,
{ simp },
intros b t hbt h,
rw [gcd_insert, gcd_insert, h, ← gcd_mul_left],
apply ((normalize_associated a).mul_right _).gcd_eq_right
end
lemma gcd_mul_right {a : α} : s.gcd (λ x, f x * a) = s.gcd f * normalize a :=
begin
classical,
apply s.induction_on,
{ simp },
intros b t hbt h,
rw [gcd_insert, gcd_insert, h, ← gcd_mul_right],
apply ((normalize_associated a).mul_left _).gcd_eq_right
end
end gcd
end finset
namespace finset
section integral_domain
variables [comm_ring α] [integral_domain α] [normalized_gcd_monoid α]
lemma gcd_eq_of_dvd_sub {s : finset β} {f g : β → α} {a : α}
(h : ∀ x : β, x ∈ s → a ∣ f x - g x) :
gcd_monoid.gcd a (s.gcd f) = gcd_monoid.gcd a (s.gcd g) :=
begin
classical,
revert h,
apply s.induction_on,
{ simp },
intros b s bs hi h,
rw [gcd_insert, gcd_insert, gcd_comm (f b), ← gcd_assoc, hi (λ x hx, h _ (mem_insert_of_mem hx)),
gcd_comm a, gcd_assoc, gcd_comm a (gcd_monoid.gcd _ _),
gcd_comm (g b), gcd_assoc _ _ a, gcd_comm _ a],
exact congr_arg _ (gcd_eq_of_dvd_sub_right (h _ (mem_insert_self _ _)))
end
end integral_domain
end finset
|
470339837b91d16d03ee3a05beb4361ae3345841 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/ring_theory/rees_algebra.lean | 8668d8794b884e508b4e4fed91cf162701a22a12 | [
"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,192 | lean | /-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import ring_theory.finite_type
/-!
# Rees algebra
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
The Rees algebra of an ideal `I` is the subalgebra `R[It]` of `R[t]` defined as `R[It] = ⨁ₙ Iⁿ tⁿ`.
This is used to prove the Artin-Rees lemma, and will potentially enable us to calculate some
blowup in the future.
## Main definition
- `rees_algebra` : The Rees algebra of an ideal `I`, defined as a subalgebra of `R[X]`.
- `adjoin_monomial_eq_rees_algebra` : The Rees algebra is generated by the degree one elements.
- `rees_algebra.fg` : The Rees algebra of a f.g. ideal is of finite type. In particular, this
implies that the rees algebra over a noetherian ring is still noetherian.
-/
universes u v
variables {R M : Type u} [comm_ring R] [add_comm_group M] [module R M] (I : ideal R)
open polynomial
open_locale polynomial big_operators
/-- The Rees algebra of an ideal `I`, defined as the subalgebra of `R[X]` whose `i`-th coefficient
falls in `I ^ i`. -/
def rees_algebra : subalgebra R R[X] :=
{ carrier := { f | ∀ i, f.coeff i ∈ I ^ i },
mul_mem' := λ f g hf hg i, begin
rw coeff_mul,
apply ideal.sum_mem,
rintros ⟨j, k⟩ e,
rw [← finset.nat.mem_antidiagonal.mp e, pow_add],
exact ideal.mul_mem_mul (hf j) (hg k)
end,
one_mem' := λ i, begin
rw coeff_one,
split_ifs,
{ subst h, simp },
{ simp }
end,
add_mem' := λ f g hf hg i, begin
rw coeff_add,
exact ideal.add_mem _ (hf i) (hg i)
end,
zero_mem' := λ i, ideal.zero_mem _,
algebra_map_mem' := λ r i, begin
rw [algebra_map_apply, coeff_C],
split_ifs,
{ subst h, simp },
{ simp }
end }
lemma mem_rees_algebra_iff (f : R[X]) :
f ∈ rees_algebra I ↔ ∀ i, f.coeff i ∈ I ^ i := iff.rfl
lemma mem_rees_algebra_iff_support (f : R[X]) :
f ∈ rees_algebra I ↔ ∀ i ∈ f.support, f.coeff i ∈ I ^ i :=
begin
apply forall_congr,
intro a,
rw [mem_support_iff, iff.comm, imp_iff_right_iff, ne.def, ← imp_iff_not_or],
exact λ e, e.symm ▸ (I ^ a).zero_mem
end
lemma rees_algebra.monomial_mem {I : ideal R} {i : ℕ} {r : R} :
monomial i r ∈ rees_algebra I ↔ r ∈ I ^ i :=
by simp [mem_rees_algebra_iff_support, coeff_monomial, ← imp_iff_not_or] { contextual := tt }
lemma monomial_mem_adjoin_monomial {I : ideal R} {n : ℕ} {r : R} (hr : r ∈ I ^ n) :
monomial n r ∈ algebra.adjoin R (submodule.map (monomial 1 : R →ₗ[R] R[X]) I : set R[X]) :=
begin
induction n with n hn generalizing r,
{ exact subalgebra.algebra_map_mem _ _ },
{ rw pow_succ at hr,
apply submodule.smul_induction_on hr,
{ intros r hr s hs,
rw [nat.succ_eq_one_add, smul_eq_mul, ← monomial_mul_monomial],
exact subalgebra.mul_mem _ (algebra.subset_adjoin (set.mem_image_of_mem _ hr)) (hn hs) },
{ intros x y hx hy, rw monomial_add, exact subalgebra.add_mem _ hx hy } }
end
lemma adjoin_monomial_eq_rees_algebra :
algebra.adjoin R (submodule.map (monomial 1 : R →ₗ[R] R[X]) I : set R[X]) = rees_algebra I :=
begin
apply le_antisymm,
{ apply algebra.adjoin_le _,
rintro _ ⟨r, hr, rfl⟩,
exact rees_algebra.monomial_mem.mpr (by rwa pow_one) },
{ intros p hp,
rw p.as_sum_support,
apply subalgebra.sum_mem _ _,
rintros i -,
exact monomial_mem_adjoin_monomial (hp i) }
end
variables {I}
lemma rees_algebra.fg (hI : I.fg) : (rees_algebra I).fg :=
begin
classical,
obtain ⟨s, hs⟩ := hI,
rw [← adjoin_monomial_eq_rees_algebra, ← hs],
use s.image (monomial 1),
rw finset.coe_image,
change _ = algebra.adjoin R (submodule.map (monomial 1 : R →ₗ[R] R[X])
(submodule.span R ↑s) : set R[X]),
rw [submodule.map_span, algebra.adjoin_span]
end
instance [is_noetherian_ring R] : algebra.finite_type R (rees_algebra I) :=
⟨(rees_algebra I).fg_top.mpr (rees_algebra.fg $ is_noetherian.noetherian I)⟩
instance [is_noetherian_ring R] : is_noetherian_ring (rees_algebra I) :=
algebra.finite_type.is_noetherian_ring R _
|
2c20505951249450d244a913f882d95ebb0b2108 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Leanpkg/LeanVersion.lean | b1cfeb72089ff89b440b062a1178c537d615303c | [
"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 | 776 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Sebastian Ullrich
-/
namespace Leanpkg
def leanVersionStringCore :=
s!"{Lean.version.major}.{Lean.version.minor}.{Lean.version.patch}"
def origin := "leanprover/lean4"
def leanVersionString :=
if Lean.version.isRelease then
s!"{origin}:{leanVersionStringCore}"
else if Lean.version.specialDesc ≠ "" then
s!"{origin}:{Lean.version.specialDesc}"
else
s!"{origin}:master"
def uiLeanVersionString :=
if Lean.version.isRelease then
leanVersionStringCore
else if Lean.version.specialDesc ≠ "" then
Lean.version.specialDesc
else
s!"master ({leanVersionStringCore})"
end Leanpkg
|
5b23c233f1bd9db90276c8b26a35c7fff524f080 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/run/do_let_notation.lean | 99752ba450736a938a3be9e130cc17310fc6ab4f | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 312 | lean | open tactic
example : true :=
by do
let n := 10,
let b := 20,
trace $ n + b,
constructor
example : true ∧ true :=
by do
t ← target,
let f := t^.get_app_fn,
trace f,
constructor,
repeat triv
example : true ∧ true :=
by do
t ← target,
let f := t^.get_app_fn in
constructor; triv
|
6de30b47f686fa931eb56e2355e8aba3451522ee | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Compiler/Decl.lean | be1db97fa53f63011cc448af1fa10ecefdb3bb6d | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 6,628 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Transform
import Lean.Meta.Check
import Lean.Compiler.LCNF
import Lean.Compiler.Check
import Lean.Compiler.CompilerM
import Lean.Compiler.JoinPoints
namespace Lean.Compiler
/--
Declaration being processed by the Lean to Lean compiler passes.
-/
structure Decl where
/--
The name of the declaration from the `Environment` it came from
-/
name : Name
/--
The type of the declaration. Note that this is an erased LCNF type
instead of the fully dependent one that might have been the original
type of the declaration in the `Environment`.
-/
type : Expr
/--
The value of the declaration, usually changes as it progresses
through compiler passes.
-/
value : Expr
/--
Inline constants tagged with the `[macroInline]` attribute occurring in `e`.
-/
def macroInline (e : Expr) : CoreM Expr :=
Core.transform e fun e => do
let .const declName us := e.getAppFn | return .visit e
unless hasMacroInlineAttribute (← getEnv) declName do return .visit e
let val ← Core.instantiateValueLevelParams (← getConstInfo declName) us
return .visit <| val.beta e.getAppArgs
private def normalizeAlt (e : Expr) (numParams : Nat) : MetaM Expr :=
Meta.lambdaTelescope e fun xs body => do
if xs.size == numParams then
return e
else if xs.size > numParams then
let body ← Meta.mkLambdaFVars xs[numParams:] body
let body ← Meta.withLetDecl (← mkFreshUserName `_k) (← Meta.inferType body) body fun x => Meta.mkLetFVars #[x] x
Meta.mkLambdaFVars xs[:numParams] body
else
Meta.forallBoundedTelescope (← Meta.inferType e) (numParams - xs.size) fun ys _ =>
Meta.mkLambdaFVars (xs ++ ys) (mkAppN e ys)
/--
Inline auxiliary `matcher` applications.
-/
partial def inlineMatchers (e : Expr) : CoreM Expr :=
Meta.MetaM.run' <| Meta.transform e fun e => do
let .const declName us := e.getAppFn | return .visit e
let some info ← Meta.getMatcherInfo? declName | return .visit e
let numArgs := e.getAppNumArgs
if numArgs > info.arity then
return .visit e
else if numArgs < info.arity then
Meta.forallBoundedTelescope (← Meta.inferType e) (info.arity - numArgs) fun xs _ =>
return .visit (← Meta.mkLambdaFVars xs (mkAppN e xs))
else
let mut args := e.getAppArgs
let numAlts := info.numAlts
let altNumParams := info.altNumParams
let rec inlineMatcher (i : Nat) (args : Array Expr) (letFVars : Array Expr) : MetaM Expr := do
if i < numAlts then
let altIdx := i + info.getFirstAltPos
let numParams := altNumParams[i]!
let alt ← normalizeAlt args[altIdx]! numParams
Meta.withLetDecl (← mkFreshUserName `_alt) (← Meta.inferType alt) alt fun altFVar =>
inlineMatcher (i+1) (args.set! altIdx altFVar) (letFVars.push altFVar)
else
let info ← getConstInfo declName
let value := (← Core.instantiateValueLevelParams info us).beta args
Meta.mkLetFVars letFVars value
return .visit (← inlineMatcher 0 args #[])
/--
Replace nested occurrences of `unsafeRec` names with the safe ones.
-/
private def replaceUnsafeRecNames (value : Expr) : CoreM Expr :=
Core.transform value fun e =>
match e with
| .const declName us =>
if let some safeDeclName := isUnsafeRecName? declName then
return .done (.const safeDeclName us)
else
return .done e
| _ => return .visit e
/--
Convert the given declaration from the Lean environment into `Decl`.
The steps for this are roughly:
- partially erasing type information of the declaration
- eta-expanding the declaration value.
- if the declaration has an unsafe-rec version, use it.
- expand declarations tagged with the `[macroInline]` attribute
- turn the resulting term into LCNF
-/
def toDecl (declName : Name) : CoreM Decl := do
let env ← getEnv
let some info := env.find? (mkUnsafeRecName declName) <|> env.find? declName | throwError "declaration `{declName}` not found"
let some value := info.value? | throwError "declaration `{declName}` does not have a value"
Meta.MetaM.run' do
let type ← toLCNFType info.type
let value ← Meta.lambdaTelescope value fun xs body => do Meta.mkLambdaFVars xs (← Meta.etaExpand body)
let value ← replaceUnsafeRecNames value
let value ← macroInline value
let value ← inlineMatchers value
let value ← toLCNF value
return { name := declName, type, value }
/--
Join points are let bound variables with an _jp name prefix.
They always need to satisfy two conditions:
1. Be fully applied
2. Always be called in tail position
in order to allow the optimizer to turn them into efficient machine code.
This function ensures that inside the given declaration both of these
conditions are satisfied and throws an exception otherwise.
-/
def Decl.checkJoinPoints (decl : Decl) : CompilerM Unit :=
JoinPointChecker.checkJoinPoints decl.value
/--
Check whether a declaration still fulfills all the invariants that we put
on them, if it does not throw an exception. This is meant as a sanity
check for the code generator itself, not to find errors in the user code.
These invariants are:
- The ones enforced by `Compiler.check`
- The stored and the inferred LCNF type of the declaration are compatible according to `compatibleTypes`
-/
def Decl.check (decl : Decl) (cfg : Check.Config := {}): CoreM Unit := do
Compiler.check decl.value cfg { lctx := {} }
checkJoinPoints decl |>.run' {}
let valueType ← InferType.inferType decl.value { lctx := {} }
unless compatibleTypes decl.type valueType do
throwError "declaration type mismatch at `{decl.name}`, value has type{indentExpr valueType}\nbut is expected to have type{indentExpr decl.type}"
/-- Apply `f` to declaration `value`. -/
def Decl.mapValue (decl : Decl) (f : Expr → CompilerM Expr) : CoreM Decl := do
return { decl with value := (← f decl.value |>.run' { nextIdx := (← getMaxLetVarIdx decl.value) + 1 }) }
def Decl.toString (decl : Decl) : CoreM String := do
Meta.MetaM.run' do
return s!"{decl.name} : {← Meta.ppExpr decl.type} :=\n{← Meta.ppExpr decl.value}"
/--
Make sure all let-declarations have unique user-facing names.
See `Compiler.ensureUniqueLetVarNames`
-/
def Decl.ensureUniqueLetVarNames (decl : Decl) : CoreM Decl := do
return { decl with value := (← Compiler.ensureUniqueLetVarNames decl.value) }
end Lean.Compiler
|
c41fc18a750208bd5b66452a4f5aa5547a5f3024 | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/valid/imo-1990-p3.lean | 795888b5a19874246925ecfed640f72777e7d07f | [
"MIT",
"Apache-2.0"
] | permissive | zeta1999/miniF2F | 6d66c75d1c18152e224d07d5eed57624f731d4b7 | c1ba9629559c5273c92ec226894baa0c1ce27861 | refs/heads/main | 1,681,897,460,642 | 1,620,646,361,000 | 1,620,646,361,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 261 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng
-/
import data.nat.basic
example ( n : ℕ) (h₀ : 2 ≤ n) (h₁ : n ^ 2 ∣ 2 ^ n + 1) : n = 3 :=
begin
sorry
end
|
adc56f51b67297740b143e6e0a7c866753d94553 | 367134ba5a65885e863bdc4507601606690974c1 | /src/combinatorics/simple_graph/basic.lean | 2b5d887313e157a0d5e2499a69ec77def1dceb5e | [
"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 | 15,970 | lean | /-
Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Aaron Anderson, Jalex Stark, Kyle Miller, Alena Gusakov
-/
import data.fintype.basic
import data.sym2
import data.set.finite
/-!
# Simple graphs
This module defines simple graphs on a vertex type `V` as an
irreflexive symmetric relation.
There is a basic API for locally finite graphs and for graphs with
finitely many vertices.
## Main definitions
* `simple_graph` is a structure for symmetric, irreflexive relations
* `neighbor_set` is the `set` of vertices adjacent to a given vertex
* `neighbor_finset` is the `finset` of vertices adjacent to a given vertex,
if `neighbor_set` is finite
* `incidence_set` is the `set` of edges containing a given vertex
* `incidence_finset` is the `finset` of edges containing a given vertex,
if `incidence_set` is finite
## Implementation notes
* A locally finite graph is one with instances `∀ v, fintype (G.neighbor_set v)`.
* Given instances `decidable_rel G.adj` and `fintype V`, then the graph
is locally finite, too.
## Naming Conventions
* If the vertex type of a graph is finite, we refer to its cardinality as `card_verts`.
TODO: This is the simplest notion of an unoriented graph. This should
eventually fit into a more complete combinatorics hierarchy which
includes multigraphs and directed graphs. We begin with simple graphs
in order to start learning what the combinatorics hierarchy should
look like.
TODO: Part of this would include defining, for example, subgraphs of a
simple graph.
-/
open finset
universe u
/--
A simple graph is an irreflexive symmetric relation `adj` on a vertex type `V`.
The relation describes which pairs of vertices are adjacent.
There is exactly one edge for every pair of adjacent edges;
see `simple_graph.edge_set` for the corresponding edge set.
-/
@[ext]
structure simple_graph (V : Type u) :=
(adj : V → V → Prop)
(sym : symmetric adj . obviously)
(loopless : irreflexive adj . obviously)
/--
Construct the simple graph induced by the given relation. It
symmetrizes the relation and makes it irreflexive.
-/
def simple_graph.from_rel {V : Type u} (r : V → V → Prop) : simple_graph V :=
{ adj := λ a b, (a ≠ b) ∧ (r a b ∨ r b a),
sym := λ a b ⟨hn, hr⟩, ⟨hn.symm, hr.symm⟩,
loopless := λ a ⟨hn, _⟩, hn rfl }
noncomputable instance {V : Type u} [fintype V] : fintype (simple_graph V) :=
by { classical, exact fintype.of_injective simple_graph.adj simple_graph.ext }
@[simp]
lemma simple_graph.from_rel_adj {V : Type u} (r : V → V → Prop) (v w : V) :
(simple_graph.from_rel r).adj v w ↔ v ≠ w ∧ (r v w ∨ r w v) :=
iff.rfl
/--
The complete graph on a type `V` is the simple graph with all pairs of distinct vertices adjacent.
-/
def complete_graph (V : Type u) : simple_graph V :=
{ adj := ne }
instance (V : Type u) : inhabited (simple_graph V) :=
⟨complete_graph V⟩
instance complete_graph_adj_decidable (V : Type u) [decidable_eq V] :
decidable_rel (complete_graph V).adj :=
λ v w, not.decidable
namespace simple_graph
variables {V : Type u} (G : simple_graph V)
/-- `G.neighbor_set v` is the set of vertices adjacent to `v` in `G`. -/
def neighbor_set (v : V) : set V := set_of (G.adj v)
instance neighbor_set.mem_decidable (v : V) [decidable_rel G.adj] :
decidable_pred (G.neighbor_set v) := by { unfold neighbor_set, apply_instance }
lemma ne_of_adj {a b : V} (hab : G.adj a b) : a ≠ b :=
by { rintro rfl, exact G.loopless a hab }
/--
The edges of G consist of the unordered pairs of vertices related by
`G.adj`.
-/
def edge_set : set (sym2 V) := sym2.from_rel G.sym
/--
The `incidence_set` is the set of edges incident to a given vertex.
-/
def incidence_set (v : V) : set (sym2 V) := {e ∈ G.edge_set | v ∈ e}
lemma incidence_set_subset (v : V) : G.incidence_set v ⊆ G.edge_set :=
λ _ h, h.1
@[simp]
lemma mem_edge_set {v w : V} : ⟦(v, w)⟧ ∈ G.edge_set ↔ G.adj v w :=
by refl
/--
Two vertices are adjacent iff there is an edge between them. The
condition `v ≠ w` ensures they are different endpoints of the edge,
which is necessary since when `v = w` the existential
`∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e` is satisfied by every edge
incident to `v`.
-/
lemma adj_iff_exists_edge {v w : V} :
G.adj v w ↔ v ≠ w ∧ ∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e :=
begin
refine ⟨λ _, ⟨G.ne_of_adj ‹_›, ⟦(v,w)⟧, _⟩, _⟩,
{ simpa },
{ rintro ⟨hne, e, he, hv⟩,
rw sym2.elems_iff_eq hne at hv,
subst e,
rwa mem_edge_set at he }
end
lemma edge_other_ne {e : sym2 V} (he : e ∈ G.edge_set) {v : V} (h : v ∈ e) : h.other ≠ v :=
begin
erw [← sym2.mem_other_spec h, sym2.eq_swap] at he,
exact G.ne_of_adj he,
end
instance edge_set_decidable_pred [decidable_rel G.adj] :
decidable_pred G.edge_set := sym2.from_rel.decidable_pred _
instance edges_fintype [decidable_eq V] [fintype V] [decidable_rel G.adj] :
fintype G.edge_set := subtype.fintype _
instance incidence_set_decidable_pred [decidable_eq V] [decidable_rel G.adj] (v : V) :
decidable_pred (G.incidence_set v) := λ e, and.decidable
/--
The `edge_set` of the graph as a `finset`.
-/
def edge_finset [decidable_eq V] [fintype V] [decidable_rel G.adj] : finset (sym2 V) :=
set.to_finset G.edge_set
@[simp] lemma mem_edge_finset [decidable_eq V] [fintype V] [decidable_rel G.adj] (e : sym2 V) :
e ∈ G.edge_finset ↔ e ∈ G.edge_set :=
set.mem_to_finset
@[simp] lemma edge_set_univ_card [decidable_eq V] [fintype V] [decidable_rel G.adj] :
(univ : finset G.edge_set).card = G.edge_finset.card :=
fintype.card_of_subtype G.edge_finset (mem_edge_finset _)
@[simp] lemma irrefl {v : V} : ¬G.adj v v := G.loopless v
@[symm] lemma edge_symm (u v : V) : G.adj u v ↔ G.adj v u := ⟨λ x, G.sym x, λ x, G.sym x⟩
@[simp] lemma mem_neighbor_set (v w : V) : w ∈ G.neighbor_set v ↔ G.adj v w :=
iff.rfl
@[simp] lemma mem_incidence_set (v w : V) : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ G.adj v w :=
by simp [incidence_set]
lemma mem_incidence_iff_neighbor {v w : V} : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ w ∈ G.neighbor_set v :=
by simp only [mem_incidence_set, mem_neighbor_set]
lemma adj_incidence_set_inter {v : V} {e : sym2 V} (he : e ∈ G.edge_set) (h : v ∈ e) :
G.incidence_set v ∩ G.incidence_set h.other = {e} :=
begin
ext e',
simp only [incidence_set, set.mem_sep_eq, set.mem_inter_eq, set.mem_singleton_iff],
split,
{ intro h', rw ←sym2.mem_other_spec h,
exact (sym2.elems_iff_eq (edge_other_ne G he h).symm).mp ⟨h'.1.2, h'.2.2⟩, },
{ rintro rfl, use [he, h, he], apply sym2.mem_other_mem, },
end
/--
The set of common neighbors between two vertices `v` and `w` in a graph `G` is the
intersection of the neighbor sets of `v` and `w`.
-/
def common_neighbors (v w : V) : set V := G.neighbor_set v ∩ G.neighbor_set w
lemma common_neighbors_eq (v w : V) :
G.common_neighbors v w = G.neighbor_set v ∩ G.neighbor_set w := rfl
lemma mem_common_neighbors {u v w : V} : u ∈ G.common_neighbors v w ↔ G.adj v u ∧ G.adj w u :=
by simp [common_neighbors]
lemma common_neighbors_symm (v w : V) : G.common_neighbors v w = G.common_neighbors w v :=
by { rw [common_neighbors, set.inter_comm], refl }
lemma not_mem_common_neighbors_left (v w : V) : v ∉ G.common_neighbors v w :=
λ h, ne_of_adj G h.1 rfl
lemma not_mem_common_neighbors_right (v w : V) : w ∉ G.common_neighbors v w :=
λ h, ne_of_adj G h.2 rfl
lemma common_neighbors_subset_neighbor_set (v w : V) : G.common_neighbors v w ⊆ G.neighbor_set v :=
by simp [common_neighbors]
instance [decidable_rel G.adj] (v w : V) : decidable_pred (G.common_neighbors v w) :=
λ a, and.decidable
section incidence
variable [decidable_eq V]
/--
Given an edge incident to a particular vertex, get the other vertex on the edge.
-/
def other_vertex_of_incident {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : V := h.2.other'
lemma edge_mem_other_incident_set {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) :
e ∈ G.incidence_set (G.other_vertex_of_incident h) :=
by { use h.1, simp [other_vertex_of_incident, sym2.mem_other_mem'] }
lemma incidence_other_prop {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) :
G.other_vertex_of_incident h ∈ G.neighbor_set v :=
by { cases h with he hv, rwa [←sym2.mem_other_spec' hv, mem_edge_set] at he }
@[simp]
lemma incidence_other_neighbor_edge {v w : V} (h : w ∈ G.neighbor_set v) :
G.other_vertex_of_incident (G.mem_incidence_iff_neighbor.mpr h) = w :=
sym2.congr_right.mp (sym2.mem_other_spec' (G.mem_incidence_iff_neighbor.mpr h).right)
/--
There is an equivalence between the set of edges incident to a given
vertex and the set of vertices adjacent to the vertex.
-/
@[simps] def incidence_set_equiv_neighbor_set (v : V) : G.incidence_set v ≃ G.neighbor_set v :=
{ to_fun := λ e, ⟨G.other_vertex_of_incident e.2, G.incidence_other_prop e.2⟩,
inv_fun := λ w, ⟨⟦(v, w.1)⟧, G.mem_incidence_iff_neighbor.mpr w.2⟩,
left_inv := λ x, by simp [other_vertex_of_incident],
right_inv := λ ⟨w, hw⟩, by simp }
end incidence
section finite_at
/-!
## Finiteness at a vertex
This section contains definitions and lemmas concerning vertices that
have finitely many adjacent vertices. We denote this condition by
`fintype (G.neighbor_set v)`.
We define `G.neighbor_finset v` to be the `finset` version of `G.neighbor_set v`.
Use `neighbor_finset_eq_filter` to rewrite this definition as a `filter`.
-/
variables (v : V) [fintype (G.neighbor_set v)]
/--
`G.neighbors v` is the `finset` version of `G.adj v` in case `G` is
locally finite at `v`.
-/
def neighbor_finset : finset V := (G.neighbor_set v).to_finset
@[simp] lemma mem_neighbor_finset (w : V) :
w ∈ G.neighbor_finset v ↔ G.adj v w :=
set.mem_to_finset
/--
`G.degree v` is the number of vertices adjacent to `v`.
-/
def degree : ℕ := (G.neighbor_finset v).card
@[simp]
lemma card_neighbor_set_eq_degree : fintype.card (G.neighbor_set v) = G.degree v :=
(set.to_finset_card _).symm
lemma degree_pos_iff_exists_adj : 0 < G.degree v ↔ ∃ w, G.adj v w :=
by simp only [degree, card_pos, finset.nonempty, mem_neighbor_finset]
instance incidence_set_fintype [decidable_eq V] : fintype (G.incidence_set v) :=
fintype.of_equiv (G.neighbor_set v) (G.incidence_set_equiv_neighbor_set v).symm
/--
This is the `finset` version of `incidence_set`.
-/
def incidence_finset [decidable_eq V] : finset (sym2 V) := (G.incidence_set v).to_finset
@[simp]
lemma card_incidence_set_eq_degree [decidable_eq V] :
fintype.card (G.incidence_set v) = G.degree v :=
by { rw fintype.card_congr (G.incidence_set_equiv_neighbor_set v), simp }
@[simp]
lemma mem_incidence_finset [decidable_eq V] (e : sym2 V) :
e ∈ G.incidence_finset v ↔ e ∈ G.incidence_set v :=
set.mem_to_finset
end finite_at
section locally_finite
/--
A graph is locally finite if every vertex has a finite neighbor set.
-/
@[reducible]
def locally_finite := Π (v : V), fintype (G.neighbor_set v)
variable [locally_finite G]
/--
A locally finite simple graph is regular of degree `d` if every vertex has degree `d`.
-/
def is_regular_of_degree (d : ℕ) : Prop := ∀ (v : V), G.degree v = d
lemma is_regular_of_degree_eq {d : ℕ} (h : G.is_regular_of_degree d) (v : V) : G.degree v = d := h v
end locally_finite
section finite
variables [fintype V]
instance neighbor_set_fintype [decidable_rel G.adj] (v : V) : fintype (G.neighbor_set v) :=
@subtype.fintype _ _ (by { simp_rw mem_neighbor_set, apply_instance }) _
lemma neighbor_finset_eq_filter {v : V} [decidable_rel G.adj] :
G.neighbor_finset v = finset.univ.filter (G.adj v) :=
by { ext, simp }
@[simp]
lemma complete_graph_degree [decidable_eq V] (v : V) :
(complete_graph V).degree v = fintype.card V - 1 :=
begin
convert univ.card.pred_eq_sub_one,
erw [degree, neighbor_finset_eq_filter, filter_ne, card_erase_of_mem (mem_univ v)],
end
lemma complete_graph_is_regular [decidable_eq V] :
(complete_graph V).is_regular_of_degree (fintype.card V - 1) :=
by { intro v, simp }
/--
The minimum degree of all vertices
-/
def min_degree (G : simple_graph V) [nonempty V] [decidable_rel G.adj] : ℕ :=
finset.min' (univ.image (λ (v : V), G.degree v)) (nonempty.image univ_nonempty _)
/--
The maximum degree of all vertices
-/
def max_degree (G : simple_graph V) [nonempty V] [decidable_rel G.adj] : ℕ :=
finset.max' (univ.image (λ (v : V), G.degree v)) (nonempty.image univ_nonempty _)
lemma degree_lt_card_verts [decidable_rel G.adj] (v : V) : G.degree v < fintype.card V :=
begin
classical,
apply finset.card_lt_card,
rw finset.ssubset_iff,
exact ⟨v, by simp, finset.subset_univ _⟩,
end
lemma card_common_neighbors_le_degree_left [decidable_rel G.adj] (v w : V) :
fintype.card (G.common_neighbors v w) ≤ G.degree v :=
begin
rw [←card_neighbor_set_eq_degree],
exact set.card_le_of_subset (set.inter_subset_left _ _),
end
lemma card_common_neighbors_le_degree_right [decidable_rel G.adj] (v w : V) :
fintype.card (G.common_neighbors v w) ≤ G.degree w :=
begin
convert G.card_common_neighbors_le_degree_left w v using 3,
apply common_neighbors_symm,
end
lemma card_common_neighbors_lt_card_verts [decidable_rel G.adj] (v w : V) :
fintype.card (G.common_neighbors v w) < fintype.card V :=
nat.lt_of_le_of_lt (G.card_common_neighbors_le_degree_left _ _) (G.degree_lt_card_verts v)
/--
If the condition `G.adj v w` fails, then `card_common_neighbors_le_degree` is
the best we can do in general.
-/
lemma adj.card_common_neighbors_lt_degree {G : simple_graph V} [decidable_rel G.adj]
{v w : V} (h : G.adj v w) :
fintype.card (G.common_neighbors v w) < G.degree v :=
begin
classical,
erw [←set.to_finset_card],
apply finset.card_lt_card,
rw finset.ssubset_iff,
use w,
split,
{ rw set.mem_to_finset,
apply not_mem_common_neighbors_right },
{ rw finset.insert_subset,
split,
{ simpa, },
{ rw [neighbor_finset, ← set.subset_iff_to_finset_subset],
apply common_neighbors_subset_neighbor_set } },
end
end finite
section complement
/-!
## Complement of a simple graph
This section contains definitions and lemmas concerning the complement of a simple graph.
-/
/--
We define `compl G` to be the `simple_graph V` such that no two adjacent vertices in `G`
are adjacent in the complement, and every nonadjacent pair of vertices is adjacent
(still ensuring that vertices are not adjacent to themselves.)
-/
def compl (G : simple_graph V) : simple_graph V :=
{ adj := λ v w, v ≠ w ∧ ¬G.adj v w,
sym := λ v w ⟨hne, _⟩, ⟨hne.symm, by rwa edge_symm⟩,
loopless := λ v ⟨hne, _⟩, false.elim (hne rfl) }
instance has_compl : has_compl (simple_graph V) :=
{ compl := compl }
@[simp]
lemma compl_adj (G : simple_graph V) (v w : V) : Gᶜ.adj v w ↔ v ≠ w ∧ ¬G.adj v w := iff.rfl
instance compl_adj_decidable (V : Type u) [decidable_eq V] (G : simple_graph V)
[decidable_rel G.adj] : decidable_rel Gᶜ.adj := λ v w, and.decidable
@[simp]
lemma compl_compl (G : simple_graph V) : Gᶜᶜ = G :=
begin
ext v w,
split; simp only [compl_adj, not_and, not_not],
{ exact λ ⟨hne, h⟩, h hne },
{ intro h,
simpa [G.ne_of_adj h], },
end
@[simp]
lemma compl_involutive : function.involutive (@compl V) := compl_compl
lemma compl_neighbor_set_disjoint (G : simple_graph V) (v : V) :
disjoint (G.neighbor_set v) (Gᶜ.neighbor_set v) :=
begin
rw set.disjoint_iff,
rintro w ⟨h, h'⟩,
rw [mem_neighbor_set, compl_adj] at h',
exact h'.2 h,
end
lemma neighbor_set_union_compl_neighbor_set_eq (G : simple_graph V) (v : V) :
G.neighbor_set v ∪ Gᶜ.neighbor_set v = {v}ᶜ :=
begin
ext w,
have h := @ne_of_adj _ G,
simp_rw [set.mem_union, mem_neighbor_set, compl_adj, set.mem_compl_eq, set.mem_singleton_iff],
tauto,
end
end complement
end simple_graph
|
b100b1c08ea153c9d73c6165e6eda12b78f13450 | fa01e273a2a9f22530e6adb1ed7d4f54bb15c8d7 | /src/N2O/Network/Default.lean | fb3cea2257795fb9cbb7097522e1c97ed1db0217 | [
"LicenseRef-scancode-mit-taylor-variant",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | o89/n2o | 4c99afb11fff0a1e3dae6b3bc8a3b7fc42c314ac | 58c1fbf4ef892ed86bdc6b78ec9ca5a403715c2d | refs/heads/master | 1,670,314,676,229 | 1,669,086,375,000 | 1,669,086,375,000 | 200,506,953 | 16 | 6 | null | null | null | null | UTF-8 | Lean | false | false | 59 | lean | import N2O.Network.Internal
import N2O.Network.Web.Default
|
c062edc3ba76b53ab313bf2ee00c829d5d459a48 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /test/tidy.lean | 977b37eaa18a5a384213296ebc61efdcc7be7cc2 | [
"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 | 1,147 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import tactic.tidy
open tactic
namespace tidy.test
meta def interactive_simp := `[simp]
def tidy_test_0 : ∀ x : unit, x = unit.star :=
begin
success_if_fail { chain [ interactive_simp ] },
intro1,
induction x,
refl
end
def tidy_test_1 (a : string) : ∀ x : unit, x = unit.star :=
begin
tidy -- intros x, exact dec_trivial
end
structure A :=
(z : ℕ)
structure B :=
(a : A)
(aa : a.z = 0)
structure C :=
(a : A)
(b : B)
(ab : a.z = b.a.z)
structure D :=
(a : B)
(b : C)
(ab : a.a.z = b.a.z)
open tactic
def d : D :=
begin
tidy,
-- /- obviously says -/ fsplit, work_on_goal 0 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { refl } }, work_on_goal 0 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { refl } }, work_on_goal 1 { refl } }, refl
end.
def f : unit → unit → unit := by tidy -- intros a a_1, cases a_1, cases a, fsplit
def g (P Q : Prop) (p : P) (h : P ↔ Q) : Q := by tidy
end tidy.test
|
5109966c6a4b56fa1d5319fe3352d81767b7be3a | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/combinatorics/set_family/shadow.lean | 7471273e79fb1ba9b84f3539ad9e2c7530072673 | [
"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 | 11,039 | lean | /-
Copyright (c) 2021 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Alena Gusakov, Yaël Dillies
-/
import data.finset.slice
import logic.function.iterate
/-!
# Shadows
This file defines shadows of a set family. The shadow of a set family is the set family of sets we
get by removing any element from any set of the original family. If one pictures `finset α` as a big
hypercube (each dimension being membership of a given element), then taking the shadow corresponds
to projecting each finset down once in all available directions.
## Main definitions
* `finset.shadow`: The shadow of a set family. Everything we can get by removing a new element from
some set.
* `finset.up_shadow`: The upper shadow of a set family. Everything we can get by adding an element
to some set.
## Notation
We define notation in locale `finset_family`:
* `∂ 𝒜`: Shadow of `𝒜`.
* `∂⁺ 𝒜`: Upper shadow of `𝒜`.
We also maintain the convention that `a, b : α` are elements of the ground type, `s, t : finset α`
are finsets, and `𝒜, ℬ : finset (finset α)` are finset families.
## References
* https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf
* http://discretemath.imp.fu-berlin.de/DMII-2015-16/kruskal.pdf
## Tags
shadow, set family
-/
open finset nat
variables {α : Type*}
namespace finset
section shadow
variables [decidable_eq α] {𝒜 : finset (finset α)} {s t : finset α} {a : α} {k r : ℕ}
/-- The shadow of a set family `𝒜` is all sets we can get by removing one element from any set in
`𝒜`, and the (`k` times) iterated shadow (`shadow^[k]`) is all sets we can get by removing `k`
elements from any set in `𝒜`. -/
def shadow (𝒜 : finset (finset α)) : finset (finset α) := 𝒜.sup (λ s, s.image (erase s))
localized "notation (name := finset.shadow) `∂ `:90 := finset.shadow" in finset_family
/-- The shadow of the empty set is empty. -/
@[simp] lemma shadow_empty : ∂ (∅ : finset (finset α)) = ∅ := rfl
@[simp] lemma shadow_singleton_empty : ∂ ({∅} : finset (finset α)) = ∅ := rfl
--TODO: Prove `∂ {{a}} = {∅}` quickly using `covers` and `grade_order`
/-- The shadow is monotone. -/
@[mono] lemma shadow_monotone : monotone (shadow : finset (finset α) → finset (finset α)) :=
λ 𝒜 ℬ, sup_mono
/-- `s` is in the shadow of `𝒜` iff there is an `t ∈ 𝒜` from which we can remove one element to
get `s`. -/
lemma mem_shadow_iff : s ∈ ∂ 𝒜 ↔ ∃ t ∈ 𝒜, ∃ a ∈ t, erase t a = s :=
by simp only [shadow, mem_sup, mem_image]
lemma erase_mem_shadow (hs : s ∈ 𝒜) (ha : a ∈ s) : erase s a ∈ ∂ 𝒜 :=
mem_shadow_iff.2 ⟨s, hs, a, ha, rfl⟩
/-- `t` is in the shadow of `𝒜` iff we can add an element to it so that the resulting finset is in
`𝒜`. -/
lemma mem_shadow_iff_insert_mem : s ∈ ∂ 𝒜 ↔ ∃ a ∉ s, insert a s ∈ 𝒜 :=
begin
refine mem_shadow_iff.trans ⟨_, _⟩,
{ rintro ⟨s, hs, a, ha, rfl⟩,
refine ⟨a, not_mem_erase a s, _⟩,
rwa insert_erase ha },
{ rintro ⟨a, ha, hs⟩,
exact ⟨insert a s, hs, a, mem_insert_self _ _, erase_insert ha⟩ }
end
/-- The shadow of a family of `r`-sets is a family of `r - 1`-sets. -/
protected lemma _root_.set.sized.shadow (h𝒜 : (𝒜 : set (finset α)).sized r) :
(∂ 𝒜 : set (finset α)).sized (r - 1) :=
begin
intros A h,
obtain ⟨A, hA, i, hi, rfl⟩ := mem_shadow_iff.1 h,
rw [card_erase_of_mem hi, h𝒜 hA],
end
lemma sized_shadow_iff (h : ∅ ∉ 𝒜) :
(∂ 𝒜 : set (finset α)).sized r ↔ (𝒜 : set (finset α)).sized (r + 1) :=
begin
refine ⟨λ h𝒜 s hs, _, set.sized.shadow⟩,
obtain ⟨a, ha⟩ := nonempty_iff_ne_empty.2 (ne_of_mem_of_not_mem hs h),
rw [←h𝒜 (erase_mem_shadow hs ha), card_erase_add_one ha],
end
/-- `s ∈ ∂ 𝒜` iff `s` is exactly one element less than something from `𝒜` -/
lemma mem_shadow_iff_exists_mem_card_add_one :
s ∈ ∂ 𝒜 ↔ ∃ t ∈ 𝒜, s ⊆ t ∧ t.card = s.card + 1 :=
begin
refine mem_shadow_iff_insert_mem.trans ⟨_, _⟩,
{ rintro ⟨a, ha, hs⟩,
exact ⟨insert a s, hs, subset_insert _ _, card_insert_of_not_mem ha⟩ },
{ rintro ⟨t, ht, hst, h⟩,
obtain ⟨a, ha⟩ : ∃ a, t \ s = {a} :=
card_eq_one.1 (by rw [card_sdiff hst, h, add_tsub_cancel_left]),
exact ⟨a, λ hat,
not_mem_sdiff_of_mem_right hat ((ha.ge : _ ⊆ _) $ mem_singleton_self a),
by rwa [insert_eq a s, ←ha, sdiff_union_of_subset hst]⟩ }
end
/-- Being in the shadow of `𝒜` means we have a superset in `𝒜`. -/
lemma exists_subset_of_mem_shadow (hs : s ∈ ∂ 𝒜) : ∃ t ∈ 𝒜, s ⊆ t :=
let ⟨t, ht, hst⟩ := mem_shadow_iff_exists_mem_card_add_one.1 hs in ⟨t, ht, hst.1⟩
/-- `t ∈ ∂^k 𝒜` iff `t` is exactly `k` elements less than something in `𝒜`. -/
lemma mem_shadow_iff_exists_mem_card_add :
s ∈ (∂^[k]) 𝒜 ↔ ∃ t ∈ 𝒜, s ⊆ t ∧ t.card = s.card + k :=
begin
induction k with k ih generalizing 𝒜 s,
{ refine ⟨λ hs, ⟨s, hs, subset.refl _, rfl⟩, _⟩,
rintro ⟨t, ht, hst, hcard⟩,
rwa eq_of_subset_of_card_le hst hcard.le },
simp only [exists_prop, function.comp_app, function.iterate_succ],
refine ih.trans _,
clear ih,
split,
{ rintro ⟨t, ht, hst, hcardst⟩,
obtain ⟨u, hu, htu, hcardtu⟩ := mem_shadow_iff_exists_mem_card_add_one.1 ht,
refine ⟨u, hu, hst.trans htu, _⟩,
rw [hcardtu, hcardst],
refl },
{ rintro ⟨t, ht, hst, hcard⟩,
obtain ⟨u, hsu, hut, hu⟩ := finset.exists_intermediate_set k
(by { rw [add_comm, hcard], exact le_succ _ }) hst,
rw add_comm at hu,
refine ⟨u, mem_shadow_iff_exists_mem_card_add_one.2 ⟨t, ht, hut, _⟩, hsu, hu⟩,
rw [hcard, hu],
refl }
end
end shadow
open_locale finset_family
section up_shadow
variables [decidable_eq α] [fintype α] {𝒜 : finset (finset α)} {s t : finset α} {a : α} {k r : ℕ}
/-- The upper shadow of a set family `𝒜` is all sets we can get by adding one element to any set in
`𝒜`, and the (`k` times) iterated upper shadow (`up_shadow^[k]`) is all sets we can get by adding
`k` elements from any set in `𝒜`. -/
def up_shadow (𝒜 : finset (finset α)) : finset (finset α) :=
𝒜.sup $ λ s, sᶜ.image $ λ a, insert a s
localized "notation (name := finset.up_shadow) `∂⁺ `:90 := finset.up_shadow" in finset_family
/-- The upper shadow of the empty set is empty. -/
@[simp] lemma up_shadow_empty : ∂⁺ (∅ : finset (finset α)) = ∅ := rfl
/-- The upper shadow is monotone. -/
@[mono] lemma up_shadow_monotone : monotone (up_shadow : finset (finset α) → finset (finset α)) :=
λ 𝒜 ℬ, sup_mono
/-- `s` is in the upper shadow of `𝒜` iff there is an `t ∈ 𝒜` from which we can remove one element
to get `s`. -/
lemma mem_up_shadow_iff : s ∈ ∂⁺ 𝒜 ↔ ∃ t ∈ 𝒜, ∃ a ∉ t, insert a t = s :=
by simp_rw [up_shadow, mem_sup, mem_image, exists_prop, mem_compl]
lemma insert_mem_up_shadow (hs : s ∈ 𝒜) (ha : a ∉ s) : insert a s ∈ ∂⁺ 𝒜 :=
mem_up_shadow_iff.2 ⟨s, hs, a, ha, rfl⟩
/-- The upper shadow of a family of `r`-sets is a family of `r + 1`-sets. -/
protected lemma _root_.set.sized.up_shadow (h𝒜 : (𝒜 : set (finset α)).sized r) :
(∂⁺ 𝒜 : set (finset α)).sized (r + 1) :=
begin
intros A h,
obtain ⟨A, hA, i, hi, rfl⟩ := mem_up_shadow_iff.1 h,
rw [card_insert_of_not_mem hi, h𝒜 hA],
end
/-- `t` is in the upper shadow of `𝒜` iff we can remove an element from it so that the resulting
finset is in `𝒜`. -/
lemma mem_up_shadow_iff_erase_mem : s ∈ ∂⁺ 𝒜 ↔ ∃ a ∈ s, s.erase a ∈ 𝒜 :=
begin
refine mem_up_shadow_iff.trans ⟨_, _⟩,
{ rintro ⟨s, hs, a, ha, rfl⟩,
refine ⟨a, mem_insert_self a s, _⟩,
rwa erase_insert ha },
{ rintro ⟨a, ha, hs⟩,
exact ⟨s.erase a, hs, a, not_mem_erase _ _, insert_erase ha⟩ }
end
/-- `s ∈ ∂⁺ 𝒜` iff `s` is exactly one element less than something from `𝒜`. -/
lemma mem_up_shadow_iff_exists_mem_card_add_one :
s ∈ ∂⁺ 𝒜 ↔ ∃ t ∈ 𝒜, t ⊆ s ∧ t.card + 1 = s.card :=
begin
refine mem_up_shadow_iff_erase_mem.trans ⟨_, _⟩,
{ rintro ⟨a, ha, hs⟩,
exact ⟨s.erase a, hs, erase_subset _ _, card_erase_add_one ha⟩ },
{ rintro ⟨t, ht, hts, h⟩,
obtain ⟨a, ha⟩ : ∃ a, s \ t = {a} :=
card_eq_one.1 (by rw [card_sdiff hts, ←h, add_tsub_cancel_left]),
refine ⟨a, sdiff_subset _ _ ((ha.ge : _ ⊆ _) $ mem_singleton_self a), _⟩,
rwa [←sdiff_singleton_eq_erase, ←ha, sdiff_sdiff_eq_self hts] }
end
/-- Being in the upper shadow of `𝒜` means we have a superset in `𝒜`. -/
lemma exists_subset_of_mem_up_shadow (hs : s ∈ ∂⁺ 𝒜) : ∃ t ∈ 𝒜, t ⊆ s :=
let ⟨t, ht, hts, _⟩ := mem_up_shadow_iff_exists_mem_card_add_one.1 hs in ⟨t, ht, hts⟩
/-- `t ∈ ∂^k 𝒜` iff `t` is exactly `k` elements more than something in `𝒜`. -/
lemma mem_up_shadow_iff_exists_mem_card_add :
s ∈ (∂⁺^[k]) 𝒜 ↔ ∃ t ∈ 𝒜, t ⊆ s ∧ t.card + k = s.card :=
begin
induction k with k ih generalizing 𝒜 s,
{ refine ⟨λ hs, ⟨s, hs, subset.refl _, rfl⟩, _⟩,
rintro ⟨t, ht, hst, hcard⟩,
rwa ←eq_of_subset_of_card_le hst hcard.ge },
simp only [exists_prop, function.comp_app, function.iterate_succ],
refine ih.trans _,
clear ih,
split,
{ rintro ⟨t, ht, hts, hcardst⟩,
obtain ⟨u, hu, hut, hcardtu⟩ := mem_up_shadow_iff_exists_mem_card_add_one.1 ht,
refine ⟨u, hu, hut.trans hts, _⟩,
rw [←hcardst, ←hcardtu, add_right_comm],
refl },
{ rintro ⟨t, ht, hts, hcard⟩,
obtain ⟨u, htu, hus, hu⟩ := finset.exists_intermediate_set 1
(by { rw [add_comm, ←hcard], exact add_le_add_left (zero_lt_succ _) _ }) hts,
rw add_comm at hu,
refine ⟨u, mem_up_shadow_iff_exists_mem_card_add_one.2 ⟨t, ht, htu, hu.symm⟩, hus, _⟩,
rw [hu, ←hcard, add_right_comm],
refl }
end
@[simp] lemma shadow_image_compl : (∂ 𝒜).image compl = ∂⁺ (𝒜.image compl) :=
begin
ext s,
simp only [mem_image, exists_prop, mem_shadow_iff, mem_up_shadow_iff],
split,
{ rintro ⟨_, ⟨s, hs, a, ha, rfl⟩, rfl⟩,
exact ⟨sᶜ, ⟨s, hs, rfl⟩, a, not_mem_compl.2 ha, compl_erase.symm⟩ },
{ rintro ⟨_, ⟨s, hs, rfl⟩, a, ha, rfl⟩,
exact ⟨s.erase a, ⟨s, hs, a, not_mem_compl.1 ha, rfl⟩, compl_erase⟩ }
end
@[simp] lemma up_shadow_image_compl : (∂⁺ 𝒜).image compl = ∂ (𝒜.image compl) :=
begin
ext s,
simp only [mem_image, exists_prop, mem_shadow_iff, mem_up_shadow_iff],
split,
{ rintro ⟨_, ⟨s, hs, a, ha, rfl⟩, rfl⟩,
exact ⟨sᶜ, ⟨s, hs, rfl⟩, a, mem_compl.2 ha, compl_insert.symm⟩ },
{ rintro ⟨_, ⟨s, hs, rfl⟩, a, ha, rfl⟩,
exact ⟨insert a s, ⟨s, hs, a, mem_compl.1 ha, rfl⟩, compl_insert⟩ }
end
end up_shadow
end finset
|
c749c11f4840c5fe81ea6ee3a7ad6b53f38077e6 | fe84e287c662151bb313504482b218a503b972f3 | /src/commutative_algebra/ring_of_subsets.lean | 24906b246029707cea4ea309ff16f5af558266f8 | [] | no_license | NeilStrickland/lean_lib | 91e163f514b829c42fe75636407138b5c75cba83 | 6a9563de93748ace509d9db4302db6cd77d8f92c | refs/heads/master | 1,653,408,198,261 | 1,652,996,419,000 | 1,652,996,419,000 | 181,006,067 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 5,219 | lean | import algebra.ring
import commutative_algebra.bool_field
import tactic.pi_instances tactic.squeeze
universes u v
variables (U : Type u) (V : Type v)
def ring_of_bool_subsets := (U → bool)
instance : comm_ring (ring_of_bool_subsets U) :=
by { unfold ring_of_bool_subsets, pi_instance, }
lemma val_zero (x : U) : (0 : ring_of_bool_subsets U) x = ff := rfl
lemma val_one (x : U) : (1 : ring_of_bool_subsets U) x = tt := rfl
lemma val_neg (f : ring_of_bool_subsets U) (x : U) : (- f) x = f x := rfl
lemma val_add (f g : ring_of_bool_subsets U) (x : U) : (f + g) x = bxor (f x) (g x) := rfl
lemma val_mul (f g : ring_of_bool_subsets U) (x : U) : (f * g) x = band (f x) (g x) := rfl
open classical
def ring_of_subsets := set V
namespace ring_of_subsets
local attribute [instance] classical.dec
instance : has_zero (ring_of_subsets V) := ⟨(∅ : set V)⟩
instance : has_one (ring_of_subsets V) := ⟨(set.univ : set V)⟩
instance : has_neg (ring_of_subsets V) := ⟨(λ s, s)⟩
instance : has_add (ring_of_subsets V) :=
⟨(λ s t : set V, (s \ t ∪ t \ s : set V))⟩
instance : has_mul (ring_of_subsets V) :=
⟨(λ s t : set V, (s ∩ t : set V))⟩
instance : has_mem V (ring_of_subsets V) :=
⟨λ (x : V) (s : set V), x ∈ s⟩
variable (x : V)
lemma mem_zero_iff : x ∈ (0 : ring_of_subsets V) ↔ false :=
(iff_false _).mpr (set.not_mem_empty x)
lemma mem_one_iff : x ∈ (1 : ring_of_subsets V) ↔ true :=
(iff_true _).mpr (set.mem_univ x)
lemma mem_neg_iff (s : ring_of_subsets V) : x ∈ (- s) ↔ x ∈ s :=
by { change x ∈ s ↔ x ∈ s, refl }
lemma mem_add_iff (s t : ring_of_subsets V) :
x ∈ s + t ↔ ((x ∈ s ∧ x ∉ t) ∨ (x∈ t ∧ x ∉ s)) :=
by { unfold has_add.add, rw[set.mem_union,set.mem_diff,set.mem_diff],}
lemma mem_mul_iff (s t : ring_of_subsets V) :
x ∈ s * t ↔ (x ∈ s ∧ x ∈ t) :=
by { unfold has_mul.mul, rw[set.mem_inter_iff], }
instance : comm_ring (ring_of_subsets V) := {
zero := (0 : ring_of_subsets V), one := 1,
neg := has_neg.neg, add := (+), mul := (*),
add_zero := λ a, by { ext x, rw[mem_add_iff, mem_zero_iff], simp },
zero_add := λ a, by { ext x, rw[mem_add_iff, mem_zero_iff], simp },
add_left_neg := λ a, begin
ext x, rw[mem_add_iff, mem_neg_iff, mem_zero_iff],
by_cases ha : x ∈ a;
simp[ha]
end,
add_comm := λ a b, begin
ext x, rw[mem_add_iff, mem_add_iff],
by_cases ha : x ∈ a; by_cases hb : x ∈ b;
simp[ha,hb]
end,
add_assoc := λ a b c, begin
ext x, repeat { rw[mem_add_iff] },
by_cases ha : x ∈ a; by_cases hb : x ∈ b; by_cases hc : x ∈ c;
simp[ha,hb,hc],
end,
mul_one := λ a, by { ext x, rw[mem_mul_iff, mem_one_iff], simp },
one_mul := λ a, by { ext x, rw[mem_mul_iff, mem_one_iff], simp },
mul_comm := λ a b, begin
ext x, rw[mem_mul_iff, mem_mul_iff, and_comm],
end,
mul_assoc := λ a b c, begin
ext x, repeat { rw[mem_mul_iff] }, rw[and_assoc],
end,
left_distrib := λ a b c, begin
ext x, rw[mem_add_iff, mem_mul_iff, mem_add_iff, mem_mul_iff, mem_mul_iff],
by_cases ha : x ∈ a; by_cases hb : x ∈ b;
simp[ha,hb]
end,
right_distrib := λ a b c, begin
ext x, rw[mem_add_iff, mem_mul_iff, mem_add_iff, mem_mul_iff, mem_mul_iff],
by_cases ha : x ∈ a; by_cases hb : x ∈ b;
simp[ha,hb]
end
}
variable {V}
noncomputable def indicator : ring_of_subsets V →+* ring_of_bool_subsets V := {
to_fun := λ s x, (if x ∈ s then tt else ff),
map_zero' := by { ext x, rw[mem_zero_iff V x,if_false], refl },
map_add' := λ s t, by {
ext x,
rw[mem_add_iff, val_add],
by_cases hs : x ∈ s; by_cases ht : x ∈ t; simp[hs,ht],
},
map_one' := by { ext x, rw[mem_one_iff V x,if_true], refl },
map_mul' := λ s t, by {
ext x,
rw[mem_mul_iff, val_mul],
by_cases hs : x ∈ s; by_cases ht : x ∈ t;
simp[hs, ht],
}
}
end ring_of_subsets
namespace ring_of_bool_subsets
variable {U}
def support : (ring_of_bool_subsets U) →+* (ring_of_subsets U) := {
to_fun := λ (f : U → bool), (λ x, f x = tt),
map_zero' := begin
ext x, rw[set.mem_def, val_zero, ring_of_subsets.mem_zero_iff], simp only [],
end,
map_add' := λ s t, begin
ext x, rw[ring_of_subsets.mem_add_iff],
repeat { rw[set.mem_def] },
rw[val_add],
cases (s x); cases (t x); rw[bxor]; exact dec_trivial,
end,
map_one' := begin
ext x, rw[set.mem_def, val_one, ring_of_subsets.mem_one_iff, eq_self_iff_true]
end,
map_mul' := λ s t, begin
ext x, rw[ring_of_subsets.mem_mul_iff],
repeat { rw[set.mem_def] },
rw[val_mul],
cases (s x); cases (t x); rw[band]; exact dec_trivial,
end,
}
end ring_of_bool_subsets
namespace ring_of_subsets
noncomputable def bool_equiv : (ring_of_subsets U) ≃ (ring_of_bool_subsets U) := {
to_fun := @indicator U,
inv_fun := @ring_of_bool_subsets.support U,
left_inv := λ s, begin
haveI := classical.dec,
rw[ring_of_bool_subsets.support,indicator],
ext x,dsimp[has_mem.mem,set.mem],
split_ifs;simp only [h,iff_self,eq_self_iff_true],
end,
right_inv := λ f, begin
ext x,
dsimp[indicator,ring_of_bool_subsets.support,has_mem.mem,set.mem],
cases f x; simp,
end
}
end ring_of_subsets
|
e52f5f4e9d5adf5f0bf9753ed73df9671626f4bc | 41ebf3cb010344adfa84907b3304db00e02db0a6 | /uexp/tactic_paper_supplemental_material/nano_crush/cpdt_nano.lean | 5cede5690f298c7c2000ba609341c495276dae04 | [
"BSD-2-Clause"
] | permissive | ReinierKoops/Cosette | e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb | eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29 | refs/heads/master | 1,686,483,953,198 | 1,624,293,498,000 | 1,624,293,498,000 | 378,997,885 | 0 | 0 | BSD-2-Clause | 1,624,293,485,000 | 1,624,293,484,000 | null | UTF-8 | Lean | false | false | 1,027 | lean | import .nano_crush
/- "Proving in the Large" chapter of CPDT -/
inductive exp : Type
| Const (n : nat) : exp
| Plus (e1 e2 : exp) : exp
| Mult (e1 e2 : exp) : exp
open exp
def eeval : exp → nat
| (Const n) := n
| (Plus e1 e2) := eeval e1 + eeval e2
| (Mult e1 e2) := eeval e1 * eeval e2
def times (k : nat) : exp → exp
| (Const n) := Const (k * n)
| (Plus e1 e2) := Plus (times e1) (times e2)
| (Mult e1 e2) := Mult (times e1) e2
def reassoc : exp → exp
| (Const n) := (Const n)
| (Plus e1 e2) :=
let e1' := reassoc e1 in
let e2' := reassoc e2 in
match e2' with
| (Plus e21 e22) := Plus (Plus e1' e21) e22
| _ := Plus e1' e2'
end
| (Mult e1 e2) :=
let e1' := reassoc e1 in
let e2' := reassoc e2 in
match e2' with
| (Mult e21 e22) := Mult (Mult e1' e21) e22
| _ := Mult e1' e2'
end
attribute [simp] mul_add
lemma eeval_times (k e) : eeval (times k e) = k * eeval e :=
by nano_crush
lemma reassoc_correct (e) : eeval (reassoc e) = eeval e :=
by nano_crush
|
19d1056eb27611a86dee2252961ed9f95e3b4e61 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/hmulDefaultIntance.lean | 9bf6d911846de0605f9f5bfaaa6133687d6a9a48 | [
"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 | 129 | lean | instance : HMul Nat Bool Nat where
hMul
| x, true => x
| x, false => 0
#check (10:Nat) * true
#check fun x => x * 1
|
7d0ef95c105f67d9a8ddb53299d24429030124f5 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/one2.lean | 91d7638b582bf041eb40c5ee0b7bf5ad716c06c3 | [
"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 | 407 | lean | import data.num
inductive one1.{l} : Type.{l} :=
unit : one1
inductive pone : Type.{0} :=
unit : pone
inductive two.{l} : Type.{max 1 l} :=
| o : two
| u : two
inductive wrap.{l} : Type.{max 1 l} :=
mk : true → wrap
inductive wrap2.{l} (A : Type.{l}) : Type.{max 1 l} :=
mk : A → wrap2 A
set_option pp.universes true
check @one1.rec
check @pone.rec
check @two.rec
check @wrap.rec
check @wrap2.rec
|
eff23e3e5d3e2940a6c6aea30cac65b94f5c8306 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /stage0/src/Lean/Meta/Instances.lean | 8bb1512da2954991066dd0ae57c10b5154bed34c | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,984 | 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.ScopedEnvExtension
import Lean.Meta.DiscrTree
namespace Lean.Meta
structure InstanceEntry where
keys : Array DiscrTree.Key
val : Expr
priority : Nat
globalName? : Option Name := none
deriving Inhabited
instance : BEq InstanceEntry where
beq e₁ e₂ := e₁.val == e₂.val
instance : ToFormat InstanceEntry where
format e := match e.globalName? with
| some n => fmt n
| _ => "<local>"
structure Instances where
discrTree : DiscrTree InstanceEntry := DiscrTree.empty
globalInstances : NameSet := {}
deriving Inhabited
def addInstanceEntry (d : Instances) (e : InstanceEntry) : Instances := {
d with
discrTree := d.discrTree.insertCore e.keys e
globalInstances := match e.globalName? with
| some n => d.globalInstances.insert n
| none => d.globalInstances
}
builtin_initialize instanceExtension : SimpleScopedEnvExtension InstanceEntry Instances ←
registerSimpleScopedEnvExtension {
name := `instanceExt
initial := {}
addEntry := addInstanceEntry
}
private def mkInstanceKey (e : Expr) : MetaM (Array DiscrTree.Key) := do
let type ← inferType e
withNewMCtxDepth do
let (_, _, type) ← forallMetaTelescopeReducing type
DiscrTree.mkPath type
def addInstance (declName : Name) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do
let cinfo ← getConstInfo declName
let c := mkConst declName (cinfo.levelParams.map mkLevelParam)
let keys ← mkInstanceKey c
instanceExtension.add { keys := keys, val := c, priority := prio, globalName? := declName } attrKind
builtin_initialize
registerBuiltinAttribute {
name := `instance
descr := "type class instance"
add := fun declName stx attrKind => do
let prio ← getAttrParamOptPrio stx[1]
discard <| addInstance declName attrKind prio |>.run {} {}
}
@[export lean_is_instance]
def isGlobalInstance (env : Environment) (declName : Name) : Bool :=
Meta.instanceExtension.getState env |>.globalInstances.contains declName
def getGlobalInstancesIndex : MetaM (DiscrTree InstanceEntry) :=
return Meta.instanceExtension.getState (← getEnv) |>.discrTree
/- Default instance support -/
structure DefaultInstanceEntry where
className : Name
instanceName : Name
priority : Nat
abbrev PrioritySet := Std.RBTree Nat (.>.)
structure DefaultInstances where
defaultInstances : NameMap (List (Name × Nat)) := {}
priorities : PrioritySet := {}
deriving Inhabited
def addDefaultInstanceEntry (d : DefaultInstances) (e : DefaultInstanceEntry) : DefaultInstances :=
let d := { d with priorities := d.priorities.insert e.priority }
match d.defaultInstances.find? e.className with
| some insts => { d with defaultInstances := d.defaultInstances.insert e.className <| (e.instanceName, e.priority) :: insts }
| none => { d with defaultInstances := d.defaultInstances.insert e.className [(e.instanceName, e.priority)] }
builtin_initialize defaultInstanceExtension : SimplePersistentEnvExtension DefaultInstanceEntry DefaultInstances ←
registerSimplePersistentEnvExtension {
name := `defaultInstanceExt
addEntryFn := addDefaultInstanceEntry
addImportedFn := fun es => (mkStateFromImportedEntries addDefaultInstanceEntry {} es)
}
def addDefaultInstance (declName : Name) (prio : Nat := 0) : MetaM Unit := do
match (← getEnv).find? declName with
| none => throwError! "unknown constant '{declName}'"
| some info =>
forallTelescopeReducing info.type fun _ type => do
match type.getAppFn with
| Expr.const className _ _ =>
unless isClass (← getEnv) className do
throwError! "invalid default instance '{declName}', it has type '({className} ...)', but {className}' is not a type class"
setEnv <| defaultInstanceExtension.addEntry (← getEnv) { className := className, instanceName := declName, priority := prio }
| _ => throwError! "invalid default instance '{declName}', type must be of the form '(C ...)' where 'C' is a type class"
builtin_initialize
registerBuiltinAttribute {
name := `defaultInstance
descr := "type class default instance"
add := fun declName stx kind => do
let prio ← getAttrParamOptPrio stx[1]
unless kind == AttributeKind.global do throwError "invalid attribute 'defaultInstance', must be global"
discard <| addDefaultInstance declName prio |>.run {} {}
}
def getDefaultInstancesPriorities [Monad m] [MonadEnv m] : m PrioritySet :=
return defaultInstanceExtension.getState (← getEnv) |>.priorities
def getDefaultInstances [Monad m] [MonadEnv m] (className : Name) : m (List (Name × Nat)) :=
return defaultInstanceExtension.getState (← getEnv) |>.defaultInstances.find? className |>.getD []
end Lean.Meta
|
8e59419b87615c755d18f912162d5314e676656f | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/limits/shapes/types.lean | 221d50479f94ded5e8852c03dd0c3973f1440e29 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,549 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.limits.types
import Mathlib.category_theory.limits.shapes.products
import Mathlib.category_theory.limits.shapes.binary_products
import Mathlib.category_theory.limits.shapes.terminal
import Mathlib.PostPort
universes u
namespace Mathlib
/-!
# Special shapes for limits in `Type`.
The general shape (co)limits defined in `category_theory.limits.types`
are intended for use through the limits API,
and the actual implementation should mostly be considered "sealed".
In this file, we provide definitions of the "standard" special shapes of limits in `Type`,
giving the expected definitional implementation:
* the terminal object is `punit`
* the binary product of `X` and `Y` is `X × Y`
* the product of a family `f : J → Type` is `Π j, f j`.
Because these are not intended for use with the `has_limit` API,
we instead construct terms of `limit_data`.
As an example, when setting up the monoidal category structure on `Type`
we use the `types_has_terminal` and `types_has_binary_products` instances.
-/
namespace category_theory.limits.types
/-- A restatement of `types.lift_π_apply` that uses `pi.π` and `pi.lift`. -/
@[simp] theorem pi_lift_π_apply {β : Type u} (f : β → Type u) {P : Type u} (s : (b : β) → P ⟶ f b) (b : β) (x : P) : pi.π f b (pi.lift s x) = s b x :=
congr_fun (limit.lift_π (fan.mk P s) b) x
/-- A restatement of `types.map_π_apply` that uses `pi.π` and `pi.map`. -/
@[simp] theorem pi_map_π_apply {β : Type u} {f : β → Type u} {g : β → Type u} (α : (j : β) → f j ⟶ g j) (b : β) (x : ∏ fun (j : β) => f j) : pi.π g b (pi.map α x) = α b (pi.π f b x) :=
limit.map_π_apply (discrete.nat_trans α) b x
/-- The category of types has `punit` as a terminal object. -/
def terminal_limit_cone : limit_cone (functor.empty (Type u)) :=
limit_cone.mk (cone.mk PUnit (nat_trans.mk sorry)) (id (is_limit.mk sorry))
/-- The category of types has `pempty` as an initial object. -/
def initial_limit_cone : colimit_cocone (functor.empty (Type u)) :=
colimit_cocone.mk (cocone.mk pempty (nat_trans.mk sorry)) (id (is_colimit.mk sorry))
/-- The product type `X × Y` forms a cone for the binary product of `X` and `Y`. -/
-- We manually generate the other projection lemmas since the simp-normal form for the legs is
-- otherwise not created correctly.
@[simp] theorem binary_product_cone_X (X : Type u) (Y : Type u) : cone.X (binary_product_cone X Y) = (X × Y) :=
Eq.refl (X × Y)
@[simp] theorem binary_product_cone_fst (X : Type u) (Y : Type u) : binary_fan.fst (binary_product_cone X Y) = prod.fst :=
rfl
@[simp] theorem binary_product_cone_snd (X : Type u) (Y : Type u) : binary_fan.snd (binary_product_cone X Y) = prod.snd :=
rfl
/-- The product type `X × Y` is a binary product for `X` and `Y`. -/
@[simp] theorem binary_product_limit_lift (X : Type u) (Y : Type u) (s : binary_fan X Y) (x : cone.X s) : is_limit.lift (binary_product_limit X Y) s x = (binary_fan.fst s x, binary_fan.snd s x) :=
Eq.refl (is_limit.lift (binary_product_limit X Y) s x)
/--
The category of types has `X × Y`, the usual cartesian product,
as the binary product of `X` and `Y`.
-/
@[simp] theorem binary_product_limit_cone_is_limit (X : Type u) (Y : Type u) : limit_cone.is_limit (binary_product_limit_cone X Y) = binary_product_limit X Y :=
Eq.refl (limit_cone.is_limit (binary_product_limit_cone X Y))
/-- The functor which sends `X, Y` to the product type `X × Y`. -/
-- We add the option `type_md` to tell `@[simps]` to not treat homomorphisms `X ⟶ Y` in `Type*` as
-- a function type
@[simp] theorem binary_product_functor_obj_map (X : Type u) (Y₁ : Type u) (Y₂ : Type u) (f : Y₁ ⟶ Y₂) : functor.map (functor.obj binary_product_functor X) f =
is_limit.lift (binary_product_limit X Y₂) (binary_fan.mk prod.fst (prod.snd ≫ f)) :=
Eq.refl (functor.map (functor.obj binary_product_functor X) f)
/--
The product functor given by the instance `has_binary_products (Type u)` is isomorphic to the
explicit binary product functor given by the product type.
-/
def binary_product_iso_prod : binary_product_functor ≅ prod.functor :=
nat_iso.of_components
(fun (X : Type u) =>
nat_iso.of_components
(fun (Y : Type u) =>
iso.symm (is_limit.cone_point_unique_up_to_iso (limit.is_limit (pair X Y)) (binary_product_limit X Y)))
sorry)
sorry
/-- The sum type `X ⊕ Y` forms a cocone for the binary coproduct of `X` and `Y`. -/
@[simp] theorem binary_coproduct_cocone_ι_app (X : Type u) (Y : Type u) (j : discrete walking_pair) : ∀ (ᾰ : functor.obj (pair X Y) j),
nat_trans.app (cocone.ι (binary_coproduct_cocone X Y)) j ᾰ = walking_pair.rec sum.inl sum.inr j ᾰ :=
fun (ᾰ : functor.obj (pair X Y) j) => Eq.refl (walking_pair.rec sum.inl sum.inr j ᾰ)
/-- The sum type `X ⊕ Y` is a binary coproduct for `X` and `Y`. -/
def binary_coproduct_colimit (X : Type u) (Y : Type u) : is_colimit (binary_coproduct_cocone X Y) :=
is_colimit.mk fun (s : binary_cofan X Y) => sum.elim (binary_cofan.inl s) (binary_cofan.inr s)
/--
The category of types has `X ⊕ Y`,
as the binary coproduct of `X` and `Y`.
-/
def binary_coproduct_colimit_cocone (X : Type u) (Y : Type u) : colimit_cocone (pair X Y) :=
colimit_cocone.mk (binary_coproduct_cocone X Y) (binary_coproduct_colimit X Y)
/--
The category of types has `Π j, f j` as the product of a type family `f : J → Type`.
-/
def product_limit_cone {J : Type u} (F : J → Type u) : limit_cone (discrete.functor F) :=
limit_cone.mk
(cone.mk ((j : J) → F j)
(nat_trans.mk
fun (j : discrete J) (f : functor.obj (functor.obj (functor.const (discrete J)) ((j : J) → F j)) j) => f j))
(is_limit.mk fun (s : cone (discrete.functor F)) (x : cone.X s) (j : J) => nat_trans.app (cone.π s) j x)
/--
The category of types has `Σ j, f j` as the coproduct of a type family `f : J → Type`.
-/
def coproduct_colimit_cocone {J : Type u} (F : J → Type u) : colimit_cocone (discrete.functor F) :=
colimit_cocone.mk
(cocone.mk (sigma fun (j : J) => F j)
(nat_trans.mk fun (j : discrete J) (x : functor.obj (discrete.functor F) j) => sigma.mk j x))
(is_colimit.mk
fun (s : cocone (discrete.functor F))
(x :
cocone.X
(cocone.mk (sigma fun (j : J) => F j)
(nat_trans.mk fun (j : discrete J) (x : functor.obj (discrete.functor F) j) => sigma.mk j x))) =>
nat_trans.app (cocone.ι s) (sigma.fst x) (sigma.snd x))
/--
Show the given fork in `Type u` is an equalizer given that any element in the "difference kernel"
comes from `X`.
The converse of `unique_of_type_equalizer`.
-/
def type_equalizer_of_unique {X : Type u} {Y : Type u} {Z : Type u} (f : X ⟶ Y) {g : Y ⟶ Z} {h : Y ⟶ Z} (w : f ≫ g = f ≫ h) (t : ∀ (y : Y), g y = h y → exists_unique fun (x : X) => f x = y) : is_limit (fork.of_ι f w) :=
fork.is_limit.mk' (fork.of_ι f w)
fun (s : fork g h) =>
{ val :=
fun
(i : functor.obj (functor.obj (functor.const walking_parallel_pair) (cone.X s)) walking_parallel_pair.zero) =>
classical.some sorry,
property := sorry }
/-- The converse of `type_equalizer_of_unique`. -/
theorem unique_of_type_equalizer {X : Type u} {Y : Type u} {Z : Type u} (f : X ⟶ Y) {g : Y ⟶ Z} {h : Y ⟶ Z} (w : f ≫ g = f ≫ h) (t : is_limit (fork.of_ι f w)) (y : Y) (hy : g y = h y) : exists_unique fun (x : X) => f x = y := sorry
theorem type_equalizer_iff_unique {X : Type u} {Y : Type u} {Z : Type u} (f : X ⟶ Y) {g : Y ⟶ Z} {h : Y ⟶ Z} (w : f ≫ g = f ≫ h) : Nonempty (is_limit (fork.of_ι f w)) ↔ ∀ (y : Y), g y = h y → exists_unique fun (x : X) => f x = y := sorry
/-- Show that the subtype `{x : Y // g x = h x}` is an equalizer for the pair `(g,h)`. -/
def equalizer_limit {Y : Type u} {Z : Type u} {g : Y ⟶ Z} {h : Y ⟶ Z} : limit_cone (parallel_pair g h) :=
limit_cone.mk (fork.of_ι subtype.val sorry)
(fork.is_limit.mk' (fork.of_ι subtype.val sorry)
fun (s : fork g h) =>
{ val :=
fun
(i :
functor.obj (functor.obj (functor.const walking_parallel_pair) (cone.X s)) walking_parallel_pair.zero) =>
{ val := fork.ι s i, property := sorry },
property := sorry })
|
66487a95aafc4435e2921df9b13066e9e7bb077a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/array/lemmas.lean | c459b4f2800dcbf5baeedd411b430610a2feafb4 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 8,556 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
-/
import data.fin.basic
import data.list.basic
universes u v w
namespace d_array
variables {n : ℕ} {α : fin n → Type u}
instance [∀ i, inhabited (α i)] : inhabited (d_array n α) :=
⟨⟨default⟩⟩
end d_array
namespace array
instance {n α} [inhabited α] : inhabited (array n α) :=
d_array.inhabited
theorem to_list_of_heq {n₁ n₂ α} {a₁ : array n₁ α} {a₂ : array n₂ α}
(hn : n₁ = n₂) (ha : a₁ == a₂) : a₁.to_list = a₂.to_list :=
by congr; assumption
/- rev_list -/
section rev_list
variables {n : ℕ} {α : Type u} {a : array n α}
theorem rev_list_reverse_aux : ∀ i (h : i ≤ n) (t : list α),
(a.iterate_aux (λ _, (::)) i h []).reverse_core t = a.rev_iterate_aux (λ _, (::)) i h t
| 0 h t := rfl
| (i+1) h t := rev_list_reverse_aux i _ _
@[simp] theorem rev_list_reverse : a.rev_list.reverse = a.to_list :=
rev_list_reverse_aux _ _ _
@[simp] theorem to_list_reverse : a.to_list.reverse = a.rev_list :=
by rw [←rev_list_reverse, list.reverse_reverse]
end rev_list
/- mem -/
section mem
variables {n : ℕ} {α : Type u} {v : α} {a : array n α}
theorem mem.def : v ∈ a ↔ ∃ i, a.read i = v :=
iff.rfl
theorem mem_rev_list_aux : ∀ {i} (h : i ≤ n),
(∃ (j : fin n), (j : ℕ) < i ∧ read a j = v) ↔ v ∈ a.iterate_aux (λ _, (::)) i h []
| 0 _ := ⟨λ ⟨i, n, _⟩, absurd n i.val.not_lt_zero, false.elim⟩
| (i+1) h := let IH := mem_rev_list_aux (le_of_lt h) in
⟨λ ⟨j, ji1, e⟩, or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ ji1)
(λ ji, list.mem_cons_of_mem _ $ IH.1 ⟨j, ji, e⟩)
(λ je, by simp [d_array.iterate_aux]; apply or.inl; unfold read at e;
have H : j = ⟨i, h⟩ := fin.eq_of_veq je; rwa [←H, e]),
λ m, begin
simp [d_array.iterate_aux, list.mem] at m,
cases m with e m',
exact ⟨⟨i, h⟩, nat.lt_succ_self _, eq.symm e⟩,
exact let ⟨j, ji, e⟩ := IH.2 m' in
⟨j, nat.le_succ_of_le ji, e⟩
end⟩
@[simp] theorem mem_rev_list : v ∈ a.rev_list ↔ v ∈ a :=
iff.symm $ iff.trans
(exists_congr $ λ j, iff.symm $
show j.1 < n ∧ read a j = v ↔ read a j = v,
from and_iff_right j.2)
(mem_rev_list_aux _)
@[simp] theorem mem_to_list : v ∈ a.to_list ↔ v ∈ a :=
by rw ←rev_list_reverse; exact list.mem_reverse.trans mem_rev_list
end mem
/- foldr -/
section foldr
variables {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : α → β → β} {a : array n α}
theorem rev_list_foldr_aux : ∀ {i} (h : i ≤ n),
(d_array.iterate_aux a (λ _, (::)) i h []).foldr f b = d_array.iterate_aux a (λ _, f) i h b
| 0 h := rfl
| (j+1) h := congr_arg (f (read a ⟨j, h⟩)) (rev_list_foldr_aux _)
theorem rev_list_foldr : a.rev_list.foldr f b = a.foldl b f :=
rev_list_foldr_aux _
end foldr
/- foldl -/
section foldl
variables {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : β → α → β} {a : array n α}
theorem to_list_foldl : a.to_list.foldl f b = a.foldl b (function.swap f) :=
by rw [←rev_list_reverse, list.foldl_reverse, rev_list_foldr]
end foldl
/- length -/
section length
variables {n : ℕ} {α : Type u}
theorem rev_list_length_aux (a : array n α) (i h) :
(a.iterate_aux (λ _, (::)) i h []).length = i :=
by induction i; simp [*, d_array.iterate_aux]
@[simp] theorem rev_list_length (a : array n α) : a.rev_list.length = n :=
rev_list_length_aux a _ _
@[simp] theorem to_list_length (a : array n α) : a.to_list.length = n :=
by rw[←rev_list_reverse, list.length_reverse, rev_list_length]
end length
/- nth -/
section nth
variables {n : ℕ} {α : Type u} {a : array n α}
theorem to_list_nth_le_aux (i : ℕ) (ih : i < n) : ∀ j {jh t h'},
(∀ k tl, j + k = i → list.nth_le t k tl = a.read ⟨i, ih⟩) →
(a.rev_iterate_aux (λ _, (::)) j jh t).nth_le i h' = a.read ⟨i, ih⟩
| 0 _ _ _ al := al i _ $ zero_add _
| (j+1) jh t h' al := to_list_nth_le_aux j $ λ k tl hjk,
show list.nth_le (a.read ⟨j, jh⟩ :: t) k tl = a.read ⟨i, ih⟩, from
match k, hjk, tl with
| 0, e, tl := match i, e, ih with ._, rfl, _ := rfl end
| k'+1, _, tl := by simp[list.nth_le]; exact al _ _ (by simp [add_comm, add_assoc, *]; cc)
end
theorem to_list_nth_le (i : ℕ) (h h') : list.nth_le a.to_list i h' = a.read ⟨i, h⟩ :=
to_list_nth_le_aux _ _ _ (λ k tl, absurd tl k.not_lt_zero)
@[simp] theorem to_list_nth_le' (a : array n α) (i : fin n) (h') :
list.nth_le a.to_list i h' = a.read i :=
by cases i; apply to_list_nth_le
theorem to_list_nth {i v} : list.nth a.to_list i = some v ↔ ∃ h, a.read ⟨i, h⟩ = v :=
begin
rw list.nth_eq_some,
have ll := to_list_length a,
split; intro h; cases h with h e; subst v,
{ exact ⟨ll ▸ h, (to_list_nth_le _ _ _).symm⟩ },
{ exact ⟨ll.symm ▸ h, to_list_nth_le _ _ _⟩ }
end
theorem write_to_list {i v} : (a.write i v).to_list = a.to_list.update_nth i v :=
list.ext_le (by simp) $ λ j h₁ h₂, begin
have h₃ : j < n, {simpa using h₁},
rw [to_list_nth_le _ h₃],
refine let ⟨_, e⟩ := list.nth_eq_some.1 _ in e.symm,
by_cases ij : (i : ℕ) = j,
{ subst j, rw [show (⟨(i : ℕ), h₃⟩ : fin _) = i, from fin.eq_of_veq rfl,
array.read_write, list.nth_update_nth_of_lt],
simp [h₃] },
{ rw [list.nth_update_nth_ne _ _ ij, a.read_write_of_ne,
to_list_nth.2 ⟨h₃, rfl⟩],
exact fin.ne_of_vne ij }
end
end nth
/- enum -/
section enum
variables {n : ℕ} {α : Type u} {a : array n α}
theorem mem_to_list_enum {i v} : (i, v) ∈ a.to_list.enum ↔ ∃ h, a.read ⟨i, h⟩ = v :=
by simp [list.mem_iff_nth, to_list_nth, and.comm, and.assoc, and.left_comm]
end enum
/- to_array -/
section to_array
variables {n : ℕ} {α : Type u}
@[simp] theorem to_list_to_array (a : array n α) : a.to_list.to_array == a :=
heq_of_heq_of_eq
(@@eq.drec_on (λ m (e : a.to_list.length = m), (d_array.mk (λ v, a.to_list.nth_le v.1 v.2)) ==
(@d_array.mk m (λ _, α) $ λ v, a.to_list.nth_le v.1 $ e.symm ▸ v.2)) a.to_list_length heq.rfl) $
d_array.ext $ λ ⟨i, h⟩, to_list_nth_le i h _
@[simp] theorem to_array_to_list (l : list α) : l.to_array.to_list = l :=
list.ext_le (to_list_length _) $ λ n h1 h2, to_list_nth_le _ h2 _
end to_array
/- push_back -/
section push_back
variables {n : ℕ} {α : Type u} {v : α} {a : array n α}
lemma push_back_rev_list_aux : ∀ i h h',
d_array.iterate_aux (a.push_back v) (λ _, (::)) i h [] = d_array.iterate_aux a (λ _, (::)) i h' []
| 0 h h' := rfl
| (i+1) h h' := begin
simp [d_array.iterate_aux],
refine ⟨_, push_back_rev_list_aux _ _ _⟩,
dsimp [read, d_array.read, push_back],
rw [dif_neg], refl,
exact ne_of_lt h',
end
@[simp] theorem push_back_rev_list : (a.push_back v).rev_list = v :: a.rev_list :=
begin
unfold push_back rev_list foldl iterate d_array.iterate,
dsimp [d_array.iterate_aux, read, d_array.read, push_back],
rw [dif_pos (eq.refl n)],
apply congr_arg,
apply push_back_rev_list_aux
end
@[simp] theorem push_back_to_list : (a.push_back v).to_list = a.to_list ++ [v] :=
by rw [←rev_list_reverse, ←rev_list_reverse, push_back_rev_list, list.reverse_cons]
@[simp] lemma read_push_back_left (i : fin n) : (a.push_back v).read i.cast_succ = a.read i :=
begin
cases i with i hi,
have : ¬ i = n := ne_of_lt hi,
simp [push_back, this, fin.cast_succ, fin.cast_add, fin.cast_le, fin.cast_lt, read, d_array.read]
end
@[simp] lemma read_push_back_right : (a.push_back v).read (fin.last _) = v :=
begin
cases hn : fin.last n with k hk,
have : k = n := by simpa [fin.eq_iff_veq ] using hn.symm,
simp [push_back, this, fin.cast_succ, fin.cast_add, fin.cast_le, fin.cast_lt, read, d_array.read]
end
end push_back
/- foreach -/
section foreach
variables {n : ℕ} {α : Type u} {β : Type v} {i : fin n} {f : fin n → α → β} {a : array n α}
@[simp] theorem read_foreach : (foreach a f).read i = f i (a.read i) :=
rfl
end foreach
/- map -/
section map
variables {n : ℕ} {α : Type u} {β : Type v} {i : fin n} {f : α → β} {a : array n α}
theorem read_map : (a.map f).read i = f (a.read i) :=
read_foreach
end map
/- map₂ -/
section map₂
variables {n : ℕ} {α : Type u} {i : fin n} {f : α → α → α} {a₁ a₂ : array n α}
@[simp] theorem read_map₂ : (map₂ f a₁ a₂).read i = f (a₁.read i) (a₂.read i) :=
read_foreach
end map₂
end array
|
8acf78af11687c3d5ef4ff9381a7a01db1c6f223 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/set_theory/game/ordinal.lean | 1fb9ef66b97e6329e7b703e03df226f9f9efd578 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 6,560 | lean | /-
Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Violeta Hernández Palacios
-/
import set_theory.game.basic
import set_theory.ordinal.natural_ops
/-!
# Ordinals as games
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define the canonical map `ordinal → pgame`, where every ordinal is mapped to the game whose left
set consists of all previous ordinals.
The map to surreals is defined in `ordinal.to_surreal`.
# Main declarations
- `ordinal.to_pgame`: The canonical map between ordinals and pre-games.
- `ordinal.to_pgame_embedding`: The order embedding version of the previous map.
-/
universe u
open pgame
open_locale natural_ops pgame
namespace ordinal
/-- Converts an ordinal into the corresponding pre-game. -/
noncomputable! def to_pgame : ordinal.{u} → pgame.{u}
| o := ⟨o.out.α, pempty, λ x, let hwf := ordinal.typein_lt_self x in
(typein (<) x).to_pgame, pempty.elim⟩
using_well_founded { dec_tac := tactic.assumption }
theorem to_pgame_def (o : ordinal) :
o.to_pgame = ⟨o.out.α, pempty, λ x, (typein (<) x).to_pgame, pempty.elim⟩ :=
by rw to_pgame
@[simp] theorem to_pgame_left_moves (o : ordinal) : o.to_pgame.left_moves = o.out.α :=
by rw [to_pgame, left_moves]
@[simp] theorem to_pgame_right_moves (o : ordinal) : o.to_pgame.right_moves = pempty :=
by rw [to_pgame, right_moves]
instance is_empty_zero_to_pgame_left_moves : is_empty (to_pgame 0).left_moves :=
by { rw to_pgame_left_moves, apply_instance }
instance is_empty_to_pgame_right_moves (o : ordinal) : is_empty o.to_pgame.right_moves :=
by { rw to_pgame_right_moves, apply_instance }
/-- Converts an ordinal less than `o` into a move for the `pgame` corresponding to `o`, and vice
versa. -/
noncomputable def to_left_moves_to_pgame {o : ordinal} : set.Iio o ≃ o.to_pgame.left_moves :=
(enum_iso_out o).to_equiv.trans (equiv.cast (to_pgame_left_moves o).symm)
@[simp] theorem to_left_moves_to_pgame_symm_lt {o : ordinal} (i : o.to_pgame.left_moves) :
↑(to_left_moves_to_pgame.symm i) < o :=
(to_left_moves_to_pgame.symm i).prop
theorem to_pgame_move_left_heq {o : ordinal} :
o.to_pgame.move_left == λ x : o.out.α, (typein (<) x).to_pgame :=
by { rw to_pgame, refl }
@[simp] theorem to_pgame_move_left' {o : ordinal} (i) :
o.to_pgame.move_left i = (to_left_moves_to_pgame.symm i).val.to_pgame :=
(congr_heq to_pgame_move_left_heq.symm (cast_heq _ i)).symm
theorem to_pgame_move_left {o : ordinal} (i) :
o.to_pgame.move_left (to_left_moves_to_pgame i) = i.val.to_pgame :=
by simp
/-- `0.to_pgame` has the same moves as `0`. -/
noncomputable def zero_to_pgame_relabelling : to_pgame 0 ≡r 0 :=
relabelling.is_empty _
noncomputable instance unique_one_to_pgame_left_moves : unique (to_pgame 1).left_moves :=
(equiv.cast $ to_pgame_left_moves 1).unique
@[simp] theorem one_to_pgame_left_moves_default_eq :
(default : (to_pgame 1).left_moves) = @to_left_moves_to_pgame 1 ⟨0, zero_lt_one⟩ :=
rfl
@[simp] theorem to_left_moves_one_to_pgame_symm (i) :
(@to_left_moves_to_pgame 1).symm i = ⟨0, zero_lt_one⟩ :=
by simp
theorem one_to_pgame_move_left (x) : (to_pgame 1).move_left x = to_pgame 0 :=
by simp
/-- `1.to_pgame` has the same moves as `1`. -/
noncomputable def one_to_pgame_relabelling : to_pgame 1 ≡r 1 :=
⟨equiv.equiv_of_unique _ _, equiv.equiv_of_is_empty _ _,
λ i, by simpa using zero_to_pgame_relabelling, is_empty_elim⟩
theorem to_pgame_lf {a b : ordinal} (h : a < b) : a.to_pgame ⧏ b.to_pgame :=
by { convert move_left_lf (to_left_moves_to_pgame ⟨a, h⟩), rw to_pgame_move_left }
theorem to_pgame_le {a b : ordinal} (h : a ≤ b) : a.to_pgame ≤ b.to_pgame :=
begin
refine le_iff_forall_lf.2 ⟨λ i, _, is_empty_elim⟩,
rw to_pgame_move_left',
exact to_pgame_lf ((to_left_moves_to_pgame_symm_lt i).trans_le h)
end
theorem to_pgame_lt {a b : ordinal} (h : a < b) : a.to_pgame < b.to_pgame :=
⟨to_pgame_le h.le, to_pgame_lf h⟩
theorem to_pgame_nonneg (a : ordinal) : 0 ≤ a.to_pgame :=
zero_to_pgame_relabelling.ge.trans $ to_pgame_le $ ordinal.zero_le a
@[simp] theorem to_pgame_lf_iff {a b : ordinal} : a.to_pgame ⧏ b.to_pgame ↔ a < b :=
⟨by { contrapose, rw [not_lt, not_lf], exact to_pgame_le }, to_pgame_lf⟩
@[simp] theorem to_pgame_le_iff {a b : ordinal} : a.to_pgame ≤ b.to_pgame ↔ a ≤ b :=
⟨by { contrapose, rw [not_le, pgame.not_le], exact to_pgame_lf }, to_pgame_le⟩
@[simp] theorem to_pgame_lt_iff {a b : ordinal} : a.to_pgame < b.to_pgame ↔ a < b :=
⟨by { contrapose, rw not_lt, exact λ h, not_lt_of_le (to_pgame_le h) }, to_pgame_lt⟩
@[simp] theorem to_pgame_equiv_iff {a b : ordinal} : a.to_pgame ≈ b.to_pgame ↔ a = b :=
by rw [pgame.equiv, le_antisymm_iff, to_pgame_le_iff, to_pgame_le_iff]
theorem to_pgame_injective : function.injective ordinal.to_pgame :=
λ a b h, to_pgame_equiv_iff.1 $ equiv_of_eq h
@[simp] theorem to_pgame_eq_iff {a b : ordinal} : a.to_pgame = b.to_pgame ↔ a = b :=
to_pgame_injective.eq_iff
/-- The order embedding version of `to_pgame`. -/
@[simps] noncomputable def to_pgame_embedding : ordinal.{u} ↪o pgame.{u} :=
{ to_fun := ordinal.to_pgame,
inj' := to_pgame_injective,
map_rel_iff' := @to_pgame_le_iff }
/-- The sum of ordinals as games corresponds to natural addition of ordinals. -/
theorem to_pgame_add : ∀ a b : ordinal.{u}, a.to_pgame + b.to_pgame ≈ (a ♯ b).to_pgame
| a b := begin
refine ⟨le_of_forall_lf (λ i, _) is_empty_elim, le_of_forall_lf (λ i, _) is_empty_elim⟩,
{ apply left_moves_add_cases i;
intro i;
let wf := to_left_moves_to_pgame_symm_lt i;
try { rw add_move_left_inl }; try { rw add_move_left_inr };
rw [to_pgame_move_left', lf_congr_left (to_pgame_add _ _), to_pgame_lf_iff],
{ exact nadd_lt_nadd_right wf _ },
{ exact nadd_lt_nadd_left wf _ } },
{ rw to_pgame_move_left',
rcases lt_nadd_iff.1 (to_left_moves_to_pgame_symm_lt i) with ⟨c, hc, hc'⟩ | ⟨c, hc, hc'⟩;
rw [←to_pgame_le_iff, ←le_congr_right (to_pgame_add _ _)] at hc';
apply lf_of_le_of_lf hc',
{ apply add_lf_add_right,
rwa to_pgame_lf_iff },
{ apply add_lf_add_left,
rwa to_pgame_lf_iff } }
end
using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] }
@[simp] theorem to_pgame_add_mk (a b : ordinal) :
⟦a.to_pgame⟧ + ⟦b.to_pgame⟧ = ⟦(a ♯ b).to_pgame⟧ :=
quot.sound (to_pgame_add a b)
end ordinal
|
65b2a6b36083ecf6dda06b018e6992f54fc1fa14 | 48f4f349e1bb919d14ab7e5921d0cfe825f4c423 | /folklore/core.lean | 4df6419c9e89dfcabce94f418c40f75566ae5167 | [] | no_license | thalesant/formalabstracts-2017 | fdf4ff90d30ab1dcb6d4cf16a068a997ea5ecc80 | c47181342c9e41954aa8d41f5049965b5f332bca | refs/heads/master | 1,584,610,453,925 | 1,528,277,508,000 | 1,528,277,508,000 | 136,299,625 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,799 | lean | /- Thomas Hales
Start over, using bundled structures.
Feb 3, 2018
-/
prelude
--basic core stuff
/- The default behavior for Type is Type u,
for an arbitrary type variable u
(unlike Official-Lean).
The intention is for universe variables to be mostly
handled behind the scenes. -/
notation `Prop` := Sort 0
notation f ` $ `:1 a:0 := f a
inductive true : Prop
| intro : true
inductive false : Prop
inductive empty : Type
def not (a : Prop) := a → false
prefix `(¬) := not
@[reducible] def ne {α : Sort} (a b : α) := ¬(a = b)
notation a ≠ b := ne a b
inductive eq {α : Sort} (a : α) : α → Prop
| refl : eq a
infix ` = `:50 := eq
structure prod (α : Type) (β : Type) :=
(fst : α)
(snd : β)
structure and (a b : Prop) : Prop :=
(left : a)
(right : b)
inductive sum (α : Type) (β : Type)
| inl {} (val : α) : sum
| inr {} (val : β) : sum
inductive or (a b : Prop) : Prop
| inl {} (h : a) : or
| inr {} (h : b) : or
structure sigma {α : Type} (β : α → Type) :=
(fst : α)
(snd : β fst)
inductive bool : Type
| ff : bool
| tt : bool
structure subtype {α : Sort} (p : α → Prop) :=
(val : α) (property : p val)
inductive option (α : Type)
| none {} : option
| some (val : α) : option
inductive list (T : Type)
| nil {} : list
| cons (hd : T) (tl : list) : list
notation h :: t := list.cons h t
notation `[` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := l
inductive nat
| zero : nat
| succ (n : nat) : nat
structure unification_constraint :=
{α : Type} (lhs : α) (rhs : α)
infix ` ≟ `:50 := unification_constraint.mk
infix ` =?= `:50 := unification_constraint.mk
structure unification_hint :=
(pattern : unification_constraint)
(constraints : list unification_constraint)
-- basic set notation.
class_infix `has_mem.mem `(∈)
class_infix `has_sub.sub `(-)
class_infix `has_div.div `(/)
class_infix `has_dvd.dvd `(∣)
class_infix `has_mod.mod `(%)
class_infix `has_le.le `(<=)
class_infix `has_le.le `(≤)
class_infix `has_lt.lt `(<)
class_infix `has_append.append `(++)
class_infix `has_andthen `(;)
class_field `has_emptyc.emptyc `(∅)
class_infix `has_union.union `(∪)
class_infix `has_inter.inter `(∩)
class_infix `has_subset.subset `(⊆)
class_infix `has_ssubset.ssubset `(⊂)
class_infix `has_sdiff.sdiff `(\)
class_infix `has_equiv.equiv `(≈)
class has_sub := (α : Type) ((-) : α → α → α)
class has_div := (α : Type) ((/) : α → α → α)
class has_dvd := (α : Type) ((|) : α → α → Prop)
class has_mod := (α : Type) ((%) : α → α → α)
class has_le := (α : Type) ((≤) : α → α → Prop)
class has_lt := (α : Type) ((<) : α → α → Prop)
class has_append := (α : Type) ((++) : α → α → α)
class has_andthen := (α : Type) (β : Type) (σ : Type) ((;) : α → β → σ)
class has_union := (α : Type) ((∪) : α → α → α)
class has_inter := (α : Type) ((∩) : α → α → α)
class has_sdiff := (α : Type) ((\) : α → α → α)
class has_equiv := (α : Sort) ((≈) : α → α → Prop)
class has_subset := (α : Type) ((⊆) : α → α → Prop)
class has_ssubset := (α : Type) ((⊂) : α → α → Prop)
class has_subset :=
(has_subset)
(has_ssubset)
((⊂) :≡ λ a a', (a ⊆ a' ∧ ¬ (a' ⊆ a)))
/- polymorphic notation for collections.
Example: {a, b, c}. -/
class has_emptyc := (α : Type) (emptyc : α)
class has_insert := (α : Type) (γ : Type) := (insert : α → γ → γ)
class has_mem := (α : Type) (β : Type) ((∈) : α → β → Prop)
notation a ∉ s := ¬ has_mem.mem a s
class has_mem :=
(has_mem)
(has_subset (renaming α → β))
((⊆) :≡ λ b b', ∀ (x : α ), x ∈ b → x ∈ b')
/- Type class used to implement the notation { a ∈ c | p a } -/
class has_sep := (α : Type) (γ : Type) (sep : (α → Prop) → γ → γ)
def set (α : Type) := α → Prop
def set_of {α : Type} (p : α → Prop) : set α := p
protected def set.mem (a : α) (s : set α) := s a
instance {α} (set α) : has_mem :=
{α := α, β := set α, (∈) := set.mem}
protected def set.sep (p : α → Prop) (s : set α) : set α :=
{a | a ∈ s ∧ p a}
instance {α} (set α): has_sep :=
{α := α, γ := set α, set.sep⟩
instance {α} (set α) : has_emptyc :=
⟨set α , (λ a, false) ⟩
def univ : set α := λ a, true
protected def set.insert (a : α) (s : set α) : set α :=
{b | b = a ∨ b ∈ s}
instance {α} (set α) : has_insert :=
⟨set α, set.insert⟩
protected def set.union (s₁ s₂ : set α) : set α :=
{a | a ∈ s₁ ∨ a ∈ s₂}
instance {α} (set α) : set.has_union :=
⟨set α, set.union⟩
protected def set.inter (s₁ s₂ : set α) : set α :=
{a | a ∈ s₁ ∧ a ∈ s₂}
instance {α} (set α) : set.has_inter :=
⟨set α, set.inter⟩
def compl (s : set α) : set α :=
{a | a ∉ s}
instance {α} (set α) : has_neg :=
⟨set α, compl⟩
protected def diff (s t : set α) : set α :=
{a ∈ s | a ∉ t}
instance {α} (set α) : has_sdiff :=
⟨set α, set.diff⟩
def powerset (s : set α) : set (set α) :=
{t | t ⊆ s}
prefix `𝒫`:100 := powerset
@[reducible]
def sUnion (s : set (set α)) : set α := {t | ∃ a ∈ s, t ∈ a}
prefix `⋃₀`:110 := sUnion
def image (f : α → β) (s : set α) : set β :=
{b | ∃ a, a ∈ s ∧ f a = b}
/-
Using 1 as a field name in structures is problematic,
because the natural numbers are used to name the projections:
semigroup.1 is the first field of the semigroup structure.
We need a notational way to distinguish them. Say
semigroup.(1) (field name) vs. semigroup.1 (first field)
The class_* records the hidden name that is used for the
field, `mul `one `inv, etc.
Elaboration is expected to replace each ` * ` with the
appropriate instance R.mul, where R has upcast to has_mul
Field must have exact name match,
and the class must have upcast to has_mul (e.g.)
Special notation does not survive renaming of fields.
-/
class_infixl `has_mul.mul `( * ):70
class_field `has_one.one `( 1 )
class_postfix `has_inv.inv `( ⁻¹ ):70
class_infixl `has_add.add `( + ):70
class_fix `has_zero.zero `( 0 )
class_prefix `has_neg.neg `( - ):70 -- unary
class_infix `has_le.le `( ≤ ):50
class_infix `has_le.lt `( < ):50
/- We might have to choose non-generic names α and β
for fields because they effectively become global
names for algebraic structure carriers. -/
structure has_mul :=
(α : Type)
( ( * ) : α → α → α )
structure semigroup :=
(has_mul)
(mul_assoc : ∀ a b c : α, a * b * c = a * (b * c))
structure has_one :=
(α : Type)
( ( 1 ) : α)
structure monoid :=
(semigroup)
(has_one)
(one_mul : ∀ a : α, 1 * a = a)
(mul_one : ∀ a : α, a * 1 = a)
structure has_inv :=
(α : Type)
( ( ⁻¹ ) : α → α )
structure group :=
(monoid)
(has_inv)
(mul_left_inv : ∀ a : α, a⁻¹ * a = 1)
/-
"abelian" is a mixin for semigroup.
-/
structure abelian :=
(semigroup)
(mul_comm : ∀ (a b : α), a * b = b * a)
-- additive structures
structure has_add :=
(α : Type)
( ( + ) : α → α → α)
structure has_zero :=
(α : Type)
( ( 0 ) : α)
structure has_neg :=
(α : Type)
( ( - ) : α → α)
/-
We must not prove any theorems about add_monoid.
We use the upcast to monoid to use all its theorems.
-/
structure add_monoid :=
(has_add)
(has_zero)
(monoid + abelian
(renaming
( * ) -> ( + ),
( 1 ) -> ( 0 ),
mul_assoc -> add_assoc,
one_mul -> zero_add,
mul_one -> add_zero,
mul_comm -> add_comm
))
/-
add_group repeats add_monoid renamings,
but we tolerate repetition, because renaming is infrequent.
-/
structure add_group :=
(has_neg)
(add_monoid)
(group + abelian
(renaming
( * ) -> ( + ),
( 1 ) -> ( 0 ),
mul_assoc -> add_assoc,
one_mul -> zero_add,
mul_one -> add_zero,
mul_comm -> add_comm
( ⁻¹ ) -> ( - )
(mul_left_inv -> add_left_inv)
(group -> add_group)
))
structure semiring :=
(monoid)
(add_monoid)
(left_distrib : ∀ a b c : α, a * (b + c) = (a * b) + (a * c))
(right_distrib : ∀ a b c : α, (a + b) * c = (a * c) + (b * c))
(zero_mul : ∀ a : α, 0 * a = 0)
(mul_zero : ∀ a : α, a * 0 = 0)
structure commutative :=
(semiring)
(mul_comm : ∀ a b : α, a * b = b * a)
structure ring :=
(semiring)
(add_group)
structure integral_domain :=
(ring + commutative)
(zero_ne_one : 0 ≠ (1:α))
(eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0)
structure division_ring :=
(ring)
( ( ⁻¹ ) : α → α )
(zero_ne_one : 0 ≠ (1:α))
(mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1)
(inv_mul_cancel : ∀ {a : α}, a ≠ 0 → a⁻¹ * a = 1)
/-
qed box ▢ "\sqo" has the facetious meaning "quite easily done".
It marks true statements that are to be filled in by automation or the user.
Internally, it means sorry.
-/
/-
If there are two identical fields, the parser should remove duplicates.
For prop fields, it should keep one that provides a proof, if one exists, and
retain its given position among fields.
-/
structure field :=
(division_ring)
(integral_domain)
(eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0 := ▢ )
-- modules
class_infixl `scalar ` • `:73
class has_scalar :=
(α : Type)
(β : Type)
( ( • ) : α → β → β)
/-
We pull the ring out as a parameter because mathematicians
do when they write "R-module".
-/
class module (R : ring) :=
(has_scalar)
(α := R.α)
(add_group (renaming α -> β ))
(smul_left_distrib : ∀r (x y : β), r • (x + y) = r • x + r • y)
(smul_right_distrib : ∀r s (x : β), (r + s) • x = r • x + s • x)
(mul_smul : ∀r s (x : β), (r * s) • x = r • (s • x))
(one_smul : ∀x : β, (1 : α) • x = x)
/-
We don't need a separate definition of vector_space.
Upcasting occurs to allow us to write module F.
variables (F : field) (V : module F)
-/
/- order structures -/
/-
The symbol :≡ marks a static (immutable) field.
-/
structure has_le :=
(α : Type)
( ( ≤ ) : α → α → Prop)
( ( < ) :≡ λ a b, a ≤ b ∧ ¬ b ≤ a)
structure preorder :=
(has_le)
(le_refl : ∀ a : α, a ≤ a)
(le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c)
structure partial_order :=
(preorder)
(le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b)
structure linear_order :=
(partial_order)
(le_total : ∀ a b : α, a ≤ b ∨ b ≤ a)
structure ordered_cancel_add_monoid :=
(add_monoid)
(partial_order)
(add_left_cancel : ∀ a b c : α, a + b = a + c → b = c)
(add_right_cancel : ∀ a b c : α, a + b = c + b → a = c := ▢ )
(add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b)
(le_of_add_le_add_left : ∀ a b c : α, a + b ≤ a + c → b ≤ c)
structure ordered_add_group :=
(ordered_cancel_add_monoid)
(add_group)
(mul_lt_mul_left : ∀ a b : α, a < b → ∀ c : α, c + a < c + b)
/- No separate definition is necessary for linear_order mixin.
For this to work smoothly, an upcast to target A
needs to extend automatically to target A + mixins.
-/
/-
structure linear_ordered_add_group := (ordered_add_group + linear_order)
structure linear_ordered_cancel_add_monoid :=
(ordered_cancel_add_monoid + linear_order)
-/
structure ordered_semiring :=
(semiring)
(ordered_cancel_add_monoid)
(mul_le_mul_of_nonneg_left: ∀ a b c : α, a ≤ b → 0 ≤ c → c * a ≤ c * b)
(mul_le_mul_of_nonneg_right: ∀ a b c : α, a ≤ b → 0 ≤ c → a * c ≤ b * c)
(mul_lt_mul_of_pos_left: ∀ a b c : α, a < b → 0 < c → c * a < c * b)
(mul_lt_mul_of_pos_right: ∀ a b c : α, a < b → 0 < c → a * c < b * c)
structure linear_ordered_semiring :=
(ordered_semiring)
(linear_order)
(zero_lt_one : zero < one)
structure ordered_ring :=
(ring)
(ordered_add_group)
(ordered_semiring) -- redundant, but adds it to the hierarchy.
(zero_ne_one : 0 ≠ (1:α))
(mul_nonneg : ∀ a b : α, 0 ≤ a → 0 ≤ b → 0 ≤ a * b)
(mul_pos : ∀ a b : α, 0 < a → 0 < b → 0 < a * b)
(mul_le_mul_of_nonneg_left:= ▢ )
(mul_le_mul_of_nonneg_right:= ▢ )
(mul_lt_mul_of_pos_left:= ▢ )
(mul_lt_mul_of_pos_right:= ▢ )
class linear_ordered_ring :=
(linear_ordered_semiring)
(ordered_ring)
/-
linear_ordered_comm_ring, is replaced with
linear_ordered_ring + commutative.
-/
class linear_ordered_field :=
(linear_ordered_ring)
(field)
-- powers
class_infixr `has_pow_nat.pow_nat `pow ` ^ `:70
/-
XX We meed to introduce natural numbers, integers,
and associated notation and operations here.
-/
class has_pow_nat :=
(α : Type)
( ( ^ ) : α → ℕ → α)
class has_pow_int :=
(α : Type)
(pow_int : α → ℤ → α)
def monoid.pow (monoid M) (a : M.α) : ℕ → α
| 0 := 1
| (n+1) := a * monoid.pow n
/-
We allow conservative extensions of the class.
In this case we are adding has_pow_nat to the hierarchy.
It also propagates automatically to a field of descendants.
Handling of "this": when inside the class declaration,
"this" becomes an implicit argument, so that
monoid.pow _ a n becomes monoid.pow a n.
-/
class monoid :=
(monoid)
(has_pow_nat)
( ( ^ ) :≡ λ a n, monoid.pow a n)
/-
-[1+n] is an abbreviation in Official-Lean.
-/
def gpow (a : α) : ℤ → α
| (of_nat n) := a^n
| -[1+n] := (a^(nat.succ n))⁻¹
/-
Lattices
-/
class_field `has_top.top ` ⊤ `
class_field `has_bot.bot ` ⊥ `
class_infixl `has_inf.inf ` ⊓ `:70
class_infixl `has_sup.sup ` ⊔ `:65
structure has_top :=
(α : Type)
( ( ⊤ ) : α)
structure has_bot :=
(α : Type)
( ( ⊥ ) : α)
structure has_inf :=
(α : Type)
( ( ⊓ ) : α → α → α)
structure has_sup :=
(α : Type)
( ( ⊔ ) : α → α → α)
-- class has_imp (α : Type u) := (imp : α → α → α) /- Better name -/
structure order_top :=
(has_top)
(partial_order)
(le_top : ∀ a : α, a ≤ ⊤)
structure order_bot :=
(has_bot)
(partial_order)
(bot_le : ∀ a : α, ⊥ ≤ a)
structure semilattice_sup :=
(has_sup)
(partial_order)
(le_sup_left : ∀ a b : α, a ≤ a ⊔ b)
(le_sup_right : ∀ a b : α, b ≤ a ⊔ b)
(sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c)
structure semilattice_inf :=
(has_inf)
(partial_order)
(inf_le_left : ∀ a b : α, a ⊓ b ≤ a)
(inf_le_right : ∀ a b : α, a ⊓ b ≤ b)
(le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c)
structure semilattice_sup_top :=
(order_top)
(semilattice_sup)
structure semilattice_sup_bot :=
(order_bot)
(semilattice_sup)
structure semilattice_inf_top :=
(order_top)
(semilattice_inf)
structure semilattice_inf_bot :=
(order_bot)
(semilattice_inf)
structure lattice :=
(semilattice_sup)
(semilattice_inf)
def galois_connection (A : preorder) (B : preorder)
(l : A.α → B.α) (u : B.α → A.α) := ∀a b, l a ≤ b ↔ a ≤ u b
|
24f84c187a0549b5230585bbb75b2b74d4cfd83c | 4fa161becb8ce7378a709f5992a594764699e268 | /test/library_search/basic.lean | d5a44cb67ada99d44c5f5e16032bf9a8181a1dca | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 6,511 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import data.nat.basic
/- Turn off trace messages so they don't pollute the test build: -/
set_option trace.silence_library_search true
/- For debugging purposes, we can display the list of lemmas: -/
-- set_option trace.suggest true
namespace test.library_search
-- Check that `library_search` fails if there are no goals.
example : true :=
begin
trivial,
success_if_fail { library_search },
end
-- Verify that `library_search` solves goals via `solve_by_elim` when the library isn't
-- even needed.
example (P : Prop) (p : P) : P :=
by library_search
example (P : Prop) (p : P) (np : ¬P) : false :=
by library_search
example (X : Type) (P : Prop) (x : X) (h : Π x : X, x = x → P) : P :=
by library_search
def lt_one (n : ℕ) := n < 1
lemma zero_lt_one (n : ℕ) (h : n = 0) : lt_one n := by subst h; dsimp [lt_one]; simp
-- Verify that calls to solve_by_elim to discharge subgoals use `rfl`
example : lt_one 0 :=
by library_search
example (α : Prop) : α → α :=
by library_search -- says: `exact id`
example (p : Prop) [decidable p] : (¬¬p) → p :=
by library_search -- says: `exact not_not.mp`
example (a b : Prop) (h : a ∧ b) : a :=
by library_search -- says: `exact h.left`
example (P Q : Prop) [decidable P] [decidable Q]: (¬ Q → ¬ P) → (P → Q) :=
by library_search -- says: `exact not_imp_not.mp`
example (a b : ℕ) : a + b = b + a :=
by library_search -- says: `exact add_comm a b`
example {a b : ℕ} : a ≤ a + b :=
by library_search -- says: `exact nat.le.intro rfl`
example (n m k : ℕ) : n * (m - k) = n * m - n * k :=
by library_search -- says: `exact nat.mul_sub_left_distrib n m k`
example (n m k : ℕ) : n * m - n * k = n * (m - k) :=
by library_search -- says: `exact eq.symm (nat.mul_sub_left_distrib n m k)`
example {n m : ℕ} (h : m < n) : m ≤ n - 1 :=
by library_search -- says: `exact nat.le_pred_of_lt h`
example {α : Type} (x y : α) : x = y ↔ y = x :=
by library_search -- says: `exact eq_comm`
example (a b : ℕ) (ha : 0 < a) (hb : 0 < b) : 0 < a + b :=
by library_search -- says: `exact add_pos ha hb`
example (a b : ℕ) : 0 < a → 0 < b → 0 < a + b :=
by library_search -- says: `exact add_pos`
section synonym
-- Synonym `>` for `<` in the goal
example (a b : ℕ) : 0 < a → 0 < b → a + b > 0 :=
by library_search -- says: `exact add_pos`
-- Synonym `>` for `<` in another part of the goal
example (a b : ℕ) : a > 0 → 0 < b → 0 < a + b :=
by library_search -- says: `exact add_pos`
-- Synonym `>` for `<` in another part of the goal
example (a b : ℕ) (ha : a > 0) (hb : 0 < b) : 0 < a + b :=
by library_search -- says: `exact add_pos ha hb`
example (a b : ℕ) (h : a ∣ b) (w : b > 0) : a ≤ b :=
by library_search -- says: `exact nat.le_of_dvd w h`
example (a b : ℕ) (h : a ∣ b) (w : b > 0) : b ≥ a :=
by library_search -- says: `exact nat.le_of_dvd w h`
-- A lemma with head symbol `¬` can be used to prove `¬ p` or `⊥`
example (a : ℕ) : ¬ (a < 0) := by library_search -- says `exact not_lt_bot`
example (a : ℕ) (h : a < 0) : false := by library_search -- says `exact not_lt_bot h`
-- An inductive type hides the constructor's arguments enough
-- so that `library_search` doesn't accidentally close the goal.
inductive P : ℕ → Prop
| gt_in_head {n : ℕ} : n < 0 → P n
-- This lemma with `>` as its head symbol should also be found for goals with head symbol `<`.
lemma lemma_with_gt_in_head (a : ℕ) (h : P a) : 0 > a := by { cases h, assumption }
-- This lemma with `false` as its head symbols should also be found for goals with head symbol `¬`.
lemma lemma_with_false_in_head (a b : ℕ) (h1 : a < b) (h2 : P a) : false :=
by { apply nat.not_lt_zero, cases h2, assumption }
example (a : ℕ) (h : P a) : 0 > a := by library_search -- says `exact lemma_with_gt_in_head a h`
example (a : ℕ) (h : P a) : a < 0 := by library_search -- says `exact lemma_with_gt_in_head a h`
example (a b : ℕ) (h1 : a < b) (h2 : P a) : false := by library_search
-- says `exact lemma_with_false_in_head a b h1 h2`
example (a b : ℕ) (h1 : a < b) : ¬ (P a) := by library_search!
-- says `exact lemma_with_false_in_head a b h1`
end synonym
-- We even find `iff` results:
example : ∀ P : Prop, ¬(P ↔ ¬P) :=
by library_search! -- says: `λ (a : Prop), (iff_not_self a).mp`
example {a b c : ℕ} (ha : a > 0) (w : b ∣ c) : a * b ∣ a * c :=
by library_search -- exact mul_dvd_mul_left a w
example {a b c : ℕ} (h₁ : a ∣ c) (h₂ : a ∣ b + c) : a ∣ b :=
by library_search -- says `exact (nat.dvd_add_left h₁).mp h₂`
-- We have control of how `library_search` uses `solve_by_elim`.
-- In particular, we can add extra lemmas to the `solve_by_elim` step
-- (i.e. for `library_search` to use to attempt to discharge subgoals
-- after successfully applying a lemma from the library.)
example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) :=
begin
library_search [add_lt_add], -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)`
end
-- We can also use attributes:
meta def ex_attr : user_attribute := {
name := `ex,
descr := "A lemma that should be applied by `library_search` when discharging subgoals."
}
run_cmd attribute.register ``ex_attr
attribute [ex] add_lt_add
example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) :=
begin
library_search with ex, -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)`
end
example (a b : ℕ) (h : 0 < b) : (a * b) / b = a :=
by library_search -- Says: `exact nat.mul_div_left a h`
example (a b : ℕ) (h : b ≠ 0) : (a * b) / b = a :=
begin
success_if_fail { library_search },
library_search [nat.pos_iff_ne_zero.mpr],
end
-- Checking examples from issue #2220
example {α : Sort*} (h : empty) : α :=
by library_search
example {α : Type*} (h : empty) : α :=
by library_search
def map_from_sum {A B C : Type} (f : A → C) (g : B → C) : (A ⊕ B) → C := by library_search
-- Test that we can provide custom `apply` tactics,
-- e.g. to change how aggressively we unfold definitions in trying to apply lemmas.
lemma bind_singleton {α β} (x : α) (f : α → list β) : list.bind [x] f = f x :=
begin
success_if_fail {
library_search { apply := λ e, tactic.apply e { md := tactic.transparency.reducible } },
},
library_search!,
end
end test.library_search
|
c0649e4c577cf6b6d25a732c97015cfd230a8a79 | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/calc2.lean | b759371c02f4095640b6fe0ea0e2ebe77bc8504e | [
"Apache-2.0"
] | permissive | codyroux/lean0.1 | 1ce92751d664aacff0529e139083304a7bbc8a71 | 0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef | refs/heads/master | 1,610,830,535,062 | 1,402,150,480,000 | 1,402,150,480,000 | 19,588,851 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 222 | lean |
variables a b c d e : Nat.
variable f : Nat -> Nat.
axiom H1 : f a = a.
theorem T : f (f (f a)) = a
:= calc f (f (f a)) = f (f a) : { H1 }
... = f a : { H1 }
... = a : { H1 }.
|
aae221009963093a020295c93e084b1a04867f57 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/analysis/convex/function.lean | 380240a9d1ea4f3dec2a489f2c683790477a7ae5 | [
"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 | 24,564 | lean | /-
Copyright (c) 2019 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, François Dupuis
-/
import algebra.module.ordered
import analysis.convex.basic
import tactic.field_simp
import tactic.linarith
import tactic.ring
/-!
# Convex and concave functions
This file defines convex and concave functions in vector spaces and proves the finite Jensen
inequality. The integral version can be found in `analysis.convex.integral`.
A function `f : E → β` is `convex_on` a set `s` if `s` is itself a convex set, and for any two
points `x y ∈ s`, the segment joining `(x, f x)` to `(y, f y)` is above the graph of `f`.
Equivalently, `convex_on 𝕜 f s` means that the epigraph `{p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2}` is
a convex set.
## Main declarations
* `convex_on 𝕜 s f`: The function `f` is convex on `s` with scalars `𝕜`.
* `concave_on 𝕜 s f`: The function `f` is concave on `s` with scalars `𝕜`.
* `strict_convex_on 𝕜 s f`: The function `f` is strictly convex on `s` with scalars `𝕜`.
* `strict_concave_on 𝕜 s f`: The function `f` is strictly concave on `s` with scalars `𝕜`.
-/
open finset linear_map set
open_locale big_operators classical convex pointwise
variables {𝕜 E F β ι : Type*}
section ordered_semiring
variables [ordered_semiring 𝕜]
section add_comm_monoid
variables [add_comm_monoid E] [add_comm_monoid F]
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β]
section has_scalar
variables (𝕜) [has_scalar 𝕜 E] [has_scalar 𝕜 β] (s : set E) (f : E → β)
/-- Convexity of functions -/
def convex_on : Prop :=
convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 →
f (a • x + b • y) ≤ a • f x + b • f y
/-- Concavity of functions -/
def concave_on : Prop :=
convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 →
a • f x + b • f y ≤ f (a • x + b • y)
/-- Strict convexity of functions -/
def strict_convex_on : Prop :=
convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x ≠ y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 →
f (a • x + b • y) < a • f x + b • f y
/-- Strict concavity of functions -/
def strict_concave_on : Prop :=
convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x ≠ y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 →
a • f x + b • f y < f (a • x + b • y)
variables {𝕜 s f}
lemma convex_on_id {s : set 𝕜} (hs : convex 𝕜 s) : convex_on 𝕜 s id := ⟨hs, by { intros, refl }⟩
lemma concave_on_id {s : set 𝕜} (hs : convex 𝕜 s) : concave_on 𝕜 s id := ⟨hs, by { intros, refl }⟩
lemma convex_on.subset {t : set E} (hf : convex_on 𝕜 t f) (hst : s ⊆ t) (hs : convex 𝕜 s) :
convex_on 𝕜 s f :=
⟨hs, λ x y hx hy, hf.2 (hst hx) (hst hy)⟩
lemma concave_on.subset {t : set E} (hf : concave_on 𝕜 t f) (hst : s ⊆ t) (hs : convex 𝕜 s) :
concave_on 𝕜 s f :=
⟨hs, λ x y hx hy, hf.2 (hst hx) (hst hy)⟩
end has_scalar
section distrib_mul_action
variables [has_scalar 𝕜 E] [distrib_mul_action 𝕜 β] {s : set E} {f g : E → β}
lemma convex_on.add (hf : convex_on 𝕜 s f) (hg : convex_on 𝕜 s g) :
convex_on 𝕜 s (λ x, f x + g x) :=
⟨hf.1, λ x y hx hy a b ha hb hab,
calc
f (a • x + b • y) + g (a • x + b • y) ≤ (a • f x + b • f y) + (a • g x + b • g y)
: add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab)
... = a • (f x + g x) + b • (f y + g y) : by rw [smul_add, smul_add, add_add_add_comm]⟩
lemma concave_on.add (hf : concave_on 𝕜 s f) (hg : concave_on 𝕜 s g) :
concave_on 𝕜 s (λ x, f x + g x) :=
@convex_on.add _ _ (order_dual β) _ _ _ _ _ _ f g hf hg
end distrib_mul_action
section module
variables [has_scalar 𝕜 E] [module 𝕜 β] {s : set E} {f : E → β}
lemma convex_on_const (c : β) (hs : convex 𝕜 s) : convex_on 𝕜 s (λ x:E, c) :=
⟨hs, λ x y _ _ a b _ _ hab, (convex.combo_self hab c).ge⟩
lemma concave_on_const (c : β) (hs : convex 𝕜 s) : concave_on 𝕜 s (λ x:E, c) :=
@convex_on_const _ _ (order_dual β) _ _ _ _ _ _ c hs
end module
section ordered_smul
variables [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f : E → β}
lemma convex_on.convex_le (hf : convex_on 𝕜 s f) (r : β) :
convex 𝕜 {x ∈ s | f x ≤ r} :=
λ x y hx hy a b ha hb hab, ⟨hf.1 hx.1 hy.1 ha hb hab,
calc
f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx.1 hy.1 ha hb hab
... ≤ a • r + b • r : add_le_add (smul_le_smul_of_nonneg hx.2 ha)
(smul_le_smul_of_nonneg hy.2 hb)
... = r : convex.combo_self hab r⟩
lemma concave_on.convex_ge (hf : concave_on 𝕜 s f) (r : β) :
convex 𝕜 {x ∈ s | r ≤ f x} :=
@convex_on.convex_le 𝕜 E (order_dual β) _ _ _ _ _ _ _ f hf r
lemma convex_on.convex_epigraph (hf : convex_on 𝕜 s f) :
convex 𝕜 {p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2} :=
begin
rintro ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab,
refine ⟨hf.1 hx hy ha hb hab, _⟩,
calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab
... ≤ a • r + b • t : add_le_add (smul_le_smul_of_nonneg hr ha)
(smul_le_smul_of_nonneg ht hb)
end
lemma concave_on.convex_hypograph (hf : concave_on 𝕜 s f) :
convex 𝕜 {p : E × β | p.1 ∈ s ∧ p.2 ≤ f p.1} :=
@convex_on.convex_epigraph 𝕜 E (order_dual β) _ _ _ _ _ _ _ f hf
lemma convex_on_iff_convex_epigraph :
convex_on 𝕜 s f ↔ convex 𝕜 {p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2} :=
⟨convex_on.convex_epigraph, λ h,
⟨λ x y hx hy a b ha hb hab, (@h (x, f x) (y, f y) ⟨hx, le_rfl⟩ ⟨hy, le_rfl⟩ a b ha hb hab).1,
λ x y hx hy a b ha hb hab, (@h (x, f x) (y, f y) ⟨hx, le_rfl⟩ ⟨hy, le_rfl⟩ a b ha hb hab).2⟩⟩
lemma concave_on_iff_convex_hypograph :
concave_on 𝕜 s f ↔ convex 𝕜 {p : E × β | p.1 ∈ s ∧ p.2 ≤ f p.1} :=
@convex_on_iff_convex_epigraph 𝕜 E (order_dual β) _ _ _ _ _ _ _ f
end ordered_smul
section module
variables [module 𝕜 E] [has_scalar 𝕜 β] {s : set E} {f : E → β} {c : E}
/-- If a function is convex on `s`, it remains convex after a translation. -/
lemma convex_on.translate_right (hf : convex_on 𝕜 s f) :
convex_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, c + z)) :=
⟨hf.1.translate_preimage_right _, λ x y hx hy a b ha hb hab,
calc
f (c + (a • x + b • y)) = f (a • (c + x) + b • (c + y))
: by rw [smul_add, smul_add, add_add_add_comm, convex.combo_self hab]
... ≤ a • f (c + x) + b • f (c + y) : hf.2 hx hy ha hb hab⟩
/-- If a function is concave on `s`, it remains concave after a translation. -/
lemma concave_on.translate_right (hf : concave_on 𝕜 s f) :
concave_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, c + z)) :=
@convex_on.translate_right 𝕜 E (order_dual β) _ _ _ _ _ _ _ _ hf
/-- If a function is convex on `s`, it remains convex after a translation. -/
lemma convex_on.translate_left (hf : convex_on 𝕜 s f) :
convex_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, z + c)) :=
by simpa only [add_comm] using hf.translate_right
/-- If a function is concave on `s`, it remains concave after a translation. -/
lemma concave_on.translate_left (hf : concave_on 𝕜 s f) :
concave_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, z + c)) :=
by simpa only [add_comm] using hf.translate_right
end module
section module
variables [module 𝕜 E] [module 𝕜 β]
lemma convex_on_iff_forall_pos {s : set E} {f : E → β} :
convex_on 𝕜 s f ↔ convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1
→ f (a • x + b • y) ≤ a • f x + b • f y :=
begin
refine and_congr_right' ⟨λ h x y hx hy a b ha hb hab, h hx hy ha.le hb.le hab,
λ h x y hx hy a b ha hb hab, _⟩,
obtain rfl | ha' := ha.eq_or_lt,
{ rw [zero_add] at hab, subst b, simp_rw [zero_smul, zero_add, one_smul] },
obtain rfl | hb' := hb.eq_or_lt,
{ rw [add_zero] at hab, subst a, simp_rw [zero_smul, add_zero, one_smul] },
exact h hx hy ha' hb' hab,
end
lemma concave_on_iff_forall_pos {s : set E} {f : E → β} :
concave_on 𝕜 s f ↔ convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1
→ a • f x + b • f y ≤ f (a • x + b • y) :=
@convex_on_iff_forall_pos 𝕜 E (order_dual β) _ _ _ _ _ _ _
lemma convex_on_iff_forall_pos_ne {s : set E} {f : E → β} :
convex_on 𝕜 s f ↔ convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x ≠ y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1
→ f (a • x + b • y) ≤ a • f x + b • f y :=
begin
rw convex_on_iff_forall_pos,
refine and_congr_right' ⟨λ h x y hx hy _ a b ha hb hab, h hx hy ha hb hab,
λ h x y hx hy a b ha hb hab, _⟩,
obtain rfl | hxy := eq_or_ne x y,
{ rw [convex.combo_self hab, convex.combo_self hab] },
exact h hx hy hxy ha hb hab,
end
lemma concave_on_iff_forall_pos_ne {s : set E} {f : E → β} :
concave_on 𝕜 s f ↔ convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x ≠ y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1
→ a • f x + b • f y ≤ f (a • x + b • y) :=
@convex_on_iff_forall_pos_ne 𝕜 E (order_dual β) _ _ _ _ _ _ _
/-- A linear map is convex. -/
lemma linear_map.convex_on (f : E →ₗ[𝕜] β) {s : set E} (hs : convex 𝕜 s) : convex_on 𝕜 s f :=
⟨hs, λ _ _ _ _ _ _ _ _ _, by rw [f.map_add, f.map_smul, f.map_smul]⟩
/-- A linear map is concave. -/
lemma linear_map.concave_on (f : E →ₗ[𝕜] β) {s : set E} (hs : convex 𝕜 s) : concave_on 𝕜 s f :=
⟨hs, λ _ _ _ _ _ _ _ _ _, by rw [f.map_add, f.map_smul, f.map_smul]⟩
section linear_order
variables [linear_order E] {s : set E} {f : E → β}
/-- For a function on a convex set in a linear ordered space (where the order and the algebraic
structures aren't necessarily compatible), in order to prove that it is convex, it suffices to
verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` only for `x < y` and positive `a`,
`b`. The main use case is `E = 𝕜` however one can apply it, e.g., to `𝕜^n` with lexicographic order.
-/
lemma linear_order.convex_on_of_lt (hs : convex 𝕜 s)
(hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 →
f (a • x + b • y) ≤ a • f x + b • f y) : convex_on 𝕜 s f :=
begin
refine convex_on_iff_forall_pos_ne.2 ⟨hs, λ x y hx hy hxy a b ha hb hab, _⟩,
wlog h : x ≤ y using [x y a b, y x b a],
{ exact le_total _ _ },
exact hf hx hy (h.lt_of_ne hxy) ha hb hab,
end
/-- For a function on a convex set in a linear ordered space (where the order and the algebraic
structures aren't necessarily compatible), in order to prove that it is concave it suffices to
verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` for `x < y` and positive `a`, `b`. The
main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/
lemma linear_order.concave_on_of_lt (hs : convex 𝕜 s)
(hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 →
a • f x + b • f y ≤ f (a • x + b • y)) : concave_on 𝕜 s f :=
@linear_order.convex_on_of_lt _ _ (order_dual β) _ _ _ _ _ _ s f hs hf
end linear_order
end module
section module
variables [module 𝕜 E] [module 𝕜 F] [has_scalar 𝕜 β]
/-- If `g` is convex on `s`, so is `(f ∘ g)` on `f ⁻¹' s` for a linear `f`. -/
lemma convex_on.comp_linear_map {f : F → β} {s : set F} (hf : convex_on 𝕜 s f) (g : E →ₗ[𝕜] F) :
convex_on 𝕜 (g ⁻¹' s) (f ∘ g) :=
⟨hf.1.linear_preimage _, λ x y hx hy a b ha hb hab,
calc
f (g (a • x + b • y)) = f (a • (g x) + b • (g y)) : by rw [g.map_add, g.map_smul, g.map_smul]
... ≤ a • f (g x) + b • f (g y) : hf.2 hx hy ha hb hab⟩
/-- If `g` is concave on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/
lemma concave_on.comp_linear_map {f : F → β} {s : set F} (hf : concave_on 𝕜 s f) (g : E →ₗ[𝕜] F) :
concave_on 𝕜 (g ⁻¹' s) (f ∘ g) :=
@convex_on.comp_linear_map 𝕜 E F (order_dual β) _ _ _ _ _ _ _ f s hf g
end module
end ordered_add_comm_monoid
section ordered_cancel_add_comm_monoid
variables [ordered_cancel_add_comm_monoid β]
section module
variables [module 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f : E → β}
lemma convex_on.convex_lt (hf : convex_on 𝕜 s f) (r : β) : convex 𝕜 {x ∈ s | f x < r} :=
convex_iff_forall_pos.2 $ λ x y hx hy a b ha hb hab, ⟨hf.1 hx.1 hy.1 ha.le hb.le hab,
calc
f (a • x + b • y)
≤ a • f x + b • f y : hf.2 hx.1 hy.1 ha.le hb.le hab
... < a • r + b • r : add_lt_add_of_lt_of_le (smul_lt_smul_of_pos hx.2 ha)
(smul_le_smul_of_nonneg hy.2.le hb.le)
... = r : convex.combo_self hab _⟩
lemma concave_on.convex_lt (hf : concave_on 𝕜 s f) (r : β) : convex 𝕜 {x ∈ s | r < f x} :=
@convex_on.convex_lt 𝕜 E (order_dual β) _ _ _ _ _ _ _ f hf r
lemma convex_on.convex_strict_epigraph (hf : convex_on 𝕜 s f) :
convex 𝕜 {p : E × β | p.1 ∈ s ∧ f p.1 < p.2} :=
begin
rw convex_iff_forall_pos,
rintro ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab,
refine ⟨hf.1 hx hy ha.le hb.le hab, _⟩,
calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha.le hb.le hab
... < a • r + b • t : add_lt_add (smul_lt_smul_of_pos hr ha)
(smul_lt_smul_of_pos ht hb)
end
lemma concave_on.convex_strict_hypograph (hf : concave_on 𝕜 s f) :
convex 𝕜 {p : E × β | p.1 ∈ s ∧ p.2 < f p.1} :=
@convex_on.convex_strict_epigraph 𝕜 E (order_dual β) _ _ _ _ _ _ _ _ hf
end module
end ordered_cancel_add_comm_monoid
section linear_ordered_add_comm_monoid
variables [linear_ordered_add_comm_monoid β] [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β]
{s : set E} {f g : E → β}
/-- The pointwise maximum of convex functions is convex. -/
lemma convex_on.sup (hf : convex_on 𝕜 s f) (hg : convex_on 𝕜 s g) :
convex_on 𝕜 s (f ⊔ g) :=
begin
refine ⟨hf.left, λ x y hx hy a b ha hb hab, sup_le _ _⟩,
{ calc f (a • x + b • y) ≤ a • f x + b • f y : hf.right hx hy ha hb hab
... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add
(smul_le_smul_of_nonneg le_sup_left ha)
(smul_le_smul_of_nonneg le_sup_left hb) },
{ calc g (a • x + b • y) ≤ a • g x + b • g y : hg.right hx hy ha hb hab
... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add
(smul_le_smul_of_nonneg le_sup_right ha)
(smul_le_smul_of_nonneg le_sup_right hb) }
end
/-- The pointwise minimum of concave functions is concave. -/
lemma concave_on.inf (hf : concave_on 𝕜 s f) (hg : concave_on 𝕜 s g) :
concave_on 𝕜 s (f ⊓ g) :=
@convex_on.sup 𝕜 E (order_dual β) _ _ _ _ _ _ _ f g hf hg
/-- A convex function on a segment is upper-bounded by the max of its endpoints. -/
lemma convex_on.le_on_segment' (hf : convex_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s)
{a b : 𝕜} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) :
f (a • x + b • y) ≤ max (f x) (f y) :=
calc
f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab
... ≤ a • max (f x) (f y) + b • max (f x) (f y) :
add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha)
(smul_le_smul_of_nonneg (le_max_right _ _) hb)
... = max (f x) (f y) : convex.combo_self hab _
/-- A concave function on a segment is lower-bounded by the min of its endpoints. -/
lemma concave_on.le_on_segment' (hf : concave_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s)
{a b : 𝕜} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) :
min (f x) (f y) ≤ f (a • x + b • y) :=
@convex_on.le_on_segment' 𝕜 E (order_dual β) _ _ _ _ _ _ _ f hf x y hx hy a b ha hb hab
/-- A convex function on a segment is upper-bounded by the max of its endpoints. -/
lemma convex_on.le_on_segment (hf : convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s)
(hz : z ∈ [x -[𝕜] y]) :
f z ≤ max (f x) (f y) :=
let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.le_on_segment' hx hy ha hb hab
/-- A concave function on a segment is lower-bounded by the min of its endpoints. -/
lemma concave_on.le_on_segment (hf : concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s)
(hz : z ∈ [x -[𝕜] y]) :
min (f x) (f y) ≤ f z :=
@convex_on.le_on_segment 𝕜 E (order_dual β) _ _ _ _ _ _ _ f hf x y z hx hy hz
end linear_ordered_add_comm_monoid
section linear_ordered_cancel_add_comm_monoid
variables [linear_ordered_cancel_add_comm_monoid β]
section ordered_smul
variables [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f g : E → β}
lemma convex_on.le_left_of_right_le' (hf : convex_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s)
{a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) (hfy : f y ≤ f (a • x + b • y)) :
f (a • x + b • y) ≤ f x :=
le_of_not_lt $ λ h, lt_irrefl (f (a • x + b • y)) $
calc
f (a • x + b • y)
≤ a • f x + b • f y : hf.2 hx hy ha.le hb hab
... < a • f (a • x + b • y) + b • f (a • x + b • y)
: add_lt_add_of_lt_of_le (smul_lt_smul_of_pos h ha) (smul_le_smul_of_nonneg hfy hb)
... = f (a • x + b • y) : convex.combo_self hab _
lemma concave_on.left_le_of_le_right' (hf : concave_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s)
{a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) (hfy : f (a • x + b • y) ≤ f y) :
f x ≤ f (a • x + b • y) :=
@convex_on.le_left_of_right_le' 𝕜 E (order_dual β) _ _ _ _ _ _ _ f hf x y hx hy a b ha hb hab hfy
lemma convex_on.le_right_of_left_le' (hf : convex_on 𝕜 s f) {x y : E} {a b : 𝕜}
(hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1)
(hfx : f x ≤ f (a • x + b • y)) :
f (a • x + b • y) ≤ f y :=
begin
rw add_comm at ⊢ hab hfx,
exact hf.le_left_of_right_le' hy hx hb ha hab hfx,
end
lemma concave_on.le_right_of_left_le' (hf : concave_on 𝕜 s f) {x y : E} {a b : 𝕜}
(hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1)
(hfx : f (a • x + b • y) ≤ f x) :
f y ≤ f (a • x + b • y) :=
@convex_on.le_right_of_left_le' 𝕜 E (order_dual β) _ _ _ _ _ _ _ f hf x y a b hx hy ha hb hab hfx
lemma convex_on.le_left_of_right_le (hf : convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hyz : f y ≤ f z) :
f z ≤ f x :=
begin
obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz,
exact hf.le_left_of_right_le' hx hy ha hb.le hab hyz,
end
lemma concave_on.left_le_of_le_right (hf : concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hyz : f z ≤ f y) :
f x ≤ f z :=
@convex_on.le_left_of_right_le 𝕜 E (order_dual β) _ _ _ _ _ _ _ f hf x y z hx hy hz hyz
lemma convex_on.le_right_of_left_le (hf : convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hxz : f x ≤ f z) :
f z ≤ f y :=
begin
obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz,
exact hf.le_right_of_left_le' hx hy ha.le hb hab hxz,
end
lemma concave_on.le_right_of_left_le (hf : concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hxz : f z ≤ f x) :
f y ≤ f z :=
@convex_on.le_right_of_left_le 𝕜 E (order_dual β) _ _ _ _ _ _ _ f hf x y z hx hy hz hxz
end ordered_smul
end linear_ordered_cancel_add_comm_monoid
section ordered_add_comm_group
variables [ordered_add_comm_group β] [has_scalar 𝕜 E] [module 𝕜 β] {s : set E} {f : E → β}
/-- A function `-f` is convex iff `f` is concave. -/
@[simp] lemma neg_convex_on_iff : convex_on 𝕜 s (-f) ↔ concave_on 𝕜 s f :=
begin
split,
{ rintro ⟨hconv, h⟩,
refine ⟨hconv, λ x y hx hy a b ha hb hab, _⟩,
simp [neg_apply, neg_le, add_comm] at h,
exact h hx hy ha hb hab },
{ rintro ⟨hconv, h⟩,
refine ⟨hconv, λ x y hx hy a b ha hb hab, _⟩,
rw ←neg_le_neg_iff,
simp_rw [neg_add, pi.neg_apply, smul_neg, neg_neg],
exact h hx hy ha hb hab }
end
/-- A function `-f` is concave iff `f` is convex. -/
@[simp] lemma neg_concave_on_iff : concave_on 𝕜 s (-f) ↔ convex_on 𝕜 s f:=
by rw [← neg_convex_on_iff, neg_neg f]
alias neg_convex_on_iff ↔ _ concave_on.neg
alias neg_concave_on_iff ↔ _ convex_on.neg
end ordered_add_comm_group
end add_comm_monoid
end ordered_semiring
section ordered_comm_semiring
variables [ordered_comm_semiring 𝕜] [add_comm_monoid E]
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β]
section module
variables [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f : E → β}
lemma convex_on.smul {c : 𝕜} (hc : 0 ≤ c)
(hf : convex_on 𝕜 s f) : convex_on 𝕜 s (λ x, c • f x) :=
⟨hf.1, λ x y hx hy a b ha hb hab,
calc
c • f (a • x + b • y) ≤ c • (a • f x + b • f y)
: smul_le_smul_of_nonneg (hf.2 hx hy ha hb hab) hc
... = a • (c • f x) + b • (c • f y)
: by rw [smul_add, smul_comm c, smul_comm c]; apply_instance⟩
lemma concave_on.smul {c : 𝕜} (hc : 0 ≤ c)
(hf : concave_on 𝕜 s f) : concave_on 𝕜 s (λ x, c • f x) :=
@convex_on.smul _ _ (order_dual β) _ _ _ _ _ _ _ f c hc hf
end module
end ordered_add_comm_monoid
end ordered_comm_semiring
section ordered_ring
variables [linear_ordered_field 𝕜] [add_comm_group E] [add_comm_group F]
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β]
section module
variables [module 𝕜 E] [module 𝕜 F] [has_scalar 𝕜 β]
/-- If a function is convex on `s`, it remains convex when precomposed by an affine map. -/
lemma convex_on.comp_affine_map {f : F → β} (g : E →ᵃ[𝕜] F) {s : set F} (hf : convex_on 𝕜 s f) :
convex_on 𝕜 (g ⁻¹' s) (f ∘ g) :=
⟨hf.1.affine_preimage _, λ x y hx hy a b ha hb hab,
calc
(f ∘ g) (a • x + b • y) = f (g (a • x + b • y)) : rfl
... = f (a • (g x) + b • (g y)) : by rw [convex.combo_affine_apply hab]
... ≤ a • f (g x) + b • f (g y) : hf.2 hx hy ha hb hab⟩
/-- If a function is concave on `s`, it remains concave when precomposed by an affine map. -/
lemma concave_on.comp_affine_map {f : F → β} (g : E →ᵃ[𝕜] F) {s : set F} (hf : concave_on 𝕜 s f) :
concave_on 𝕜 (g ⁻¹' s) (f ∘ g) :=
@convex_on.comp_affine_map _ _ _ (order_dual β) _ _ _ _ _ _ _ f g s hf
end module
end ordered_add_comm_monoid
end ordered_ring
section linear_ordered_field
variables [linear_ordered_field 𝕜] [add_comm_monoid E]
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β]
section has_scalar
variables [has_scalar 𝕜 E] [has_scalar 𝕜 β] {s : set E}
lemma convex_on_iff_div {f : E → β} :
convex_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → 0 < a + b
→ f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) • f x + (b/(a+b)) • f y :=
and_congr iff.rfl
⟨begin
intros h x y hx hy a b ha hb hab,
apply h hx hy (div_nonneg ha hab.le) (div_nonneg hb hab.le),
rw [←add_div, div_self hab.ne'],
end,
begin
intros h x y hx hy a b ha hb hab,
simpa [hab, zero_lt_one] using h hx hy ha hb,
end⟩
lemma concave_on_iff_div {f : E → β} :
concave_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b
→ 0 < a + b → (a/(a+b)) • f x + (b/(a+b)) • f y ≤ f ((a/(a+b)) • x + (b/(a+b)) • y) :=
@convex_on_iff_div _ _ (order_dual β) _ _ _ _ _ _ _
end has_scalar
end ordered_add_comm_monoid
end linear_ordered_field
|
4ffb5907a5cece828a947eb4984c11bd4e8343c0 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/ordered_group.lean | c5b69b1e54b0b496cfc2b857ee8a4305ca869a9f | [] | 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 | 42,477 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.ordered_monoid
import Mathlib.PostPort
universes u l u_1 u_2
namespace Mathlib
/-!
# Ordered groups
This file develops the basics of ordered groups.
## Implementation details
Unfortunately, the number of `'` appended to lemmas in this file
may differ between the multiplicative and the additive version of a lemma.
The reason is that we did not want to change existing names in the library.
-/
/-- An ordered additive commutative group is an additive commutative group
with a partial order in which addition is strictly monotone. -/
class ordered_add_comm_group (α : Type u)
extends partial_order α, add_comm_group α
where
add_le_add_left : ∀ (a b : α), a ≤ b → ∀ (c : α), c + a ≤ c + b
/-- An ordered commutative group is an commutative group
with a partial order in which multiplication is strictly monotone. -/
class ordered_comm_group (α : Type u)
extends comm_group α, partial_order α
where
mul_le_mul_left : ∀ (a b : α), a ≤ b → ∀ (c : α), c * a ≤ c * b
/--The units of an ordered commutative monoid form an ordered commutative group. -/
protected instance add_units.ordered_add_comm_group {α : Type u} [ordered_add_comm_monoid α] : ordered_add_comm_group (add_units α) :=
ordered_add_comm_group.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub
sorry sorry partial_order.le partial_order.lt sorry sorry sorry sorry
theorem ordered_comm_group.mul_lt_mul_left' {α : Type u} [ordered_comm_group α] (a : α) (b : α) (h : a < b) (c : α) : c * a < c * b := sorry
theorem ordered_comm_group.le_of_mul_le_mul_left {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : a * b ≤ a * c) : b ≤ c := sorry
theorem ordered_comm_group.lt_of_mul_lt_mul_left {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : a * b < a * c) : b < c := sorry
protected instance ordered_add_comm_group.to_ordered_cancel_add_comm_monoid (α : Type u) [s : ordered_add_comm_group α] : ordered_cancel_add_comm_monoid α :=
ordered_cancel_add_comm_monoid.mk ordered_add_comm_group.add ordered_add_comm_group.add_assoc sorry
ordered_add_comm_group.zero ordered_add_comm_group.zero_add ordered_add_comm_group.add_zero
ordered_add_comm_group.add_comm sorry ordered_add_comm_group.le ordered_add_comm_group.lt
ordered_add_comm_group.le_refl ordered_add_comm_group.le_trans ordered_add_comm_group.le_antisymm
ordered_add_comm_group.add_le_add_left ordered_add_comm_group.le_of_add_le_add_left
theorem neg_le_neg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : a ≤ b) : -b ≤ -a := sorry
theorem le_of_inv_le_inv {α : Type u} [ordered_comm_group α] {a : α} {b : α} (h : b⁻¹ ≤ (a⁻¹)) : a ≤ b := sorry
theorem one_le_of_inv_le_one {α : Type u} [ordered_comm_group α] {a : α} (h : a⁻¹ ≤ 1) : 1 ≤ a :=
(fun (this : a⁻¹ ≤ (1⁻¹)) => le_of_inv_le_inv this) (eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ ≤ (1⁻¹))) one_inv)) h)
theorem inv_le_one_of_one_le {α : Type u} [ordered_comm_group α] {a : α} (h : 1 ≤ a) : a⁻¹ ≤ 1 :=
(fun (this : a⁻¹ ≤ (1⁻¹)) => eq.mp (Eq._oldrec (Eq.refl (a⁻¹ ≤ (1⁻¹))) one_inv) this) (inv_le_inv' h)
theorem le_one_of_one_le_inv {α : Type u} [ordered_comm_group α] {a : α} (h : 1 ≤ (a⁻¹)) : a ≤ 1 :=
(fun (this : 1⁻¹ ≤ (a⁻¹)) => le_of_inv_le_inv this) (eq.mpr (id (Eq._oldrec (Eq.refl (1⁻¹ ≤ (a⁻¹))) one_inv)) h)
theorem neg_nonneg_of_nonpos {α : Type u} [ordered_add_comm_group α] {a : α} (h : a ≤ 0) : 0 ≤ -a :=
(fun (this : -0 ≤ -a) => eq.mp (Eq._oldrec (Eq.refl (-0 ≤ -a)) neg_zero) this) (neg_le_neg h)
theorem neg_lt_neg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : a < b) : -b < -a := sorry
theorem lt_of_neg_lt_neg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : -b < -a) : a < b :=
neg_neg a ▸ neg_neg b ▸ neg_lt_neg h
theorem pos_of_neg_neg {α : Type u} [ordered_add_comm_group α] {a : α} (h : -a < 0) : 0 < a :=
(fun (this : -a < -0) => lt_of_neg_lt_neg this) (eq.mpr (id (Eq._oldrec (Eq.refl (-a < -0)) neg_zero)) h)
theorem inv_inv_of_one_lt {α : Type u} [ordered_comm_group α] {a : α} (h : 1 < a) : a⁻¹ < 1 :=
(fun (this : a⁻¹ < (1⁻¹)) => eq.mp (Eq._oldrec (Eq.refl (a⁻¹ < (1⁻¹))) one_inv) this) (inv_lt_inv' h)
theorem inv_of_one_lt_inv {α : Type u} [ordered_comm_group α] {a : α} (h : 1 < (a⁻¹)) : a < 1 :=
(fun (this : 1⁻¹ < (a⁻¹)) => lt_of_inv_lt_inv this) (eq.mpr (id (Eq._oldrec (Eq.refl (1⁻¹ < (a⁻¹))) one_inv)) h)
theorem one_lt_inv_of_inv {α : Type u} [ordered_comm_group α] {a : α} (h : a < 1) : 1 < (a⁻¹) :=
(fun (this : 1⁻¹ < (a⁻¹)) => eq.mp (Eq._oldrec (Eq.refl (1⁻¹ < (a⁻¹))) one_inv) this) (inv_lt_inv' h)
theorem le_inv_of_le_inv {α : Type u} [ordered_comm_group α] {a : α} {b : α} (h : a ≤ (b⁻¹)) : b ≤ (a⁻¹) :=
eq.mp (Eq._oldrec (Eq.refl (b⁻¹⁻¹ ≤ (a⁻¹))) (inv_inv b)) (inv_le_inv' h)
theorem neg_le_of_neg_le {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : -a ≤ b) : -b ≤ a :=
eq.mp (Eq._oldrec (Eq.refl (-b ≤ --a)) (neg_neg a)) (neg_le_neg h)
theorem lt_inv_of_lt_inv {α : Type u} [ordered_comm_group α] {a : α} {b : α} (h : a < (b⁻¹)) : b < (a⁻¹) :=
eq.mp (Eq._oldrec (Eq.refl (b⁻¹⁻¹ < (a⁻¹))) (inv_inv b)) (inv_lt_inv' h)
theorem neg_lt_of_neg_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : -a < b) : -b < a :=
eq.mp (Eq._oldrec (Eq.refl (-b < --a)) (neg_neg a)) (neg_lt_neg h)
theorem add_le_of_le_neg_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : b ≤ -a + c) : a + b ≤ c :=
eq.mp (Eq._oldrec (Eq.refl (a + b ≤ a + (-a + c))) (add_neg_cancel_left a c)) (add_le_add_left h a)
theorem le_inv_mul_of_mul_le {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : a * b ≤ c) : b ≤ a⁻¹ * c :=
eq.mp (Eq._oldrec (Eq.refl (a⁻¹ * (a * b) ≤ a⁻¹ * c)) (inv_mul_cancel_left a b)) (mul_le_mul_left' h (a⁻¹))
theorem le_mul_of_inv_mul_le {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : b⁻¹ * a ≤ c) : a ≤ b * c :=
eq.mp (Eq._oldrec (Eq.refl (b * (b⁻¹ * a) ≤ b * c)) (mul_inv_cancel_left b a)) (mul_le_mul_left' h b)
theorem inv_mul_le_of_le_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : a ≤ b * c) : b⁻¹ * a ≤ c :=
eq.mp (Eq._oldrec (Eq.refl (b⁻¹ * a ≤ b⁻¹ * (b * c))) (inv_mul_cancel_left b c)) (mul_le_mul_left' h (b⁻¹))
theorem le_mul_of_inv_mul_le_left {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : b⁻¹ * a ≤ c) : a ≤ b * c :=
le_mul_of_inv_mul_le h
theorem neg_add_le_left_of_le_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : a ≤ b + c) : -b + a ≤ c :=
neg_add_le_of_le_add h
theorem le_add_of_neg_add_le_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : -c + a ≤ b) : a ≤ b + c :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ b + c)) (add_comm b c))) (le_add_of_neg_add_le h)
theorem inv_mul_le_right_of_le_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : a ≤ b * c) : c⁻¹ * a ≤ b :=
inv_mul_le_left_of_le_mul (eq.mp (Eq._oldrec (Eq.refl (a ≤ b * c)) (mul_comm b c)) h)
theorem mul_lt_of_lt_inv_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : b < a⁻¹ * c) : a * b < c :=
eq.mp (Eq._oldrec (Eq.refl (a * b < a * (a⁻¹ * c))) (mul_inv_cancel_left a c)) (mul_lt_mul_left' h a)
theorem lt_neg_add_of_add_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : a + b < c) : b < -a + c :=
eq.mp (Eq._oldrec (Eq.refl (-a + (a + b) < -a + c)) (neg_add_cancel_left a b)) (add_lt_add_left h (-a))
theorem lt_mul_of_inv_mul_lt {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : b⁻¹ * a < c) : a < b * c :=
eq.mp (Eq._oldrec (Eq.refl (b * (b⁻¹ * a) < b * c)) (mul_inv_cancel_left b a)) (mul_lt_mul_left' h b)
theorem neg_add_lt_of_lt_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : a < b + c) : -b + a < c :=
eq.mp (Eq._oldrec (Eq.refl (-b + a < -b + (b + c))) (neg_add_cancel_left b c)) (add_lt_add_left h (-b))
theorem lt_add_of_neg_add_lt_left {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : -b + a < c) : a < b + c :=
lt_add_of_neg_add_lt h
theorem neg_add_lt_left_of_lt_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : a < b + c) : -b + a < c :=
neg_add_lt_of_lt_add h
theorem lt_add_of_neg_add_lt_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : -c + a < b) : a < b + c :=
eq.mpr (id (Eq._oldrec (Eq.refl (a < b + c)) (add_comm b c))) (lt_add_of_neg_add_lt h)
theorem neg_add_lt_right_of_lt_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : a < b + c) : -c + a < b :=
neg_add_lt_of_lt_add (eq.mp (Eq._oldrec (Eq.refl (a < b + c)) (add_comm b c)) h)
@[simp] theorem neg_neg_iff_pos {α : Type u} [ordered_add_comm_group α] {a : α} : -a < 0 ↔ 0 < a :=
{ mp := pos_of_neg_neg, mpr := neg_neg_of_pos }
@[simp] theorem neg_le_neg_iff {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : -a ≤ -b ↔ b ≤ a := sorry
theorem inv_le' {α : Type u} [ordered_comm_group α] {a : α} {b : α} : a⁻¹ ≤ b ↔ b⁻¹ ≤ a :=
(fun (this : a⁻¹ ≤ (b⁻¹⁻¹) ↔ b⁻¹ ≤ a) => eq.mp (Eq._oldrec (Eq.refl (a⁻¹ ≤ (b⁻¹⁻¹) ↔ b⁻¹ ≤ a)) (inv_inv b)) this)
inv_le_inv_iff
theorem le_inv' {α : Type u} [ordered_comm_group α] {a : α} {b : α} : a ≤ (b⁻¹) ↔ b ≤ (a⁻¹) :=
(fun (this : a⁻¹⁻¹ ≤ (b⁻¹) ↔ b ≤ (a⁻¹)) => eq.mp (Eq._oldrec (Eq.refl (a⁻¹⁻¹ ≤ (b⁻¹) ↔ b ≤ (a⁻¹))) (inv_inv a)) this)
inv_le_inv_iff
theorem inv_le_iff_one_le_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} : a⁻¹ ≤ b ↔ 1 ≤ b * a :=
iff.trans (iff.symm (mul_le_mul_iff_right a))
(eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * a ≤ b * a ↔ 1 ≤ b * a)) (inv_mul_self a))) (iff.refl (1 ≤ b * a)))
theorem neg_le_iff_add_nonneg' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : -a ≤ b ↔ 0 ≤ a + b :=
iff.trans (iff.symm (add_le_add_iff_left a))
(eq.mpr (id (Eq._oldrec (Eq.refl (a + -a ≤ a + b ↔ 0 ≤ a + b)) (add_neg_self a))) (iff.refl (0 ≤ a + b)))
theorem inv_lt_iff_one_lt_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} : a⁻¹ < b ↔ 1 < b * a :=
iff.trans (iff.symm (mul_lt_mul_iff_right a))
(eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * a < b * a ↔ 1 < b * a)) (inv_mul_self a))) (iff.refl (1 < b * a)))
theorem neg_lt_iff_pos_add' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : -a < b ↔ 0 < a + b :=
iff.trans (iff.symm (add_lt_add_iff_left a))
(eq.mpr (id (Eq._oldrec (Eq.refl (a + -a < a + b ↔ 0 < a + b)) (add_neg_self a))) (iff.refl (0 < a + b)))
theorem le_neg_iff_add_nonpos {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a ≤ -b ↔ a + b ≤ 0 :=
iff.trans (iff.symm (add_le_add_iff_right b))
(eq.mpr (id (Eq._oldrec (Eq.refl (a + b ≤ -b + b ↔ a + b ≤ 0)) (neg_add_self b))) (iff.refl (a + b ≤ 0)))
theorem le_inv_iff_mul_le_one' {α : Type u} [ordered_comm_group α] {a : α} {b : α} : a ≤ (b⁻¹) ↔ b * a ≤ 1 :=
iff.trans (iff.symm (mul_le_mul_iff_left b))
(eq.mpr (id (Eq._oldrec (Eq.refl (b * a ≤ b * (b⁻¹) ↔ b * a ≤ 1)) (mul_inv_self b))) (iff.refl (b * a ≤ 1)))
theorem lt_neg_iff_add_neg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a < -b ↔ a + b < 0 :=
iff.trans (iff.symm (add_lt_add_iff_right b))
(eq.mpr (id (Eq._oldrec (Eq.refl (a + b < -b + b ↔ a + b < 0)) (neg_add_self b))) (iff.refl (a + b < 0)))
theorem lt_inv_iff_mul_lt_one' {α : Type u} [ordered_comm_group α] {a : α} {b : α} : a < (b⁻¹) ↔ b * a < 1 :=
iff.trans (iff.symm (mul_lt_mul_iff_left b))
(eq.mpr (id (Eq._oldrec (Eq.refl (b * a < b * (b⁻¹) ↔ b * a < 1)) (mul_inv_self b))) (iff.refl (b * a < 1)))
@[simp] theorem inv_le_one' {α : Type u} [ordered_comm_group α] {a : α} : a⁻¹ ≤ 1 ↔ 1 ≤ a :=
(fun (this : a⁻¹ ≤ (1⁻¹) ↔ 1 ≤ a) => eq.mp (Eq._oldrec (Eq.refl (a⁻¹ ≤ (1⁻¹) ↔ 1 ≤ a)) one_inv) this) inv_le_inv_iff
@[simp] theorem one_le_inv' {α : Type u} [ordered_comm_group α] {a : α} : 1 ≤ (a⁻¹) ↔ a ≤ 1 :=
(fun (this : 1⁻¹ ≤ (a⁻¹) ↔ a ≤ 1) => eq.mp (Eq._oldrec (Eq.refl (1⁻¹ ≤ (a⁻¹) ↔ a ≤ 1)) one_inv) this) inv_le_inv_iff
theorem inv_le_self {α : Type u} [ordered_comm_group α] {a : α} (h : 1 ≤ a) : a⁻¹ ≤ a :=
le_trans (iff.mpr inv_le_one' h) h
theorem self_le_inv {α : Type u} [ordered_comm_group α] {a : α} (h : a ≤ 1) : a ≤ (a⁻¹) :=
le_trans h (iff.mpr one_le_inv' h)
@[simp] theorem neg_lt_neg_iff {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : -a < -b ↔ b < a := sorry
theorem neg_lt_zero {α : Type u} [ordered_add_comm_group α] {a : α} : -a < 0 ↔ 0 < a :=
(fun (this : -a < -0 ↔ 0 < a) => eq.mp (Eq._oldrec (Eq.refl (-a < -0 ↔ 0 < a)) neg_zero) this) neg_lt_neg_iff
theorem one_lt_inv' {α : Type u} [ordered_comm_group α] {a : α} : 1 < (a⁻¹) ↔ a < 1 :=
(fun (this : 1⁻¹ < (a⁻¹) ↔ a < 1) => eq.mp (Eq._oldrec (Eq.refl (1⁻¹ < (a⁻¹) ↔ a < 1)) one_inv) this) inv_lt_inv_iff
theorem neg_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : -a < b ↔ -b < a :=
(fun (this : -a < --b ↔ -b < a) => eq.mp (Eq._oldrec (Eq.refl (-a < --b ↔ -b < a)) (neg_neg b)) this) neg_lt_neg_iff
theorem lt_neg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a < -b ↔ b < -a :=
(fun (this : --a < -b ↔ b < -a) => eq.mp (Eq._oldrec (Eq.refl ( --a < -b ↔ b < -a)) (neg_neg a)) this) neg_lt_neg_iff
theorem neg_lt_self {α : Type u} [ordered_add_comm_group α] {a : α} (h : 0 < a) : -a < a :=
has_lt.lt.trans (iff.mpr neg_lt_zero h) h
theorem le_inv_mul_iff_mul_le {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} : b ≤ a⁻¹ * c ↔ a * b ≤ c :=
(fun (this : a⁻¹ * (a * b) ≤ a⁻¹ * c ↔ a * b ≤ c) =>
eq.mp (Eq._oldrec (Eq.refl (a⁻¹ * (a * b) ≤ a⁻¹ * c ↔ a * b ≤ c)) (inv_mul_cancel_left a b)) this)
(mul_le_mul_iff_left (a⁻¹))
@[simp] theorem inv_mul_le_iff_le_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} : b⁻¹ * a ≤ c ↔ a ≤ b * c :=
(fun (this : b⁻¹ * a ≤ b⁻¹ * (b * c) ↔ a ≤ b * c) =>
eq.mp (Eq._oldrec (Eq.refl (b⁻¹ * a ≤ b⁻¹ * (b * c) ↔ a ≤ b * c)) (inv_mul_cancel_left b c)) this)
(mul_le_mul_iff_left (b⁻¹))
theorem mul_inv_le_iff_le_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} : a * (c⁻¹) ≤ b ↔ a ≤ b * c := sorry
@[simp] theorem mul_inv_le_iff_le_mul' {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} : a * (b⁻¹) ≤ c ↔ a ≤ b * c :=
eq.mpr (id (Eq._oldrec (Eq.refl (a * (b⁻¹) ≤ c ↔ a ≤ b * c)) (Eq.symm (propext inv_mul_le_iff_le_mul))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a * (b⁻¹) ≤ c ↔ b⁻¹ * a ≤ c)) (mul_comm a (b⁻¹)))) (iff.refl (b⁻¹ * a ≤ c)))
theorem neg_add_le_iff_le_add' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : -c + a ≤ b ↔ a ≤ b + c :=
eq.mpr (id (Eq._oldrec (Eq.refl (-c + a ≤ b ↔ a ≤ b + c)) (propext neg_add_le_iff_le_add)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ c + b ↔ a ≤ b + c)) (add_comm c b))) (iff.refl (a ≤ b + c)))
@[simp] theorem lt_neg_add_iff_add_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : b < -a + c ↔ a + b < c :=
(fun (this : -a + (a + b) < -a + c ↔ a + b < c) =>
eq.mp (Eq._oldrec (Eq.refl (-a + (a + b) < -a + c ↔ a + b < c)) (neg_add_cancel_left a b)) this)
(add_lt_add_iff_left (-a))
@[simp] theorem inv_mul_lt_iff_lt_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} : b⁻¹ * a < c ↔ a < b * c :=
(fun (this : b⁻¹ * a < b⁻¹ * (b * c) ↔ a < b * c) =>
eq.mp (Eq._oldrec (Eq.refl (b⁻¹ * a < b⁻¹ * (b * c) ↔ a < b * c)) (inv_mul_cancel_left b c)) this)
(mul_lt_mul_iff_left (b⁻¹))
theorem inv_mul_lt_iff_lt_mul_right {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} : c⁻¹ * a < b ↔ a < b * c :=
eq.mpr (id (Eq._oldrec (Eq.refl (c⁻¹ * a < b ↔ a < b * c)) (propext inv_mul_lt_iff_lt_mul)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a < c * b ↔ a < b * c)) (mul_comm c b))) (iff.refl (a < b * c)))
theorem add_neg_le_add_neg_iff {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} {d : α} : a + -b ≤ c + -d ↔ a + d ≤ c + b := sorry
theorem sub_le_sub {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} {d : α} (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := sorry
theorem sub_lt_sub {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} {d : α} (hab : a < b) (hcd : c < d) : a - d < b - c := sorry
@[simp] theorem sub_le_self_iff {α : Type u} [ordered_add_comm_group α] (a : α) {b : α} : a - b ≤ a ↔ 0 ≤ b := sorry
theorem sub_le_self {α : Type u} [ordered_add_comm_group α] (a : α) {b : α} : 0 ≤ b → a - b ≤ a :=
iff.mpr (sub_le_self_iff a)
@[simp] theorem sub_lt_self_iff {α : Type u} [ordered_add_comm_group α] (a : α) {b : α} : a - b < a ↔ 0 < b := sorry
theorem sub_lt_self {α : Type u} [ordered_add_comm_group α] (a : α) {b : α} : 0 < b → a - b < a :=
iff.mpr (sub_lt_self_iff a)
theorem sub_le_sub_iff {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} {d : α} : a - b ≤ c - d ↔ a + d ≤ c + b := sorry
@[simp] theorem sub_le_sub_iff_left {α : Type u} [ordered_add_comm_group α] (a : α) {b : α} {c : α} : a - b ≤ a - c ↔ c ≤ b := sorry
theorem sub_le_sub_left {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : a ≤ b) (c : α) : c - b ≤ c - a :=
iff.mpr (sub_le_sub_iff_left c) h
@[simp] theorem sub_le_sub_iff_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (c : α) : a - c ≤ b - c ↔ a ≤ b := sorry
theorem sub_le_sub_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : a ≤ b) (c : α) : a - c ≤ b - c :=
iff.mpr (sub_le_sub_iff_right c) h
@[simp] theorem sub_lt_sub_iff_left {α : Type u} [ordered_add_comm_group α] (a : α) {b : α} {c : α} : a - b < a - c ↔ c < b := sorry
theorem sub_lt_sub_left {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : a < b) (c : α) : c - b < c - a :=
iff.mpr (sub_lt_sub_iff_left c) h
@[simp] theorem sub_lt_sub_iff_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (c : α) : a - c < b - c ↔ a < b := sorry
theorem sub_lt_sub_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : a < b) (c : α) : a - c < b - c :=
iff.mpr (sub_lt_sub_iff_right c) h
@[simp] theorem sub_nonneg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : 0 ≤ a - b ↔ b ≤ a :=
eq.mpr (id (Eq._oldrec (Eq.refl (0 ≤ a - b ↔ b ≤ a)) (Eq.symm (sub_self a))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a - a ≤ a - b ↔ b ≤ a)) (propext (sub_le_sub_iff_left a)))) (iff.refl (b ≤ a)))
theorem sub_nonneg_of_le {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : b ≤ a → 0 ≤ a - b :=
iff.mpr sub_nonneg
@[simp] theorem sub_nonpos {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a - b ≤ 0 ↔ a ≤ b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a - b ≤ 0 ↔ a ≤ b)) (Eq.symm (sub_self b))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a - b ≤ b - b ↔ a ≤ b)) (propext (sub_le_sub_iff_right b)))) (iff.refl (a ≤ b)))
theorem le_of_sub_nonpos {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a - b ≤ 0 → a ≤ b :=
iff.mp sub_nonpos
@[simp] theorem sub_pos {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : 0 < a - b ↔ b < a :=
eq.mpr (id (Eq._oldrec (Eq.refl (0 < a - b ↔ b < a)) (Eq.symm (sub_self a))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a - a < a - b ↔ b < a)) (propext (sub_lt_sub_iff_left a)))) (iff.refl (b < a)))
theorem lt_of_sub_pos {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : 0 < a - b → b < a :=
iff.mp sub_pos
@[simp] theorem sub_lt_zero {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a - b < 0 ↔ a < b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a - b < 0 ↔ a < b)) (Eq.symm (sub_self b))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a - b < b - b ↔ a < b)) (propext (sub_lt_sub_iff_right b)))) (iff.refl (a < b)))
theorem lt_of_sub_neg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a - b < 0 → a < b :=
iff.mp sub_lt_zero
theorem le_sub_iff_add_le' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : b ≤ c - a ↔ a + b ≤ c := sorry
theorem le_sub_iff_add_le {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a ≤ c - b ↔ a + b ≤ c :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ c - b ↔ a + b ≤ c)) (propext le_sub_iff_add_le')))
(eq.mpr (id (Eq._oldrec (Eq.refl (b + a ≤ c ↔ a + b ≤ c)) (add_comm b a))) (iff.refl (a + b ≤ c)))
theorem add_le_of_le_sub_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a ≤ c - b → a + b ≤ c :=
iff.mp le_sub_iff_add_le
theorem sub_le_iff_le_add' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - b ≤ c ↔ a ≤ b + c := sorry
theorem le_sub_left_of_add_le {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a + b ≤ c → b ≤ c - a :=
iff.mpr le_sub_iff_add_le'
theorem sub_le_iff_le_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - c ≤ b ↔ a ≤ b + c :=
eq.mpr (id (Eq._oldrec (Eq.refl (a - c ≤ b ↔ a ≤ b + c)) (propext sub_le_iff_le_add')))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ c + b ↔ a ≤ b + c)) (add_comm c b))) (iff.refl (a ≤ b + c)))
@[simp] theorem neg_le_sub_iff_le_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : -b ≤ a - c ↔ c ≤ a + b :=
iff.trans le_sub_iff_add_le neg_add_le_iff_le_add'
theorem neg_le_sub_iff_le_add' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : -a ≤ b - c ↔ c ≤ a + b :=
eq.mpr (id (Eq._oldrec (Eq.refl (-a ≤ b - c ↔ c ≤ a + b)) (propext neg_le_sub_iff_le_add)))
(eq.mpr (id (Eq._oldrec (Eq.refl (c ≤ b + a ↔ c ≤ a + b)) (add_comm b a))) (iff.refl (c ≤ a + b)))
theorem sub_le {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - b ≤ c ↔ a - c ≤ b :=
iff.trans sub_le_iff_le_add' (iff.symm sub_le_iff_le_add)
theorem le_sub {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a ≤ b - c ↔ c ≤ b - a :=
iff.trans le_sub_iff_add_le' (iff.symm le_sub_iff_add_le)
theorem lt_sub_iff_add_lt' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : b < c - a ↔ a + b < c := sorry
theorem add_lt_of_lt_sub_left {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : b < c - a → a + b < c :=
iff.mp lt_sub_iff_add_lt'
theorem lt_sub_iff_add_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a < c - b ↔ a + b < c :=
eq.mpr (id (Eq._oldrec (Eq.refl (a < c - b ↔ a + b < c)) (propext lt_sub_iff_add_lt')))
(eq.mpr (id (Eq._oldrec (Eq.refl (b + a < c ↔ a + b < c)) (add_comm b a))) (iff.refl (a + b < c)))
theorem lt_sub_right_of_add_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a + b < c → a < c - b :=
iff.mpr lt_sub_iff_add_lt
theorem sub_lt_iff_lt_add' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - b < c ↔ a < b + c := sorry
theorem lt_add_of_sub_left_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - b < c → a < b + c :=
iff.mp sub_lt_iff_lt_add'
theorem sub_lt_iff_lt_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - c < b ↔ a < b + c :=
eq.mpr (id (Eq._oldrec (Eq.refl (a - c < b ↔ a < b + c)) (propext sub_lt_iff_lt_add')))
(eq.mpr (id (Eq._oldrec (Eq.refl (a < c + b ↔ a < b + c)) (add_comm c b))) (iff.refl (a < b + c)))
theorem sub_right_lt_of_lt_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a < b + c → a - c < b :=
iff.mpr sub_lt_iff_lt_add
@[simp] theorem neg_lt_sub_iff_lt_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : -b < a - c ↔ c < a + b :=
iff.trans lt_sub_iff_add_lt neg_add_lt_iff_lt_add_right
theorem neg_lt_sub_iff_lt_add' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : -a < b - c ↔ c < a + b :=
eq.mpr (id (Eq._oldrec (Eq.refl (-a < b - c ↔ c < a + b)) (propext neg_lt_sub_iff_lt_add)))
(eq.mpr (id (Eq._oldrec (Eq.refl (c < b + a ↔ c < a + b)) (add_comm b a))) (iff.refl (c < a + b)))
theorem sub_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - b < c ↔ a - c < b :=
iff.trans sub_lt_iff_lt_add' (iff.symm sub_lt_iff_lt_add)
theorem lt_sub {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a < b - c ↔ c < b - a :=
iff.trans lt_sub_iff_add_lt' (iff.symm lt_sub_iff_add_lt)
/-!
### Linearly ordered commutative groups
-/
/-- A linearly ordered additive commutative group is an
additive commutative group with a linear order in which
addition is monotone. -/
class linear_ordered_add_comm_group (α : Type u)
extends add_comm_group α, linear_order α
where
add_le_add_left : ∀ (a b : α), a ≤ b → ∀ (c : α), c + a ≤ c + b
/-- A linearly ordered commutative group is a
commutative group with a linear order in which
multiplication is monotone. -/
class linear_ordered_comm_group (α : Type u)
extends linear_order α, comm_group α
where
mul_le_mul_left : ∀ (a b : α), a ≤ b → ∀ (c : α), c * a ≤ c * b
protected instance linear_ordered_comm_group.to_ordered_comm_group (α : Type u) [s : linear_ordered_comm_group α] : ordered_comm_group α :=
ordered_comm_group.mk linear_ordered_comm_group.mul linear_ordered_comm_group.mul_assoc linear_ordered_comm_group.one
linear_ordered_comm_group.one_mul linear_ordered_comm_group.mul_one linear_ordered_comm_group.inv
linear_ordered_comm_group.div linear_ordered_comm_group.mul_left_inv linear_ordered_comm_group.mul_comm
linear_ordered_comm_group.le linear_ordered_comm_group.lt linear_ordered_comm_group.le_refl
linear_ordered_comm_group.le_trans linear_ordered_comm_group.le_antisymm linear_ordered_comm_group.mul_le_mul_left
protected instance linear_ordered_add_comm_group.to_linear_ordered_cancel_add_comm_monoid {α : Type u} [linear_ordered_add_comm_group α] : linear_ordered_cancel_add_comm_monoid α :=
linear_ordered_cancel_add_comm_monoid.mk linear_ordered_add_comm_group.add linear_ordered_add_comm_group.add_assoc sorry
linear_ordered_add_comm_group.zero linear_ordered_add_comm_group.zero_add linear_ordered_add_comm_group.add_zero
linear_ordered_add_comm_group.add_comm sorry linear_ordered_add_comm_group.le linear_ordered_add_comm_group.lt
linear_ordered_add_comm_group.le_refl linear_ordered_add_comm_group.le_trans linear_ordered_add_comm_group.le_antisymm
linear_ordered_add_comm_group.add_le_add_left sorry linear_ordered_add_comm_group.le_total
linear_ordered_add_comm_group.decidable_le linear_ordered_add_comm_group.decidable_eq
linear_ordered_add_comm_group.decidable_lt
theorem linear_ordered_add_comm_group.add_lt_add_left {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (h : a < b) (c : α) : c + a < c + b :=
ordered_add_comm_group.add_lt_add_left a b h c
theorem le_of_forall_pos_le_add {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} [densely_ordered α] (h : ∀ (ε : α), 0 < ε → a ≤ b + ε) : a ≤ b :=
le_of_forall_le_of_dense
fun (c : α) (hc : c > b) => trans_rel_left LessEq (h (c - b) (sub_pos_of_lt hc)) (add_sub_cancel'_right b c)
theorem min_neg_neg {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : min (-a) (-b) = -max a b :=
Eq.symm (monotone.map_max fun (a b : α) => neg_le_neg)
theorem max_neg_neg {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : max (-a) (-b) = -min a b :=
Eq.symm (monotone.map_min fun (a b : α) => neg_le_neg)
theorem min_sub_sub_right {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : min (a - c) (b - c) = min a b - c := sorry
theorem max_sub_sub_right {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : max (a - c) (b - c) = max a b - c := sorry
theorem min_sub_sub_left {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : min (a - b) (a - c) = a - max b c := sorry
theorem max_sub_sub_left {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : max (a - b) (a - c) = a - min b c := sorry
theorem max_zero_sub_eq_self {α : Type u} [linear_ordered_add_comm_group α] (a : α) : max a 0 - max (-a) 0 = a := sorry
/-- `abs a` is the absolute value of `a`. -/
def abs {α : Type u} [linear_ordered_add_comm_group α] (a : α) : α :=
max a (-a)
theorem abs_of_nonneg {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : 0 ≤ a) : abs a = a :=
max_eq_left (has_le.le.trans (iff.mpr neg_nonpos h) h)
theorem abs_of_pos {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : 0 < a) : abs a = a :=
abs_of_nonneg (has_lt.lt.le h)
theorem abs_of_nonpos {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : a ≤ 0) : abs a = -a :=
max_eq_right (has_le.le.trans h (iff.mpr neg_nonneg h))
theorem abs_of_neg {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : a < 0) : abs a = -a :=
abs_of_nonpos (has_lt.lt.le h)
@[simp] theorem abs_zero {α : Type u} [linear_ordered_add_comm_group α] : abs 0 = 0 :=
abs_of_nonneg le_rfl
@[simp] theorem abs_neg {α : Type u} [linear_ordered_add_comm_group α] (a : α) : abs (-a) = abs a := sorry
@[simp] theorem abs_pos {α : Type u} [linear_ordered_add_comm_group α] {a : α} : 0 < abs a ↔ a ≠ 0 := sorry
theorem abs_pos_of_pos {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : 0 < a) : 0 < abs a :=
iff.mpr abs_pos (ne.symm (has_lt.lt.ne h))
theorem abs_pos_of_neg {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : a < 0) : 0 < abs a :=
iff.mpr abs_pos (has_lt.lt.ne h)
theorem abs_sub {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : abs (a - b) = abs (b - a) :=
eq.mpr (id (Eq._oldrec (Eq.refl (abs (a - b) = abs (b - a))) (Eq.symm (neg_sub b a))))
(eq.mpr (id (Eq._oldrec (Eq.refl (abs (-(b - a)) = abs (b - a))) (abs_neg (b - a)))) (Eq.refl (abs (b - a))))
theorem abs_le' {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} : abs a ≤ b ↔ a ≤ b ∧ -a ≤ b :=
max_le_iff
theorem abs_le {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} : abs a ≤ b ↔ -b ≤ a ∧ a ≤ b :=
eq.mpr (id (Eq._oldrec (Eq.refl (abs a ≤ b ↔ -b ≤ a ∧ a ≤ b)) (propext abs_le')))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ b ∧ -a ≤ b ↔ -b ≤ a ∧ a ≤ b)) (propext and.comm)))
(eq.mpr (id (Eq._oldrec (Eq.refl (-a ≤ b ∧ a ≤ b ↔ -b ≤ a ∧ a ≤ b)) (propext neg_le))) (iff.refl (-b ≤ a ∧ a ≤ b))))
theorem le_abs_self {α : Type u} [linear_ordered_add_comm_group α] (a : α) : a ≤ abs a :=
le_max_left a (-a)
theorem neg_le_abs_self {α : Type u} [linear_ordered_add_comm_group α] (a : α) : -a ≤ abs a :=
le_max_right a (-a)
theorem abs_nonneg {α : Type u} [linear_ordered_add_comm_group α] (a : α) : 0 ≤ abs a :=
or.elim (le_total 0 a) (fun (h : 0 ≤ a) => has_le.le.trans h (le_abs_self a))
fun (h : a ≤ 0) => has_le.le.trans (iff.mpr neg_nonneg h) (neg_le_abs_self a)
@[simp] theorem abs_abs {α : Type u} [linear_ordered_add_comm_group α] (a : α) : abs (abs a) = abs a :=
abs_of_nonneg (abs_nonneg a)
@[simp] theorem abs_eq_zero {α : Type u} [linear_ordered_add_comm_group α] {a : α} : abs a = 0 ↔ a = 0 :=
iff.mp not_iff_not (iff.trans ne_comm (iff.trans (iff.symm (has_le.le.lt_iff_ne (abs_nonneg a))) abs_pos))
@[simp] theorem abs_nonpos_iff {α : Type u} [linear_ordered_add_comm_group α] {a : α} : abs a ≤ 0 ↔ a = 0 :=
iff.trans (has_le.le.le_iff_eq (abs_nonneg a)) abs_eq_zero
theorem abs_lt {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} : abs a < b ↔ -b < a ∧ a < b :=
iff.trans max_lt_iff
(iff.trans and.comm
(eq.mpr (id (Eq._oldrec (Eq.refl (-a < b ∧ a < b ↔ -b < a ∧ a < b)) (propext neg_lt))) (iff.refl (-b < a ∧ a < b))))
theorem lt_abs {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} : a < abs b ↔ a < b ∨ a < -b :=
lt_max_iff
theorem max_sub_min_eq_abs' {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : max a b - min a b = abs (a - b) := sorry
theorem max_sub_min_eq_abs {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : max a b - min a b = abs (b - a) :=
eq.mpr (id (Eq._oldrec (Eq.refl (max a b - min a b = abs (b - a))) (abs_sub b a))) (max_sub_min_eq_abs' a b)
theorem abs_add {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : abs (a + b) ≤ abs a + abs b := sorry
theorem abs_sub_le_iff {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} : abs (a - b) ≤ c ↔ a - b ≤ c ∧ b - a ≤ c := sorry
theorem abs_sub_lt_iff {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} : abs (a - b) < c ↔ a - b < c ∧ b - a < c := sorry
theorem sub_le_of_abs_sub_le_left {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : abs (a - b) ≤ c) : b - c ≤ a :=
iff.mp sub_le (and.right (iff.mp abs_sub_le_iff h))
theorem sub_le_of_abs_sub_le_right {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : abs (a - b) ≤ c) : a - c ≤ b :=
sub_le_of_abs_sub_le_left (abs_sub a b ▸ h)
theorem sub_lt_of_abs_sub_lt_left {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : abs (a - b) < c) : b - c < a :=
iff.mp sub_lt (and.right (iff.mp abs_sub_lt_iff h))
theorem sub_lt_of_abs_sub_lt_right {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : abs (a - b) < c) : a - c < b :=
sub_lt_of_abs_sub_lt_left (abs_sub a b ▸ h)
theorem abs_sub_abs_le_abs_sub {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : abs a - abs b ≤ abs (a - b) := sorry
theorem abs_abs_sub_abs_le_abs_sub {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : abs (abs a - abs b) ≤ abs (a - b) := sorry
theorem abs_eq {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} (hb : 0 ≤ b) : abs a = b ↔ a = b ∨ a = -b := sorry
theorem abs_le_max_abs_abs {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} (hab : a ≤ b) (hbc : b ≤ c) : abs b ≤ max (abs a) (abs c) := sorry
theorem abs_le_abs {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} (h₀ : a ≤ b) (h₁ : -a ≤ b) : abs a ≤ abs b :=
has_le.le.trans (iff.mpr abs_le' { left := h₀, right := h₁ }) (le_abs_self b)
theorem abs_max_sub_max_le_abs {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : abs (max a c - max b c) ≤ abs (a - b) := sorry
theorem eq_zero_of_neg_eq {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : -a = a) : a = 0 := sorry
theorem eq_of_abs_sub_eq_zero {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} (h : abs (a - b) = 0) : a = b :=
iff.mp sub_eq_zero (iff.mp abs_eq_zero h)
theorem abs_by_cases {α : Type u} [linear_ordered_add_comm_group α] (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) :=
sup_ind a (-a) h1 h2
theorem abs_sub_le {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) := sorry
theorem abs_add_three {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : abs (a + b + c) ≤ abs a + abs b + abs c :=
has_le.le.trans (abs_add (a + b) c) (add_le_add_right (abs_add a b) (abs c))
theorem dist_bdd_within_interval {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {lb : α} {ub : α} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb :=
iff.mpr abs_sub_le_iff { left := sub_le_sub hau hbl, right := sub_le_sub hbu hal }
theorem eq_of_abs_sub_nonpos {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} (h : abs (a - b) ≤ 0) : a = b :=
eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b)))
theorem exists_zero_lt {α : Type u} [linear_ordered_add_comm_group α] [nontrivial α] : ∃ (a : α), 0 < a := sorry
protected instance linear_ordered_add_comm_group.to_no_top_order {α : Type u} [linear_ordered_add_comm_group α] [nontrivial α] : no_top_order α :=
no_top_order.mk
(Exists.dcases_on exists_zero_lt fun (y : α) (hy : 0 < y) (a : α) => Exists.intro (a + y) (lt_add_of_pos_right a hy))
protected instance linear_ordered_add_comm_group.to_no_bot_order {α : Type u} [linear_ordered_add_comm_group α] [nontrivial α] : no_bot_order α :=
no_bot_order.mk
(Exists.dcases_on exists_zero_lt fun (y : α) (hy : 0 < y) (a : α) => Exists.intro (a - y) (sub_lt_self a hy))
/-- This is not so much a new structure as a construction mechanism
for ordered groups, by specifying only the "positive cone" of the group. -/
class nonneg_add_comm_group (α : Type u_1)
extends add_comm_group α
where
nonneg : α → Prop
pos : α → Prop
pos_iff : autoParam (∀ (a : α), pos a ↔ nonneg a ∧ ¬nonneg (-a))
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.order_laws_tac")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "order_laws_tac") [])
zero_nonneg : nonneg 0
add_nonneg : ∀ {a b : α}, nonneg a → nonneg b → nonneg (a + b)
nonneg_antisymm : ∀ {a : α}, nonneg a → nonneg (-a) → a = 0
namespace nonneg_add_comm_group
protected instance to_ordered_add_comm_group {α : Type u} [s : nonneg_add_comm_group α] : ordered_add_comm_group α :=
ordered_add_comm_group.mk add add_assoc zero zero_add add_zero neg sub add_left_neg add_comm
(fun (a b : α) => nonneg (b - a)) (fun (a b : α) => pos (b - a)) sorry sorry sorry sorry
theorem nonneg_def {α : Type u} [s : nonneg_add_comm_group α] {a : α} : nonneg a ↔ 0 ≤ a := sorry
theorem pos_def {α : Type u} [s : nonneg_add_comm_group α] {a : α} : pos a ↔ 0 < a := sorry
theorem not_zero_pos {α : Type u} [s : nonneg_add_comm_group α] : ¬pos 0 :=
mt (iff.mp pos_def) (lt_irrefl 0)
theorem zero_lt_iff_nonneg_nonneg {α : Type u} [s : nonneg_add_comm_group α] {a : α} : 0 < a ↔ nonneg a ∧ ¬nonneg (-a) :=
iff.trans (iff.symm pos_def) (pos_iff a)
theorem nonneg_total_iff {α : Type u} [s : nonneg_add_comm_group α] : (∀ (a : α), nonneg a ∨ nonneg (-a)) ↔ ∀ (a b : α), a ≤ b ∨ b ≤ a := sorry
/--
A `nonneg_add_comm_group` is a `linear_ordered_add_comm_group`
if `nonneg` is total and decidable.
-/
def to_linear_ordered_add_comm_group {α : Type u} [s : nonneg_add_comm_group α] [decidable_pred nonneg] (nonneg_total : ∀ (a : α), nonneg a ∨ nonneg (-a)) : linear_ordered_add_comm_group α :=
linear_ordered_add_comm_group.mk ordered_add_comm_group.add sorry ordered_add_comm_group.zero sorry sorry
ordered_add_comm_group.neg ordered_add_comm_group.sub sorry sorry LessEq Less sorry sorry sorry sorry
(fun (a b : α) => _inst_1 (b - a))
(linear_order.decidable_eq._default LessEq Less sorry sorry sorry fun (a b : α) => _inst_1 (b - a))
(fun (a b : α) => Mathlib.decidable_lt_of_decidable_le a b) sorry
end nonneg_add_comm_group
namespace order_dual
protected instance ordered_add_comm_group {α : Type u} [ordered_add_comm_group α] : ordered_add_comm_group (order_dual α) :=
ordered_add_comm_group.mk ordered_add_comm_monoid.add sorry ordered_add_comm_monoid.zero sorry sorry add_comm_group.neg
(fun (a b : order_dual α) => a - b) sorry sorry ordered_add_comm_monoid.le ordered_add_comm_monoid.lt sorry sorry
sorry sorry
protected instance linear_ordered_add_comm_group {α : Type u} [linear_ordered_add_comm_group α] : linear_ordered_add_comm_group (order_dual α) :=
linear_ordered_add_comm_group.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg
add_comm_group.sub sorry sorry linear_order.le linear_order.lt sorry sorry sorry sorry linear_order.decidable_le
linear_order.decidable_eq linear_order.decidable_lt sorry
end order_dual
namespace prod
protected instance ordered_add_comm_group {G : Type u_1} {H : Type u_2} [ordered_add_comm_group G] [ordered_add_comm_group H] : ordered_add_comm_group (G × H) :=
ordered_add_comm_group.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub
sorry sorry partial_order.le partial_order.lt sorry sorry sorry sorry
end prod
protected instance multiplicative.ordered_comm_group {α : Type u} [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) :=
ordered_comm_group.mk comm_group.mul sorry comm_group.one sorry sorry comm_group.inv comm_group.div sorry sorry
ordered_comm_monoid.le ordered_comm_monoid.lt sorry sorry sorry sorry
protected instance additive.ordered_add_comm_group {α : Type u} [ordered_comm_group α] : ordered_add_comm_group (additive α) :=
ordered_add_comm_group.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub
sorry sorry ordered_add_comm_monoid.le ordered_add_comm_monoid.lt sorry sorry sorry sorry
|
1abdc5fe1e3aefe59ec847ce336e7d18dd14b15b | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Init/WFTactics.lean | 6c985eafdc38649431517f2ff6990cfbfd55d06d | [
"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 | 2,638 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.SizeOf
import Init.WF
/-- Unfold definitions commonly used in well founded relation definitions.
This is primarily intended for internal use in `decreasing_tactic`. -/
macro "simp_wf" : tactic =>
`(tactic| try simp [invImage, InvImage, Prod.lex, sizeOfWFRel, measure, Nat.lt_wfRel, WellFoundedRelation.rel])
/-- Extensible helper tactic for `decreasing_tactic`. This handles the "base case"
reasoning after applying lexicographic order lemmas.
It can be extended by adding more macro definitions, e.g.
```
macro_rules | `(tactic| decreasing_trivial) => `(tactic| linarith)
```
-/
syntax "decreasing_trivial" : tactic
macro_rules | `(tactic| decreasing_trivial) => `(tactic| (simp (config := { arith := true, failIfUnchanged := false })); done)
macro_rules | `(tactic| decreasing_trivial) => `(tactic| assumption)
macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply Nat.sub_succ_lt_self; assumption) -- a - (i+1) < a - i if i < a
macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply Nat.pred_lt'; assumption) -- i-1 < i if j < i
macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply Nat.pred_lt; assumption) -- i-1 < i if i ≠ 0
/-- Constructs a proof of decreasing along a well founded relation, by applying
lexicographic order lemmas and using `ts` to solve the base case. If it fails,
it prints a message to help the user diagnose an ill-founded recursive definition. -/
macro "decreasing_with " ts:tacticSeq : tactic =>
`(tactic|
(simp_wf
repeat (first | apply Prod.Lex.right | apply Prod.Lex.left)
repeat (first | apply PSigma.Lex.right | apply PSigma.Lex.left)
first
| done
| $ts
| fail "failed to prove termination, possible solutions:
- Use `have`-expressions to prove the remaining goals
- Use `termination_by` to specify a different well-founded relation
- Use `decreasing_by` to specify your own tactic for discharging this kind of goal"))
/-- `decreasing_tactic` is called by default on well-founded recursions in order
to synthesize a proof that recursive calls decrease along the selected
well founded relation. It can be locally overridden by using `decreasing_by tac`
on the recursive definition, and it can also be globally extended by adding
more definitions for `decreasing_tactic` (or `decreasing_trivial`,
which this tactic calls). -/
macro "decreasing_tactic" : tactic =>
`(tactic| decreasing_with first | decreasing_trivial | subst_vars; decreasing_trivial)
|
627c487d6ee8f7c8a7ba4b52bb0d56ca697c341d | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/category_theory/category/Pointed.lean | 7cecd81f9261da8a82e519274cee3650bdca9204 | [
"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 | 2,706 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import category_theory.concrete_category.basic
/-!
# The category of pointed types
This defines `Pointed`, the category of pointed types.
## TODO
* Monoidal structure
* Upgrade `Type_to_Pointed` to an equivalence
-/
open category_theory
universes u
variables {α β : Type*}
/-- The category of pointed types. -/
structure Pointed : Type.{u + 1} :=
(X : Type.{u})
(point : X)
namespace Pointed
instance : has_coe_to_sort Pointed Type* := ⟨X⟩
attribute [protected] Pointed.X
/-- Turns a point into a pointed type. -/
def of {X : Type*} (point : X) : Pointed := ⟨X, point⟩
alias of ← prod.Pointed
instance : inhabited Pointed := ⟨of ((), ())⟩
/-- Morphisms in `Pointed`. -/
@[ext] protected structure hom (X Y : Pointed.{u}) : Type u :=
(to_fun : X → Y)
(map_point : to_fun X.point = Y.point)
namespace hom
/-- The identity morphism of `X : Pointed`. -/
@[simps] def id (X : Pointed) : hom X X := ⟨id, rfl⟩
instance (X : Pointed) : inhabited (hom X X) := ⟨id X⟩
/-- Composition of morphisms of `Pointed`. -/
@[simps] def comp {X Y Z : Pointed.{u}} (f : hom X Y) (g : hom Y Z) : hom X Z :=
⟨g.to_fun ∘ f.to_fun, by rw [function.comp_apply, f.map_point, g.map_point]⟩
end hom
instance large_category : large_category Pointed :=
{ hom := hom,
id := hom.id,
comp := @hom.comp,
id_comp' := λ _ _ _, hom.ext _ _ rfl,
comp_id' := λ _ _ _, hom.ext _ _ rfl,
assoc' := λ _ _ _ _ _ _ _, hom.ext _ _ rfl }
instance concrete_category : concrete_category Pointed :=
{ forget := { obj := Pointed.X, map := @hom.to_fun },
forget_faithful := ⟨@hom.ext⟩ }
end Pointed
--TODO: This is actually an equivalence
/-- `option` as a functor from types to pointed types. This is the free functor. -/
@[simps] def Type_to_Pointed : Type.{u} ⥤ Pointed.{u} :=
{ obj := λ X, ⟨option X, none⟩,
map := λ X Y f, ⟨option.map f, rfl⟩,
map_id' := λ X, Pointed.hom.ext _ _ option.map_id,
map_comp' := λ X Y Z f g, Pointed.hom.ext _ _ (option.map_comp_map _ _).symm }
/-- `Type_to_Pointed` is the free functor. -/
def Type_to_Pointed_forget_adjunction : Type_to_Pointed ⊣ forget Pointed :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Y, { to_fun := λ f, f.to_fun ∘ option.some,
inv_fun := λ f, ⟨λ o, o.elim Y.point f, rfl⟩,
left_inv := λ f, by { ext, cases x, exact f.map_point.symm, refl },
right_inv := λ f, funext $ λ _, rfl },
hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl }, }
|
bc332d0bd4e385df6ea374b7397cd56259f0caab | d642a6b1261b2cbe691e53561ac777b924751b63 | /src/algebra/ring.lean | 2ff9a4872c8c78517f3f9c73d3d1260c8e4563ca | [
"Apache-2.0"
] | permissive | cipher1024/mathlib | fee56b9954e969721715e45fea8bcb95f9dc03fe | d077887141000fefa5a264e30fa57520e9f03522 | refs/heads/master | 1,651,806,490,504 | 1,573,508,694,000 | 1,573,508,694,000 | 107,216,176 | 0 | 0 | Apache-2.0 | 1,647,363,136,000 | 1,508,213,014,000 | Lean | UTF-8 | Lean | false | false | 24,468 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston
-/
import algebra.group
import tactic.norm_cast
/-!
# Properties and homomorphisms of semirings and rings
This file proves simple properties of semirings, rings and domains and their unit groups. It also
defines homomorphisms of semirings and rings, both unbundled (e.g. `is_semiring_hom f`)
and bundled (e.g. `ring_hom a β`, a.k.a. `α →+* β`). The unbundled ones are deprecated
and the plan is to slowly remove them from mathlib.
## Main definitions
is_semiring_hom (deprecated), is_ring_hom (deprecated), ring_hom, nonzero_comm_semiring,
nonzero_comm_ring, domain
## Notations
→+* for bundled ring homs (also use for semiring homs)
## Implementation notes
There's a coercion from bundled homs to fun, and the canonical
notation is to use the bundled hom as a function via this coercion.
There is no `semiring_hom` -- the idea is that `ring_hom` is used.
The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and
`map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs
between rings from monoid homs given only a proof that addition is preserved.
Throughout the section on `ring_hom` implicit `{}` brackets are often used instead of type class `[]` brackets.
This is done when the instances can be inferred because they are implicit arguments to the type `ring_hom`.
When they can be inferred from the type it is faster to use this method than to use type class inference.
## Tags
is_ring_hom, is_semiring_hom, ring_hom, semiring_hom, semiring, comm_semiring, ring, comm_ring,
domain, integral_domain, nonzero_comm_semiring, nonzero_comm_ring, units
-/
universes u v w
variable {α : Type u}
section
variable [semiring α]
theorem mul_two (n : α) : n * 2 = n + n :=
(left_distrib n 1 1).trans (by simp)
theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n :=
(two_mul _).symm
@[simp] lemma mul_ite {α} [semiring α] (P : Prop) [decidable P] (a : α) :
a * (if P then 1 else 0) = if P then a else 0 :=
by split_ifs; simp
variable (α)
/-- Either zero and one are nonequal in a semiring, or the semiring is the zero ring. -/
lemma zero_ne_one_or_forall_eq_0 : (0 : α) ≠ 1 ∨ (∀a:α, a = 0) :=
by haveI := classical.dec;
refine not_or_of_imp (λ h a, _); simpa using congr_arg ((*) a) h.symm
/-- If zero equals one in a semiring, the semiring is the zero ring. -/
lemma eq_zero_of_zero_eq_one (h : (0 : α) = 1) : (∀a:α, a = 0) :=
(zero_ne_one_or_forall_eq_0 α).neg_resolve_left h
/-- If zero equals one in a semiring, all elements of that semiring are equal. -/
theorem subsingleton_of_zero_eq_one (h : (0 : α) = 1) : subsingleton α :=
⟨λa b, by rw [eq_zero_of_zero_eq_one α h a, eq_zero_of_zero_eq_one α h b]⟩
end
namespace units
variables [ring α] {a b : α}
/-- Each element of the group of units of a ring has an additive inverse. -/
instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩
/-- Representing an element of a ring's unit group as an element of the ring commutes with
mapping this element to its additive inverse. -/
@[simp] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl
/-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element
to its additive inverse. -/
@[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl
/-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/
@[simp] protected theorem neg_neg (u : units α) : - -u = u :=
units.ext $ neg_neg _
/-- Multiplication of elements of a ring's unit group commutes with mapping the first
argument to its additive inverse. -/
@[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) :=
units.ext $ neg_mul_eq_neg_mul_symm _ _
/-- Multiplication of elements of a ring's unit group commutes with mapping the second argument
to its additive inverse. -/
@[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) :=
units.ext $ (neg_mul_eq_mul_neg _ _).symm
/-- Multiplication of the additive inverses of two elements of a ring's unit group equals
multiplication of the two original elements. -/
@[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp
/-- The additive inverse of an element of a ring's unit group equals the additive inverse of
one times the original element. -/
protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp
end units
instance [semiring α] : semiring (with_zero α) :=
{ left_distrib := λ a b c, begin
cases a with a, {refl},
cases b with b; cases c with c; try {refl},
exact congr_arg some (left_distrib _ _ _)
end,
right_distrib := λ a b c, begin
cases c with c,
{ change (a + b) * 0 = a * 0 + b * 0, simp },
cases a with a; cases b with b; try {refl},
exact congr_arg some (right_distrib _ _ _)
end,
..with_zero.add_comm_monoid,
..with_zero.mul_zero_class,
..with_zero.monoid }
attribute [refl] dvd_refl
attribute [trans] dvd.trans
/-- Predicate for semiring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/
class is_semiring_hom {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) : Prop :=
(map_zero : f 0 = 0)
(map_one : f 1 = 1)
(map_add : ∀ {x y}, f (x + y) = f x + f y)
(map_mul : ∀ {x y}, f (x * y) = f x * f y)
namespace is_semiring_hom
variables {β : Type v} [semiring α] [semiring β]
variables (f : α → β) [is_semiring_hom f] {x y : α}
/-- The identity map is a semiring homomorphism. -/
instance id : is_semiring_hom (@id α) := by refine {..}; intros; refl
/-- The composition of two semiring homomorphisms is a semiring homomorphism. -/
instance comp {γ} [semiring γ] (g : β → γ) [is_semiring_hom g] :
is_semiring_hom (g ∘ f) :=
{ map_zero := by simp [map_zero f]; exact map_zero g,
map_one := by simp [map_one f]; exact map_one g,
map_add := λ x y, by simp [map_add f]; rw map_add g; refl,
map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl }
/-- A semiring homomorphism is an additive monoid homomorphism. -/
instance : is_add_monoid_hom f :=
{ ..‹is_semiring_hom f› }
/-- A semiring homomorphism is a monoid homomorphism. -/
instance : is_monoid_hom f :=
{ ..‹is_semiring_hom f› }
end is_semiring_hom
section
variables [ring α] (a b c d e : α)
/-- An element of a ring multiplied by the additive inverse of one is the element's additive
inverse. -/
lemma mul_neg_one (a : α) : a * -1 = -a := by simp
/-- The additive inverse of one multiplied by an element of a ring is the element's additive
inverse. -/
lemma neg_one_mul (a : α) : -1 * a = -a := by simp
/-- An iff statement following from right distributivity in rings and the definition
of subtraction. -/
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 simp
... ↔ a * e + c - b * e = d : iff.intro (λ h, begin simp [h] end) (λ h,
begin simp [h.symm] end)
... ↔ (a - b) * e + c = d : begin simp [@sub_eq_add_neg α, @right_distrib α] end
/-- A simplification of one side of an equation exploiting right distributivity in rings
and the definition of subtraction. -/
theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d :=
assume h,
calc
(a - b) * e + c = (a * e + c) - b * e : begin simp [@sub_eq_add_neg α, @right_distrib α] end
... = d : begin rw h, simp [@add_sub_cancel α] end
/-- If the product of two elements of a ring is nonzero, both elements are nonzero. -/
theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : α} (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 :=
begin
split,
{ intro ha, apply h, simp [ha] },
{ intro hb, apply h, simp [hb] }
end
end
/-- Given an element a of a commutative semiring, there exists another element whose product
with zero equals a iff a equals zero. -/
@[simp] lemma zero_dvd_iff [comm_semiring α] {a : α} : 0 ∣ a ↔ a = 0 :=
⟨eq_zero_of_zero_dvd, λ h, by rw h⟩
section comm_ring
variable [comm_ring α]
/-- Representation of a difference of two squares in a commutative ring as a product. -/
theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) :=
by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel]
/-- An element a of a commutative ring divides the additive inverse of an element b iff a
divides b. -/
@[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) :=
⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩
/-- The additive inverse of an element a of a commutative ring divides another element b iff a
divides b. -/
@[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) :=
⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩
/-- If an element a divides another element c in a commutative ring, a divides the sum of another
element b with c iff a divides b. -/
theorem dvd_add_left {a b c : α} (h : a ∣ c) : a ∣ b + c ↔ a ∣ b :=
(dvd_add_iff_left h).symm
/-- If an element a divides another element b in a commutative ring, a divides the sum of b and
another element c iff a divides c. -/
theorem dvd_add_right {a b c : α} (h : a ∣ b) : a ∣ b + c ↔ a ∣ c :=
(dvd_add_iff_right h).symm
/-- An element a divides the sum a + b if and only if a divides b.-/
@[simp] lemma dvd_add_self_left {a b : α} :
a ∣ a + b ↔ a ∣ b :=
dvd_add_right (dvd_refl a)
/-- An element a divides the sum b + a if and only if a divides b.-/
@[simp] lemma dvd_add_self_right {a b : α} :
a ∣ b + a ↔ a ∣ b :=
dvd_add_left (dvd_refl a)
/-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with
its roots. This particular version states that if we have a root `x` of a monic quadratic
polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient
and `x * y` is the `a_0` coefficient. -/
lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) :
∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c :=
begin
have : c = b * x - x * x, { apply eq_of_sub_eq_zero, simpa using h },
use b - x, simp [left_distrib, mul_comm, this],
end
end comm_ring
/-- Predicate for ring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/
class is_ring_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) : Prop :=
(map_one : f 1 = 1)
(map_mul : ∀ {x y}, f (x * y) = f x * f y)
(map_add : ∀ {x y}, f (x + y) = f x + f y)
namespace is_ring_hom
variables {β : Type v} [ring α] [ring β]
/-- A map of rings that is a semiring homomorphism is also a ring homomorphism. -/
lemma of_semiring (f : α → β) [H : is_semiring_hom f] : is_ring_hom f := {..H}
variables (f : α → β) [is_ring_hom f] {x y : α}
/-- Ring homomorphisms map zero to zero. -/
lemma map_zero : f 0 = 0 :=
calc f 0 = f (0 + 0) - f 0 : by rw [map_add f]; simp
... = 0 : by simp
/-- Ring homomorphisms preserve additive inverses. -/
lemma map_neg : f (-x) = -f x :=
calc f (-x) = f (-x + x) - f x : by rw [map_add f]; simp
... = -f x : by simp [map_zero f]
/-- Ring homomorphisms preserve subtraction. -/
lemma map_sub : f (x - y) = f x - f y :=
by simp [map_add f, map_neg f]
/-- The identity map is a ring homomorphism. -/
instance id : is_ring_hom (@id α) := by refine {..}; intros; refl
/-- The composition of two ring homomorphisms is a ring homomorphism. -/
instance comp {γ} [ring γ] (g : β → γ) [is_ring_hom g] :
is_ring_hom (g ∘ f) :=
{ map_add := λ x y, by simp [map_add f]; rw map_add g; refl,
map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl,
map_one := by simp [map_one f]; exact map_one g }
/-- A ring homomorphism is also a semiring homomorphism. -/
instance : is_semiring_hom f :=
{ map_zero := map_zero f, ..‹is_ring_hom f› }
instance : is_add_group_hom f := { }
end is_ring_hom
set_option old_structure_cmd true
/-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. -/
structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β]
extends monoid_hom α β, add_monoid_hom α β
infixr ` →+* `:25 := ring_hom
instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe_to_fun (α →+* β) :=
⟨_, ring_hom.to_fun⟩
instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe (α →+* β) (α →* β) :=
⟨ring_hom.to_monoid_hom⟩
instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe (α →+* β) (α →+ β) :=
⟨ring_hom.to_add_monoid_hom⟩
@[squash_cast] lemma coe_monoid_hom {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} (f : α →+* β) (a : α) :
((f : α →* β) : α → β) a = (f : α → β) a := rfl
@[squash_cast] lemma coe_add_monoid_hom {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} (f : α →+* β) (a : α) :
((f : α →+ β) : α → β) a = (f : α → β) a := rfl
namespace ring_hom
variables {β : Type v} {γ : Type w} [rα : semiring α] [rβ : semiring β]
include rα rβ
/-- Interpret `f : α → β` with `is_semiring_hom f` as a ring homomorphism. -/
def of (f : α → β) [is_semiring_hom f] : α →+* β :=
{ to_fun := f,
.. monoid_hom.of f,
.. add_monoid_hom.of f }
@[simp] lemma coe_of (f : α → β) [is_semiring_hom f] : ⇑(of f) = f := rfl
variables (f : α →+* β) {x y : α} {rα rβ}
theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g :=
by cases f; cases g; cases h; refl
@[ext] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g :=
coe_inj (funext h)
theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, ext h⟩
/-- Ring homomorphisms map zero to zero. -/
@[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero'
/-- Ring homomorphisms map one to one. -/
@[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one'
/-- Ring homomorphisms preserve addition. -/
@[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b
/-- Ring homomorphisms preserve multiplication. -/
@[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b
instance (f : α →+* β) : is_semiring_hom f :=
{ map_zero := f.map_zero,
map_one := f.map_one,
map_add := f.map_add,
map_mul := f.map_mul }
omit rα rβ
instance {α γ} [ring α] [ring γ] (g : α →+* γ) : is_ring_hom g :=
is_ring_hom.of_semiring g
/-- The identity ring homomorphism from a semiring to itself. -/
def id (α : Type*) [semiring α] : α →+* α :=
by refine {to_fun := id, ..}; intros; refl
include rα
@[simp] lemma id_apply : ring_hom.id α x = x := rfl
variable {rγ : semiring γ}
include rβ rγ
/-- Composition of ring homomorphisms is a ring homomorphism. -/
def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ :=
{ to_fun := hnp ∘ hmn,
map_zero' := by simp,
map_one' := by simp,
map_add' := λ x y, by simp,
map_mul' := λ x y, by simp}
@[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl
@[simp] lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x =
(hnp (hmn x)) := rfl
omit rα rβ rγ
/-- Ring homomorphisms preserve additive inverse. -/
@[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) :=
eq_neg_of_add_eq_zero $ by rw [←f.map_add, neg_add_self, f.map_zero]
/-- Ring homomorphisms preserve subtraction. -/
@[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) :
f (x - y) = (f x) - (f y) := by simp
include rα
/-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/
def mk' {γ} [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ :=
{ to_fun := f,
map_zero' := add_self_iff_eq_zero.1 $ by rw [←map_add, add_zero],
map_one' := f.map_one,
map_mul' := f.map_mul,
map_add' := map_add }
end ring_hom
/-- Predicate for commutative semirings in which zero does not equal one. -/
class nonzero_comm_semiring (α : Type*) extends comm_semiring α, zero_ne_one_class α
/-- Predicate for commutative rings in which zero does not equal one. -/
class nonzero_comm_ring (α : Type*) extends comm_ring α, zero_ne_one_class α
/-- A nonzero commutative ring is a nonzero commutative semiring. -/
instance nonzero_comm_ring.to_nonzero_comm_semiring {α : Type*} [I : nonzero_comm_ring α] :
nonzero_comm_semiring α :=
{ zero_ne_one := by convert zero_ne_one,
..show comm_semiring α, by apply_instance }
/-- An integral domain is a nonzero commutative ring. -/
instance integral_domain.to_nonzero_comm_ring (α : Type*) [id : integral_domain α] :
nonzero_comm_ring α :=
{ ..id }
/-- An element of the unit group of a nonzero commutative semiring represented as an element
of the semiring is nonzero. -/
lemma units.coe_ne_zero [nonzero_comm_semiring α] (u : units α) : (u : α) ≠ 0 :=
λ h : u.1 = 0, by simpa [h, zero_ne_one] using u.3
/-- Makes a nonzero commutative ring from a commutative ring containing at least two distinct
elements. -/
def nonzero_comm_ring.of_ne [comm_ring α] {x y : α} (h : x ≠ y) : nonzero_comm_ring α :=
{ one := 1,
zero := 0,
zero_ne_one := λ h01, h $ by rw [← one_mul x, ← one_mul y, ← h01, zero_mul, zero_mul],
..show comm_ring α, by apply_instance }
/-- Makes a nonzero commutative semiring from a commutative semiring containing at least two
distinct elements. -/
def nonzero_comm_semiring.of_ne [comm_semiring α] {x y : α} (h : x ≠ y) : nonzero_comm_semiring α :=
{ one := 1,
zero := 0,
zero_ne_one := λ h01, h $ by rw [← one_mul x, ← one_mul y, ← h01, zero_mul, zero_mul],
..show comm_semiring α, by apply_instance }
/-- this is needed for compatibility between Lean 3.4.2 and Lean 3.5.0c -/
def has_div_of_division_ring [division_ring α] : has_div α := division_ring_has_div
/-- A domain is a ring with no zero divisors, i.e. satisfying
the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain
is an integral domain without assuming commutativity of multiplication. -/
class domain (α : Type u) extends ring α, no_zero_divisors α, zero_ne_one_class α
section domain
variable [domain α]
/-- Simplification theorems for the definition of a domain. -/
@[simp] theorem mul_eq_zero {a b : α} : a * b = 0 ↔ a = 0 ∨ b = 0 :=
⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo,
or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩
@[simp] theorem zero_eq_mul {a b : α} : 0 = a * b ↔ a = 0 ∨ b = 0 :=
by rw [eq_comm, mul_eq_zero]
lemma mul_self_eq_zero {α} [domain α] {x : α} : x * x = 0 ↔ x = 0 := by simp
lemma zero_eq_mul_self {α} [domain α] {x : α} : 0 = x * x ↔ x = 0 := by simp
/-- The product of two nonzero elements of a domain is nonzero. -/
theorem mul_ne_zero' {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 :=
λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) h₁ h₂
/-- Right multiplication by a nonzero element in a domain is injective. -/
theorem domain.mul_right_inj {a b c : α} (ha : a ≠ 0) : b * a = c * a ↔ b = c :=
by rw [← sub_eq_zero, ← mul_sub_right_distrib, mul_eq_zero];
simp [ha]; exact sub_eq_zero
/-- Left multiplication by a nonzero element in a domain is injective. -/
theorem domain.mul_left_inj {a b c : α} (ha : a ≠ 0) : a * b = a * c ↔ b = c :=
by rw [← sub_eq_zero, ← mul_sub_left_distrib, mul_eq_zero];
simp [ha]; exact sub_eq_zero
/-- An element of a domain fixed by right multiplication by an element other than one must
be zero. -/
theorem eq_zero_of_mul_eq_self_right' {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 :=
by apply (mul_eq_zero.1 _).resolve_right (sub_ne_zero.2 h₁);
rw [mul_sub_left_distrib, mul_one, sub_eq_zero, h₂]
/-- An element of a domain fixed by left multiplication by an element other than one must
be zero. -/
theorem eq_zero_of_mul_eq_self_left' {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 :=
by apply (mul_eq_zero.1 _).resolve_left (sub_ne_zero.2 h₁);
rw [mul_sub_right_distrib, one_mul, sub_eq_zero, h₂]
/-- For elements a, b of a domain, if a*b is nonzero, so is b*a. -/
theorem mul_ne_zero_comm' {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 :=
mul_ne_zero' (ne_zero_of_mul_ne_zero_left h) (ne_zero_of_mul_ne_zero_right h)
end domain
/- integral domains -/
section
variables [s : integral_domain α] (a b c d e : α)
include s
/-- An integral domain is a domain. -/
instance integral_domain.to_domain : domain α := {..s}
/-- Right multiplcation by a nonzero element of an integral domain is injective. -/
theorem eq_of_mul_eq_mul_right_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : b * a = c * a) : b = c :=
have b * a - c * a = 0, by simp [h],
have (b - c) * a = 0, by rw [mul_sub_right_distrib, this],
have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha,
eq_of_sub_eq_zero this
/-- Left multiplication by a nonzero element of an integral domain is injective. -/
theorem eq_of_mul_eq_mul_left_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : a * b = a * c) : b = c :=
have a * b - a * c = 0, by simp [h],
have a * (b - c) = 0, by rw [mul_sub_left_distrib, this],
have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha,
eq_of_sub_eq_zero this
/-- Given two elements b, c of an integral domain and a nonzero element a, a*b divides a*c iff
b divides c. -/
theorem mul_dvd_mul_iff_left {a b c : α} (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c :=
exists_congr $ λ d, by rw [mul_assoc, domain.mul_left_inj ha]
/-- Given two elements a, b of an integral domain and a nonzero element c, a*c divides b*c iff
a divides b. -/
theorem mul_dvd_mul_iff_right {a b c : α} (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b :=
exists_congr $ λ d, by rw [mul_right_comm, domain.mul_right_inj hc]
/-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or
one's additive inverse. -/
lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 :=
by conv {to_lhs, rw [inv_eq_iff_mul_eq_one, ← mul_one (1 : units α), units.ext_iff, units.coe_mul,
units.coe_mul, mul_self_eq_mul_self_iff, ← units.ext_iff, ← units.coe_neg, ← units.ext_iff] }
end
/- units in various rings -/
namespace units
section comm_semiring
variables [comm_semiring α] (a b : α) (u : units α)
/-- Elements of the unit group of a commutative semiring represented as elements of the semiring
divide any element of the semiring. -/
@[simp] lemma coe_dvd : ↑u ∣ a := ⟨↑u⁻¹ * a, by simp⟩
/-- In a commutative semiring, an element a divides an element b iff a divides all
associates of b. -/
@[simp] lemma dvd_coe_mul : a ∣ b * u ↔ a ∣ b :=
iff.intro
(assume ⟨c, eq⟩, ⟨c * ↑u⁻¹, by rw [← mul_assoc, ← eq, units.mul_inv_cancel_right]⟩)
(assume ⟨c, eq⟩, eq.symm ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)
/-- An element of a commutative semiring divides a unit iff the element divides one. -/
@[simp] lemma dvd_coe : a ∣ ↑u ↔ a ∣ 1 :=
suffices a ∣ 1 * ↑u ↔ a ∣ 1, by simpa,
dvd_coe_mul _ _ _
/-- In a commutative semiring, an element a divides an element b iff all associates of a divide b.-/
@[simp] lemma coe_mul_dvd : a * u ∣ b ↔ a ∣ b :=
iff.intro
(assume ⟨c, eq⟩, ⟨c * ↑u, eq.symm ▸ by ac_refl⟩)
(assume h, suffices a * ↑u ∣ b * 1, by simpa, mul_dvd_mul h (coe_dvd _ _))
end comm_semiring
section domain
variables [domain α]
/-- Every unit in a domain is nonzero. -/
@[simp] theorem ne_zero : ∀(u : units α), (↑u : α) ≠ 0
| ⟨u, v, (huv : 0 * v = 1), hvu⟩ rfl := by simpa using huv
end domain
end units
|
3109268cd3f1fa7d69bc4513645c986e3aa6f6d9 | a4673261e60b025e2c8c825dfa4ab9108246c32e | /tests/lean/run/extmacro.lean | 483bf56380d5aca2180da95d5ed6baf222bd45c6 | [
"Apache-2.0"
] | permissive | jcommelin/lean4 | c02dec0cc32c4bccab009285475f265f17d73228 | 2909313475588cc20ac0436e55548a4502050d0a | refs/heads/master | 1,674,129,550,893 | 1,606,415,348,000 | 1,606,415,348,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 458 | lean |
macro ext_tactic t:tactic "=>" newT:tactic : command => `(macro_rules | `($t) => `($newT))
syntax "trivial" : tactic
ext_tactic trivial => apply Eq.refl
theorem tst1 (x : Nat) : x = x :=
by trivial
-- theorem tst2 (x y : Nat) (h : x = y) : x = y :=
-- by trivial -- fail as expected
ext_tactic trivial => assumption
theorem tst1b (x : Nat) : x = x :=
by trivial -- still works
theorem tst2 (x y : Nat) (h : x = y) : x = y :=
by trivial -- works too
|
c066db2a9073b7c2c2e4dd891816a7ebd6928bc6 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/algebra/big_operators/ring.lean | 82426fd790a6753402476c2f737ad4b8f591b0f9 | [
"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 | 9,932 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import algebra.big_operators.basic
import data.finset.pi
import data.finset.powerset
/-!
# Results about big operators with values in a (semi)ring
We prove results about big operators that involve some interaction between
multiplicative and additive structures on the values being combined.
-/
universes u v w
open_locale big_operators
variables {α : Type u} {β : Type v} {γ : Type w}
namespace finset
variables {s s₁ s₂ : finset α} {a : α} {b : β} {f g : α → β}
section semiring
variables [non_unital_non_assoc_semiring β]
lemma sum_mul : (∑ x in s, f x) * b = ∑ x in s, f x * b :=
add_monoid_hom.map_sum (add_monoid_hom.mul_right b) _ s
lemma mul_sum : b * (∑ x in s, f x) = ∑ x in s, b * f x :=
add_monoid_hom.map_sum (add_monoid_hom.mul_left b) _ s
lemma sum_mul_sum {ι₁ : Type*} {ι₂ : Type*} (s₁ : finset ι₁) (s₂ : finset ι₂)
(f₁ : ι₁ → β) (f₂ : ι₂ → β) :
(∑ x₁ in s₁, f₁ x₁) * (∑ x₂ in s₂, f₂ x₂) = ∑ p in s₁.product s₂, f₁ p.1 * f₂ p.2 :=
by { rw [sum_product, sum_mul, sum_congr rfl], intros, rw mul_sum }
end semiring
section semiring
variables [non_assoc_semiring β]
lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∑ x in s, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 :=
by simp
lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∑ x in s, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 :=
by simp
end semiring
lemma sum_div [division_ring β] {s : finset α} {f : α → β} {b : β} :
(∑ x in s, f x) / b = ∑ x in s, f x / b :=
by simp only [div_eq_mul_inv, sum_mul]
section comm_semiring
variables [comm_semiring β]
/-- The product over a sum can be written as a sum over the product of sets, `finset.pi`.
`finset.prod_univ_sum` is an alternative statement when the product is over `univ`. -/
lemma prod_sum {δ : α → Type*} [decidable_eq α] [∀a, decidable_eq (δ a)]
{s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} :
(∏ a in s, ∑ b in (t a), f a b) =
∑ p in (s.pi t), ∏ x in s.attach, f x.1 (p x.1 x.2) :=
begin
induction s using finset.induction with a s ha ih,
{ rw [pi_empty, sum_singleton], refl },
{ have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y,
disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)),
{ assume x hx y hy h,
simp only [disjoint_iff_ne, mem_image],
rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq,
have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _),
{ rw [eq₂, eq₃, eq] },
rw [pi.cons_same, pi.cons_same] at this,
exact h this },
rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bUnion h₁],
refine sum_congr rfl (λ b _, _),
have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from
assume p₁ h₁ p₂ h₂ eq, pi_cons_injective ha eq,
rw [sum_image h₂, mul_sum],
refine sum_congr rfl (λ g _, _),
rw [attach_insert, prod_insert, prod_image],
{ simp only [pi.cons_same],
congr' with ⟨v, hv⟩, congr',
exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm },
{ exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj },
{ simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } }
end
open_locale classical
/-- The product of `f a + g a` over all of `s` is the sum
over the powerset of `s` of the product of `f` over a subset `t` times
the product of `g` over the complement of `t` -/
lemma prod_add (f g : α → β) (s : finset α) :
∏ a in s, (f a + g a) = ∑ t in s.powerset, ((∏ a in t, f a) * (∏ a in (s \ t), g a)) :=
calc ∏ a in s, (f a + g a)
= ∏ a in s, ∑ p in ({true, false} : finset Prop), if p then f a else g a : by simp
... = ∑ p in (s.pi (λ _, {true, false}) : finset (Π a ∈ s, Prop)),
∏ a in s.attach, if p a.1 a.2 then f a.1 else g a.1 : prod_sum
... = ∑ t in s.powerset, (∏ a in t, f a) * (∏ a in (s \ t), g a) : begin
refine eq.symm (sum_bij (λ t _ a _, a ∈ t) _ _ _ _),
{ simp [subset_iff]; tauto },
{ intros t ht,
erw [prod_ite (λ a : {a // a ∈ s}, f a.1) (λ a : {a // a ∈ s}, g a.1)],
refine congr_arg2 _
(prod_bij (λ (a : α) (ha : a ∈ t), ⟨a, mem_powerset.1 ht ha⟩)
_ _ _
(λ b hb, ⟨b, by cases b; finish⟩))
(prod_bij (λ (a : α) (ha : a ∈ s \ t), ⟨a, by simp * at *⟩)
_ _ _
(λ b hb, ⟨b, by cases b; finish⟩));
intros; simp * at *; simp * at * },
{ finish [function.funext_iff, finset.ext_iff, subset_iff] },
{ assume f hf,
exact ⟨s.filter (λ a : α, ∃ h : a ∈ s, f a h),
by simp, by funext; intros; simp *⟩ }
end
/-- `∏ i, (f i + g i) = (∏ i, f i) + ∑ i, g i * (∏ j < i, f j + g j) * (∏ j > i, f j)`. -/
lemma prod_add_ordered {ι R : Type*} [comm_semiring R] [linear_order ι] (s : finset ι)
(f g : ι → R) :
(∏ i in s, (f i + g i)) = (∏ i in s, f i) +
∑ i in s, g i * (∏ j in s.filter (< i), (f j + g j)) * ∏ j in s.filter (λ j, i < j), f j :=
begin
refine finset.induction_on_max s (by simp) _,
clear s, intros a s ha ihs,
have ha' : a ∉ s, from λ ha', (ha a ha').false,
rw [prod_insert ha', prod_insert ha', sum_insert ha', filter_insert, if_neg (lt_irrefl a),
filter_true_of_mem ha, ihs, add_mul, mul_add, mul_add, add_assoc],
congr' 1, rw add_comm, congr' 1,
{ rw [filter_false_of_mem, prod_empty, mul_one],
exact (forall_mem_insert _ _ _).2 ⟨lt_irrefl a, λ i hi, (ha i hi).not_lt⟩ },
{ rw mul_sum,
refine sum_congr rfl (λ i hi, _),
rw [filter_insert, if_neg (ha i hi).not_lt, filter_insert, if_pos (ha i hi), prod_insert,
mul_left_comm],
exact mt (λ ha, (mem_filter.1 ha).1) ha' }
end
/-- `∏ i, (f i - g i) = (∏ i, f i) - ∑ i, g i * (∏ j < i, f j - g j) * (∏ j > i, f j)`. -/
lemma prod_sub_ordered {ι R : Type*} [comm_ring R] [linear_order ι] (s : finset ι) (f g : ι → R) :
(∏ i in s, (f i - g i)) = (∏ i in s, f i) -
∑ i in s, g i * (∏ j in s.filter (< i), (f j - g j)) * ∏ j in s.filter (λ j, i < j), f j :=
begin
simp only [sub_eq_add_neg],
convert prod_add_ordered s f (λ i, -g i),
simp,
end
/-- `∏ i, (1 - f i) = 1 - ∑ i, f i * (∏ j < i, 1 - f j)`. This formula is useful in construction of
a partition of unity from a collection of “bump” functions. -/
lemma prod_one_sub_ordered {ι R : Type*} [comm_ring R] [linear_order ι] (s : finset ι) (f : ι → R) :
(∏ i in s, (1 - f i)) = 1 - ∑ i in s, f i * ∏ j in s.filter (< i), (1 - f j) :=
by { rw prod_sub_ordered, simp }
/-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a `finset`
gives `(a + b)^s.card`.-/
lemma sum_pow_mul_eq_add_pow
{α R : Type*} [comm_semiring R] (a b : R) (s : finset α) :
(∑ t in s.powerset, a ^ t.card * b ^ (s.card - t.card)) = (a + b) ^ s.card :=
begin
rw [← prod_const, prod_add],
refine finset.sum_congr rfl (λ t ht, _),
rw [prod_const, prod_const, ← card_sdiff (mem_powerset.1 ht)]
end
lemma prod_pow_eq_pow_sum {x : β} {f : α → ℕ} :
∀ {s : finset α}, (∏ i in s, x ^ (f i)) = x ^ (∑ x in s, f x) :=
begin
apply finset.induction,
{ simp },
{ assume a s has H,
rw [finset.prod_insert has, finset.sum_insert has, pow_add, H] }
end
theorem dvd_sum {b : β} {s : finset α} {f : α → β}
(h : ∀ x ∈ s, b ∣ f x) : b ∣ ∑ x in s, f x :=
multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx)
@[norm_cast]
lemma prod_nat_cast (s : finset α) (f : α → ℕ) :
↑(∏ x in s, f x : ℕ) = (∏ x in s, (f x : β)) :=
(nat.cast_ring_hom β).map_prod f s
end comm_semiring
section comm_ring
variables {R : Type*} [comm_ring R]
lemma prod_range_cast_nat_sub (n k : ℕ) :
∏ i in range k, (n - i : R) = (∏ i in range k, (n - i) : ℕ) :=
begin
rw prod_nat_cast,
cases le_or_lt k n with hkn hnk,
{ exact prod_congr rfl (λ i hi, (nat.cast_sub $ (mem_range.1 hi).le.trans hkn).symm) },
{ rw ← mem_range at hnk,
rw [prod_eq_zero hnk, prod_eq_zero hnk]; simp }
end
end comm_ring
/-- A product over all subsets of `s ∪ {x}` is obtained by multiplying the product over all subsets
of `s`, and over all subsets of `s` to which one adds `x`. -/
@[to_additive]
lemma prod_powerset_insert [decidable_eq α] [comm_monoid β] {s : finset α} {x : α} (h : x ∉ s)
(f : finset α → β) :
(∏ a in (insert x s).powerset, f a) =
(∏ a in s.powerset, f a) * (∏ t in s.powerset, f (insert x t)) :=
begin
rw [powerset_insert, finset.prod_union, finset.prod_image],
{ assume t₁ h₁ t₂ h₂ heq,
rw [← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₁ h),
← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₂ h), heq] },
{ rw finset.disjoint_iff_ne,
assume t₁ h₁ t₂ h₂,
rcases finset.mem_image.1 h₂ with ⟨t₃, h₃, H₃₂⟩,
rw ← H₃₂,
exact ne_insert_of_not_mem _ _ (not_mem_of_mem_powerset_of_not_mem h₁ h) }
end
/-- A product over `powerset s` is equal to the double product over
sets of subsets of `s` with `card s = k`, for `k = 1, ... , card s`. -/
@[to_additive]
lemma prod_powerset [comm_monoid β] (s : finset α) (f : finset α → β) :
∏ t in powerset s, f t = ∏ j in range (card s + 1), ∏ t in powerset_len j s, f t :=
begin
classical,
rw [powerset_card_bUnion, prod_bUnion],
intros i hi j hj hij,
rw [function.on_fun, powerset_len_eq_filter, powerset_len_eq_filter, disjoint_filter],
intros x hx hc hnc,
apply hij,
rwa ← hc,
end
end finset
|
e1b013dea262cc0c7b7a8896c19043f5cd8a2c29 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/solve_by_elim.lean | b16784995b3a52689a70f777854b05013d2eb3ad | [
"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 | 15,233 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Scott Morrison
-/
import tactic.core
/-!
# solve_by_elim
A depth-first search backwards reasoner.
`solve_by_elim` takes a list of lemmas, and repeating tries to `apply` these against
the goals, recursively acting on any generated subgoals.
It accepts a variety of configuration options described below, enabling
* backtracking across multiple goals,
* pruning the search tree, and
* invoking other tactics before or after trying to apply lemmas.
At present it has no "premise selection", and simply tries the supplied lemmas in order
at each step of the search.
-/
namespace tactic
namespace solve_by_elim
/--
`mk_assumption_set` builds a collection of lemmas for use in
the backtracking search in `solve_by_elim`.
* By default, it includes all local hypotheses, along with `rfl`, `trivial`, `congr_fun` and
`congr_arg`.
* The flag `no_dflt` removes these.
* The argument `hs` is a list of `simp_arg_type`s,
and can be used to add, or remove, lemmas or expressions from the set.
* The argument `attr : list name` adds all lemmas tagged with one of a specified list of attributes.
`mk_assumption_set` returns not a `list expr`, but a `list (tactic expr) × tactic (list expr)`.
There are two separate problems that need to be solved.
### Relevant local hypotheses
`solve_by_elim*` works with multiple goals,
and we need to use separate sets of local hypotheses for each goal.
The second component of the returned value provides these local hypotheses.
(Essentially using `local_context`, along with some filtering to remove hypotheses
that have been explicitly removed via `only` or `[-h]`.)
### Stuck metavariables
Lemmas with implicit arguments would be filled in with metavariables if we created the
`expr` objects immediately, so instead we return thunks that generate the expressions
on demand. This is the first component, with type `list (tactic expr)`.
As an example, we have `def rfl : ∀ {α : Sort u} {a : α}, a = a`, which on elaboration will become
`@rfl ?m_1 ?m_2`.
Because `solve_by_elim` works by repeated application of lemmas against subgoals,
the first time such a lemma is successfully applied,
those metavariables will be unified, and thereafter have fixed values.
This would make it impossible to apply the lemma
a second time with different values of the metavariables.
See https://github.com/leanprover-community/mathlib/issues/2269
As an optimisation, after we build the list of `tactic expr`s, we actually run them, and replace any
that do not in fact produce metavariables with a simple `return` tactic.
-/
meta def mk_assumption_set (no_dflt : bool) (hs : list simp_arg_type) (attr : list name) :
tactic (list (tactic expr) × tactic (list expr)) :=
-- We lock the tactic state so that any spurious goals generated during
-- elaboration of pre-expressions are discarded
lock_tactic_state $
do
-- `hs` are expressions specified explicitly,
-- `hex` are exceptions (specified via `solve_by_elim [-h]`) referring to local hypotheses,
-- `gex` are the other exceptions
(hs, gex, hex, all_hyps) ← decode_simp_arg_list hs,
-- Recall, per the discussion above, we produce `tactic expr` thunks rather than actual `expr`s.
-- Note that while we evaluate these thunks on two occasions below while preparing the list,
-- this is a one-time cost during `mk_assumption_set`, rather than a cost proportional to the
-- length of the search `solve_by_elim` executes.
let hs := hs.map (λ h, i_to_expr_for_apply h),
l ← attr.mmap $ λ a, attribute.get_instances a,
let l := l.join,
let m := l.map (λ h, mk_const h),
-- In order to remove the expressions we need to evaluate the thunks.
hs ← (hs ++ m).mfilter $ λ h, (do h ← h, return $ expr.const_name h ∉ gex),
let hs := if no_dflt then hs else
([`rfl, `trivial, `congr_fun, `congr_arg].map (λ n, (mk_const n))) ++ hs,
let locals : tactic (list expr) := if ¬ no_dflt ∨ all_hyps then do
ctx ← local_context,
-- Remove local exceptions specified in `hex`:
return $ ctx.filter (λ h : expr, h.local_uniq_name ∉ hex)
else return [],
-- Finally, run all of the tactics: any that return an expression without metavariables can safely
-- be replaced by a `return` tactic.
hs ← hs.mmap (λ h : tactic expr, do e ← h, if e.has_meta_var then return h else return (return e)),
return (hs, locals)
/--
Configuration options for `solve_by_elim`.
* `accept : list expr → tactic unit` determines whether the current branch should be explored.
At each step, before the lemmas are applied,
`accept` is passed the proof terms for the original goals,
as reported by `get_goals` when `solve_by_elim` started.
These proof terms may be metavariables (if no progress has been made on that goal)
or may contain metavariables at some leaf nodes
(if the goal has been partially solved by previous `apply` steps).
If the `accept` tactic fails `solve_by_elim` aborts searching this branch and backtracks.
By default `accept := λ _, skip` always succeeds.
(There is an example usage in `tests/solve_by_elim.lean`.)
* `pre_apply : tactic unit` specifies an additional tactic to run before each round of `apply`.
* `discharger : tactic unit` specifies an additional tactic to apply on subgoals
for which no lemma applies.
If that tactic succeeds, `solve_by_elim` will continue applying lemmas on resulting goals.
-/
meta structure basic_opt extends apply_any_opt :=
(accept : list expr → tactic unit := λ _, skip)
(pre_apply : tactic unit := skip)
(discharger : tactic unit := failed)
(max_depth : ℕ := 3)
declare_trace solve_by_elim -- trace attempted lemmas
/--
A helper function for trace messages, prepending '....' depending on the current search depth.
-/
meta def solve_by_elim_trace (n : ℕ) (f : format) : tactic unit :=
trace_if_enabled `solve_by_elim
(format!"[solve_by_elim {(list.repeat '.' (n+1)).as_string} " ++ f ++ "]")
/-- A helper function to generate trace messages on successful applications. -/
meta def on_success (g : format) (n : ℕ) (e : expr) : tactic unit :=
do
pp ← pp e,
solve_by_elim_trace n (format!"✅ `{pp}` solves `⊢ {g}`")
/-- A helper function to generate trace messages on unsuccessful applications. -/
meta def on_failure (g : format) (n : ℕ) : tactic unit :=
solve_by_elim_trace n (format!"❌ failed to solve `⊢ {g}`")
/--
A helper function to generate the tactic that print trace messages.
This function exists to ensure the target is pretty printed only as necessary.
-/
meta def trace_hooks (n : ℕ) : tactic ((expr → tactic unit) × tactic unit) :=
if is_trace_enabled_for `solve_by_elim then
do
g ← target >>= pp,
return (on_success g n, on_failure g n)
else
return (λ _, skip, skip)
/--
The internal implementation of `solve_by_elim`, with a limiting counter.
-/
meta def solve_by_elim_aux (opt : basic_opt)
(original_goals : list expr) (lemmas : list (tactic expr)) (ctx : tactic (list expr)) : ℕ → tactic unit
| n := do
-- First, check that progress so far is `accept`able.
lock_tactic_state (original_goals.mmap instantiate_mvars >>= opt.accept),
-- Then check if we've finished.
(done >> solve_by_elim_trace (opt.max_depth - n) "success!") <|> (do
-- Otherwise, if there's more time left,
(guard (n > 0) <|>
solve_by_elim_trace opt.max_depth "🛑 aborting, hit depth limit" >> failed),
-- run the `pre_apply` tactic, then
opt.pre_apply,
-- try either applying a lemma and recursing,
(on_success, on_failure) ← trace_hooks (opt.max_depth - n),
ctx_lemmas ← ctx,
(apply_any_thunk (lemmas ++ (ctx_lemmas.map return)) opt.to_apply_any_opt (solve_by_elim_aux (n-1))
on_success on_failure) <|>
-- or if that doesn't work, run the discharger and recurse.
(opt.discharger >> solve_by_elim_aux (n-1)))
/--
Arguments for `solve_by_elim`:
* By default `solve_by_elim` operates only on the first goal,
but with `backtrack_all_goals := true`, it operates on all goals at once,
backtracking across goals as needed,
and only succeeds if it discharges all goals.
* `lemmas` specifies the list of lemmas to use in the backtracking search.
If `none`, `solve_by_elim` uses the local hypotheses,
along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`.
* `lemma_thunks` provides the lemmas as a list of `tactic expr`,
which are used to regenerate the `expr` objects to avoid binding metavariables.
It should not usually be specified by the user.
(If both `lemmas` and `lemma_thunks` are specified, only `lemma_thunks` is used.)
* `ctx_thunk` is for internal use only: it returns the local hypotheses which will be used.
* `max_depth` bounds the depth of the search.
-/
meta structure opt extends basic_opt :=
(backtrack_all_goals : bool := ff)
(lemmas : option (list expr) := none)
(lemma_thunks : option (list (tactic expr)) := lemmas.map (λ l, l.map return))
(ctx_thunk : tactic (list expr) := local_context)
/--
If no lemmas have been specified, generate the default set
(local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`).
-/
meta def opt.get_lemma_thunks (opt : opt) : tactic (list (tactic expr) × tactic (list expr)) :=
match opt.lemma_thunks with
| none := mk_assumption_set ff [] []
| some lemma_thunks := return (lemma_thunks, opt.ctx_thunk)
end
end solve_by_elim
open solve_by_elim
/--
`solve_by_elim` repeatedly tries `apply`ing a lemma
from the list of assumptions (passed via the `opt` argument),
recursively operating on any generated subgoals, backtracking as necessary.
`solve_by_elim` succeeds only if it discharges the goal.
(By default, `solve_by_elim` focuses on the first goal, and only attempts to solve that.
With the option `backtrack_all_goals := tt`,
it attempts to solve all goals, and only succeeds if it does so.
With `backtrack_all_goals := tt`, `solve_by_elim` will backtrack a solution it has found for
one goal if it then can't discharge other goals.)
If passed an empty list of assumptions, `solve_by_elim` builds a default set
as per the interactive tactic, using the `local_context` along with
`rfl`, `trivial`, `congr_arg`, and `congr_fun`.
To pass a particular list of assumptions, use the `lemmas` field
in the configuration argument. This expects an
`option (list expr)`. In certain situations it may be necessary to instead use the
`lemma_thunks` field, which expects a `option (list (tactic expr))`.
This allows for regenerating metavariables
for each application, which might otherwise get stuck.
See also the simpler tactic `apply_rules`, which does not perform backtracking.
-/
meta def solve_by_elim (opt : opt := { }) : tactic unit :=
do
tactic.fail_if_no_goals,
(lemmas, ctx_lemmas) ← opt.get_lemma_thunks,
(if opt.backtrack_all_goals then id else focus1) $ (do
gs ← get_goals,
solve_by_elim_aux opt.to_basic_opt gs lemmas ctx_lemmas opt.max_depth <|>
fail ("`solve_by_elim` failed.\n" ++
"Try `solve_by_elim { max_depth := N }` for `N > " ++ (to_string opt.max_depth) ++ "`\n" ++
"or use `set_option trace.solve_by_elim true` to view the search."))
open interactive lean.parser interactive.types
local postfix `?`:9001 := optional
namespace interactive
/--
`apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head`
where `head` matches the current goal.
If this fails, `apply_assumption` will call `symmetry` and try again.
If this also fails, `apply_assumption` will call `exfalso` and try again,
so that if there is an assumption of the form `P → ¬ Q`, the new tactic state
will have two goals, `P` and `Q`.
Optional arguments:
- `lemmas`: a list of expressions to apply, instead of the local constants
- `tac`: a tactic to run on each subgoal after applying an assumption; if
this tactic fails, the corresponding assumption will be rejected and
the next one will be attempted.
-/
meta def apply_assumption
(lemmas : option (list expr) := none)
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
do
lemmas ← match lemmas with
| none := local_context
| some lemmas := return lemmas
end,
tactic.apply_any lemmas opt tac
add_tactic_doc
{ name := "apply_assumption",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply_assumption],
tags := ["context management", "lemma application"] }
/--
`solve_by_elim` calls `apply` on the main goal to find an assumption whose head matches
and then repeatedly calls `apply` on the generated subgoals until no subgoals remain,
performing at most `max_depth` recursive steps.
`solve_by_elim` discharges the current goal or fails.
`solve_by_elim` performs back-tracking if subgoals can not be solved.
By default, the assumptions passed to `apply` are the local context, `rfl`, `trivial`,
`congr_fun` and `congr_arg`.
The assumptions can be modified with similar syntax as for `simp`:
* `solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the named lemmas.
* `solve_by_elim with attr₁ ... attrᵣ` also applies all lemmas tagged with the specified attributes.
* `solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context,
`rfl`, `trivial`, `congr_fun`, or `congr_arg` unless they are explicitly included.
* `solve_by_elim [-id_1, ... -id_n]` uses the default assumptions, removing the specified ones.
`solve_by_elim*` tries to solve all goals together, using backtracking if a solution for one goal
makes other goals impossible.
optional arguments passed via a configuration argument as `solve_by_elim { ... }`
- max_depth: number of attempts at discharging generated sub-goals
- discharger: a subsidiary tactic to try at each step when no lemmas apply
(e.g. `cc` may be helpful).
- pre_apply: a subsidiary tactic to run at each step before applying lemmas (e.g. `intros`).
- accept: a subsidiary tactic `list expr → tactic unit` that at each step,
before any lemmas are applied, is passed the original proof terms
as reported by `get_goals` when `solve_by_elim` started
(but which may by now have been partially solved by previous `apply` steps).
If the `accept` tactic fails,
`solve_by_elim` will abort searching the current branch and backtrack.
This may be used to filter results, either at every step of the search,
or filtering complete results
(by testing for the absence of metavariables, and then the filtering condition).
-/
meta def solve_by_elim (all_goals : parse $ (tk "*")?) (no_dflt : parse only_flag)
(hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : solve_by_elim.opt := { }) :
tactic unit :=
do (lemma_thunks, ctx_thunk) ← mk_assumption_set no_dflt hs attr_names,
tactic.solve_by_elim
{ backtrack_all_goals := all_goals.is_some ∨ opt.backtrack_all_goals,
lemma_thunks := some lemma_thunks,
ctx_thunk := ctx_thunk,
..opt }
add_tactic_doc
{ name := "solve_by_elim",
category := doc_category.tactic,
decl_names := [`tactic.interactive.solve_by_elim],
tags := ["search"] }
end interactive
end tactic
|
0d97a7acf9ae6c9483f9282881e7cb36689a099a | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/init/meta/constructor_tactic.lean | b2e47a6cd1513296fecfbfa43ca332df64c11a1c | [
"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 | 2,607 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.tactic init.function
namespace tactic
private meta_definition get_constructors_for (e : expr) : tactic (list name) :=
do env ← get_env,
I ← return $ expr.const_name (expr.get_app_fn e),
when (environment.is_inductive env I = ff) (fail "constructor tactic failed, target is not an inductive datatype"),
return $ environment.constructors_of env I
private meta_definition try_constructors : list name → tactic unit
| [] := fail "constructor tactic failed, none of the constructors is applicable"
| (c::cs) := (mk_const c >>= apply) <|> try_constructors cs
meta_definition constructor : tactic unit :=
target >>= get_constructors_for >>= try_constructors
meta_definition left : tactic unit :=
do tgt ← target,
[c₁, c₂] ← get_constructors_for tgt | fail "left tactic failed, target is not an inductive datatype with two constructors",
mk_const c₁ >>= apply
meta_definition right : tactic unit :=
do tgt ← target,
[c₁, c₂] ← get_constructors_for tgt | fail "left tactic failed, target is not an inductive datatype with two constructors",
mk_const c₂ >>= apply
meta_definition constructor_idx (idx : nat) : tactic unit :=
do cs ← target >>= get_constructors_for,
some c ← return $ list.nth cs (idx - 1) | fail "constructor_idx tactic failed, target is an inductive datatype, but it does not have sufficient constructors",
mk_const c >>= apply
meta_definition split : tactic unit :=
do [c] ← target >>= get_constructors_for | fail "split tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= apply
open expr
private meta_definition apply_num_metavars : expr → expr → nat → tactic expr
| f ftype 0 := return f
| f ftype (n+1) := do
pi m bi d b ← whnf ftype | failed,
a ← mk_meta_var d,
new_f ← return $ expr.app f a,
new_ftype ← return $ expr.instantiate_var b a,
apply_num_metavars new_f new_ftype n
meta_definition existsi (e : expr) : tactic unit :=
do [c] ← target >>= get_constructors_for | fail "existsi tactic failed, target is not an inductive datatype with only one constructor",
fn ← mk_const c,
fn_type ← infer_type fn,
n ← get_arity fn,
when (n < 2) (fail "existsi tactic failed, constructor must have at least two arguments"),
t ← apply_num_metavars fn fn_type (n - 2),
apply (app t e)
end tactic
|
731c64bb84d898ee432bc3158c0e3f2a7e03948a | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/algebra/gcd_monoid.lean | e2739ffed0cbe997191ad43a8aa87e25f98ce29e | [
"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 | 31,333 | 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
TODO: Provide a GCD monoid instance for `ℕ`, port GCD facts about nats
TODO: Generalize normalization monoids commutative (cancellative) monoids with or without zero
TODO: Generalize GCD monoid to not require normalization in all cases
-/
import algebra.associated
import data.nat.basic
import data.int.gcd
/-!
# Monoids with normalization functions, `gcd`, and `lcm`
This file defines extra structures on `comm_cancel_monoid_with_zero`s, including `integral_domain`s.
## Main Definitions
* `normalization_monoid`
* `gcd_monoid`
## Implementation Notes
* `normalization_monoid` is defined by assigning to each element a `norm_unit` such that multiplying
by that unit normalizes the monoid, and `normalize` is an idempotent monoid homomorphism. This
definition as currently implemented does casework on `0`.
* `gcd_monoid` extends `normalization_monoid`, so the `gcd` and `lcm` are always normalized.
This makes `gcd`s of polynomials easier to work with, but excludes Euclidean domains, and monoids
without zero.
## TODO
* Provide a GCD monoid instance for `ℕ`, port GCD facts about nats, definition of coprime
* Generalize normalization monoids to commutative (cancellative) monoids with or without zero
* Generalize GCD monoid to not require normalization in all cases
## Tags
divisibility, gcd, lcm, normalize
-/
variables {α : Type*}
set_option old_structure_cmd true
section prio
set_option default_priority 100 -- see Note [default priority]
/-- Normalization monoid: multiplying with `norm_unit` gives a normal form for associated elements. -/
@[protect_proj] class normalization_monoid (α : Type*) [nontrivial α]
[comm_cancel_monoid_with_zero α] :=
(norm_unit : α → units α)
(norm_unit_zero : norm_unit 0 = 1)
(norm_unit_mul : ∀{a b}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b)
(norm_unit_coe_units : ∀(u : units α), norm_unit u = u⁻¹)
end prio
export normalization_monoid (norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units)
attribute [simp] norm_unit_coe_units norm_unit_zero norm_unit_mul
section normalization_monoid
variables [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α]
@[simp] theorem norm_unit_one : norm_unit (1:α) = 1 :=
norm_unit_coe_units 1
/-- Chooses an element of each associate class, by multiplying by `norm_unit` -/
def normalize : α →* α :=
{ to_fun := λ x, x * norm_unit x,
map_one' := by rw [norm_unit_one, units.coe_one, mul_one],
map_mul' := λ x y,
classical.by_cases (λ hx : x = 0, by rw [hx, zero_mul, zero_mul, zero_mul]) $ λ hx,
classical.by_cases (λ hy : y = 0, by rw [hy, mul_zero, zero_mul, mul_zero]) $ λ hy,
by simp only [norm_unit_mul hx hy, units.coe_mul]; simp only [mul_assoc, mul_left_comm y], }
@[simp] lemma normalize_apply {x : α} : normalize x = x * norm_unit x := rfl
theorem associated_normalize {x : α} : associated x (normalize x) :=
⟨_, rfl⟩
theorem normalize_associated {x : α} : associated (normalize x) x :=
associated_normalize.symm
@[simp] lemma normalize_zero : normalize (0 : α) = 0 := by simp
@[simp] lemma normalize_one : normalize (1 : α) = 1 := normalize.map_one
lemma normalize_coe_units (u : units α) : normalize (u : α) = 1 := by simp
lemma normalize_eq_zero {x : α} : normalize x = 0 ↔ x = 0 :=
⟨λ hx, (associated_zero_iff_eq_zero x).1 $ hx ▸ associated_normalize, by rintro rfl; exact normalize_zero⟩
lemma normalize_eq_one {x : α} : normalize x = 1 ↔ is_unit x :=
⟨λ hx, is_unit_iff_exists_inv.2 ⟨_, hx⟩, λ ⟨u, hu⟩, hu ▸ normalize_coe_units u⟩
@[simp] theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 :=
classical.by_cases (assume : a = 0, by simp only [this, norm_unit_zero, zero_mul]) $
assume h, by rw [norm_unit_mul h (units.ne_zero _), norm_unit_coe_units, mul_inv_eq_one]
theorem normalize_idem (x : α) : normalize (normalize x) = normalize x := by simp
theorem normalize_eq_normalize {a b : α}
(hab : a ∣ b) (hba : b ∣ a) : normalize a = normalize b :=
begin
rcases associated_of_dvd_dvd hab hba with ⟨u, rfl⟩,
refine classical.by_cases (by rintro rfl; simp only [zero_mul]) (assume ha : a ≠ 0, _),
suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹,
by simpa only [normalize_apply, mul_assoc, norm_unit_mul ha u.ne_zero, norm_unit_coe_units],
calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑u * ↑u⁻¹:
(units.mul_inv_cancel_right _ _).symm
... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by rw mul_right_comm a
end
lemma normalize_eq_normalize_iff {x y : α} : normalize x = normalize y ↔ x ∣ y ∧ y ∣ x :=
⟨λ h, ⟨units.dvd_mul_right.1 ⟨_, h.symm⟩, units.dvd_mul_right.1 ⟨_, h⟩⟩,
λ ⟨hxy, hyx⟩, normalize_eq_normalize hxy hyx⟩
theorem dvd_antisymm_of_normalize_eq {a b : α}
(ha : normalize a = a) (hb : normalize b = b) (hab : a ∣ b) (hba : b ∣ a) :
a = b :=
ha ▸ hb ▸ normalize_eq_normalize hab hba
--can be proven by simp
lemma dvd_normalize_iff {a b : α} : a ∣ normalize b ↔ a ∣ b :=
units.dvd_mul_right
--can be proven by simp
lemma normalize_dvd_iff {a b : α} : normalize a ∣ b ↔ a ∣ b :=
units.mul_right_dvd
end normalization_monoid
namespace associates
variables [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α]
local attribute [instance] associated.setoid
/-- Maps an element of `associates` back to the normalized element of its associate class -/
protected def out : associates α → α :=
quotient.lift (normalize : α → α) $ λ a b ⟨u, hu⟩, hu ▸
normalize_eq_normalize ⟨_, rfl⟩ (units.mul_right_dvd.2 $ dvd_refl a)
lemma out_mk (a : α) : (associates.mk a).out = normalize a := rfl
@[simp] lemma out_one : (1 : associates α).out = 1 :=
normalize_one
lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out :=
quotient.induction_on₂ a b $ assume a b,
by simp only [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk, normalize.map_mul]
lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b :=
quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff]
lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a :=
quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff]
@[simp] lemma out_top : (⊤ : associates α).out = 0 :=
normalize_zero
@[simp] lemma normalize_out (a : associates α) : normalize a.out = a.out :=
quotient.induction_on a normalize_idem
end associates
section prio
set_option default_priority 100 -- see Note [default priority]
/-- GCD monoid: a `comm_cancel_monoid_with_zero` with normalization and `gcd`
(greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and
`lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the
supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the
corresponding `lcm` facts from `gcd`.
-/
@[protect_proj] class gcd_monoid (α : Type*) [comm_cancel_monoid_with_zero α] [nontrivial α]
extends normalization_monoid α :=
(gcd : α → α → α)
(lcm : α → α → α)
(gcd_dvd_left : ∀a b, gcd a b ∣ a)
(gcd_dvd_right : ∀a b, gcd a b ∣ b)
(dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b)
(normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b)
(gcd_mul_lcm : ∀a b, gcd a b * lcm a b = normalize (a * b))
(lcm_zero_left : ∀a, lcm 0 a = 0)
(lcm_zero_right : ∀a, lcm a 0 = 0)
end prio
export gcd_monoid (gcd lcm gcd_dvd_left gcd_dvd_right dvd_gcd lcm_zero_left lcm_zero_right)
attribute [simp] lcm_zero_left lcm_zero_right
section gcd_monoid
variables [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α]
@[simp] theorem normalize_gcd : ∀a b:α, normalize (gcd a b) = gcd a b :=
gcd_monoid.normalize_gcd
@[simp] theorem gcd_mul_lcm : ∀a b:α, gcd a b * lcm a b = normalize (a * b) :=
gcd_monoid.gcd_mul_lcm
section gcd
theorem dvd_gcd_iff (a b c : α) : a ∣ gcd b c ↔ (a ∣ b ∧ a ∣ c) :=
iff.intro
(assume h, ⟨dvd_trans h (gcd_dvd_left _ _), dvd_trans h (gcd_dvd_right _ _)⟩)
(assume ⟨hab, hac⟩, dvd_gcd hab hac)
theorem gcd_comm (a b : α) : gcd a b = gcd b a :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _)
(dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _))
(dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _))
theorem gcd_assoc (m n k : α) : gcd (gcd m n) k = gcd m (gcd n k) :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _)
(dvd_gcd
(dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n))
(dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k)))
(dvd_gcd
(dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k)))
(dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k)))
instance : is_commutative α gcd := ⟨gcd_comm⟩
instance : is_associative α gcd := ⟨gcd_assoc⟩
theorem gcd_eq_normalize {a b c : α} (habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) :
gcd a b = normalize c :=
normalize_gcd a b ▸ normalize_eq_normalize habc hcab
@[simp] theorem gcd_zero_left (a : α) : gcd 0 a = normalize a :=
gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a))
@[simp] theorem gcd_zero_right (a : α) : gcd a 0 = normalize a :=
gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _))
@[simp] theorem gcd_eq_zero_iff (a b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 :=
iff.intro
(assume h, let ⟨ca, ha⟩ := gcd_dvd_left a b, ⟨cb, hb⟩ := gcd_dvd_right a b in
by rw [h, zero_mul] at ha hb; exact ⟨ha, hb⟩)
(assume ⟨ha, hb⟩, by rw [ha, hb, gcd_zero_left, normalize_zero])
@[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_left _ _) (one_dvd _)
@[simp] theorem gcd_one_right (a : α) : gcd a 1 = 1 :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_right _ _) (one_dvd _)
theorem gcd_dvd_gcd {a b c d: α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d :=
dvd_gcd (dvd.trans (gcd_dvd_left _ _) hab) (dvd.trans (gcd_dvd_right _ _) hcd)
@[simp] theorem gcd_same (a : α) : gcd a a = normalize a :=
gcd_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a))
@[simp] theorem gcd_mul_left (a b c : α) : gcd (a * b) (a * c) = normalize a * gcd b c :=
classical.by_cases (by rintro rfl; simp only [zero_mul, gcd_zero_left, normalize_zero]) $ assume ha : a ≠ 0,
suffices gcd (a * b) (a * c) = normalize (a * gcd b c),
by simpa only [normalize.map_mul, normalize_gcd],
let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in
gcd_eq_normalize
(eq.symm ▸ mul_dvd_mul_left a $ show d ∣ gcd b c, from
dvd_gcd
((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _)
((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _))
(dvd_gcd
(mul_dvd_mul_left a $ gcd_dvd_left _ _)
(mul_dvd_mul_left a $ gcd_dvd_right _ _))
@[simp] theorem gcd_mul_right (a b c : α) : gcd (b * a) (c * a) = gcd b c * normalize a :=
by simp only [mul_comm, gcd_mul_left]
theorem gcd_eq_left_iff (a b : α) (h : normalize a = a) : gcd a b = a ↔ a ∣ b :=
iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $
assume hab, dvd_antisymm_of_normalize_eq (normalize_gcd _ _) h (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) hab)
theorem gcd_eq_right_iff (a b : α) (h : normalize b = b) : gcd a b = b ↔ b ∣ a :=
by simpa only [gcd_comm a b] using gcd_eq_left_iff b a h
theorem gcd_dvd_gcd_mul_left (m n k : α) : gcd m n ∣ gcd (k * m) n :=
gcd_dvd_gcd (dvd_mul_left _ _) (dvd_refl _)
theorem gcd_dvd_gcd_mul_right (m n k : α) : gcd m n ∣ gcd (m * k) n :=
gcd_dvd_gcd (dvd_mul_right _ _) (dvd_refl _)
theorem gcd_dvd_gcd_mul_left_right (m n k : α) : gcd m n ∣ gcd m (k * n) :=
gcd_dvd_gcd (dvd_refl _) (dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right_right (m n k : α) : gcd m n ∣ gcd m (n * k) :=
gcd_dvd_gcd (dvd_refl _) (dvd_mul_right _ _)
end gcd
section lcm
lemma lcm_dvd_iff {a b c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c :=
classical.by_cases
(assume : a = 0 ∨ b = 0, by rcases this with rfl | rfl;
simp only [iff_def, lcm_zero_left, lcm_zero_right, zero_dvd_iff, dvd_zero,
eq_self_iff_true, and_true, imp_true_iff] {contextual:=tt})
(assume this : ¬ (a = 0 ∨ b = 0),
let ⟨h1, h2⟩ := not_or_distrib.1 this in
have h : gcd a b ≠ 0, from λ H, h1 ((gcd_eq_zero_iff _ _).1 H).1,
by rw [← mul_dvd_mul_iff_left h, gcd_mul_lcm, normalize_dvd_iff, ← dvd_normalize_iff,
normalize.map_mul, normalize_gcd, ← gcd_mul_right, dvd_gcd_iff,
mul_comm b c, mul_dvd_mul_iff_left h1, mul_dvd_mul_iff_right h2, and_comm])
lemma dvd_lcm_left (a b : α) : a ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).1
lemma dvd_lcm_right (a b : α) : b ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).2
lemma lcm_dvd {a b c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b :=
lcm_dvd_iff.2 ⟨hab, hcb⟩
@[simp] theorem lcm_eq_zero_iff (a b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 :=
iff.intro
(assume h : lcm a b = 0,
have normalize (a * b) = 0,
by rw [← gcd_mul_lcm _ _, h, mul_zero],
by simpa only [normalize_eq_zero, mul_eq_zero, units.ne_zero, or_false])
(by rintro (rfl | rfl); [apply lcm_zero_left, apply lcm_zero_right])
@[simp] lemma normalize_lcm (a b : α) : normalize (lcm a b) = lcm a b :=
classical.by_cases (assume : lcm a b = 0, by rw [this, normalize_zero]) $
assume h_lcm : lcm a b ≠ 0,
have h1 : gcd a b ≠ 0, from mt (by rw [gcd_eq_zero_iff, lcm_eq_zero_iff];
rintros ⟨rfl, rfl⟩; left; refl) h_lcm,
have h2 : normalize (gcd a b * lcm a b) = gcd a b * lcm a b,
by rw [gcd_mul_lcm, normalize_idem],
by simpa only [normalize.map_mul, normalize_gcd, one_mul, mul_right_inj' h1] using h2
theorem lcm_comm (a b : α) : lcm a b = lcm b a :=
dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _)
(lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _))
(lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _))
theorem lcm_assoc (m n k : α) : lcm (lcm m n) k = lcm m (lcm n k) :=
dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _)
(lcm_dvd
(lcm_dvd (dvd_lcm_left _ _) (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_right _ _)))
(dvd.trans (dvd_lcm_right _ _) (dvd_lcm_right _ _)))
(lcm_dvd
(dvd.trans (dvd_lcm_left _ _) (dvd_lcm_left _ _))
(lcm_dvd (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (dvd_lcm_right _ _)))
instance : is_commutative α lcm := ⟨lcm_comm⟩
instance : is_associative α lcm := ⟨lcm_assoc⟩
lemma lcm_eq_normalize {a b c : α} (habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) :
lcm a b = normalize c :=
normalize_lcm a b ▸ normalize_eq_normalize habc hcab
theorem lcm_dvd_lcm {a b c d : α} (hab : a ∣ b) (hcd : c ∣ d) : lcm a c ∣ lcm b d :=
lcm_dvd (dvd.trans hab (dvd_lcm_left _ _)) (dvd.trans hcd (dvd_lcm_right _ _))
@[simp] theorem lcm_units_coe_left (u : units α) (a : α) : lcm ↑u a = normalize a :=
lcm_eq_normalize (lcm_dvd units.coe_dvd (dvd_refl _)) (dvd_lcm_right _ _)
@[simp] theorem lcm_units_coe_right (a : α) (u : units α) : lcm a ↑u = normalize a :=
(lcm_comm a u).trans $ lcm_units_coe_left _ _
@[simp] theorem lcm_one_left (a : α) : lcm 1 a = normalize a :=
lcm_units_coe_left 1 a
@[simp] theorem lcm_one_right (a : α) : lcm a 1 = normalize a :=
lcm_units_coe_right a 1
@[simp] theorem lcm_same (a : α) : lcm a a = normalize a :=
lcm_eq_normalize (lcm_dvd (dvd_refl _) (dvd_refl _)) (dvd_lcm_left _ _)
@[simp] theorem lcm_eq_one_iff (a b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 :=
iff.intro
(assume eq, eq ▸ ⟨dvd_lcm_left _ _, dvd_lcm_right _ _⟩)
(assume ⟨⟨c, hc⟩, ⟨d, hd⟩⟩,
show lcm (units.mk_of_mul_eq_one a c hc.symm : α) (units.mk_of_mul_eq_one b d hd.symm) = 1,
by rw [lcm_units_coe_left, normalize_coe_units])
@[simp] theorem lcm_mul_left (a b c : α) : lcm (a * b) (a * c) = normalize a * lcm b c :=
classical.by_cases (by rintro rfl; simp only [zero_mul, lcm_zero_left, normalize_zero]) $ assume ha : a ≠ 0,
suffices lcm (a * b) (a * c) = normalize (a * lcm b c),
by simpa only [normalize.map_mul, normalize_lcm],
have a ∣ lcm (a * b) (a * c), from dvd.trans (dvd_mul_right _ _) (dvd_lcm_left _ _),
let ⟨d, eq⟩ := this in
lcm_eq_normalize
(lcm_dvd (mul_dvd_mul_left a (dvd_lcm_left _ _)) (mul_dvd_mul_left a (dvd_lcm_right _ _)))
(eq.symm ▸ (mul_dvd_mul_left a $ lcm_dvd
((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_left _ _)
((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_right _ _)))
@[simp] theorem lcm_mul_right (a b c : α) : lcm (b * a) (c * a) = lcm b c * normalize a :=
by simp only [mul_comm, lcm_mul_left]
theorem lcm_eq_left_iff (a b : α) (h : normalize a = a) : lcm a b = a ↔ b ∣ a :=
iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $
assume hab, dvd_antisymm_of_normalize_eq (normalize_lcm _ _) h (lcm_dvd (dvd_refl a) hab) (dvd_lcm_left _ _)
theorem lcm_eq_right_iff (a b : α) (h : normalize b = b) : lcm a b = b ↔ a ∣ b :=
by simpa only [lcm_comm b a] using lcm_eq_left_iff b a h
theorem lcm_dvd_lcm_mul_left (m n k : α) : lcm m n ∣ lcm (k * m) n :=
lcm_dvd_lcm (dvd_mul_left _ _) (dvd_refl _)
theorem lcm_dvd_lcm_mul_right (m n k : α) : lcm m n ∣ lcm (m * k) n :=
lcm_dvd_lcm (dvd_mul_right _ _) (dvd_refl _)
theorem lcm_dvd_lcm_mul_left_right (m n k : α) : lcm m n ∣ lcm m (k * n) :=
lcm_dvd_lcm (dvd_refl _) (dvd_mul_left _ _)
theorem lcm_dvd_lcm_mul_right_right (m n k : α) : lcm m n ∣ lcm m (n * k) :=
lcm_dvd_lcm (dvd_refl _) (dvd_mul_right _ _)
end lcm
namespace gcd_monoid
theorem prime_of_irreducible {x : α} (hi: irreducible x) : prime x :=
⟨hi.ne_zero, ⟨hi.1, λ a b h,
begin
cases gcd_dvd_left x a with y hy,
cases hi.2 _ _ hy with hu hu; cases hu with u hu,
{ right, transitivity (gcd (x * b) (a * b)), apply dvd_gcd (dvd_mul_right x b) h,
rw gcd_mul_right, rw ← hu,
apply dvd_of_associated, transitivity (normalize b), symmetry, use u, apply mul_comm,
apply normalize_associated, },
{ left, rw [hy, ← hu],
transitivity, {apply dvd_of_associated, symmetry, use u}, apply gcd_dvd_right, }
end ⟩⟩
theorem irreducible_iff_prime {p : α} : irreducible p ↔ prime p :=
⟨prime_of_irreducible, irreducible_of_prime⟩
end gcd_monoid
end gcd_monoid
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
by_cases ha : 0 ≤ a; by_cases hb : 0 ≤ b; simp [ha, hb],
exact if_pos (mul_nonneg ha hb),
exact if_neg (assume h, hb $ nonneg_of_mul_nonneg_left h $ lt_of_le_of_ne ha hna.symm),
exact if_neg (assume h, ha $ nonneg_of_mul_nonneg_right h $ lt_of_le_of_ne hb hnb.symm),
exact if_pos (mul_nonneg_of_nonpos_of_nonpos (le_of_not_ge ha) (le_of_not_ge hb))
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 simp [@neg_lt ℤ _ 1 0])), }
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
/-- ℤ specific version of least common multiple. -/
def lcm (i j : ℤ) : ℕ := nat.lcm (nat_abs i) (nat_abs j)
theorem lcm_def (i j : ℤ) : lcm i j = nat.lcm (nat_abs i) (nat_abs j) := rfl
section gcd_monoid
theorem gcd_dvd_left (i j : ℤ) : (gcd i j : ℤ) ∣ i :=
dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_left _ _
theorem gcd_dvd_right (i j : ℤ) : (gcd i j : ℤ) ∣ j :=
dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_right _ _
theorem dvd_gcd {i j k : ℤ} (h1 : k ∣ i) (h2 : k ∣ j) : k ∣ gcd i j :=
nat_abs_dvd.1 $ coe_nat_dvd.2 $ nat.dvd_gcd (nat_abs_dvd_abs_iff.2 h1) (nat_abs_dvd_abs_iff.2 h2)
theorem gcd_mul_lcm (i j : ℤ) : gcd i j * lcm i j = nat_abs (i * j) :=
by rw [int.gcd, int.lcm, nat.gcd_mul_lcm, nat_abs_mul]
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
theorem gcd_comm (i j : ℤ) : gcd i j = gcd j i := nat.gcd_comm _ _
theorem gcd_assoc (i j k : ℤ) : gcd (gcd i j) k = gcd i (gcd j k) := nat.gcd_assoc _ _ _
@[simp] theorem gcd_self (i : ℤ) : gcd i i = nat_abs i := by simp [gcd]
@[simp] theorem gcd_zero_left (i : ℤ) : gcd 0 i = nat_abs i := by simp [gcd]
@[simp] theorem gcd_zero_right (i : ℤ) : gcd i 0 = nat_abs i := by simp [gcd]
@[simp] theorem gcd_one_left (i : ℤ) : gcd 1 i = 1 := nat.gcd_one_left _
@[simp] theorem gcd_one_right (i : ℤ) : gcd i 1 = 1 := nat.gcd_one_right _
theorem gcd_mul_left (i j k : ℤ) : gcd (i * j) (i * k) = nat_abs i * gcd j k :=
by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize]
theorem gcd_mul_right (i j k : ℤ) : gcd (i * j) (k * j) = gcd i k * nat_abs j :=
by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize]
theorem gcd_pos_of_non_zero_left {i : ℤ} (j : ℤ) (i_non_zero : i ≠ 0) : 0 < gcd i j :=
nat.gcd_pos_of_pos_left (nat_abs j) (nat_abs_pos_of_ne_zero i_non_zero)
theorem gcd_pos_of_non_zero_right (i : ℤ) {j : ℤ} (j_non_zero : j ≠ 0) : 0 < gcd i j :=
nat.gcd_pos_of_pos_right (nat_abs i) (nat_abs_pos_of_ne_zero j_non_zero)
theorem gcd_eq_zero_iff {i j : ℤ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 :=
by rw [← int.coe_nat_eq_coe_nat_iff, int.coe_nat_zero, coe_gcd, gcd_eq_zero_iff]
theorem gcd_div {i j k : ℤ} (H1 : k ∣ i) (H2 : k ∣ j) :
gcd (i / k) (j / k) = gcd i j / nat_abs k :=
by rw [gcd, nat_abs_div i k H1, nat_abs_div j k H2];
exact nat.gcd_div (nat_abs_dvd_abs_iff.mpr H1) (nat_abs_dvd_abs_iff.mpr H2)
theorem gcd_div_gcd_div_gcd {i j : ℤ} (H : 0 < gcd i j) :
gcd (i / gcd i j) (j / gcd i j) = 1 :=
begin
rw [gcd_div (gcd_dvd_left i j) (gcd_dvd_right i j)],
rw [nat_abs_of_nat, nat.div_self H]
end
theorem gcd_dvd_gcd_of_dvd_left {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd i j ∣ gcd k j :=
int.coe_nat_dvd.1 $ dvd_gcd (dvd.trans (gcd_dvd_left i j) H) (gcd_dvd_right i j)
theorem gcd_dvd_gcd_of_dvd_right {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd j i ∣ gcd j k :=
int.coe_nat_dvd.1 $ dvd_gcd (gcd_dvd_left j i) (dvd.trans (gcd_dvd_right j i) H)
theorem gcd_dvd_gcd_mul_left (i j k : ℤ) : gcd i j ∣ gcd (k * i) j :=
gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right (i j k : ℤ) : gcd i j ∣ gcd (i * k) j :=
gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _)
theorem gcd_dvd_gcd_mul_left_right (i j k : ℤ) : gcd i j ∣ gcd i (k * j) :=
gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right_right (i j k : ℤ) : gcd i j ∣ gcd i (j * k) :=
gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _)
theorem gcd_eq_left {i j : ℤ} (H : i ∣ j) : gcd i j = nat_abs i :=
nat.dvd_antisymm (by unfold gcd; exact nat.gcd_dvd_left _ _)
(by unfold gcd; exact nat.dvd_gcd (dvd_refl _) (nat_abs_dvd_abs_iff.mpr H))
theorem gcd_eq_right {i j : ℤ} (H : j ∣ i) : gcd i j = nat_abs j :=
by rw [gcd_comm, gcd_eq_left H]
theorem ne_zero_of_gcd {x y : ℤ}
(hc : gcd x y ≠ 0) : x ≠ 0 ∨ y ≠ 0 :=
begin
contrapose! hc,
rw [hc.left, hc.right, gcd_zero_right, nat_abs_zero]
end
theorem exists_gcd_one {m n : ℤ} (H : 0 < gcd m n) :
∃ (m' n' : ℤ), gcd m' n' = 1 ∧ m = m' * gcd m n ∧ n = n' * gcd m n :=
⟨_, _, gcd_div_gcd_div_gcd H,
(int.div_mul_cancel (gcd_dvd_left m n)).symm,
(int.div_mul_cancel (gcd_dvd_right m n)).symm⟩
theorem exists_gcd_one' {m n : ℤ} (H : 0 < gcd m n) :
∃ (g : ℕ) (m' n' : ℤ), 0 < g ∧ gcd m' n' = 1 ∧ m = m' * g ∧ n = n' * g :=
let ⟨m', n', h⟩ := exists_gcd_one H in ⟨_, m', n', H, h⟩
theorem pow_dvd_pow_iff {m n : ℤ} {k : ℕ} (k0 : 0 < k) : m ^ k ∣ n ^ k ↔ m ∣ n :=
begin
refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩,
apply int.nat_abs_dvd_abs_iff.mp,
apply (nat.pow_dvd_pow_iff k0).mp,
rw [← int.nat_abs_pow, ← int.nat_abs_pow],
exact int.nat_abs_dvd_abs_iff.mpr h
end
/- lcm -/
theorem lcm_comm (i j : ℤ) : lcm i j = lcm j i :=
by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_comm]
theorem lcm_assoc (i j k : ℤ) : lcm (lcm i j) k = lcm i (lcm j k) :=
by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_assoc]
@[simp] theorem lcm_zero_left (i : ℤ) : lcm 0 i = 0 :=
by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm]
@[simp] theorem lcm_zero_right (i : ℤ) : lcm i 0 = 0 :=
by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm]
@[simp] theorem lcm_one_left (i : ℤ) : lcm 1 i = nat_abs i :=
by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize]
@[simp] theorem lcm_one_right (i : ℤ) : lcm i 1 = nat_abs i :=
by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize]
@[simp] theorem lcm_self (i : ℤ) : lcm i i = nat_abs i :=
by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize]
theorem dvd_lcm_left (i j : ℤ) : i ∣ lcm i j :=
by rw [coe_lcm]; exact dvd_lcm_left _ _
theorem dvd_lcm_right (i j : ℤ) : j ∣ lcm i j :=
by rw [coe_lcm]; exact dvd_lcm_right _ _
theorem lcm_dvd {i j k : ℤ} : i ∣ k → j ∣ k → (lcm i j : ℤ) ∣ k :=
by rw [coe_lcm]; exact lcm_dvd
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, (≥), 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, ⟨nat.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 is_unit_int.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 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 two_pos hp2) (nat.prime.two_le hp) },
{ apply or.intro_right,
rw [pow_two, int.nat_abs_mul] at hpp,
exact (or_self _).mp ((nat.prime.dvd_mul hp).mp hpp)}
end
section unique_unit
instance nat.unique_units : unique (units ℕ) :=
{ default := 1, uniq := nat.units_eq_one }
variables [comm_cancel_monoid_with_zero α] [unique (units α)]
lemma units_eq_one (u : units α) : u = 1 := subsingleton.elim u 1
variable [nontrivial α]
section prio
set_option default_priority 100 -- see Note [default priority]
instance normalization_monoid_of_unique_units : normalization_monoid α :=
{ norm_unit := λ x, 1,
norm_unit_zero := rfl,
norm_unit_mul := λ x y hx hy, (mul_one 1).symm,
norm_unit_coe_units := λ u, subsingleton.elim _ _ }
end prio
@[simp] lemma norm_unit_eq_one (x : α) : norm_unit x = 1 := rfl
@[simp] lemma normalize_eq (x : α) : normalize x = x := mul_one x
end unique_unit
|
81d86953b017b41922c673d2b9fc488686cbc962 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/simplifier_prove_failures.lean | 9b06fbcdafb56f577cdf89d7e7754abd7e5d37a8 | [
"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 | 727 | lean | open tactic
constants (P Q R : Prop) (HP : P) (HPQ : P → Q) (HQR : Q → R = true)
attribute HQR [simp]
meta_definition prove_skip : tactic unit := skip
meta_definition prove_fail : tactic unit := failed
meta_definition prove_partial_assign : tactic unit := mk_const `HPQ >>= apply
meta_definition prove_full_assign : tactic unit := (mk_const `HPQ >>= apply) >> (mk_const `HP) >>= exact
set_option trace.simplifier.prove true
example : R := by simplify_goal prove_skip [] >> try triv
example : R := by simplify_goal prove_fail [] >> try triv
example : R := by simplify_goal prove_partial_assign [] >> try triv
example : R := by simplify_goal prove_full_assign [] >> try triv
|
fcb100bed46ec663f2387209718fa73353c2718d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/deprecated/subring.lean | fa0f809eb5fae5c208aee8b0707d9656c2bc5697 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 8,915 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import deprecated.subgroup
import deprecated.group
import ring_theory.subring.basic
/-!
# Unbundled subrings (deprecated)
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file is deprecated, and is no longer imported by anything in mathlib other than other
deprecated files, and test files. You should not need to import it.
This file defines predicates for unbundled subrings. Instead of using this file, please use
`subring`, defined in `ring_theory.subring.basic`, for subrings of rings.
## Main definitions
`is_subring (S : set R) : Prop` : the predicate that `S` is the underlying set of a subring
of the ring `R`. The bundled variant `subring R` should be used in preference to this.
## Tags
is_subring
-/
universes u v
open group
variables {R : Type u} [ring R]
/-- `S` is a subring: a set containing 1 and closed under multiplication, addition and additive
inverse. -/
structure is_subring (S : set R) extends is_add_subgroup S, is_submonoid S : Prop.
/-- Construct a `subring` from a set satisfying `is_subring`. -/
def is_subring.subring {S : set R} (hs : is_subring S) : subring R :=
{ carrier := S,
one_mem' := hs.one_mem,
mul_mem' := λ _ _, hs.mul_mem,
zero_mem' := hs.zero_mem,
add_mem' := λ _ _, hs.add_mem,
neg_mem' := λ _, hs.neg_mem }
namespace ring_hom
lemma is_subring_preimage {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) {s : set S} (hs : is_subring s) : is_subring (f ⁻¹' s) :=
{ ..is_add_group_hom.preimage f.to_is_add_group_hom hs.to_is_add_subgroup,
..is_submonoid.preimage f.to_is_monoid_hom hs.to_is_submonoid, }
lemma is_subring_image {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) {s : set R} (hs : is_subring s) : is_subring (f '' s) :=
{ ..is_add_group_hom.image_add_subgroup f.to_is_add_group_hom hs.to_is_add_subgroup,
..is_submonoid.image f.to_is_monoid_hom hs.to_is_submonoid, }
lemma is_subring_set_range {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) : is_subring (set.range f) :=
{ ..is_add_group_hom.range_add_subgroup f.to_is_add_group_hom,
..range.is_submonoid f.to_is_monoid_hom, }
end ring_hom
variables {cR : Type u} [comm_ring cR]
lemma is_subring.inter {S₁ S₂ : set R} (hS₁ : is_subring S₁) (hS₂ : is_subring S₂) :
is_subring (S₁ ∩ S₂) :=
{ ..is_add_subgroup.inter hS₁.to_is_add_subgroup hS₂.to_is_add_subgroup,
..is_submonoid.inter hS₁.to_is_submonoid hS₂.to_is_submonoid }
lemma is_subring.Inter {ι : Sort*} {S : ι → set R} (h : ∀ y : ι, is_subring (S y)) :
is_subring (set.Inter S) :=
{ ..is_add_subgroup.Inter (λ i, (h i).to_is_add_subgroup),
..is_submonoid.Inter (λ i, (h i).to_is_submonoid) }
lemma is_subring_Union_of_directed {ι : Type*} [hι : nonempty ι]
{s : ι → set R} (h : ∀ i, is_subring (s i))
(directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) :
is_subring (⋃i, s i) :=
{ to_is_add_subgroup := is_add_subgroup_Union_of_directed
(λ i, (h i).to_is_add_subgroup) directed,
to_is_submonoid := is_submonoid_Union_of_directed (λ i, (h i).to_is_submonoid) directed }
namespace ring
/-- The smallest subring containing a given subset of a ring, considered as a set. This function
is deprecated; use `subring.closure`. -/
def closure (s : set R) := add_group.closure (monoid.closure s)
variable {s : set R}
local attribute [reducible] closure
theorem exists_list_of_mem_closure {a : R} (h : a ∈ closure s) :
(∃ L : list (list R), (∀ l ∈ L, ∀ x ∈ l, x ∈ s ∨ x = (-1:R)) ∧ (L.map list.prod).sum = a) :=
add_group.in_closure.rec_on h
(λ x hx, match x, monoid.exists_list_of_mem_closure hx with
| _, ⟨L, h1, rfl⟩ := ⟨[L], list.forall_mem_singleton.2 (λ r hr, or.inl (h1 r hr)), zero_add _⟩
end)
⟨[], list.forall_mem_nil _, rfl⟩
(λ b _ ih, match b, ih with
| _, ⟨L1, h1, rfl⟩ := ⟨L1.map (list.cons (-1)),
λ L2 h2, match L2, list.mem_map.1 h2 with
| _, ⟨L3, h3, rfl⟩ := list.forall_mem_cons.2 ⟨or.inr rfl, h1 L3 h3⟩
end,
by simp only [list.map_map, (∘), list.prod_cons, neg_one_mul];
exact list.rec_on L1 neg_zero.symm (λ hd tl ih,
by rw [list.map_cons, list.sum_cons, ih, list.map_cons, list.sum_cons, neg_add])⟩
end)
(λ r1 r2 hr1 hr2 ih1 ih2, match r1, r2, ih1, ih2 with
| _, _, ⟨L1, h1, rfl⟩, ⟨L2, h2, rfl⟩ := ⟨L1 ++ L2, list.forall_mem_append.2 ⟨h1, h2⟩,
by rw [list.map_append, list.sum_append]⟩
end)
@[elab_as_eliminator]
protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s)
(h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n))
(ha : ∀ {x y}, C x → C y → C (x + y)) : C x :=
begin
have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1,
rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx,
induction L with hd tl ih, { exact h0 },
rw list.forall_mem_cons at HL,
suffices : C (list.prod hd),
{ rw [list.map_cons, list.sum_cons],
exact ha this (ih HL.2) },
replace HL := HL.1, clear ih tl,
rsuffices ⟨L, HL', HP | HP⟩ : ∃ L : list R,
(∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L),
{ rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 },
rw list.forall_mem_cons at HL',
rw list.prod_cons,
exact hs _ HL'.1 _ (ih HL'.2) },
{ rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 },
rw [list.prod_cons, neg_mul_eq_mul_neg],
rw list.forall_mem_cons at HL',
exact hs _ HL'.1 _ (ih HL'.2) },
induction hd with hd tl ih,
{ exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ },
rw list.forall_mem_cons at HL,
rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd,
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $
by rw [list.prod_cons, list.prod_cons, HP]⟩ },
{ exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ },
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $
by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ },
{ exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ }
end
lemma closure.is_subring : is_subring (closure s) :=
{ one_mem := add_group.mem_closure $ is_submonoid.one_mem $ monoid.closure.is_submonoid _,
mul_mem := λ a b ha hb, add_group.in_closure.rec_on hb
( λ c hc, add_group.in_closure.rec_on ha
( λ d hd, add_group.subset_closure ((monoid.closure.is_submonoid _).mul_mem hd hc))
( (zero_mul c).symm ▸ (add_group.closure.is_add_subgroup _).zero_mem)
( λ d hd hdc, neg_mul_eq_neg_mul d c ▸ (add_group.closure.is_add_subgroup _).neg_mem hdc)
( λ d e hd he hdc hec, (add_mul d e c).symm ▸
((add_group.closure.is_add_subgroup _).add_mem hdc hec)))
( (mul_zero a).symm ▸ (add_group.closure.is_add_subgroup _).zero_mem)
( λ c hc hac, neg_mul_eq_mul_neg a c ▸ (add_group.closure.is_add_subgroup _).neg_mem hac)
( λ c d hc hd hac had, (mul_add a c d).symm ▸
(add_group.closure.is_add_subgroup _).add_mem hac had),
..add_group.closure.is_add_subgroup _}
theorem mem_closure {a : R} : a ∈ s → a ∈ closure s :=
add_group.mem_closure ∘ @monoid.subset_closure _ _ _ _
theorem subset_closure : s ⊆ closure s :=
λ _, mem_closure
theorem closure_subset {t : set R} (ht : is_subring t) : s ⊆ t → closure s ⊆ t :=
(add_group.closure_subset ht.to_is_add_subgroup) ∘ (monoid.closure_subset ht.to_is_submonoid)
theorem closure_subset_iff {s t : set R} (ht : is_subring t) : closure s ⊆ t ↔ s ⊆ t :=
(add_group.closure_subset_iff ht.to_is_add_subgroup).trans
⟨set.subset.trans monoid.subset_closure, monoid.closure_subset ht.to_is_submonoid⟩
theorem closure_mono {s t : set R} (H : s ⊆ t) : closure s ⊆ closure t :=
closure_subset closure.is_subring $ set.subset.trans H subset_closure
lemma image_closure {S : Type*} [ring S] (f : R →+* S) (s : set R) :
f '' closure s = closure (f '' s) :=
le_antisymm
begin
rintros _ ⟨x, hx, rfl⟩,
apply in_closure.rec_on hx; intros,
{ rw [f.map_one], apply closure.is_subring.to_is_submonoid.one_mem },
{ rw [f.map_neg, f.map_one],
apply closure.is_subring.to_is_add_subgroup.neg_mem,
apply closure.is_subring.to_is_submonoid.one_mem },
{ rw [f.map_mul],
apply closure.is_subring.to_is_submonoid.mul_mem;
solve_by_elim [subset_closure, set.mem_image_of_mem] },
{ rw [f.map_add], apply closure.is_subring.to_is_add_submonoid.add_mem, assumption' },
end
(closure_subset (ring_hom.is_subring_image _ closure.is_subring) $
set.image_subset _ subset_closure)
end ring
|
bf5191c8836a921efbebea12fe46b39bc04be3b8 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/category_theory/adjunction/limits.lean | 94b1fe1787f1bc7efc27c8f1b538467f94fb3fe4 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 10,186 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Johan Commelin
-/
import category_theory.adjunction.basic
import category_theory.limits.creates
open opposite
namespace category_theory.adjunction
open category_theory
open category_theory.functor
open category_theory.limits
universes u₁ u₂ v
variables {C : Type u₁} [category.{v} C] {D : Type u₂} [category.{v} D]
variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G)
include adj
section preservation_colimits
variables {J : Type v} [small_category J] (K : J ⥤ C)
/--
The right adjoint of `cocones.functoriality K F : cocone K ⥤ cocone (K ⋙ F)`.
Auxiliary definition for `functoriality_is_left_adjoint`.
-/
def functoriality_right_adjoint : cocone (K ⋙ F) ⥤ cocone K :=
(cocones.functoriality _ G) ⋙
(cocones.precompose (K.right_unitor.inv ≫ (whisker_left K adj.unit) ≫ (associator _ _ _).inv))
local attribute [reducible] functoriality_right_adjoint
/--
The unit for the adjunction for `cocones.functoriality K F : cocone K ⥤ cocone (K ⋙ F)`.
Auxiliary definition for `functoriality_is_left_adjoint`.
-/
@[simps] def functoriality_unit : 𝟭 (cocone K) ⟶ cocones.functoriality _ F ⋙ functoriality_right_adjoint adj K :=
{ app := λ c, { hom := adj.unit.app c.X } }
/--
The counit for the adjunction for `cocones.functoriality K F : cocone K ⥤ cocone (K ⋙ F)`.
Auxiliary definition for `functoriality_is_left_adjoint`.
-/
@[simps] def functoriality_counit : functoriality_right_adjoint adj K ⋙ cocones.functoriality _ F ⟶ 𝟭 (cocone (K ⋙ F)) :=
{ app := λ c, { hom := adj.counit.app c.X } }
/-- The functor `cocones.functoriality K F : cocone K ⥤ cocone (K ⋙ F)` is a left adjoint. -/
def functoriality_is_left_adjoint :
is_left_adjoint (cocones.functoriality K F) :=
{ right := functoriality_right_adjoint adj K,
adj := mk_of_unit_counit
{ unit := functoriality_unit adj K,
counit := functoriality_counit adj K } }
/--
A left adjoint preserves colimits.
See https://stacks.math.columbia.edu/tag/0038.
-/
def left_adjoint_preserves_colimits : preserves_colimits F :=
{ preserves_colimits_of_shape := λ J 𝒥,
{ preserves_colimit := λ F,
by exactI
{ preserves := λ c hc, is_colimit.iso_unique_cocone_morphism.inv
(λ s, @equiv.unique _ _ (is_colimit.iso_unique_cocone_morphism.hom hc _)
(((adj.functoriality_is_left_adjoint _).adj).hom_equiv _ _)) } } }.
omit adj
@[priority 100] -- see Note [lower instance priority]
instance is_equivalence_preserves_colimits (E : C ⥤ D) [is_equivalence E] : preserves_colimits E :=
left_adjoint_preserves_colimits E.adjunction
-- verify the preserve_colimits instance works as expected:
example (E : C ⥤ D) [is_equivalence E]
(c : cocone K) (h : is_colimit c) : is_colimit (E.map_cocone c) :=
preserves_colimit.preserves h
instance has_colimit_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit K] :
has_colimit (K ⋙ E) :=
has_colimit.mk
{ cocone := E.map_cocone (colimit.cocone K),
is_colimit := preserves_colimit.preserves (colimit.is_colimit K) }
lemma has_colimit_of_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit (K ⋙ E)] :
has_colimit K :=
@has_colimit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K
(@adjunction.has_colimit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _)
((functor.right_unitor _).symm ≪≫ (iso_whisker_left K (fun_inv_id E)).symm)
end preservation_colimits
section preservation_limits
variables {J : Type v} [small_category J] (K : J ⥤ D)
/--
The left adjoint of `cones.functoriality K G : cone K ⥤ cone (K ⋙ G)`.
Auxiliary definition for `functoriality_is_right_adjoint`.
-/
def functoriality_left_adjoint : cone (K ⋙ G) ⥤ cone K :=
(cones.functoriality _ F) ⋙ (cones.postcompose
((associator _ _ _).hom ≫ (whisker_left K adj.counit) ≫ K.right_unitor.hom))
local attribute [reducible] functoriality_left_adjoint
/--
The unit for the adjunction for`cones.functoriality K G : cone K ⥤ cone (K ⋙ G)`.
Auxiliary definition for `functoriality_is_right_adjoint`.
-/
@[simps] def functoriality_unit' : 𝟭 (cone (K ⋙ G)) ⟶ functoriality_left_adjoint adj K ⋙ cones.functoriality _ G :=
{ app := λ c, { hom := adj.unit.app c.X, } }
/--
The counit for the adjunction for`cones.functoriality K G : cone K ⥤ cone (K ⋙ G)`.
Auxiliary definition for `functoriality_is_right_adjoint`.
-/
@[simps] def functoriality_counit' : cones.functoriality _ G ⋙ functoriality_left_adjoint adj K ⟶ 𝟭 (cone K) :=
{ app := λ c, { hom := adj.counit.app c.X, } }
/-- The functor `cones.functoriality K G : cone K ⥤ cone (K ⋙ G)` is a right adjoint. -/
def functoriality_is_right_adjoint :
is_right_adjoint (cones.functoriality K G) :=
{ left := functoriality_left_adjoint adj K,
adj := mk_of_unit_counit
{ unit := functoriality_unit' adj K,
counit := functoriality_counit' adj K } }
/--
A right adjoint preserves limits.
See https://stacks.math.columbia.edu/tag/0038.
-/
def right_adjoint_preserves_limits : preserves_limits G :=
{ preserves_limits_of_shape := λ J 𝒥,
{ preserves_limit := λ K,
by exactI
{ preserves := λ c hc, is_limit.iso_unique_cone_morphism.inv
(λ s, @equiv.unique _ _ (is_limit.iso_unique_cone_morphism.hom hc _)
(((adj.functoriality_is_right_adjoint _).adj).hom_equiv _ _).symm) } } }.
omit adj
@[priority 100] -- see Note [lower instance priority]
instance is_equivalence_preserves_limits (E : D ⥤ C) [is_equivalence E] : preserves_limits E :=
right_adjoint_preserves_limits E.inv.adjunction
@[priority 100] -- see Note [lower instance priority]
instance is_equivalence_reflects_limits (E : D ⥤ C) [is_equivalence E] : reflects_limits E :=
{ reflects_limits_of_shape := λ J 𝒥, by exactI
{ reflects_limit := λ K,
{ reflects := λ c t,
begin
have l: is_limit (E.inv.map_cone (E.map_cone c)) := preserves_limit.preserves t,
convert is_limit.map_cone_equiv E.fun_inv_id l,
{ rw functor.comp_id },
{ cases c,
cases c_π,
congr; rw functor.comp_id }
end } } }
@[priority 100] -- see Note [lower instance priority]
instance is_equivalence_creates_limits (H : D ⥤ C) [is_equivalence H] : creates_limits H :=
{ creates_limits_of_shape := λ J 𝒥, by exactI
{ creates_limit := λ F,
{ lifts := λ c t,
{ lifted_cone := H.map_cone_inv c,
valid_lift := H.map_cone_map_cone_inv c } } } }
-- verify the preserve_limits instance works as expected:
example (E : D ⥤ C) [is_equivalence E]
(c : cone K) [h : is_limit c] : is_limit (E.map_cone c) :=
preserves_limit.preserves h
instance has_limit_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit K] :
has_limit (K ⋙ E) :=
has_limit.mk
{ cone := E.map_cone (limit.cone K),
is_limit := preserves_limit.preserves (limit.is_limit K) }
lemma has_limit_of_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit (K ⋙ E)] :
has_limit K :=
@has_limit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K
(@adjunction.has_limit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _)
((iso_whisker_left K (fun_inv_id E)) ≪≫ (functor.right_unitor _))
end preservation_limits
/-- auxiliary construction for `cocones_iso` -/
@[simps]
def cocones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ C}
(Y : D) (t : ((cocones J D).obj (op (K ⋙ F))).obj Y) :
(G ⋙ (cocones J C).obj (op K)).obj Y :=
{ app := λ j, (adj.hom_equiv (K.obj j) Y) (t.app j),
naturality' := λ j j' f, by { erw [← adj.hom_equiv_naturality_left, t.naturality], dsimp, simp } }
/-- auxiliary construction for `cocones_iso` -/
@[simps]
def cocones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ C}
(Y : D) (t : (G ⋙ (cocones J C).obj (op K)).obj Y) :
((cocones J D).obj (op (K ⋙ F))).obj Y :=
{ app := λ j, (adj.hom_equiv (K.obj j) Y).symm (t.app j),
naturality' := λ j j' f,
begin
erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm, t.naturality],
dsimp, simp
end }
/--
When `F ⊣ G`,
the functor associating to each `Y` the cocones over `K ⋙ F` with cone point `Y`
is naturally isomorphic to
the functor associating to each `Y` the cocones over `K` with cone point `G.obj Y`.
-/
-- Note: this is natural in K, but we do not yet have the tools to formulate that.
def cocones_iso {J : Type v} [small_category J] {K : J ⥤ C} :
(cocones J D).obj (op (K ⋙ F)) ≅ G ⋙ ((cocones J C).obj (op K)) :=
nat_iso.of_components (λ Y,
{ hom := cocones_iso_component_hom adj Y,
inv := cocones_iso_component_inv adj Y, })
(by tidy)
/-- auxiliary construction for `cones_iso` -/
@[simps]
def cones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ D}
(X : Cᵒᵖ) (t : (functor.op F ⋙ (cones J D).obj K).obj X) :
((cones J C).obj (K ⋙ G)).obj X :=
{ app := λ j, (adj.hom_equiv (unop X) (K.obj j)) (t.app j),
naturality' := λ j j' f,
begin
erw [← adj.hom_equiv_naturality_right, ← t.naturality, category.id_comp, category.id_comp],
refl
end }
/-- auxiliary construction for `cones_iso` -/
@[simps]
def cones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ D}
(X : Cᵒᵖ) (t : ((cones J C).obj (K ⋙ G)).obj X) :
(functor.op F ⋙ (cones J D).obj K).obj X :=
{ app := λ j, (adj.hom_equiv (unop X) (K.obj j)).symm (t.app j),
naturality' := λ j j' f,
begin
erw [← adj.hom_equiv_naturality_right_symm, ← t.naturality, category.id_comp, category.id_comp]
end }
-- Note: this is natural in K, but we do not yet have the tools to formulate that.
/--
When `F ⊣ G`,
the functor associating to each `X` the cones over `K` with cone point `F.op.obj X`
is naturally isomorphic to
the functor associating to each `X` the cones over `K ⋙ G` with cone point `X`.
-/
def cones_iso {J : Type v} [small_category J] {K : J ⥤ D} :
F.op ⋙ ((cones J D).obj K) ≅ (cones J C).obj (K ⋙ G) :=
nat_iso.of_components (λ X,
{ hom := cones_iso_component_hom adj X,
inv := cones_iso_component_inv adj X, } )
(by tidy)
end category_theory.adjunction
|
8493c8bfaaeb4ced9d031dc18a5a97c3dbe81665 | cc060cf567f81c404a13ee79bf21f2e720fa6db0 | /lean/logic_examples.lean | 3401ad1a977af82067c26d0af8e1a64e9b4413ef | [
"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 | 6,565 | lean | open classical
variables p q r s : Prop
-- commutativity of ∧ and ∨
example : p ∧ q ↔ q ∧ p :=
iff.intro
(assume H : p ∧ q,
and.intro (and.right H) (and.left H))
(assume H : q ∧ p,
and.intro (and.right H) (and.left H))
example : p ∨ q ↔ q ∨ p :=
iff.intro
(assume H : p ∨ q,
or.elim H or.inr or.inl)
(assume H : q ∨ p,
or.elim H or.inr or.inl)
-- associativity of ∧ and ∨
example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) :=
iff.intro
(assume H : (p ∧ q) ∧ r,
and.intro (and.left (and.left H))
(and.intro (and.right (and.left H))
(and.right H)))
(assume H : p ∧ (q ∧ r),
and.intro
(and.intro (and.left H)
(and.left (and.right H)))
(and.right (and.right H)))
example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) :=
iff.intro
(assume H : (p ∨ q) ∨ r,
or.elim H
(assume Hpq : p ∨ q,
or.elim Hpq or.inl
(assume Hq : q, or.inr (or.inl Hq)))
(assume Hr : r, or.inr (or.inr Hr)))
(assume H : p ∨ (q ∨ r),
or.elim H
(assume Hp : p, or.inl (or.inl Hp))
(assume Hqr : q ∨ r,
or.elim Hqr
(assume Hq : q, or.inl (or.inr Hq))
or.inr))
-- distributivity
example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) :=
iff.intro
(assume H : p ∧ (q ∨ r),
have Hp : p, from and.left H,
have Hqr : q ∨ r, from and.right H,
or.elim Hqr
(λ Hq, or.inl (and.intro Hp Hq))
(λ Hr, or.inr (and.intro Hp Hr)))
(assume H : (p ∧ q) ∨ (p ∧ r),
or.elim H
(assume Hpq : p ∧ q,
and.intro (and.left Hpq)
(or.inl (and.right Hpq)))
(assume Hpr : p ∧ r,
and.intro (and.left Hpr)
(or.inr (and.right Hpr))))
example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) :=
iff.intro
(assume H : p ∨ (q ∧ r),
or.elim H
(λ Hp, and.intro (or.inl Hp) (or.inl Hp))
(assume Hqr,
and.intro
(or.inr (and.left Hqr))
(or.inr (and.right Hqr))))
(assume H : (p ∨ q) ∧ (p ∨ r),
have Hpq : p ∨ q, from and.left H,
have Hpr : p ∨ r, from and.right H,
or.elim Hpq or.inl
(assume Hq : q,
or.elim Hpr or.inl
(assume Hr : r,
or.inr (and.intro Hq Hr))))
-- other properties
example : (p → q → r) ↔ (p ∧ q → r) :=
iff.intro
(assume H : p → q → r,
(assume Hpq : p ∧ q,
H (and.left Hpq) (and.right Hpq)))
(assume H : p ∧ q → r,
λ Hp, λ Hq, H (and.intro Hp Hq))
example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) :=
iff.intro
(assume H : (p ∨ q) → r,
and.intro (λ Hp, H (or.inl Hp))
(λ Hq, H (or.inr Hq)))
(assume H : (p → r) ∧ (q → r),
(assume Hpq : p ∨ q,
or.elim Hpq (and.left H) (and.right H)))
example : ¬(p ∨ q) ↔ ¬p ∧ ¬q :=
iff.intro
(assume Hpq : ¬(p ∨ q),
show ¬p ∧ ¬q, from
and.intro
(assume Hp : p,
Hpq (or.inl Hp))
(assume Hq : q,
Hpq (or.inr Hq)))
(assume H : ¬p ∧ ¬q,
have Hnp : ¬p, from and.left H,
have Hnq : ¬q, from and.right H,
not.intro
(assume Hpq : p ∨ q,
or.elim Hpq Hnp Hnq))
example : ¬p ∨ ¬q → ¬(p ∧ q) :=
(assume H : ¬p ∨ ¬q,
not.intro
(assume Hpq : p ∧ q,
have Hp : p, from and.left Hpq,
have Hq : q, from and.right Hpq,
show false, from
or.elim H
(assume Hnp : ¬p, Hnp Hp)
(assume Hnq : ¬q, Hnq Hq)))
example : ¬(p ∧ ¬ p) :=
not.intro
(assume H : p ∧ ¬p,
have Hp : p, from and.left H,
have Hn : ¬p, from and.right H,
show false, from Hn Hp)
example : p ∧ ¬q → ¬(p → q) :=
(assume H : p ∧ ¬q,
have Hp : p, from and.left H,
have Hnq : ¬q, from and.right H,
not.intro
(assume Hpq : p → q,
show false, from Hnq (Hpq Hp)))
example : ¬p → (p → q) :=
(assume Hn : ¬p, (assume Hp : p, absurd Hp Hn))
example : (¬p ∨ q) → (p → q) :=
(assume H : ¬p ∨ q,
or.elim H
(assume Hn : ¬p, (assume Hp : p, absurd Hp Hn))
(assume Hq : q, (assume Hp : p, Hq)))
example : p ∨ false ↔ p :=
iff.intro
(assume H : p ∨ false,
or.elim H id false.elim)
or.inl
example : p ∧ false ↔ false :=
iff.intro
and.right
(assume H : false, and.intro (false.elim H) H)
example : ¬(p ↔ ¬p) :=
not.intro
(assume H : p ↔ ¬p,
have Hnp: ¬p, from not.intro (λ Hp, iff.mp H Hp Hp),
have Hp: p, from iff.mpr H Hnp,
show false, from not.intro Hnp Hp)
example : (p → q) → (¬q → ¬p) :=
(assume H : p → q,
(assume Hnq : ¬q,
not.intro
(assume Hp : p,
Hnq (H Hp))))
-- these require classical reasoning
open classical
example : (p → r ∨ s) → ((p → r) ∨ (p → s)) :=
(assume H : p → r ∨ s,
by_cases
(assume Hp : p,
or.elim (H Hp)
(assume Hr : r,
or.inl (λ Hpp : p, Hr))
(assume Hs : s,
or.inr (λ Hpp : p, Hs)))
(assume Hnp : ¬p, or.inl (λ Hp : p, absurd Hp Hnp)))
example : ¬(p ∧ q) → ¬p ∨ ¬q :=
(assume H : ¬(p ∧ q),
by_cases
(assume Hp : p,
by_cases
(assume Hq : q, absurd (and.intro Hp Hq) H)
(assume Hnq : ¬q, or.inr Hnq))
(assume Hnp : ¬p, or.inl Hnp))
theorem impl_or : (p → q) → ¬p ∨ q :=
(assume H : p → q,
by_cases
or.inr
(assume Hnq : ¬q,
by_cases
(assume Hp : p, absurd (H Hp) Hnq)
or.inl))
theorem or_impl : ¬p ∨ q → (p → q) :=
(assume H : ¬p ∨ q,
(assume Hp : p,
or.elim H
(λ Hnp : ¬p, absurd Hp Hnp)
id))
theorem nimpl_and : ¬(p → q) → p ∧ ¬q :=
(assume H : ¬(p → q),
have Hnq : ¬q, from
by_cases
(assume Hq : q, absurd (λ Hp, Hq) H)
id,
have Hp : p, from
by_cases
id
(assume Hnp : ¬p, sorry),
and.intro Hp Hnq)
example : (p → q) → (¬p ∨ q) :=
(assume H : p → q,
by_cases
(assume Hp : p, or.inr (H Hp))
(assume Hnp : ¬p, or.inl Hnp))
theorem contrapositive : (¬q → ¬p) → (p → q) :=
(assume H : ¬q → ¬p,
(assume Hp : p,
or.elim (em q)
id
(λ Hnq : ¬q, absurd Hp (H Hnq))))
example : p ∨ ¬p :=
em p
example : (((p → q) → p) → p) :=
(assume Hpqp : (p → q) → p,
by_cases
(assume Hp : p, Hp)
(assume Hnp : ¬p,
have Hnpq : ¬(p → q), from sorry,
and.left (nimpl_and p q Hnpq)))
|
28a12a795802191093a364d39b9ce5c6a93fd913 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/algebraic_independent.lean | 9b7ef29765d7c646dc383c325bbd41f48a81730c | [
"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 | 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, finite t → 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
|
9e7160fc3bcf3cee5898c8a3675245baa002081e | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /library/data/set/card.lean | aa735489c12d4669458b5e1722e0d2f30b38109d | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 5,883 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
Cardinality of finite sets.
-/
import .finite data.finset.card
open nat classical
namespace set
variable {A : Type}
noncomputable definition card (s : set A) := finset.card (set.to_finset s)
theorem card_to_set (s : finset A) : card (finset.to_set s) = finset.card s :=
by rewrite [↑card, to_finset_to_set]
theorem card_of_not_finite {s : set A} (nfins : ¬ finite s) : card s = 0 :=
by rewrite [↑card, to_finset_of_not_finite nfins]
theorem card_empty : card (∅ : set A) = 0 :=
by rewrite [-finset.to_set_empty, card_to_set]
theorem card_insert_of_mem {a : A} {s : set A} (H : a ∈ s) : card (insert a s) = card s :=
if fins : finite s then
(by rewrite [↑card, to_finset_insert, -mem_to_finset_eq at H, finset.card_insert_of_mem H])
else
(assert ¬ finite (insert a s), from suppose _, absurd (!finite_of_finite_insert this) fins,
by rewrite [card_of_not_finite fins, card_of_not_finite this])
theorem card_insert_of_not_mem {a : A} {s : set A} [finite s] (H : a ∉ s) :
card (insert a s) = card s + 1 :=
by rewrite [↑card, to_finset_insert, -mem_to_finset_eq at H, finset.card_insert_of_not_mem H]
theorem card_insert_le (a : A) (s : set A) [finite s] :
card (insert a s) ≤ card s + 1 :=
if H : a ∈ s then by rewrite [card_insert_of_mem H]; apply le_succ
else by rewrite [card_insert_of_not_mem H]
theorem card_singleton (a : A) : card '{a} = 1 :=
by rewrite [card_insert_of_not_mem !not_mem_empty, card_empty]
/- Note: the induction tactic does not work well with the set induction principle with the
extra predicate "finite". -/
theorem eq_empty_of_card_eq_zero {s : set A} [finite s] : card s = 0 → s = ∅ :=
induction_on_finite s
(by intro H; exact rfl)
(begin
intro a s' fins' anins IH H,
rewrite (card_insert_of_not_mem anins) at H,
apply nat.no_confusion H
end)
theorem card_upto (n : ℕ) : card {i | i < n} = n :=
by rewrite [↑card, to_finset_upto, finset.card_upto]
theorem card_add_card (s₁ s₂ : set A) [finite s₁] [finite s₂] :
card s₁ + card s₂ = card (s₁ ∪ s₂) + card (s₁ ∩ s₂) :=
begin
rewrite [-to_set_to_finset s₁, -to_set_to_finset s₂],
rewrite [-finset.to_set_union, -finset.to_set_inter, *card_to_set],
apply finset.card_add_card
end
theorem card_union (s₁ s₂ : set A) [finite s₁] [finite s₂] :
card (s₁ ∪ s₂) = card s₁ + card s₂ - card (s₁ ∩ s₂) :=
calc
card (s₁ ∪ s₂) = card (s₁ ∪ s₂) + card (s₁ ∩ s₂) - card (s₁ ∩ s₂) : nat.add_sub_cancel
... = card s₁ + card s₂ - card (s₁ ∩ s₂) : card_add_card s₁ s₂
theorem card_union_of_disjoint {s₁ s₂ : set A} [finite s₁] [finite s₂] (H : s₁ ∩ s₂ = ∅) :
card (s₁ ∪ s₂) = card s₁ + card s₂ :=
by rewrite [card_union, H, card_empty]
theorem card_eq_card_add_card_diff {s₁ s₂ : set A} [finite s₁] [finite s₂] (H : s₁ ⊆ s₂) :
card s₂ = card s₁ + card (s₂ \ s₁) :=
have H1 : s₁ ∩ (s₂ \ s₁) = ∅,
from eq_empty_of_forall_not_mem (take x, assume H, (and.right (and.right H)) (and.left H)),
have s₂ = s₁ ∪ (s₂ \ s₁), from eq.symm (union_diff_cancel H),
calc
card s₂ = card (s₁ ∪ (s₂ \ s₁)) : {this}
... = card s₁ + card (s₂ \ s₁) : card_union_of_disjoint H1
theorem card_le_card_of_subset {s₁ s₂ : set A} [finite s₁] [finite s₂] (H : s₁ ⊆ s₂) :
card s₁ ≤ card s₂ :=
calc
card s₂ = card s₁ + card (s₂ \ s₁) : card_eq_card_add_card_diff H
... ≥ card s₁ : le_add_right
variable {B : Type}
theorem card_image_eq_of_inj_on {f : A → B} {s : set A} [finite s] (injfs : inj_on f s) :
card (image f s) = card s :=
begin
rewrite [↑card, to_finset_image];
apply finset.card_image_eq_of_inj_on,
rewrite to_set_to_finset,
apply injfs
end
theorem card_le_of_inj_on (a : set A) (b : set B) [finite b]
(Pex : ∃ f : A → B, inj_on f a ∧ (image f a ⊆ b)) :
card a ≤ card b :=
by_cases
(assume fina : finite a,
obtain f H, from Pex,
finset.card_le_of_inj_on (to_finset a) (to_finset b)
(exists.intro f
begin
rewrite [finset.subset_eq_to_set_subset, finset.to_set_image, *to_set_to_finset],
exact H
end))
(assume nfina : ¬ finite a,
by rewrite [card_of_not_finite nfina]; exact !zero_le)
theorem card_image_le (f : A → B) (s : set A) [finite s] : card (image f s) ≤ card s :=
by rewrite [↑card, to_finset_image]; apply finset.card_image_le
theorem inj_on_of_card_image_eq {f : A → B} {s : set A} [finite s]
(H : card (image f s) = card s) : inj_on f s :=
begin
rewrite -to_set_to_finset,
apply finset.inj_on_of_card_image_eq,
rewrite [-to_finset_to_set (finset.image _ _), finset.to_set_image, to_set_to_finset],
exact H
end
theorem card_pos_of_mem {a : A} {s : set A} [finite s] (H : a ∈ s) : card s > 0 :=
have (#finset a ∈ to_finset s), by rewrite [finset.mem_eq_mem_to_set, to_set_to_finset]; apply H,
finset.card_pos_of_mem this
theorem eq_of_card_eq_of_subset {s₁ s₂ : set A} [finite s₁] [finite s₂]
(Hcard : card s₁ = card s₂) (Hsub : s₁ ⊆ s₂) :
s₁ = s₂ :=
begin
rewrite [-to_set_to_finset s₁, -to_set_to_finset s₂, -finset.eq_eq_to_set_eq],
apply finset.eq_of_card_eq_of_subset Hcard,
rewrite [to_finset_subset_to_finset_eq],
exact Hsub
end
theorem exists_two_of_card_gt_one {s : set A} (H : 1 < card s) : ∃ a b, a ∈ s ∧ b ∈ s ∧ a ≠ b :=
assert fins : finite s, from
by_contradiction
(assume nfins, by rewrite [card_of_not_finite nfins at H]; apply !not_succ_le_zero H),
by rewrite [-to_set_to_finset s]; apply finset.exists_two_of_card_gt_one H
end set
|
e25e5fb13104cd5bf20e8c33eae121b5fd73589f | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/tactic5.lean | 123e494f910e9ac06c86c003334019cbad7f2a83 | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 190 | lean | import standard
using tactic (renaming id->id_tac)
definition id {A : Type} (a : A) := a
theorem tst {A B : Prop} (H1 : A) (H2 : B) : id A
:= by !(unfold @id; state); assumption
check tst |
02449de18ef3b545d0f717a8dd10205aeb2e042c | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/converter/old_conv.lean | ec12952ab5b599ccb4d8b8fe256775e8c05c2048 | [
"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 | 9,285 | 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
Converter monad for building simplifiers.
-/
import control.basic
open tactic
meta structure old_conv_result (α : Type) :=
(val : α) (rhs : expr) (proof : option expr)
meta def old_conv (α : Type) : Type :=
name → expr → tactic (old_conv_result α)
namespace old_conv
meta def lhs : old_conv expr :=
λ r e, return ⟨e, e, none⟩
meta def change (new_p : pexpr) : old_conv unit :=
λ r e, do
e_type ← infer_type e,
new_e ← to_expr ``(%%new_p : %%e_type),
unify e new_e,
return ⟨(), new_e, none⟩
protected meta def pure {α : Type} : α → old_conv α :=
λ a r e, return ⟨a, e, none⟩
private meta def join_proofs (r : name) (o₁ o₂ : option expr) : tactic (option expr) :=
match o₁, o₂ with
| none, _ := return o₂
| _, none := return o₁
| some p₁, some p₂ := do
env ← get_env,
match env.trans_for r with
| some trans := do pr ← mk_app trans [p₁, p₂], return $ some pr
| none := fail format!"converter failed, relation '{r}' is not transitive"
end
end
protected meta def seq {α β : Type} (c₁ : old_conv (α → β)) (c₂ : old_conv α) : old_conv β :=
λ r e, do
⟨fn, e₁, pr₁⟩ ← c₁ r e,
⟨a, e₂, pr₂⟩ ← c₂ r e₁,
pr ← join_proofs r pr₁ pr₂,
return ⟨fn a, e₂, pr⟩
protected meta def fail {α β : Type} [has_to_format β] (msg : β) : old_conv α :=
λ r e, tactic.fail msg
protected meta def failed {α : Type} : old_conv α :=
λ r e, tactic.failed
protected meta def orelse {α : Type} (c₁ : old_conv α) (c₂ : old_conv α) : old_conv α :=
λ r e, c₁ r e <|> c₂ r e
protected meta def map {α β : Type} (f : α → β) (c : old_conv α) : old_conv β :=
λ r e, do
⟨a, e₁, pr⟩ ← c r e,
return ⟨f a, e₁, pr⟩
protected meta def bind {α β : Type} (c₁ : old_conv α) (c₂ : α → old_conv β) : old_conv β :=
λ r e,
has_bind.bind (c₁ r e) (λ⟨a, e₁, pr₁⟩,
has_bind.bind (c₂ a r e₁) (λ⟨b, e₂, pr₂⟩,
has_bind.bind (join_proofs r pr₁ pr₂) (λpr, return ⟨b, e₂, pr⟩)))
/- do -- wrong bind instance something with `name`?
⟨a, e₁, pr₁⟩ ← c₁ r e,
⟨b, e₂, pr₂⟩ ← c₂ a r e₁,
pr ← join_proofs r pr₁ pr₂,
return ⟨b, e₂, pr⟩
-/
meta instance : monad old_conv :=
{ map := @old_conv.map,
pure := @old_conv.pure,
bind := @old_conv.bind }
meta instance : alternative old_conv :=
{ failure := @old_conv.failed,
orelse := @old_conv.orelse,
..old_conv.monad }
meta def whnf (md : transparency := reducible) : old_conv unit :=
λ r e, do n ← tactic.whnf e md, return ⟨(), n, none⟩
meta def dsimp : old_conv unit :=
λ r e, do s ← simp_lemmas.mk_default, n ← s.dsimplify [] e, return ⟨(), n, none⟩
meta def trace {α : Type} [has_to_tactic_format α] (a : α) : old_conv unit :=
λ r e, tactic.trace a >> return ⟨(), e, none⟩
meta def trace_lhs : old_conv unit :=
lhs >>= trace
meta def apply_lemmas_core (s : simp_lemmas) (prove : tactic unit) : old_conv unit :=
λ r e, do
(new_e, pr) ← s.rewrite e prove r,
return ⟨(), new_e, some pr⟩
meta def apply_lemmas (s : simp_lemmas) : old_conv unit :=
apply_lemmas_core s failed
/- adapter for using iff-lemmas as eq-lemmas -/
meta def apply_propext_lemmas_core (s : simp_lemmas) (prove : tactic unit) : old_conv unit :=
λ r e, do
guard (r = `eq),
(new_e, pr) ← s.rewrite e prove `iff,
new_pr ← mk_app `propext [pr],
return ⟨(), new_e, some new_pr⟩
meta def apply_propext_lemmas (s : simp_lemmas) : old_conv unit :=
apply_propext_lemmas_core s failed
private meta def mk_refl_proof (r : name) (e : expr) : tactic expr :=
do env ← get_env,
match (environment.refl_for env r) with
| (some refl) := do pr ← mk_app refl [e], return pr
| none := fail format!"converter failed, relation '{r}' is not reflexive"
end
meta def to_tactic (c : old_conv unit) : name → expr → tactic (expr × expr) :=
λ r e, do
⟨u, e₁, o⟩ ← c r e,
match o with
| none := do p ← mk_refl_proof r e, return (e₁, p)
| some p := return (e₁, p)
end
meta def lift_tactic {α : Type} (t : tactic α) : old_conv α :=
λ r e, do a ← t, return ⟨a, e, none⟩
meta def apply_simp_set (attr_name : name) : old_conv unit :=
lift_tactic (get_user_simp_lemmas attr_name) >>= apply_lemmas
meta def apply_propext_simp_set (attr_name : name) : old_conv unit :=
lift_tactic (get_user_simp_lemmas attr_name) >>= apply_propext_lemmas
meta def skip : old_conv unit :=
return ()
meta def repeat : old_conv unit → old_conv unit
| c r lhs :=
(do
⟨_, rhs₁, pr₁⟩ ← c r lhs,
guard (¬ lhs =ₐ rhs₁),
⟨_, rhs₂, pr₂⟩ ← repeat c r rhs₁,
pr ← join_proofs r pr₁ pr₂,
return ⟨(), rhs₂, pr⟩)
<|> return ⟨(), lhs, none⟩
meta def first {α : Type} : list (old_conv α) → old_conv α
| [] := old_conv.failed
| (c::cs) := c <|> first cs
meta def match_pattern (p : pattern) : old_conv unit :=
λ r e, tactic.match_pattern p e >> return ⟨(), e, none⟩
meta def mk_match_expr (p : pexpr) : tactic (old_conv unit) :=
do new_p ← pexpr_to_pattern p,
return (λ r e, tactic.match_pattern new_p e >> return ⟨(), e, none⟩)
meta def match_expr (p : pexpr) : old_conv unit :=
λ r e, do
new_p ← pexpr_to_pattern p,
tactic.match_pattern new_p e >> return ⟨(), e, none⟩
meta def funext (c : old_conv unit) : old_conv unit :=
λ r lhs, do
guard (r = `eq),
(expr.lam n bi d b) ← return lhs,
let aux_type := expr.pi n bi d (expr.const `true []),
(result, _) ← solve_aux aux_type $ do
{ x ← intro1,
c_result ← c r (b.instantiate_var x),
let rhs := expr.lam n bi d (c_result.rhs.abstract x),
match c_result.proof : _ → tactic (old_conv_result unit) with
| some pr := do
let aux_pr := expr.lam n bi d (pr.abstract x),
new_pr ← mk_app `funext [lhs, rhs, aux_pr],
return ⟨(), rhs, some new_pr⟩
| none := return ⟨(), rhs, none⟩
end },
return result
meta def congr_core (c_f c_a : old_conv unit) : old_conv unit :=
λ r lhs, do
guard (r = `eq),
(expr.app f a) ← return lhs,
f_type ← infer_type f >>= tactic.whnf,
guard (f_type.is_arrow),
⟨(), new_f, of⟩ ← mtry c_f r f,
⟨(), new_a, oa⟩ ← mtry c_a r a,
rhs ← return $ new_f new_a,
match of, oa with
| none, none :=
return ⟨(), rhs, none⟩
| none, some pr_a := do
pr ← mk_app `congr_arg [a, new_a, f, pr_a],
return ⟨(), new_f new_a, some pr⟩
| some pr_f, none := do
pr ← mk_app `congr_fun [f, new_f, pr_f, a],
return ⟨(), rhs, some pr⟩
| some pr_f, some pr_a := do
pr ← mk_app `congr [f, new_f, a, new_a, pr_f, pr_a],
return ⟨(), rhs, some pr⟩
end
meta def congr (c : old_conv unit) : old_conv unit :=
congr_core c c
meta def bottom_up (c : old_conv unit) : old_conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e, failed)
(λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt))
r e,
return ⟨(), new_e, some pr⟩
meta def top_down (c : old_conv unit) : old_conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt))
(λ a s r p e, failed)
r e,
return ⟨(), new_e, some pr⟩
meta def find (c : old_conv unit) : old_conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e,
(do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff))
<|>
return ((), e, none, tt))
(λ a s r p e, failed)
r e,
return ⟨(), new_e, some pr⟩
meta def find_pattern (pat : pattern) (c : old_conv unit) : old_conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e, do
matched ← (tactic.match_pattern pat e >> return tt) <|> return ff,
if matched
then do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff)
else return ((), e, none, tt))
(λ a s r p e, failed)
r e,
return ⟨(), new_e, some pr⟩
meta def findp : pexpr → old_conv unit → old_conv unit :=
λ p c r e, do
pat ← pexpr_to_pattern p,
find_pattern pat c r e
meta def conversion (c : old_conv unit) : tactic unit :=
do (r, lhs, rhs) ←
(target_lhs_rhs <|> fail "conversion failed, target is not of the form 'lhs R rhs'"),
(new_lhs, pr) ← to_tactic c r lhs,
(unify new_lhs rhs <|>
do new_lhs_fmt ← pp new_lhs,
rhs_fmt ← pp rhs,
fail (to_fmt "conversion failed, expected" ++
rhs_fmt.indent 4 ++ format.line ++ "provided" ++
new_lhs_fmt.indent 4)),
exact pr
end old_conv
|
93f63a5b2f4b6cb15adab87a6fc5f1ad22509f2a | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/order/hom/ring.lean | 6ded8e4b229e67616a233132a61bcc8e2328586b | [
"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 | 15,219 | lean | /-
Copyright (c) 2022 Alex J. Best, Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alex J. Best, Yaël Dillies
-/
import algebra.order.archimedean
import algebra.order.hom.monoid
import algebra.order.ring.defs
import algebra.ring.equiv
import tactic.wlog
/-!
# Ordered ring homomorphisms
Homomorphisms between ordered (semi)rings that respect the ordering.
## Main definitions
* `order_ring_hom` : Monotone semiring homomorphisms.
* `order_ring_iso` : Monotone semiring isomorphisms.
## Notation
* `→+*o`: Ordered ring homomorphisms.
* `≃+*o`: Ordered ring isomorphisms.
## Tags
ordered ring homomorphism, order homomorphism
-/
open function
variables {F α β γ δ : Type*}
/-- `order_ring_hom α β` is the type of monotone semiring homomorphisms from `α` to `β`.
When possible, instead of parametrizing results over `(f : order_ring_hom α β)`,
you should parametrize over `(F : Type*) [order_ring_hom_class F α β] (f : F)`.
When you extend this structure, make sure to extend `order_ring_hom_class`. -/
structure order_ring_hom (α β : Type*) [non_assoc_semiring α] [preorder α] [non_assoc_semiring β]
[preorder β]
extends α →+* β :=
(monotone' : monotone to_fun)
/-- Reinterpret an ordered ring homomorphism as a ring homomorphism. -/
add_decl_doc order_ring_hom.to_ring_hom
infix ` →+*o `:25 := order_ring_hom
/-- `order_ring_hom α β` is the type of order-preserving semiring isomorphisms between `α` and `β`.
When possible, instead of parametrizing results over `(f : order_ring_iso α β)`,
you should parametrize over `(F : Type*) [order_ring_iso_class F α β] (f : F)`.
When you extend this structure, make sure to extend `order_ring_iso_class`. -/
structure order_ring_iso (α β : Type*) [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β]
[has_le β] extends α ≃+* β :=
(map_le_map_iff' {a b : α} : to_fun a ≤ to_fun b ↔ a ≤ b)
infix ` ≃+*o `:25 := order_ring_iso
/-- `order_ring_hom_class F α β` states that `F` is a type of ordered semiring homomorphisms.
You should extend this typeclass when you extend `order_ring_hom`. -/
class order_ring_hom_class (F : Type*) (α β : out_param $ Type*) [non_assoc_semiring α] [preorder α]
[non_assoc_semiring β] [preorder β] extends ring_hom_class F α β :=
(monotone (f : F) : monotone f)
/-- `order_ring_iso_class F α β` states that `F` is a type of ordered semiring isomorphisms.
You should extend this class when you extend `order_ring_iso`. -/
class order_ring_iso_class (F : Type*) (α β : out_param Type*) [has_mul α] [has_add α] [has_le α]
[has_mul β] [has_add β] [has_le β]
extends ring_equiv_class F α β :=
(map_le_map_iff (f : F) {a b : α} : f a ≤ f b ↔ a ≤ b)
@[priority 100] -- See note [lower priority instance]
instance order_ring_hom_class.to_order_add_monoid_hom_class [non_assoc_semiring α] [preorder α]
[non_assoc_semiring β] [preorder β] [order_ring_hom_class F α β] :
order_add_monoid_hom_class F α β :=
{ .. ‹order_ring_hom_class F α β› }
@[priority 100] -- See note [lower priority instance]
instance order_ring_hom_class.to_order_monoid_with_zero_hom_class [non_assoc_semiring α]
[preorder α] [non_assoc_semiring β] [preorder β] [order_ring_hom_class F α β] :
order_monoid_with_zero_hom_class F α β :=
{ .. ‹order_ring_hom_class F α β› }
@[priority 100] -- See note [lower instance priority]
instance order_ring_iso_class.to_order_iso_class [has_mul α] [has_add α] [has_le α] [has_mul β]
[has_add β] [has_le β] [order_ring_iso_class F α β] :
order_iso_class F α β :=
{ ..‹order_ring_iso_class F α β› }
@[priority 100] -- See note [lower instance priority]
instance order_ring_iso_class.to_order_ring_hom_class [non_assoc_semiring α] [preorder α]
[non_assoc_semiring β] [preorder β] [order_ring_iso_class F α β] :
order_ring_hom_class F α β :=
{ monotone := λ f, order_hom_class.mono f, ..‹order_ring_iso_class F α β› }
instance [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β]
[order_ring_hom_class F α β] :
has_coe_t F (α →+*o β) :=
⟨λ f, ⟨f, order_hom_class.mono f⟩⟩
instance [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β] [has_le β]
[order_ring_iso_class F α β] :
has_coe_t F (α ≃+*o β) :=
⟨λ f, ⟨f, λ a b, map_le_map_iff f⟩⟩
/-! ### Ordered ring homomorphisms -/
namespace order_ring_hom
variables [non_assoc_semiring α] [preorder α]
section preorder
variables [non_assoc_semiring β] [preorder β] [non_assoc_semiring γ] [preorder γ]
[non_assoc_semiring δ] [preorder δ]
/-- Reinterpret an ordered ring homomorphism as an ordered additive monoid homomorphism. -/
def to_order_add_monoid_hom (f : α →+*o β) : α →+o β := { ..f }
/-- Reinterpret an ordered ring homomorphism as an order homomorphism. -/
def to_order_monoid_with_zero_hom (f : α →+*o β) : α →*₀o β := { ..f }
instance : order_ring_hom_class (α →+*o β) α β :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, by obtain ⟨⟨_, _⟩, _⟩ := f; obtain ⟨⟨_, _⟩, _⟩ := g; congr',
map_mul := λ f, f.map_mul',
map_one := λ f, f.map_one',
map_add := λ f, f.map_add',
map_zero := λ f, f.map_zero',
monotone := λ f, f.monotone' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (α →+*o β) (λ _, α → β) := ⟨λ f, f.to_fun⟩
lemma to_fun_eq_coe (f : α →+*o β) : f.to_fun = ⇑f := rfl
@[ext] lemma ext {f g : α →+*o β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h
@[simp] lemma to_ring_hom_eq_coe (f : α →+*o β) : f.to_ring_hom = f := ring_hom.ext $ λ _, rfl
@[simp] lemma to_order_add_monoid_hom_eq_coe (f : α →+*o β) : f.to_order_add_monoid_hom = f := rfl
@[simp] lemma to_order_monoid_with_zero_hom_eq_coe (f : α →+*o β) :
f.to_order_monoid_with_zero_hom = f := rfl
@[simp] lemma coe_coe_ring_hom (f : α →+*o β) : ⇑(f : α →+* β) = f := rfl
@[simp] lemma coe_coe_order_add_monoid_hom (f : α →+*o β) : ⇑(f : α →+o β) = f := rfl
@[simp] lemma coe_coe_order_monoid_with_zero_hom (f : α →+*o β) : ⇑(f : α →*₀o β) = f := rfl
@[norm_cast] lemma coe_ring_hom_apply (f : α →+*o β) (a : α) : (f : α →+* β) a = f a := rfl
@[norm_cast] lemma coe_order_add_monoid_hom_apply (f : α →+*o β) (a : α) : (f : α →+o β) a = f a :=
rfl
@[norm_cast] lemma coe_order_monoid_with_zero_hom_apply (f : α →+*o β) (a : α) :
(f : α →*₀o β) a = f a := rfl
/-- Copy of a `order_ring_hom` with a new `to_fun` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (f : α →+*o β) (f' : α → β) (h : f' = f) : α →+*o β :=
{ .. f.to_ring_hom.copy f' h, .. f.to_order_add_monoid_hom.copy f' h }
@[simp] lemma coe_copy (f : α →+*o β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl
lemma copy_eq (f : α →+*o β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h
variable (α)
/-- The identity as an ordered ring homomorphism. -/
protected def id : α →+*o α := { ..ring_hom.id _, ..order_hom.id }
instance : inhabited (α →+*o α) := ⟨order_ring_hom.id α⟩
@[simp] lemma coe_id : ⇑(order_ring_hom.id α) = id := rfl
variable {α}
@[simp] lemma id_apply (a : α) : order_ring_hom.id α a = a := rfl
@[simp] lemma coe_ring_hom_id : (order_ring_hom.id α : α →+* α) = ring_hom.id α := rfl
@[simp] lemma coe_order_add_monoid_hom_id :
(order_ring_hom.id α : α →+o α) = order_add_monoid_hom.id α := rfl
@[simp] lemma coe_order_monoid_with_zero_hom_id :
(order_ring_hom.id α : α →*₀o α) = order_monoid_with_zero_hom.id α := rfl
/-- Composition of two `order_ring_hom`s as an `order_ring_hom`. -/
protected def comp (f : β →+*o γ) (g : α →+*o β) : α →+*o γ :=
{ ..f.to_ring_hom.comp g.to_ring_hom, ..f.to_order_add_monoid_hom.comp g.to_order_add_monoid_hom }
@[simp] lemma coe_comp (f : β →+*o γ) (g : α →+*o β) : ⇑(f.comp g) = f ∘ g := rfl
@[simp] lemma comp_apply (f : β →+*o γ) (g : α →+*o β) (a : α) : f.comp g a = f (g a) := rfl
lemma comp_assoc (f : γ →+*o δ) (g : β →+*o γ) (h : α →+*o β) :
(f.comp g).comp h = f.comp (g.comp h) := rfl
@[simp] lemma comp_id (f : α →+*o β) : f.comp (order_ring_hom.id α) = f := ext $ λ x, rfl
@[simp] lemma id_comp (f : α →+*o β) : (order_ring_hom.id β).comp f = f := ext $ λ x, rfl
lemma cancel_right {f₁ f₂ : β →+*o γ} {g : α →+*o β} (hg : surjective g) :
f₁.comp g = f₂.comp g ↔ f₁ = f₂ :=
⟨λ h, ext $ hg.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩
lemma cancel_left {f : β →+*o γ} {g₁ g₂ : α →+*o β} (hf : injective f) :
f.comp g₁ = f.comp g₂ ↔ g₁ = g₂ :=
⟨λ h, ext $ λ a, hf $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩
end preorder
variables [non_assoc_semiring β]
instance [preorder β] : preorder (order_ring_hom α β) := preorder.lift (coe_fn : _ → α → β)
instance [partial_order β] : partial_order (order_ring_hom α β) :=
partial_order.lift _ fun_like.coe_injective
end order_ring_hom
/-! ### Ordered ring isomorphisms -/
namespace order_ring_iso
section has_le
variables [has_mul α] [has_add α] [has_le α] [has_mul β] [has_add β] [has_le β] [has_mul γ]
[has_add γ] [has_le γ] [has_mul δ] [has_add δ] [has_le δ]
/-- Reinterpret an ordered ring isomorphism as an order isomorphism. -/
def to_order_iso (f : α ≃+*o β) : α ≃o β := ⟨f.to_ring_equiv.to_equiv, λ _ _, f.map_le_map_iff'⟩
instance : order_ring_iso_class (α ≃+*o β) α β :=
{ coe := λ f, f.to_fun,
inv := λ f, f.inv_fun,
coe_injective' := λ f g h₁ h₂, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' },
map_add := λ f, f.map_add',
map_mul := λ f, f.map_mul',
map_le_map_iff := λ f _ _, f.map_le_map_iff',
left_inv := λ f, f.left_inv,
right_inv := λ f, f.right_inv }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (α ≃+*o β) (λ _, α → β) := fun_like.has_coe_to_fun
lemma to_fun_eq_coe (f : α ≃+*o β) : f.to_fun = f := rfl
@[ext] lemma ext {f g : α ≃+*o β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h
@[simp] lemma coe_mk (e : α ≃+* β) (h) : ⇑(⟨e, h⟩ : α ≃+*o β) = e := rfl
@[simp] lemma mk_coe (e : α ≃+*o β) (h) : (⟨e, h⟩ : α ≃+*o β) = e := ext $ λ _, rfl
@[simp] lemma to_ring_equiv_eq_coe (f : α ≃+*o β) : f.to_ring_equiv = f := ring_equiv.ext $ λ _, rfl
@[simp] lemma to_order_iso_eq_coe (f : α ≃+*o β) : f.to_order_iso = f := order_iso.ext rfl
@[simp, norm_cast] lemma coe_to_ring_equiv (f : α ≃+*o β) : ⇑(f : α ≃+* β) = f := rfl
@[simp, norm_cast] lemma coe_to_order_iso (f : α ≃+*o β) : ⇑(f : α ≃o β) = f := rfl
variable (α)
/-- The identity map as an ordered ring isomorphism. -/
@[refl] protected def refl : α ≃+*o α := ⟨ring_equiv.refl α, λ _ _, iff.rfl⟩
instance : inhabited (α ≃+*o α) := ⟨order_ring_iso.refl α⟩
@[simp] lemma refl_apply (x : α) : order_ring_iso.refl α x = x := rfl
@[simp] lemma coe_ring_equiv_refl : (order_ring_iso.refl α : α ≃+* α) = ring_equiv.refl α := rfl
@[simp] lemma coe_order_iso_refl : (order_ring_iso.refl α : α ≃o α) = order_iso.refl α := rfl
variables {α}
/-- The inverse of an ordered ring isomorphism as an ordered ring isomorphism. -/
@[symm] protected def symm (e : α ≃+*o β) : β ≃+*o α :=
⟨e.to_ring_equiv.symm,
λ a b, by erw [←map_le_map_iff e, e.1.apply_symm_apply, e.1.apply_symm_apply]⟩
/-- See Note [custom simps projection] -/
def simps.symm_apply (e : α ≃+*o β) : β → α := e.symm
@[simp] lemma symm_symm (e : α ≃+*o β) : e.symm.symm = e := ext $ λ _, rfl
/-- Composition of `order_ring_iso`s as an `order_ring_iso`. -/
@[trans, simps] protected def trans (f : α ≃+*o β) (g : β ≃+*o γ) : α ≃+*o γ :=
⟨f.to_ring_equiv.trans g.to_ring_equiv, λ a b, (map_le_map_iff g).trans (map_le_map_iff f)⟩
@[simp] lemma trans_apply (f : α ≃+*o β) (g : β ≃+*o γ) (a : α) : f.trans g a = g (f a) := rfl
@[simp] lemma self_trans_symm (e : α ≃+*o β) : e.trans e.symm = order_ring_iso.refl α :=
ext e.left_inv
@[simp] lemma symm_trans_self (e : α ≃+*o β) : e.symm.trans e = order_ring_iso.refl β :=
ext e.right_inv
lemma symm_bijective : bijective (order_ring_iso.symm : (α ≃+*o β) → β ≃+*o α) :=
⟨λ f g h, f.symm_symm.symm.trans $ (congr_arg order_ring_iso.symm h).trans g.symm_symm,
λ f, ⟨f.symm, f.symm_symm⟩⟩
end has_le
section non_assoc_semiring
variables [non_assoc_semiring α] [preorder α] [non_assoc_semiring β] [preorder β]
[non_assoc_semiring γ] [preorder γ]
/-- Reinterpret an ordered ring isomorphism as an ordered ring homomorphism. -/
def to_order_ring_hom (f : α ≃+*o β) : α →+*o β :=
⟨f.to_ring_equiv.to_ring_hom, λ a b, (map_le_map_iff f).2⟩
@[simp] lemma to_order_ring_hom_eq_coe (f : α ≃+*o β) : f.to_order_ring_hom = f := rfl
@[simp, norm_cast] lemma coe_to_order_ring_hom (f : α ≃+*o β) : ⇑(f : α →+*o β) = f := rfl
@[simp]
lemma coe_to_order_ring_hom_refl : (order_ring_iso.refl α : α →+*o α) = order_ring_hom.id α := rfl
lemma to_order_ring_hom_injective : injective (to_order_ring_hom : (α ≃+*o β) → α →+*o β) :=
λ f g h, fun_like.coe_injective $ by convert fun_like.ext'_iff.1 h
end non_assoc_semiring
end order_ring_iso
/-!
### Uniqueness
There is at most one ordered ring homomorphism from a linear ordered field to an archimedean linear
ordered field. Reciprocally, such an ordered ring homomorphism exists when the codomain is further
conditionally complete.
-/
/-- There is at most one ordered ring homomorphism from a linear ordered field to an archimedean
linear ordered field. -/
instance order_ring_hom.subsingleton [linear_ordered_field α] [linear_ordered_field β]
[archimedean β] :
subsingleton (α →+*o β) :=
⟨λ f g, begin
ext x,
by_contra' h,
wlog h : f x < g x using [f g, g f],
{ exact ne.lt_or_lt h },
obtain ⟨q, hf, hg⟩ := exists_rat_btwn h,
rw ←map_rat_cast f at hf,
rw ←map_rat_cast g at hg,
exact (lt_asymm ((order_hom_class.mono g).reflect_lt hg) $
(order_hom_class.mono f).reflect_lt hf).elim,
end⟩
/-- There is at most one ordered ring isomorphism between a linear ordered field and an archimedean
linear ordered field. -/
instance order_ring_iso.subsingleton_right [linear_ordered_field α] [linear_ordered_field β]
[archimedean β] :
subsingleton (α ≃+*o β) :=
order_ring_iso.to_order_ring_hom_injective.subsingleton
/-- There is at most one ordered ring isomorphism between an archimedean linear ordered field and a
linear ordered field. -/
instance order_ring_iso.subsingleton_left [linear_ordered_field α] [archimedean α]
[linear_ordered_field β] :
subsingleton (α ≃+*o β) :=
order_ring_iso.symm_bijective.injective.subsingleton
|
81930fdde9c69ac314a434299d01a970b7a294fe | 4e3bf8e2b29061457a887ac8889e88fa5aa0e34c | /lean/love03_structured_proofs_and_proof_terms_demo.lean | a1de216b9da197f3b907618efcd66131d6c96065 | [] | no_license | mukeshtiwari/logical_verification_2019 | 9f964c067a71f65eb8884743273fbeef99e6503d | 16f62717f55ed5b7b87e03ae0134791a9bef9b9a | refs/heads/master | 1,619,158,844,208 | 1,585,139,500,000 | 1,585,139,500,000 | 249,906,380 | 0 | 0 | null | 1,585,118,728,000 | 1,585,118,727,000 | null | UTF-8 | Lean | false | false | 4,765 | lean | /- LoVe Demo 3: Structured Proofs and Proof Terms -/
import .love01_definitions_and_lemma_statements_demo
namespace LoVe
/- Structured Proofs -/
lemma add_comm_zero_left (n : ℕ):
add 0 n = add n 0 :=
add_comm 0 n
lemma add_comm_zero_left₂ (n : ℕ):
add 0 n = add n 0 :=
by exact add_comm 0 n
lemma fst_of_two_props :
∀a b : Prop, a → b → a :=
assume a b ha hb,
show a, from ha
lemma fst_of_two_props₂ (a b : Prop) (ha : a) (hb : b) :
a :=
show a,
begin
exact ha
end
lemma fst_of_two_props₃ (a b : Prop) (ha : a) (hb : b) :
a :=
ha
lemma prop_comp (a b c : Prop) (hab : a → b) (hbc : b → c) :
a → c :=
assume ha,
have hb : b := hab ha,
have hc : c := hbc hb,
show c, from hc
lemma β_example {α β : Type} (f : α → β) (a : α) :
(λx, f x) a = f a :=
rfl
def double (n : ℕ) : ℕ :=
n + n
lemma nat_exists_double_iden :
∃n : ℕ, double n = n :=
exists.intro 0
(show double 0 = 0, from rfl)
lemma nat_exists_double_iden₂ :
∃n : ℕ, double n = n :=
exists.intro 0 rfl
lemma nat_exists_double_iden₃ :
∃n : ℕ, double n = n :=
exists.intro 0 (by refl)
lemma and_swap (a b : Prop) :
a ∧ b → b ∧ a :=
assume hab : a ∧ b,
have ha : a := and.elim_left hab,
have hb : b := and.elim_right hab,
show b ∧ a, from and.intro hb ha
lemma and_swap₂ (a b : Prop) :
a ∧ b → b ∧ a :=
assume hab : a ∧ b,
have ha : a := and.elim_left hab,
have hb : b := and.elim_right hab,
begin
apply and.intro,
{ exact hb },
{ exact ha }
end
lemma or_swap (a b : Prop) :
a ∨ b → b ∨ a :=
assume hab : a ∨ b,
show b ∨ a, from or.elim hab
(assume ha,
show b ∨ a, from or.intro_right b ha)
(assume hb,
show b ∨ a, from or.intro_left a hb)
lemma modus_ponens (a b : Prop) :
(a → b) → a → b :=
assume (hab : a → b) (ha : a),
show b, from hab ha
lemma proof_of_negation (a : Prop) :
a → ¬¬ a :=
assume ha hna,
show false, from hna ha
#check classical.by_contradiction
lemma proof_by_contradiction (a : Prop) :
¬¬ a → a :=
assume hnna,
show a, from classical.by_contradiction hnna
lemma exists_or {α : Type} (p q : α → Prop) :
(∃x, p x ∨ q x) ↔ (∃x, p x) ∨ (∃x, q x) :=
iff.intro
(assume hxpq,
match hxpq with
| Exists.intro x hpq :=
match hpq with
| or.inl hp := or.intro_left _ (exists.intro x hp)
| or.inr hq := or.intro_right _ (exists.intro x hq)
end
end)
(assume hxpq,
match hxpq with
| or.inl hxp :=
match hxp with
| Exists.intro x hp := exists.intro x (or.intro_left _ hp)
end
| or.inr hxq :=
match hxq with
| Exists.intro x hq := exists.intro x (or.intro_right _ hq)
end
end)
/- Calculational Proofs -/
lemma two_mul_example (m n : ℕ) :
2 * m + n = m + n + m :=
calc 2 * m + n = (m + m) + n : by rw two_mul
... = m + n + m : by ac_refl
lemma two_mul_example₂ (m n : ℕ) :
2 * m + n = m + n + m :=
have h₁ : 2 * m + n = (m + m) + n := by rw two_mul,
have h₂ : (m + m) + n = m + n + m := by ac_refl,
show _, from eq.trans h₁ h₂
/- Induction by Pattern Matching -/
lemma add_zero :
∀n : ℕ, add 0 n = n
| 0 := by refl
| (nat.succ m) := by simp [add, add_zero m]
lemma add_succ :
∀m n : ℕ, add (nat.succ m) n = nat.succ (add m n)
| m 0 := by refl
| m (nat.succ n) := by simp [add, add_succ m n]
lemma add_comm :
∀m n : ℕ, add m n = add n m
| m 0 := by simp [add, add_zero]
| m (nat.succ n) := by simp [add, add_succ, add_comm m n]
lemma add_comm₂ :
∀m n : ℕ, add m n = add n m
| m 0 := by simp [add, add_zero]
| m (nat.succ n) :=
have ih : _ := add_comm₂ m n,
by simp [add, add_succ, ih]
lemma add_assoc :
∀l m n : ℕ, add (add l m) n = add l (add m n)
| l m 0 := by refl
| l m (nat.succ n) := by simp [add, add_assoc l m n]
-- type classes (useful for `ac_refl` below)
instance : is_commutative ℕ add := ⟨add_comm⟩
instance : is_associative ℕ add := ⟨add_assoc⟩
lemma mul_add (l m : ℕ) :
∀n : ℕ, mul l (add m n) = add (mul l m) (mul l n)
| 0 := by refl
| (nat.succ l) := by simp [add, mul, mul_add l]; ac_refl
/- The Curry–Howard Correspondence -/
lemma and_swap₃ (a b : Prop) :
a ∧ b → b ∧ a :=
λhab : a ∧ b, and.intro (and.elim_right hab) (and.elim_left hab)
lemma and_swap₄ (a b : Prop) :
a ∧ b → b ∧ a :=
begin
intro hab,
apply and.intro,
apply and.elim_right,
exact hab,
apply and.elim_left,
exact hab
end
#print and_swap₃
#print and_swap₄
/- Forward Tactics -/
lemma prop_comp₂ (a b c : Prop) (hab : a → b) (hbc : b → c) :
a → c :=
begin
intro ha,
have hb : b := hab ha,
have hc : c := hbc hb,
exact hc
end
end LoVe
|
4ad10afd1f2e355f3375ebf1fe71964142306cf8 | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/valid/mathd-algebra-31.lean | 4dcc575bebba1a4c001839b51a5b8a8e71139ecb | [
"MIT",
"Apache-2.0"
] | permissive | zeta1999/miniF2F | 6d66c75d1c18152e224d07d5eed57624f731d4b7 | c1ba9629559c5273c92ec226894baa0c1ce27861 | refs/heads/main | 1,681,897,460,642 | 1,620,646,361,000 | 1,620,646,361,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 508 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng
-/
import data.real.nnreal
import data.real.basic
import data.real.sqrt
import order.filter.basic
import data.real.ennreal
import topology.basic
open_locale topological_space
example (x : nnreal) (u : ℕ → nnreal) (h₀ : ∀ n, u (n + 1) = nnreal.sqrt ( x + u n ) ) (h₁ : filter.tendsto u filter.at_top (𝓝 9)) : 9 = nnreal.sqrt (x + 9) :=
begin
sorry
end
|
1fd1f5b6038a5d8a890ce49edccb7af22f01ad13 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/group_theory/semidirect_product.lean | 6753402245f66af2aeca223fefd7174d6305b131 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 9,069 | lean | /-
Copyright (c) 2020 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.equiv.mul_add_aut
import logic.function.basic
import group_theory.subgroup
/-!
# Semidirect product
This file defines semidirect products of groups, and the canonical maps in and out of the
semidirect product. The semidirect product of `N` and `G` given a hom `φ` from
`φ` from `G` to the automorphism group of `N` is the product of sets with the group
`⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩`
## Key definitions
There are two homs into the semidirect product `inl : N →* N ⋊[φ] G` and
`inr : G →* N ⋊[φ] G`, and `lift` can be used to define maps `N ⋊[φ] G →* H`
out of the semidirect product given maps `f₁ : N →* H` and `f₂ : G →* H` that satisfy the
condition `∀ n g, f₁ (φ g n) = f₂ g * f₁ n * f₂ g⁻¹`
## Notation
This file introduces the global notation `N ⋊[φ] G` for `semidirect_product N G φ`
## Tags
group, semidirect product
-/
variables (N : Type*) (G : Type*) {H : Type*} [group N] [group G] [group H]
/-- The semidirect product of groups `N` and `G`, given a map `φ` from `G` to the automorphism
group of `N`. It the product of sets with the group operation
`⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` -/
@[ext, derive decidable_eq]
structure semidirect_product (φ : G →* mul_aut N) :=
(left : N) (right : G)
attribute [pp_using_anonymous_constructor] semidirect_product
notation N` ⋊[`:35 φ:35`] `:0 G :35 := semidirect_product N G φ
namespace semidirect_product
variables {N G} {φ : G →* mul_aut N}
private def one_aux : N ⋊[φ] G := ⟨1, 1⟩
private def mul_aux (a b : N ⋊[φ] G) : N ⋊[φ] G := ⟨a.1 * φ a.2 b.1, a.right * b.right⟩
private def inv_aux (a : N ⋊[φ] G) : N ⋊[φ] G := let i := a.2⁻¹ in ⟨φ i a.1⁻¹, i⟩
private lemma mul_assoc_aux (a b c : N ⋊[φ] G) :
mul_aux (mul_aux a b) c = mul_aux a (mul_aux b c) :=
by simp [mul_aux, mul_assoc, mul_equiv.map_mul]
private lemma mul_one_aux (a : N ⋊[φ] G) : mul_aux a one_aux = a :=
by cases a; simp [mul_aux, one_aux]
private lemma one_mul_aux (a : N ⋊[φ] G) : mul_aux one_aux a = a :=
by cases a; simp [mul_aux, one_aux]
private lemma mul_left_inv_aux (a : N ⋊[φ] G) : mul_aux (inv_aux a) a = one_aux :=
by simp only [mul_aux, inv_aux, one_aux, ← mul_equiv.map_mul, mul_left_inv]; simp
instance : group (N ⋊[φ] G) :=
{ one := one_aux,
inv := inv_aux,
mul := mul_aux,
mul_assoc := mul_assoc_aux,
one_mul := one_mul_aux,
mul_one := mul_one_aux,
mul_left_inv := mul_left_inv_aux }
instance : inhabited (N ⋊[φ] G) := ⟨1⟩
@[simp] lemma one_left : (1 : N ⋊[φ] G).left = 1 := rfl
@[simp] lemma one_right : (1 : N ⋊[φ] G).right = 1 := rfl
@[simp] lemma inv_left (a : N ⋊[φ] G) : (a⁻¹).left = φ a.right⁻¹ a.left⁻¹ := rfl
@[simp] lemma inv_right (a : N ⋊[φ] G) : (a⁻¹).right = a.right⁻¹ := rfl
@[simp] lemma mul_left (a b : N ⋊[φ] G) : (a * b).left = a.left * φ a.right b.left := rfl
@[simp] lemma mul_right (a b : N ⋊[φ] G) : (a * b).right = a.right * b.right := rfl
/-- The canonical map `N →* N ⋊[φ] G` sending `n` to `⟨n, 1⟩` -/
def inl : N →* N ⋊[φ] G :=
{ to_fun := λ n, ⟨n, 1⟩,
map_one' := rfl,
map_mul' := by intros; ext; simp }
@[simp] lemma left_inl (n : N) : (inl n : N ⋊[φ] G).left = n := rfl
@[simp] lemma right_inl (n : N) : (inl n : N ⋊[φ] G).right = 1 := rfl
lemma inl_injective : function.injective (inl : N → N ⋊[φ] G) :=
function.injective_iff_has_left_inverse.2 ⟨left, left_inl⟩
@[simp] lemma inl_inj {n₁ n₂ : N} : (inl n₁ : N ⋊[φ] G) = inl n₂ ↔ n₁ = n₂ :=
inl_injective.eq_iff
/-- The canonical map `G →* N ⋊[φ] G` sending `g` to `⟨1, g⟩` -/
def inr : G →* N ⋊[φ] G :=
{ to_fun := λ g, ⟨1, g⟩,
map_one' := rfl,
map_mul' := by intros; ext; simp }
@[simp] lemma left_inr (g : G) : (inr g : N ⋊[φ] G).left = 1 := rfl
@[simp] lemma right_inr (g : G) : (inr g : N ⋊[φ] G).right = g := rfl
lemma inr_injective : function.injective (inr : G → N ⋊[φ] G) :=
function.injective_iff_has_left_inverse.2 ⟨right, right_inr⟩
@[simp] lemma inr_inj {g₁ g₂ : G} : (inr g₁ : N ⋊[φ] G) = inr g₂ ↔ g₁ = g₂ :=
inr_injective.eq_iff
lemma inl_aut (g : G) (n : N) : (inl (φ g n) : N ⋊[φ] G) = inr g * inl n * inr g⁻¹ :=
by ext; simp
lemma inl_aut_inv (g : G) (n : N) : (inl ((φ g)⁻¹ n) : N ⋊[φ] G) = inr g⁻¹ * inl n * inr g :=
by rw [← monoid_hom.map_inv, inl_aut, inv_inv]
@[simp] lemma mk_eq_inl_mul_inr (g : G) (n : N) : (⟨n, g⟩ : N ⋊[φ] G) = inl n * inr g :=
by ext; simp
@[simp] lemma inl_left_mul_inr_right (x : N ⋊[φ] G) : inl x.left * inr x.right = x :=
by ext; simp
/-- The canonical projection map `N ⋊[φ] G →* G`, as a group hom. -/
def right_hom : N ⋊[φ] G →* G :=
{ to_fun := semidirect_product.right,
map_one' := rfl,
map_mul' := λ _ _, rfl }
@[simp] lemma right_hom_eq_right : (right_hom : N ⋊[φ] G → G) = right := rfl
@[simp] lemma right_hom_comp_inl : (right_hom : N ⋊[φ] G →* G).comp inl = 1 :=
by ext; simp [right_hom]
@[simp] lemma right_hom_comp_inr : (right_hom : N ⋊[φ] G →* G).comp inr = monoid_hom.id _ :=
by ext; simp [right_hom]
@[simp] lemma right_hom_inl (n : N) : right_hom (inl n : N ⋊[φ] G) = 1 :=
by simp [right_hom]
@[simp] lemma right_hom_inr (g : G) : right_hom (inr g : N ⋊[φ] G) = g :=
by simp [right_hom]
lemma right_hom_surjective : function.surjective (right_hom : N ⋊[φ] G → G) :=
function.surjective_iff_has_right_inverse.2 ⟨inr, right_hom_inr⟩
lemma range_inl_eq_ker_right_hom : (inl : N →* N ⋊[φ] G).range = right_hom.ker :=
le_antisymm
(λ _, by simp [monoid_hom.mem_ker, eq_comm] {contextual := tt})
(λ x hx, ⟨x.left, by ext; simp [*, monoid_hom.mem_ker] at *⟩)
section lift
variables (f₁ : N →* H) (f₂ : G →* H)
(h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁)
/-- Define a group hom `N ⋊[φ] G →* H`, by defining maps `N →* H` and `G →* H` -/
def lift (f₁ : N →* H) (f₂ : G →* H)
(h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) :
N ⋊[φ] G →* H :=
{ to_fun := λ a, f₁ a.1 * f₂ a.2,
map_one' := by simp,
map_mul' := λ a b, begin
have := λ n g, monoid_hom.ext_iff.1 (h n) g,
simp only [mul_aut.conj_apply, monoid_hom.comp_apply, mul_equiv.coe_to_monoid_hom] at this,
simp [this, mul_assoc]
end }
@[simp] lemma lift_inl (n : N) : lift f₁ f₂ h (inl n) = f₁ n := by simp [lift]
@[simp] lemma lift_comp_inl : (lift f₁ f₂ h).comp inl = f₁ := by ext; simp
@[simp] lemma lift_inr (g : G) : lift f₁ f₂ h (inr g) = f₂ g := by simp [lift]
@[simp] lemma lift_comp_inr : (lift f₁ f₂ h).comp inr = f₂ := by ext; simp
lemma lift_unique (F : N ⋊[φ] G →* H) :
F = lift (F.comp inl) (F.comp inr) (λ _, by ext; simp [inl_aut]) :=
begin
ext,
simp only [lift, monoid_hom.comp_apply, monoid_hom.coe_mk],
rw [← F.map_mul, inl_left_mul_inr_right],
end
/-- Two maps out of the semidirect product are equal if they're equal after composition
with both `inl` and `inr` -/
lemma hom_ext {f g : (N ⋊[φ] G) →* H} (hl : f.comp inl = g.comp inl)
(hr : f.comp inr = g.comp inr) : f = g :=
by { rw [lift_unique f, lift_unique g], simp only * }
end lift
section map
variables {N₁ : Type*} {G₁ : Type*} [group N₁] [group G₁] {φ₁ : G₁ →* mul_aut N₁}
/-- Define a map from `N ⋊[φ] G` to `N₁ ⋊[φ₁] G₁` given maps `N →* N₁` and `G →* G₁` that
satisfy a commutativity condition `∀ n g, f₁ (φ g n) = φ₁ (f₂ g) (f₁ n)`. -/
def map (f₁ : N →* N₁) (f₂ : G →* G₁)
(h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) :
N ⋊[φ] G →* N₁ ⋊[φ₁] G₁ :=
{ to_fun := λ x, ⟨f₁ x.1, f₂ x.2⟩,
map_one' := by simp,
map_mul' := λ x y, begin
replace h := monoid_hom.ext_iff.1 (h x.right) y.left,
ext; simp * at *,
end }
variables (f₁ : N →* N₁) (f₂ : G →* G₁)
(h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁)
@[simp] lemma map_left (g : N ⋊[φ] G) : (map f₁ f₂ h g).left = f₁ g.left := rfl
@[simp] lemma map_right (g : N ⋊[φ] G) : (map f₁ f₂ h g).right = f₂ g.right := rfl
@[simp] lemma right_hom_comp_map : right_hom.comp (map f₁ f₂ h) = f₂.comp right_hom := rfl
@[simp] lemma map_inl (n : N) : map f₁ f₂ h (inl n) = inl (f₁ n) :=
by simp [map]
@[simp] lemma map_comp_inl : (map f₁ f₂ h).comp inl = inl.comp f₁ :=
by ext; simp
@[simp] lemma map_inr (g : G) : map f₁ f₂ h (inr g) = inr (f₂ g) :=
by simp [map]
@[simp] lemma map_comp_inr : (map f₁ f₂ h).comp inr = inr.comp f₂ :=
by ext; simp [map]
end map
end semidirect_product
|
1b3f5ab86ea45cbd81d2cfaf6fafc41bb5c4950a | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/monoidal/of_has_finite_products.lean | e811c60f080e163ff7644a6d9426f62371603d83 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,366 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Simon Hudon
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.monoidal.braided
import Mathlib.category_theory.limits.shapes.binary_products
import Mathlib.category_theory.limits.shapes.terminal
import Mathlib.PostPort
universes u v
namespace Mathlib
/-!
# The natural monoidal structure on any category with finite (co)products.
A category with a monoidal structure provided in this way is sometimes called a (co)cartesian category,
although this is also sometimes used to mean a finitely complete category.
(See <https://ncatlab.org/nlab/show/cartesian+category>.)
As this works with either products or coproducts,
and sometimes we want to think of a different monoidal structure entirely,
we don't set up either construct as an instance.
## Implementation
We had previously chosen to rely on `has_terminal` and `has_binary_products` instead of
`has_finite_products`, because we were later relying on the definitional form of the tensor product.
Now that `has_limit` has been refactored to be a `Prop`,
this issue is irrelevant and we could simplify the construction here.
See `category_theory.monoidal.of_chosen_finite_products` for a variant of this construction
which allows specifying a particular choice of terminal object and binary products.
-/
namespace category_theory
/-- A category with a terminal object and binary products has a natural monoidal structure. -/
def monoidal_of_has_finite_products (C : Type u) [category C] [limits.has_terminal C] [limits.has_binary_products C] : monoidal_category C :=
monoidal_category.mk (fun (X Y : C) => X ⨯ Y)
(fun (_x _x_1 _x_2 _x_3 : C) (f : _x ⟶ _x_1) (g : _x_2 ⟶ _x_3) => limits.prod.map f g) (⊤_C) limits.prod.associator
(fun (P : C) => limits.prod.left_unitor P) fun (P : C) => limits.prod.right_unitor P
/--
The monoidal structure coming from finite products is symmetric.
-/
@[simp] theorem symmetric_of_has_finite_products_to_braided_category_braiding (C : Type u) [category C] [limits.has_terminal C] [limits.has_binary_products C] (X : C) (Y : C) : β_ = limits.prod.braiding X Y :=
Eq.refl β_
namespace monoidal_of_has_finite_products
@[simp] theorem tensor_obj (C : Type u) [category C] [limits.has_terminal C] [limits.has_binary_products C] (X : C) (Y : C) : X ⊗ Y = (X ⨯ Y) :=
rfl
@[simp] theorem tensor_hom (C : Type u) [category C] [limits.has_terminal C] [limits.has_binary_products C] {W : C} {X : C} {Y : C} {Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : f ⊗ g = limits.prod.map f g :=
rfl
@[simp] theorem left_unitor_hom (C : Type u) [category C] [limits.has_terminal C] [limits.has_binary_products C] (X : C) : iso.hom λ_ = limits.prod.snd :=
rfl
@[simp] theorem left_unitor_inv (C : Type u) [category C] [limits.has_terminal C] [limits.has_binary_products C] (X : C) : iso.inv λ_ = limits.prod.lift (limits.terminal.from X) 𝟙 :=
rfl
@[simp] theorem right_unitor_hom (C : Type u) [category C] [limits.has_terminal C] [limits.has_binary_products C] (X : C) : iso.hom ρ_ = limits.prod.fst :=
rfl
-- We don't mark this as a simp lemma, even though in many particular
@[simp] theorem right_unitor_inv (C : Type u) [category C] [limits.has_terminal C] [limits.has_binary_products C] (X : C) : iso.inv ρ_ = limits.prod.lift 𝟙 (limits.terminal.from X) :=
rfl
-- categories the right hand side will simplify significantly further.
-- For now, we'll plan to create specialised simp lemmas in each particular category.
theorem associator_hom (C : Type u) [category C] [limits.has_terminal C] [limits.has_binary_products C] (X : C) (Y : C) (Z : C) : iso.hom α_ =
limits.prod.lift (limits.prod.fst ≫ limits.prod.fst)
(limits.prod.lift (limits.prod.fst ≫ limits.prod.snd) limits.prod.snd) :=
rfl
end monoidal_of_has_finite_products
/-- A category with an initial object and binary coproducts has a natural monoidal structure. -/
def monoidal_of_has_finite_coproducts (C : Type u) [category C] [limits.has_initial C] [limits.has_binary_coproducts C] : monoidal_category C :=
monoidal_category.mk (fun (X Y : C) => X ⨿ Y)
(fun (_x _x_1 _x_2 _x_3 : C) (f : _x ⟶ _x_1) (g : _x_2 ⟶ _x_3) => limits.coprod.map f g) (⊥_C)
limits.coprod.associator limits.coprod.left_unitor limits.coprod.right_unitor
/--
The monoidal structure coming from finite coproducts is symmetric.
-/
def symmetric_of_has_finite_coproducts (C : Type u) [category C] [limits.has_initial C] [limits.has_binary_coproducts C] : symmetric_category C :=
symmetric_category.mk
namespace monoidal_of_has_finite_coproducts
@[simp] theorem tensor_obj (C : Type u) [category C] [limits.has_initial C] [limits.has_binary_coproducts C] (X : C) (Y : C) : X ⊗ Y = (X ⨿ Y) :=
rfl
@[simp] theorem tensor_hom (C : Type u) [category C] [limits.has_initial C] [limits.has_binary_coproducts C] {W : C} {X : C} {Y : C} {Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : f ⊗ g = limits.coprod.map f g :=
rfl
@[simp] theorem left_unitor_hom (C : Type u) [category C] [limits.has_initial C] [limits.has_binary_coproducts C] (X : C) : iso.hom λ_ = limits.coprod.desc (limits.initial.to X) 𝟙 :=
rfl
@[simp] theorem right_unitor_hom (C : Type u) [category C] [limits.has_initial C] [limits.has_binary_coproducts C] (X : C) : iso.hom ρ_ = limits.coprod.desc 𝟙 (limits.initial.to X) :=
rfl
@[simp] theorem left_unitor_inv (C : Type u) [category C] [limits.has_initial C] [limits.has_binary_coproducts C] (X : C) : iso.inv λ_ = limits.coprod.inr :=
rfl
-- We don't mark this as a simp lemma, even though in many particular
@[simp] theorem right_unitor_inv (C : Type u) [category C] [limits.has_initial C] [limits.has_binary_coproducts C] (X : C) : iso.inv ρ_ = limits.coprod.inl :=
rfl
-- categories the right hand side will simplify significantly further.
-- For now, we'll plan to create specialised simp lemmas in each particular category.
theorem associator_hom (C : Type u) [category C] [limits.has_initial C] [limits.has_binary_coproducts C] (X : C) (Y : C) (Z : C) : iso.hom α_ =
limits.coprod.desc (limits.coprod.desc limits.coprod.inl (limits.coprod.inl ≫ limits.coprod.inr))
(limits.coprod.inr ≫ limits.coprod.inr) :=
rfl
|
0e2b029fd66faf317f7c7c24f8cb77d8b808a6bc | 4727251e0cd73359b15b664c3170e5d754078599 | /src/linear_algebra/matrix/to_linear_equiv.lean | 3f13a364429021442e51b734eed5fb837d254d98 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 7,416 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen
-/
import linear_algebra.matrix.nondegenerate
import linear_algebra.matrix.nonsingular_inverse
import linear_algebra.matrix.to_lin
import ring_theory.localization.fraction_ring
import ring_theory.localization.integer
/-!
# Matrices and linear equivalences
This file gives the map `matrix.to_linear_equiv` from matrices with invertible determinant,
to linear equivs.
## Main definitions
* `matrix.to_linear_equiv`: a matrix with an invertible determinant forms a linear equiv
## Main results
* `matrix.exists_mul_vec_eq_zero_iff`: `M` maps some `v ≠ 0` to zero iff `det M = 0`
## Tags
matrix, linear_equiv, determinant, inverse
-/
namespace matrix
open linear_map
variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M]
variables {n : Type*} [fintype n]
section to_linear_equiv'
variables [decidable_eq n]
/-- An invertible matrix yields a linear equivalence from the free module to itself.
See `matrix.to_linear_equiv` for the same map on arbitrary modules.
-/
def to_linear_equiv' (P : matrix n n R) (h : invertible P) : (n → R) ≃ₗ[R] (n → R) :=
{ inv_fun := (⅟P).to_lin',
left_inv := λ v,
show ((⅟P).to_lin'.comp P.to_lin') v = v,
by rw [← matrix.to_lin'_mul, P.inv_of_mul_self, matrix.to_lin'_one, linear_map.id_apply],
right_inv := λ v,
show (P.to_lin'.comp (⅟P).to_lin') v = v,
by rw [← matrix.to_lin'_mul, P.mul_inv_of_self, matrix.to_lin'_one, linear_map.id_apply],
..P.to_lin' }
@[simp] lemma to_linear_equiv'_apply (P : matrix n n R) (h : invertible P) :
(↑(P.to_linear_equiv' h) : module.End R (n → R)) = P.to_lin' := rfl
@[simp] lemma to_linear_equiv'_symm_apply (P : matrix n n R) (h : invertible P) :
(↑(P.to_linear_equiv' h).symm : module.End R (n → R)) = P⁻¹.to_lin' :=
show (⅟P).to_lin' = _, from congr_arg _ P.inv_of_eq_nonsing_inv
end to_linear_equiv'
section to_linear_equiv
variables (b : basis n R M)
include b
/-- Given `hA : is_unit A.det` and `b : basis R b`, `A.to_linear_equiv b hA` is
the `linear_equiv` arising from `to_lin b b A`.
See `matrix.to_linear_equiv'` for this result on `n → R`.
-/
@[simps apply]
noncomputable def to_linear_equiv [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) :
M ≃ₗ[R] M :=
begin
refine
{ to_fun := to_lin b b A,
inv_fun := to_lin b b A⁻¹,
left_inv := λ x, _,
right_inv := λ x, _,
.. to_lin b b A };
rw ← linear_map.comp_apply;
simp only [← matrix.to_lin_mul b b b,
matrix.nonsing_inv_mul _ hA, matrix.mul_nonsing_inv _ hA,
to_lin_one, linear_map.id_apply]
end
lemma ker_to_lin_eq_bot [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) :
(to_lin b b A).ker = ⊥ :=
ker_eq_bot.mpr (to_linear_equiv b A hA).injective
lemma range_to_lin_eq_top [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) :
(to_lin b b A).range = ⊤ :=
range_eq_top.mpr (to_linear_equiv b A hA).surjective
end to_linear_equiv
section nondegenerate
open_locale matrix
/-- This holds for all integral domains (see `matrix.exists_mul_vec_eq_zero_iff`),
not just fields, but it's easier to prove it for the field of fractions first. -/
lemma exists_mul_vec_eq_zero_iff_aux {K : Type*} [decidable_eq n] [field K] {M : matrix n n K} :
(∃ (v ≠ 0), M.mul_vec v = 0) ↔ M.det = 0 :=
begin
split,
{ rintros ⟨v, hv, mul_eq⟩,
contrapose! hv,
exact eq_zero_of_mul_vec_eq_zero hv mul_eq },
{ contrapose!,
intros h,
have : function.injective M.to_lin',
{ simpa only [← linear_map.ker_eq_bot, ker_to_lin'_eq_bot_iff, not_imp_not] using h },
have : M ⬝ linear_map.to_matrix'
((linear_equiv.of_injective_endo M.to_lin' this).symm : (n → K) →ₗ[K] (n → K)) = 1,
{ refine matrix.to_lin'.injective (linear_map.ext $ λ v, _),
rw [matrix.to_lin'_mul, matrix.to_lin'_one, matrix.to_lin'_to_matrix', linear_map.comp_apply],
exact (linear_equiv.of_injective_endo M.to_lin' this).apply_symm_apply v },
exact matrix.det_ne_zero_of_right_inverse this }
end
lemma exists_mul_vec_eq_zero_iff' {A : Type*} (K : Type*) [decidable_eq n]
[comm_ring A] [nontrivial A]
[field K] [algebra A K] [is_fraction_ring A K]
{M : matrix n n A} :
(∃ (v ≠ 0), M.mul_vec v = 0) ↔ M.det = 0 :=
begin
have : (∃ (v ≠ 0), mul_vec ((algebra_map A K).map_matrix M) v = 0) ↔ _ :=
exists_mul_vec_eq_zero_iff_aux,
rw [← ring_hom.map_det, is_fraction_ring.to_map_eq_zero_iff] at this,
refine iff.trans _ this, split; rintro ⟨v, hv, mul_eq⟩,
{ refine ⟨λ i, algebra_map _ _ (v i), mt (λ h, funext $ λ i, _) hv, _⟩,
{ exact is_fraction_ring.to_map_eq_zero_iff.mp (congr_fun h i) },
{ ext i,
refine (ring_hom.map_mul_vec _ _ _ i).symm.trans _,
rw [mul_eq, pi.zero_apply, ring_hom.map_zero, pi.zero_apply] } },
{ letI := classical.dec_eq K,
obtain ⟨⟨b, hb⟩, ba_eq⟩ := is_localization.exist_integer_multiples_of_finset
(non_zero_divisors A) (finset.univ.image v),
choose f hf using ba_eq,
refine ⟨λ i, f _ (finset.mem_image.mpr ⟨i, finset.mem_univ i, rfl⟩),
mt (λ h, funext $ λ i, _) hv, _⟩,
{ have := congr_arg (algebra_map A K) (congr_fun h i),
rw [hf, subtype.coe_mk, pi.zero_apply, ring_hom.map_zero, algebra.smul_def,
mul_eq_zero, is_fraction_ring.to_map_eq_zero_iff] at this,
exact this.resolve_left (non_zero_divisors.ne_zero hb), },
{ ext i,
refine is_fraction_ring.injective A K _,
calc algebra_map A K (M.mul_vec (λ (i : n), f (v i) _) i)
= ((algebra_map A K).map_matrix M).mul_vec
(algebra_map _ K b • v) i : _
... = 0 : _
... = algebra_map A K 0 : (ring_hom.map_zero _).symm,
{ simp_rw [ring_hom.map_mul_vec, mul_vec, dot_product, function.comp_app, hf,
subtype.coe_mk, ring_hom.map_matrix_apply, pi.smul_apply, smul_eq_mul,
algebra.smul_def] },
{ rw [mul_vec_smul, mul_eq, pi.smul_apply, pi.zero_apply, smul_zero] } } },
end
lemma exists_mul_vec_eq_zero_iff {A : Type*} [decidable_eq n] [comm_ring A] [is_domain A]
{M : matrix n n A} :
(∃ (v ≠ 0), M.mul_vec v = 0) ↔ M.det = 0 :=
exists_mul_vec_eq_zero_iff' (fraction_ring A)
lemma exists_vec_mul_eq_zero_iff {A : Type*} [decidable_eq n] [comm_ring A] [is_domain A]
{M : matrix n n A} :
(∃ (v ≠ 0), M.vec_mul v = 0) ↔ M.det = 0 :=
by simpa only [← M.det_transpose, ← mul_vec_transpose] using exists_mul_vec_eq_zero_iff
theorem nondegenerate_iff_det_ne_zero {A : Type*} [decidable_eq n] [comm_ring A] [is_domain A]
{M : matrix n n A} :
nondegenerate M ↔ M.det ≠ 0 :=
begin
refine iff.trans _ (not_iff_not.mpr exists_vec_mul_eq_zero_iff),
simp only [not_exists],
split,
{ intros hM v hv hMv,
obtain ⟨w, hwMv⟩ := hM.exists_not_ortho_of_ne_zero hv,
simpa only [dot_product_mul_vec, hMv, zero_dot_product] using hwMv },
{ intros h v hv,
refine not_imp_not.mp (h v) (funext $ λ i, _),
simpa only [dot_product_mul_vec, dot_product_single, mul_one] using hv (pi.single i 1) }
end
alias nondegenerate_iff_det_ne_zero ↔
matrix.nondegenerate.det_ne_zero matrix.nondegenerate.of_det_ne_zero
end nondegenerate
end matrix
|
1966f671a34e3c05368be9ceeebcf6a642984c6e | 205f0fc16279a69ea36e9fd158e3a97b06834ce2 | /src/13_Relations/00_intro.lean | 950784006d88982d2218a1c16c2557bd54b2ce73 | [] | no_license | kevinsullivan/cs-dm-lean | b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124 | a06a94e98be77170ca1df486c8189338b16cf6c6 | refs/heads/master | 1,585,948,743,595 | 1,544,339,346,000 | 1,544,339,346,000 | 155,570,767 | 1 | 3 | null | 1,541,540,372,000 | 1,540,995,993,000 | Lean | UTF-8 | Lean | false | false | 31,065 | lean | import data.set
import data.nat.sqrt
open set
namespace relation_2102_ns
/-
We're now going to formally explain
what a "section" is for in Lean. A
section allows you to specify in one
place a set of parameters that are then
assumed to be arguments to every other
definition in the section. Here's a
very short little section to illustrate
the concept. Don't proceed until you
understand why the #check is reporting
the type of yo to be (ℕ → ℕ) → ℕ → ℕ,
even though it (looks like) it is
defined as yo (n : ℕ) := f n, with
just one argument.
-/
section demo
variable f : ℕ → ℕ
def yo (n : ℕ) := f n
#check yo
end demo
/-
The use of sections can make for
cleaner code, because you don't have
to repeat variable declarations in
each object you define within a
section. But if you don't understand
that every variable in a section is
an implicit parameter to every other
definition in the section, then you
will be mystified when it comes to
understanding those definitions.
-/
/-
Now we turn to the main content of
this unit: the theory of relations.
-/
section relation_2102_sec
/-
Here we use a section to define two
arguments that are assumed to be present
in each definition in the rest of this
file.
First, we let β be any type.
-/
variable {β : Type}
/-
Here's the key to this unit. We let
r represent a binary relation on values
of type β. Whereas we represent a set
of values of type β, or a property of
such values, as a predicate of type,
β → Prop, we represent in a binary
relation, or a set of pairs, of values
of type, β, as a predicate of type,
β → β → Prop.
-/
variable (r : β → β → Prop)
/-
So now, when you look at the definitions
in the rest of this file, you understand
that each one of them has two additional
arguments, namely β and r.
-/
/-
Applying r to two values, x and y, of
type, β, yields a proposition. You can
thus think of r as a property of pairs
of values. If the proposition is true,
then the ordered pair, (x, y), is in
the relation, otherwise it's not.
-/
variables x y : β
#check r x y
/-
In the preceding example, we wrote
the relation name before the arguments.
It's often more natural to write in in
between the arguments. We call such a
notation an infix notation. Lean gives
us a way to extend the syntax of Lean
by adding infix operators to reduce to
known prefix operators. Here we define
two infix versions of r, one called R,
and one called ≺. The number, 50, in the
following lines defines the precedence
of this operator, i.e., how tightly it
binds when appearing in an expression
with other operators.
-/
local infix `R`:50 := r
local infix `≺`:50 := r
/-
Now we can use either x R y or x ≺ y
to mean the same thing as r x y. We'll
use the x R y style in the file. Lean's
libraries happen to use x ≺ y, but they
mean the same thing, as we just said.
-/
#check x R y
#check x ≺ y
-- EXAMPLE: THE EQUALITY RELATION
/-
Let's look at equality as a binary
relation. The first thing to know is
that an expression, such as 1 = 1, is
a convenient way of writing "eq 1 1".
The = notation is defined as an infix
version of eq in just the same way
that we defined R and ≺ to be infix
versions of r. Check to see that the
following expressions mean the same
thing.
-/
#reduce 1 = 1
#reduce eq 1 1
/-
Let's look at the actual definition
of eq in Lean's libraries.
-/
#print eq
/-
Just look at the first line, skipping
the constructor for now. What is says
is that for any Type, α, eq is a binary
relation on values of that type. The "Pi"
symbol, Π, is like ∀. ∀ is used when
working with propositions, but equality
is defined for any type, so we use Π
instead. You should read the definition as
saying that if you give eq any type, you
get back a binary relation on values of
that type: namely one for which the only
proofs that can be constructed are given
by eq.refl, which takes just one argument,
α, and returns a proof of α = α.
We thus expect the type of "eq ℕ" to be
a binary relation on ℕ values. We preface
eq in the following examples with @, which
tells Lean not to use implicit typing for
the type argument, α, to eq. We really do
have to give a type argument explicitly.
-/
#check @eq nat
#check @eq β
/-
We now see that for any type, α, such as
ℕ, or, in this file, β, eq α is a binary
relation on the set of values of type, α.
It is thus of type, α → α → Prop. That is
the signal that you're looking at a binary
relation in Lean.
-/
-- REFLEXIVE
/-
A relation is said to be reflexive if
every element in the domain of definition
of the relation (the set on which it is
defined) is related to itself.
-/
def reflexive := ∀ ⦃x⦄, x R x
#check reflexive
#reduce reflexive
#check reflexive (@eq β)
#reduce reflexive (@eq β)
/-
We know that eq β is a binary
relation defined on the set of
values of type, β. Let's assert
and prove it.
-/
lemma eq_refl : reflexive (@eq β) :=
begin
unfold reflexive,
intro, apply rfl,
end
/-
Let's take just a minute to unpack
the proposition, reflexive (@eq β).
You have to remember that at this
point in the file, we've already
defined β and r as implicit args to
all definitions, including that of
eq_refl.
-/
-- SYMMETRIC
/-
A relation is symmetric if, whenever
two values, and and y, are related,
y and x are related, in the opposite
order.
-/
def symmetric := ∀ ⦃x y⦄, x R y → y R x
/-
Let's prove that equality is symmetric.
Of course we're cheating a little here
by using a rule already in the libraries
that eq is symmetric: the rule, eq.symm.
-/
lemma eq_symm : symmetric (@eq β) :=
begin
unfold symmetric,
intros,
apply eq.symm,
assumption,
end
/-
EXERCISE: Is the real-world "likes"
relation, as in "has-a-crush-on", a
symmetric relation? How about Facebook's
"likes" relation?
-/
-- TRANSITIVE
/-
A binary relation on values of some
type, β, is said to be transitive if
whenever x and y are related, and y
and z are related, then x and z are
related.
-/
def transitive :=
∀ ⦃x y z⦄, x R y → y R z → x R z
/-
EXERCISE: Is equality transitive?
-/
lemma eq_trans : transitive (@eq β) :=
begin
unfold transitive,
intros x y z xy yz,
apply eq.trans xy yz,
end
/-
An equivalence relation is a binary
relation that is reflexive, symmetric,
and transitive.
-/
def equivalence := reflexive r ∧ symmetric r ∧ transitive r
/-
Is eq an equivalence relation? Sure.
-/
theorem eq_equiv : equivalence (@eq β) :=
begin
unfold equivalence,
split, exact eq_refl,
split, exact eq_symm, exact eq_trans,
end
/-
Let's discuss another equivalence
relation. Consider the set ℕ / 12,
the natural numbers modulo 12.
What is 2 mod 12? What is 14 mod 12?
What is 26 mod 12. All these numbers,
and indeed any natural number of the
form, 2 + k * 12 are congruent to 2
mod 12.
-/
#reduce 2 % 12
#reduce 14 % 12
#reduce 26 % 12
/-
This entire set of numbers mod 12
forms an equivalence class. Let's
formalize and prove this proposition.
-/
/-
First, the relation itself.
-/
def mod_12_equiv : ℕ → ℕ → Prop :=
λ x y, x % 12 = y % 12
/-
Now a simple test case as a sanity
check.
-/
example : mod_12_equiv 2 14 :=
begin
unfold mod_12_equiv, apply rfl,
end
/-
Let's prove that the whole infinite
set of values of the form n + k * 12
is congruent.
-/
example :
∀ k : ℕ, ∀ n : ℕ,
mod_12_equiv n (n + k * 12) :=
begin
intros,
unfold mod_12_equiv,
-- The simp tactic uses many rules to simplify expressions,
-- and can prove them true when trivial would do so
simp,
end
/-
Let's show that mod_12_equiv is an equivalence
-/
example : reflexive mod_12_equiv :=
begin
unfold mod_12_equiv,
unfold reflexive, -- EX: why just x here?
intro, apply rfl,
end
example : symmetric mod_12_equiv :=
begin
unfold symmetric,
intros x y,
unfold mod_12_equiv,
intro h,
-- New tactic: rewrite using an equality
rw h,
end
example : transitive mod_12_equiv :=
begin
unfold transitive,
intros x y z xy yz,
unfold mod_12_equiv at xy,
unfold mod_12_equiv at yz,
unfold mod_12_equiv,
rw xy, assumption,
end
/-
In the rest of this file, we transition
from x R y notation to x ≺ y. You will
find both used in mathematical writing.
Be careful not to read x ≺ y as saying
that x is less than y. The ≺ symbol in
this context can refer to any relation
whatsoever.
-/
/-
We now define additional properties of
binary relations on a set. For each of
them, come up with one or more familiar
relations having these, and not having
these, properties.
-/
variable {α : Type}
def empty_relation := λ a₁ a₂ : α, false
def irreflexive := ∀ x, ¬ x ≺ x
def anti_symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x → x = y
def asymmetric := ∀ ⦃x y⦄, x ≺ y → ¬ y ≺ x
def subrelation (q r : β → β → Prop) := ∀ ⦃x y⦄, q x y → r x y
/- Closures of relations -/
def reflexive_closure /- of r -/ :=
λ x y : β, (r x y) ∨ (x = y)
def symmetric_closure /- of r -/ :=
λ x y : β, (r x y) ∨ (r y x)
/-
We're not yet ready for the following
formal definition of the transitive
closure of a relation, as we haven't
covered inductive definitions, but we
can introduce the idea informally.
Informally, it says that if there is
any path from x to y in R then (x, y)
is in the transitive closure of R.
-/
inductive tc {α : Type} (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
/-
EXAMPLE: What is the transitive closure
of the successor relation on the natural
numbers?
-/
/- *** FUNCTIONS AND THEIR PROPERTIES *** -/
/- The property of being single valued -/
/-
We define a critical property of every
function. Any function is single valued.
Given any argument, there is at most one
result. Another way to say this is that
if y = f x and z = f x, then it must be
the case that y = z, for otherwise there
would be two different results possible
for the value of f x.
EXERCISE: Name a familiar operation that
is not a function because it's not single
valued.
-/
def single_valued_fun
(f : α → β) : Prop :=
∀ x : α, ∀ y z : β,
y = f x → z = f x → y = z
/-
Let's look at the square function as
an example. We've seen it many times.
-/
def square (n :ℕ) := n * n
/-
We can easily prove that square is
single valued.
-/
lemma square_single_valued_fun :
single_valued_fun square :=
begin
unfold single_valued_fun,
intros x y z,
assume ysqx zsqx,
rw ysqx, rw zsqx,
end
/-
Indeed, we can prove that any function
in Lean is single valued. And that is
not surprising, since the distinguishing
feature of a function is that it has this
property!
-/
theorem every_function_single_valued :
∀ f : α → β, single_valued_fun f :=
begin
intro f,
unfold single_valued_fun,
intros x y z,
assume yfx zfx,
rw yfx, rw zfx,
end
/- A lambda represents a total function. -/
/-
A function is said to be total if it is
defined (which is to say it returns a
value) for every argument in its domain
of definition.
In Lean, the domain of definition of a
function is a type. We've already seen
that a function (value) of type α → β
defines a way to convert any value of
type α into some value of type β. To
"prove" the type α → β we assume that
we have some arbitary value, a : α,
and show that we can construct and
return a value of type β. Thus any
lambda abstraction in Lean represents
a *total* function: one that is defined
for *every* value of type α.
-/
/- *** Encoding Functions as Relations *** -/
/-
Given any function expressed as a lambda
abstraction, we can easily re-represent it
as a corresponding relation. Here's a one
line converter.
-/
def fun_to_rel (f : (β → β)): (β → β → Prop) :=
-- the relation is the set of pairs (m, f m)
λ m n, n = f m
/-
Here we convert the square functon to a
corresponding square relation.
-/
def square_rel := fun_to_rel square
/-
We can't "apply" a relation to an
argument to compute a result. That
is, we can't compute with relations.
-/
-- We can compute with functions
#reduce square 3
-- This doesn't work with relations
#reduce square_rel 3 -- not 9!
/-
But we can use logic prove that given
pairs of values are in a relation.
-/
example : square_rel 3 9 :=
begin
unfold square_rel,
unfold fun_to_rel,
apply rfl,
end
/- Representing Partial Funtions! -/
/-
A partial function is a function that
need not be defined for every value in
its domain of definition. An example
of a partial function is the square
root function where the domain of
definition is the whole set of real
numbers. The function is defined only
on the non-negative subset of this
domain of definition.
-/
/-
Why would we want to represent a
function as a relation? Giving up
the ability to compute seems like
(and is) a high cost. What do we
get for it? What we get for it is
the ability to represent partial
functions. A partial function is
a function that is not necessarily
defined for every value in its
domain of definition.
-/
/-
The square function, for example,
is defined for every value of type
ℕ. Suppose we wanted to represent
a partial function that is just
like the square function but that
is defined only for the values, 0,
1, 2, and 3. Here's how we can do
it.
-/
def square_partial : ℕ → ℕ → Prop :=
λ m n,
(m = 0 ∧ n = 0) ∨
(m = 1 ∧ n = 1) ∨
(m = 2 ∧ n = 4) ∨
(m = 3 ∧ n = 9)
/- Single-valued *relations* -/
/-
To prove that the square_partial
relation represents a mathematical
function, we have to prove that
it's single valued. To this end,
we give a definition of what it
means for a relation to be single
valued in general. Remember that
this definition assumes that β is
a type, that x, y, and z are of
type β, and that ≺ is just infix
notation for a relation, r : β → β.
-/
def single_valued_rel :=
∀ x y z, (x ≺ y) → (x ≺ z) → (y = z)
/-
Let's assert and prove that our
partial square relation is actually
a function, i.e., is single valued.
It is a strictly partial function,
i.e., is a partial function and is
not a total function.
Note: some mathematicials consider
the total functions to be a subset
of the the partial functions (which
is what we do here). Others consider
these sets to be disjoint, i.e., that
if a function is partial if and only
if it is not total. We will use the
term "strictly partial" for that.
-/
lemma sv_square_rel :
single_valued_rel square_partial :=
begin
unfold single_valued_rel,
unfold square_partial,
intros x y z,
assume h1 h2,
cases h1 with x0y resty,
cases h2 with x0z restz,
cases x0y,
cases x0z,
rw x0y_right,
rw x0z_right,
cases x0y,
cases restz with x1z rest,
cases x1z,
-- we can rewrite hypotheses, too!
rw x0y_left at x1z_left,
contradiction,
-- the rest in the same tedious way
sorry
end
/-
We can even prove that it's strictly
partial by showing that there actually
is a value on which it's not defined.
Such a value is 4.
-/
lemma square_rel_strictly_partial :
∃ m : ℕ, ¬ ∃ n : ℕ, square_partial m n :=
begin
apply exists.intro 4,
unfold square_partial,
assume h,
-- We use cases in several ways here
cases h with w rel,
cases rel, cases rel, contradiction,
cases rel, cases rel, cases rel_left,
cases rel, cases rel, cases rel_left,
cases rel, cases rel_left,
end
/-
*** Fundamental properties of functions ***
-/
/-
In this section, we introduce
several more crucial properties
of functions, beyond the essential
property of being single valued.
In particular, we introduce the
concepts of injective functions,
surjective functions, and bijective
functions, which are both injective
and surjective.
-/
/-
We now have two ways to represent
functions: as lambda abstractions
and as single-valued relations.
In this section, to define these
properties of functions in a way
that is applicable to both total
and partial functions, we formulate
them using our representation of
functions as single valued relations.
-/
/-
The property of being ***injective***.
A function is said to be injective
if different arguments always give
different results. We express this
by saying if x R z and y R z then
x = y; otherwise different arguments
would yield the same result.
-/
def injective_rel :=
single_valued_rel r →
∀ x y z, x R z → y R z → x = y
/-
Note that we make being single
valued a "pre-condition" for being
injective. The concept of being
injective only applies to relations
that are actually functions.
-/
/-
Mathematicians also use the phrase
"one-to-one" to mean injective. This
term is in contrast to a many-to-one
function, which can return the same
result for multiple argument values.
EXERCISE: Give examples of familiar
functions that are injective and that
are not injective.
Carefully compare and contrast the
concepts of being single-valued (which
makes a relation into a function) and
being injective (a property of some
but not all functions).
-/
/-
Extended Example: The square relation
represents an injective function. We
need a few building blocks to complete
the proof of this proposition.
-/
/-
First, we already proved that the square
function, expressed as a lambda abstraction,
is single-valued.
-/
#check square_single_valued_fun
/-
The proposition to be proved is that if
(x,z) and (y,z) are in the relation then
x = y. That is what it means for a function
to be injective. Now given that we are
talking about the square relation, what
it means for (x,z) and for (y,z) to be
in the relation is that (x, x * x) and
(y, y * y) are in the relation and that
x * x = y * y. Taking the square root of
both sides of this equation then leaves
us with the conclusion that x = y, which
is what was to be proved. QED.
-/
/-
We now formalize one of the key ideas
you've seen throughout your mathematical
career: given an equation, such as x = y,
we can "do the same thing to both sides"
and still have an equation.
We formalize this idea by showing that
if we have x = y, we can apply any
function, f, to each side, and we will
still have an equation: that f x = f y.
We prove this as a general principle. The
proof is by trivial rewriting.
-/
theorem f_equal :
∀ { α : Type },
-- with x and y of some type, α
∀ { x y : α },
-- given a function, f
∀ f: α → α,
-- and an equality, x = y
x = y →
-- derive the equality, f x = f y
f x = f y :=
begin
intros,
rw a,
end
/-
Now, the function that we're
going to want to apply to both
sides of an equation to prove
that our square relation is an
injective function is the square
root function for natural numbers.
The Lean library provides this
function as nat.sqrt. See the
includes at the top of this file
for inclusion of data.nat.sqrt.
To use proof assistants such as
Lean or Coq, in practice, at some
point it becomes necessary to learn
what's in tge libraries of already
defined data types, functions,
propositions, and proofs.
The key piece of knowledge you
need now is that the math library
provides a proof of the following:
For any n : ℕ, there is a proof
that nat.sqrt (n * n) = n. Here
is how it is declared. The point
is we can and will need to use
this already proven principle to
finish our proof of the injectivity
of the square relation.
sqrt_eq (n : ℕ) : sqrt (n * n) = n.
In particular, we can use f_equal
and nat.sqrt together to "apply the
square root function to each side
of the equation, x * x = y * y,"" to
deduce that x = y.
-/
/-
Here's a tiny example to illustrate the
basic idea. The statement of the theorem
and its proof then follow.
-/
-- introduce two variables to use
variables s t : ℕ
-- assume s squared equals t squared
variable s2t2 : s * s = t * t
-- apply square root to both sides
#check (f_equal nat.sqrt) s2t2
lemma square_injective :
injective_rel square_rel :=
-- ∀ { x y : ℕ }, x * x = y * y → x = y :=
begin
unfold square_rel, unfold fun_to_rel,
unfold injective_rel, unfold single_valued_rel,
unfold square,
assume h,
intros x y z,
assume h1 h2,
rw h1 at h2,
-- apply nat.sqrt to both sides of h
have sqrt_both_sides := (f_equal nat.sqrt) h2,
-- use sqrt_eq to simplify sqrt (x * x) to x
rw nat.sqrt_eq at sqrt_both_sides,
-- and sqrt (y * y) to y
rw nat.sqrt_eq at sqrt_both_sides,
-- and that does it
assumption,
end
/-
The property of being surjective.
A function, f : α → β is said to be
surjective if it "covers" every value
in its co-domain, β. That is, it is
surjective if for any value of type
β there is some value of type α such
that f α = β.
We formalize the concept of being a
surjective function for a relational
formulation of functions, so that the
concept applies to partial functions
as well as total functions. We make
being single valued (being a function)
a pre-condition.
-/
def surjective_rel :=
single_valued_rel r → ∀ y, ∃ x, x R y
/-
Exercise: Is the square function on
natural numbers, taking each natural
number to its square, surjective? How
would you prove that your answers is
correct?
-/
/-
Certainly the identity relation on the
natural numbers, id_nat := λ n : ℕ, n,
is surjective. To prove it, consider
an arbitrary y : ℕ and show that there
exists and x such that id_nat x = y.
The witness is just y itself.
-/
def id_nat := (λ n : ℕ, n)
def id_nat_rel := fun_to_rel id_nat
theorem id_nat_surj :
surjective_rel (id_nat_rel) :=
begin
unfold surjective_rel,
unfold single_valued_rel,
unfold id_nat_rel,
assume fn,
intro y,
apply exists.intro y,
apply rfl,
end
/-
EXERCISE: Suppose that f is an encryption
function. When applied to a plaintext, t,
it yields a cyphertext, c. To decrypt the
cyphertext, to recover the plaintext, one
applies a decryption function, g, to c.
Should f injective? What if it weren't?
-/
/-
Finally a function is said to be
bijective if it is both injective
and surjective.
-/
def bijective_rel :=
injective_rel r ∧ surjective_rel r
/-
We've already proved that the
identity function is surjective.
-/
/-
We need to prove it's injective.
-/
lemma id_nat_inj :
injective_rel id_nat_rel :=
begin
unfold id_nat_rel,
unfold fun_to_rel,
unfold injective_rel,
unfold id_nat,
assume h,
intros x y z,
assume zidx zidy,
rw <-zidx,
rw <-zidy,
end
theorem id_nat_bij :
bijective_rel id_nat_rel :=
begin
exact ⟨id_nat_inj, id_nat_surj⟩
end
/-
Relations (& thus Function) as Sets of Pairs
-/
/-
We've already seen that we can represent
a total function, f : β → β, as a relation,
of type β → β → Prop.
We now show that if we're given a predicate
r : α → β → Prop, as a representation of a
function, f : α → β (thus also satisfying the
single-value predicate on relations), we can
convert it to an equivalent representation
of f as a set of pairs.
-/
/-
Let's recall what we know about pair types
and values and sets of pairs.
A pair is a value of a product type.
-/
def v := (1, 3)
#check v
def w := (1, tt)
#check w
/-
A set of pairs is thus a set of values of
a product type. In the example, w, above,
the type of w is ℕ × bool. In the example,
v, it's ℕ × ℕ.
The values of a product type, α × β, are
all of the possible pairs of values, p,
where p.fst is any value of type, α, and
p.snd is any value of type, β.
A product type contains *all* pairs of a
given type. Often we want to represent a
relation, or a function, in particular,
as a much smaller set of such pairs. An
example is our square_partial relation.
It can be represented as the set of four
pairs, { (0,0), (1,1), (2,4), (3,9) }.
The type of this set is set (ℕ × ℕ). We
can easily represent it in a line of code.
-/
def square_partial_as_set : set (ℕ × ℕ) :=
{ (0,0), (1,1), (2,4), (3, 9) }
/-
This is the kind of representation of a
function, or a relation more generally,
that's preferred in everyday mathematics.
In your future, such "set theoretic" ways
of representing things are preferred.
-/
/-
Now we see that square_partial_as_set
is just of the many possible values of
type set ℕ × ℕ. It's just one of many
subsets of the set of pairs of the
product type ℕ × ℕ. Indeed, any relation
is representable as some set of pairs! So
we represent a relation as a subset of
the set of values of some product type.
Finally, the set of all subsets of a
set of pairs ( values of some product
type) represents the set of all possible
relations between two types of values.
-/
def power_set_of_product_type
{ α β : Type }
(s: set (α × β)):
set (set (α × β)) :=
{ s : set (α × β) | true }
#check power_set_of_product_type square_partial_as_set
/-
Now we can think of, and represent, any
function, total or partial, as a set of
pairs, i.e., of values of product types.
The following function converts, r, the
relation shared throughout this file, to
a corresponding set of pairs.
This function is for the special cases
where α and β are the same type (here,
β).
-/
def relation_to_set_of_tuples: set (β × β) :=
-- use set comprehension to define set
{ p : β × β | p.1 ≺ p.2 }
/-
We can also go back the other way,
converting a represetation of a
relation as a set of pairs, into
a representation of the relation
represeted as a predicate.
-/
def set_of_tuples_to_relation:
set (β × β) → (β → β → Prop)
:=
begin
assume s,
exact (λ x y, (x, y) ∈ s),
end
/-
Indeed, these mappings are inverses.
What we mean by this is that if we
apply one function then the other we
get back to where we started. The
precise definition is given next.
Here we prove it in one direction.
-/
theorem set_to_relation_inverse :
∀ s : set (β × β),
relation_to_set_of_tuples
(set_of_tuples_to_relation s)
= s
:=
begin
intro s,
unfold relation_to_set_of_tuples,
unfold set_of_tuples_to_relation,
/-
Looks complicated, and you could
use set extensionality to take a
next step, but it seems like this
is mostly simplifying expressions,
so let's ask Lean to try to help.
-/
simp,
/-
Nice! But now go back and make
sure you see exactly why it's
true. An English language proof
might say something like this.
The set of the left is just the
set of pairs of elements that are
in s, and that's just s, so the
equality holds, and we are done.
-/
end
/-
EXERCISE: Prove the theorem where
the functions are applied in the
other order.
-/
/- EXAMPLE: relation-set isomorphism -/
/-
We can represent a relation directly as
a set of pairs using set comprehension
notation. Here we define the set of pairs
of natural numbers where the first and
second elements of each pair are congurent
modulo 12.
-/
def mod_12_equiv': set (ℕ × ℕ) :=
{ p : (ℕ × ℕ) | p.1 % 12 = p.2 % 12 }
/-
Here we prove the equivalence of this new
representation with the representation of
this relation as a predicate, earlier in
this file. Given a set of pairs, you can
derive the relation; and given the latter,
you can derive the former. We now prove
formally that they're literally equivalent.
-/
example:
∀(n m: ℕ),
mod_12_equiv n m ↔ (n, m) ∈ mod_12_equiv'
:=
begin
assume n m,
apply iff.intro,
-- forward
unfold mod_12_equiv,
assume pf_mod_12_equiv,
unfold mod_12_equiv',
change n % 12 = m % 12,
assumption,
-- backward
unfold mod_12_equiv',
assume pf_mod_12_equiv',
unfold mod_12_equiv,
change n % 12 = m % 12 at pf_mod_12_equiv',
assumption,
end
/-
CONCLUSION
So there you have it. We have three ways to
represent functions: as lambda abstractions,
predicates, and sets. Lambda abstractions are
used to represent total functions. Predicates
and sets can represent both partial and total
functions. We can convert between equivalent
representations. Everyday mathematics prefers
the set style representation (being rooted in
set theory rather than type theory, in Lean)
We've also studied properties of relations.
These include the reflexive, symmetric, and
transitive properties and the property of
being an equivalence relation. We saw that
an equivalene relation partitions a set into
a set of disjoint subsets, the equivalence
classes of the equivalence relation.
We then looked at the property of being
single valued, which is what is required
for a relation also to be a function.
We then studied a number of properties of
functions, in particular: being injective,
surjective, and bijective (both injective
and surjective).
Finally, we spent time on the importance
of being able to represent and reason about
partial functions in CS. We can't directly
represent them as lambda abstractions, so
we represent them as "relations", by which
in this context we mean predicates. We can
also represent them as equivalent sets of
pairs, but in Lean, we will prefer to stick
with predicate representations of relations.
The fundamental tradeoff is this: you can
compute with lambda abstractions, but you
are limited to total functions; whereas,
with relations, you can represent partial
functions, but you can't compute with a
relation. Instead, you have to use logic
to state and prove propositions about them.
-/
/- EXTRA MATERIAL -/
/-
Another view of transitive closure:
Covered in Prof. Hocking's section,
but not in Sullivan's.
-/
/-
Let us define a relation R as R1
For example imagine the relation
“is one or two less than” as
defined over the naturals. It
contains the 2-tuples {(0, 1),
(0, 2), (1, 2), (1, 3), (2, 3),
(2, 4), (3, 4), (3, 5), etc.}
Now let us define R2 (or R ◦ R)
as the relation having left-hand
elements equal to the left-hand
elements of the tuples in R1, and
right-hand elements equal to the
corresponding right-hand elements
of the right-hand elements in R1
E.g., from above this would be
“is two, three, or four less than”
It contains the 2-tuples {(0, 2),
(0, 3), (0, 4), (1, 3), (1, 4),
(1, 5), etc.)
R3 (or R ◦ R2) is the relation
having left-hand elements having
left-hand elements equal to the
left-hand elements of the tuples
in R1, and right-hand elements
equal to the corresponding
right-hand elements of the
right-hand elements in R2 E.g.,
from the above this would be
“is three, four, or five less than”
-/
def successor:
(β → β → Prop) → (β → β → Prop) :=
begin
assume r,
exact λ (x y: β),
∃(b: β), (x ≺ b) ∧ (b ≺ y)
end
/-
The following is a definition for composition of two
arbitrary relations R1 and R2.
-/
def composition{α: Type}
(R1: (α → α → Prop)) (R2: (α → α → Prop)): (α → α → Prop) :=
λ(x y: α), ∃(b: α), (R1 x b) ∧ (R2 b y)
/-
Let's now define the composition operator for relations: ◦
-/
local infix `◦`:50 := composition
/-
The transitive closure of a relation, R,
can now also be understood as the union
of R and all of its successor relations.
-/
end relation_2102_sec
end relation_2102_ns
#print nat.less_than_or_equal |
f7a5166e7fb060a98c704e741f04dd5abf9b55a4 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/limits/shapes/comm_sq.lean | 9d517995a6ad7e97bf21051f3130363448bba9f8 | [
"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 | 37,889 | lean | /-
Copyright (c) 2022 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Joël Riou
-/
import category_theory.comm_sq
import category_theory.limits.opposites
import category_theory.limits.shapes.biproducts
import category_theory.limits.shapes.zero_morphisms
import category_theory.limits.constructions.binary_products
import category_theory.limits.constructions.zero_objects
/-!
# Pullback and pushout squares, and bicartesian squares
We provide another API for pullbacks and pushouts.
`is_pullback fst snd f g` is the proposition that
```
P --fst--> X
| |
snd f
| |
v v
Y ---g---> Z
```
is a pullback square.
(And similarly for `is_pushout`.)
We provide the glue to go back and forth to the usual `is_limit` API for pullbacks, and prove
`is_pullback (pullback.fst : pullback f g ⟶ X) (pullback.snd : pullback f g ⟶ Y) f g`
for the usual `pullback f g` provided by the `has_limit` API.
We don't attempt to restate everything we know about pullbacks in this language,
but do restate the pasting lemmas.
We define bicartesian squares, and
show that the pullback and pushout squares for a biproduct are bicartesian.
-/
noncomputable theory
open category_theory
open category_theory.limits
universes v₁ v₂ u₁ u₂
namespace category_theory
variables {C : Type u₁} [category.{v₁} C]
attribute [simp] comm_sq.mk
namespace comm_sq
variables {W X Y Z : C} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {i : Y ⟶ Z}
/--
The (not necessarily limiting) `pullback_cone h i` implicit in the statement
that we have `comm_sq f g h i`.
-/
def cone (s : comm_sq f g h i) : pullback_cone h i := pullback_cone.mk _ _ s.w
/--
The (not necessarily limiting) `pushout_cocone f g` implicit in the statement
that we have `comm_sq f g h i`.
-/
def cocone (s : comm_sq f g h i) : pushout_cocone f g := pushout_cocone.mk _ _ s.w
@[simp] lemma cone_fst (s : comm_sq f g h i) : s.cone.fst = f := rfl
@[simp] lemma cone_snd (s : comm_sq f g h i) : s.cone.snd = g := rfl
@[simp] lemma cocone_inl (s : comm_sq f g h i) : s.cocone.inl = h := rfl
@[simp] lemma cocone_inr (s : comm_sq f g h i) : s.cocone.inr = i := rfl
/-- The pushout cocone in the opposite category associated to the cone of
a commutative square identifies to the cocone of the flipped commutative square in
the opposite category -/
def cone_op (p : comm_sq f g h i) : p.cone.op ≅ p.flip.op.cocone :=
pushout_cocone.ext (iso.refl _) (by tidy) (by tidy)
/-- The pullback cone in the opposite category associated to the cocone of
a commutative square identifies to the cone of the flipped commutative square in
the opposite category -/
def cocone_op (p : comm_sq f g h i) : p.cocone.op ≅ p.flip.op.cone :=
pullback_cone.ext (iso.refl _) (by tidy) (by tidy)
/-- The pushout cocone obtained from the pullback cone associated to a
commutative square in the opposite category identifies to the cocone associated
to the flipped square. -/
def cone_unop {W X Y Z : Cᵒᵖ} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {i : Y ⟶ Z}
(p : comm_sq f g h i) : p.cone.unop ≅ p.flip.unop.cocone :=
pushout_cocone.ext (iso.refl _) (by tidy) (by tidy)
/-- The pullback cone obtained from the pushout cone associated to a
commutative square in the opposite category identifies to the cone associated
to the flipped square. -/
def cocone_unop {W X Y Z : Cᵒᵖ} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {i : Y ⟶ Z}
(p : comm_sq f g h i) : p.cocone.unop ≅ p.flip.unop.cone :=
pullback_cone.ext (iso.refl _) (by tidy) (by tidy)
end comm_sq
/-- The proposition that a square
```
P --fst--> X
| |
snd f
| |
v v
Y ---g---> Z
```
is a pullback square. (Also known as a fibered product or cartesian square.)
-/
structure is_pullback {P X Y Z : C} (fst : P ⟶ X) (snd : P ⟶ Y) (f : X ⟶ Z) (g : Y ⟶ Z)
extends comm_sq fst snd f g : Prop :=
(is_limit' : nonempty (is_limit (pullback_cone.mk _ _ w)))
/-- The proposition that a square
```
Z ---f---> X
| |
g inl
| |
v v
Y --inr--> P
```
is a pushout square. (Also known as a fiber coproduct or cocartesian square.)
-/
structure is_pushout {Z X Y P : C} (f : Z ⟶ X) (g : Z ⟶ Y) (inl : X ⟶ P) (inr : Y ⟶ P)
extends comm_sq f g inl inr : Prop :=
(is_colimit' : nonempty (is_colimit (pushout_cocone.mk _ _ w)))
section
set_option old_structure_cmd true
/-- A *bicartesian* square is a commutative square
```
W ---f---> X
| |
g h
| |
v v
Y ---i---> Z
```
that is both a pullback square and a pushout square.
-/
structure bicartesian_sq {W X Y Z : C} (f : W ⟶ X) (g : W ⟶ Y) (h : X ⟶ Z) (i : Y ⟶ Z)
extends is_pullback f g h i, is_pushout f g h i : Prop
-- Lean should make these parent projections as `lemma`, not `def`.
attribute [nolint def_lemma doc_blame] bicartesian_sq.to_is_pullback bicartesian_sq.to_is_pushout
end
/-!
We begin by providing some glue between `is_pullback` and the `is_limit` and `has_limit` APIs.
(And similarly for `is_pushout`.)
-/
namespace is_pullback
variables {P X Y Z : C} {fst : P ⟶ X} {snd : P ⟶ Y} {f : X ⟶ Z} {g : Y ⟶ Z}
/--
The (limiting) `pullback_cone f g` implicit in the statement
that we have a `is_pullback fst snd f g`.
-/
def cone (h : is_pullback fst snd f g) : pullback_cone f g := h.to_comm_sq.cone
@[simp] lemma cone_fst (h : is_pullback fst snd f g) : h.cone.fst = fst := rfl
@[simp] lemma cone_snd (h : is_pullback fst snd f g) : h.cone.snd = snd := rfl
/--
The cone obtained from `is_pullback fst snd f g` is a limit cone.
-/
noncomputable def is_limit (h : is_pullback fst snd f g) : is_limit h.cone :=
h.is_limit'.some
/-- If `c` is a limiting pullback cone, then we have a `is_pullback c.fst c.snd f g`. -/
lemma of_is_limit {c : pullback_cone f g} (h : limits.is_limit c) :
is_pullback c.fst c.snd f g :=
{ w := c.condition,
is_limit' := ⟨is_limit.of_iso_limit h
(limits.pullback_cone.ext (iso.refl _) (by tidy) (by tidy))⟩, }
/-- A variant of `of_is_limit` that is more useful with `apply`. -/
lemma of_is_limit' (w : comm_sq fst snd f g) (h : limits.is_limit w.cone) :
is_pullback fst snd f g :=
of_is_limit h
/-- The pullback provided by `has_pullback f g` fits into a `is_pullback`. -/
lemma of_has_pullback (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] :
is_pullback (pullback.fst : pullback f g ⟶ X) (pullback.snd : pullback f g ⟶ Y) f g :=
of_is_limit (limit.is_limit (cospan f g))
/-- If `c` is a limiting binary product cone, and we have a terminal object,
then we have `is_pullback c.fst c.snd 0 0`
(where each `0` is the unique morphism to the terminal object). -/
lemma of_is_product {c : binary_fan X Y} (h : limits.is_limit c) (t : is_terminal Z) :
is_pullback c.fst c.snd (t.from _) (t.from _) :=
of_is_limit (is_pullback_of_is_terminal_is_product _ _ _ _ t
(is_limit.of_iso_limit h (limits.cones.ext (iso.refl c.X) (by rintro ⟨⟨⟩⟩; { dsimp, simp, }))))
/-- A variant of `of_is_product` that is more useful with `apply`. -/
lemma of_is_product' (h : limits.is_limit (binary_fan.mk fst snd)) (t : is_terminal Z) :
is_pullback fst snd (t.from _) (t.from _) :=
of_is_product h t
variables (X Y)
lemma of_has_binary_product' [has_binary_product X Y] [has_terminal C] :
is_pullback limits.prod.fst limits.prod.snd (terminal.from X) (terminal.from Y) :=
of_is_product (limit.is_limit _) terminal_is_terminal
open_locale zero_object
lemma of_has_binary_product [has_binary_product X Y] [has_zero_object C] [has_zero_morphisms C] :
is_pullback limits.prod.fst limits.prod.snd (0 : X ⟶ 0) (0 : Y ⟶ 0) :=
by convert of_is_product (limit.is_limit _) has_zero_object.zero_is_terminal
variables {X Y}
/-- Any object at the top left of a pullback square is
isomorphic to the pullback provided by the `has_limit` API. -/
noncomputable
def iso_pullback (h : is_pullback fst snd f g) [has_pullback f g] : P ≅ pullback f g :=
(limit.iso_limit_cone ⟨_, h.is_limit⟩).symm
@[simp] lemma iso_pullback_hom_fst (h : is_pullback fst snd f g) [has_pullback f g] :
h.iso_pullback.hom ≫ pullback.fst = fst :=
by { dsimp [iso_pullback, cone, comm_sq.cone], simp, }
@[simp] lemma iso_pullback_hom_snd (h : is_pullback fst snd f g) [has_pullback f g] :
h.iso_pullback.hom ≫ pullback.snd = snd :=
by { dsimp [iso_pullback, cone, comm_sq.cone], simp, }
@[simp] lemma iso_pullback_inv_fst (h : is_pullback fst snd f g) [has_pullback f g] :
h.iso_pullback.inv ≫ fst = pullback.fst :=
by simp [iso.inv_comp_eq]
@[simp] lemma iso_pullback_inv_snd (h : is_pullback fst snd f g) [has_pullback f g] :
h.iso_pullback.inv ≫ snd = pullback.snd :=
by simp [iso.inv_comp_eq]
lemma of_iso_pullback (h : comm_sq fst snd f g) [has_pullback f g] (i : P ≅ pullback f g)
(w₁ : i.hom ≫ pullback.fst = fst) (w₂ : i.hom ≫ pullback.snd = snd) : is_pullback fst snd f g :=
of_is_limit' h (limits.is_limit.of_iso_limit (limit.is_limit _)
(@pullback_cone.ext _ _ _ _ _ _ _ (pullback_cone.mk _ _ _) _ i w₁.symm w₂.symm).symm)
lemma of_horiz_is_iso [is_iso fst] [is_iso g] (sq : comm_sq fst snd f g) :
is_pullback fst snd f g := of_is_limit' sq
begin
refine pullback_cone.is_limit.mk _ (λ s, s.fst ≫ inv fst) (by tidy) (λ s, _) (by tidy),
simp only [← cancel_mono g, category.assoc, ← sq.w, is_iso.inv_hom_id_assoc, s.condition],
end
end is_pullback
namespace is_pushout
variables {Z X Y P : C} {f : Z ⟶ X} {g : Z ⟶ Y} {inl : X ⟶ P} {inr : Y ⟶ P}
/--
The (colimiting) `pushout_cocone f g` implicit in the statement
that we have a `is_pushout f g inl inr`.
-/
def cocone (h : is_pushout f g inl inr) : pushout_cocone f g := h.to_comm_sq.cocone
@[simp] lemma cocone_inl (h : is_pushout f g inl inr) : h.cocone.inl = inl := rfl
@[simp] lemma cocone_inr (h : is_pushout f g inl inr) : h.cocone.inr = inr := rfl
/--
The cocone obtained from `is_pushout f g inl inr` is a colimit cocone.
-/
noncomputable def is_colimit (h : is_pushout f g inl inr) : is_colimit h.cocone :=
h.is_colimit'.some
/-- If `c` is a colimiting pushout cocone, then we have a `is_pushout f g c.inl c.inr`. -/
lemma of_is_colimit {c : pushout_cocone f g} (h : limits.is_colimit c) :
is_pushout f g c.inl c.inr :=
{ w := c.condition,
is_colimit' := ⟨is_colimit.of_iso_colimit h
(limits.pushout_cocone.ext (iso.refl _) (by tidy) (by tidy))⟩, }
/-- A variant of `of_is_colimit` that is more useful with `apply`. -/
lemma of_is_colimit' (w : comm_sq f g inl inr) (h : limits.is_colimit w.cocone) :
is_pushout f g inl inr :=
of_is_colimit h
/-- The pushout provided by `has_pushout f g` fits into a `is_pushout`. -/
lemma of_has_pushout (f : Z ⟶ X) (g : Z ⟶ Y) [has_pushout f g] :
is_pushout f g (pushout.inl : X ⟶ pushout f g) (pushout.inr : Y ⟶ pushout f g) :=
of_is_colimit (colimit.is_colimit (span f g))
/-- If `c` is a colimiting binary coproduct cocone, and we have an initial object,
then we have `is_pushout 0 0 c.inl c.inr`
(where each `0` is the unique morphism from the initial object). -/
lemma of_is_coproduct {c : binary_cofan X Y} (h : limits.is_colimit c) (t : is_initial Z) :
is_pushout (t.to _) (t.to _) c.inl c.inr :=
of_is_colimit (is_pushout_of_is_initial_is_coproduct _ _ _ _ t
(is_colimit.of_iso_colimit h
(limits.cocones.ext (iso.refl c.X) (by rintro ⟨⟨⟩⟩; { dsimp, simp, }))))
/-- A variant of `of_is_coproduct` that is more useful with `apply`. -/
lemma of_is_coproduct' (h : limits.is_colimit (binary_cofan.mk inl inr)) (t : is_initial Z) :
is_pushout (t.to _) (t.to _) inl inr :=
of_is_coproduct h t
variables (X Y)
lemma of_has_binary_coproduct' [has_binary_coproduct X Y] [has_initial C] :
is_pushout (initial.to _) (initial.to _) (coprod.inl : X ⟶ _) (coprod.inr : Y ⟶ _) :=
of_is_coproduct (colimit.is_colimit _) initial_is_initial
open_locale zero_object
lemma of_has_binary_coproduct
[has_binary_coproduct X Y] [has_zero_object C] [has_zero_morphisms C] :
is_pushout (0 : 0 ⟶ X) (0 : 0 ⟶ Y) coprod.inl coprod.inr :=
by convert of_is_coproduct (colimit.is_colimit _) has_zero_object.zero_is_initial
variables {X Y}
/-- Any object at the top left of a pullback square is
isomorphic to the pullback provided by the `has_limit` API. -/
noncomputable
def iso_pushout (h : is_pushout f g inl inr) [has_pushout f g] : P ≅ pushout f g :=
(colimit.iso_colimit_cocone ⟨_, h.is_colimit⟩).symm
@[simp] lemma inl_iso_pushout_inv (h : is_pushout f g inl inr) [has_pushout f g] :
pushout.inl ≫ h.iso_pushout.inv = inl :=
by { dsimp [iso_pushout, cocone, comm_sq.cocone], simp, }
@[simp] lemma inr_iso_pushout_inv (h : is_pushout f g inl inr) [has_pushout f g] :
pushout.inr ≫ h.iso_pushout.inv = inr :=
by { dsimp [iso_pushout, cocone, comm_sq.cocone], simp, }
@[simp] lemma inl_iso_pushout_hom (h : is_pushout f g inl inr) [has_pushout f g] :
inl ≫ h.iso_pushout.hom = pushout.inl :=
by simp [←iso.eq_comp_inv]
@[simp] lemma inr_iso_pushout_hom (h : is_pushout f g inl inr) [has_pushout f g] :
inr ≫ h.iso_pushout.hom = pushout.inr :=
by simp [←iso.eq_comp_inv]
lemma of_iso_pushout (h : comm_sq f g inl inr) [has_pushout f g] (i : P ≅ pushout f g)
(w₁ : inl ≫ i.hom = pushout.inl) (w₂ : inr ≫ i.hom = pushout.inr) : is_pushout f g inl inr :=
of_is_colimit' h (limits.is_colimit.of_iso_colimit (colimit.is_colimit _)
(@pushout_cocone.ext _ _ _ _ _ _ _ (pushout_cocone.mk _ _ _) _ i w₁ w₂).symm)
end is_pushout
namespace is_pullback
variables {P X Y Z : C} {fst : P ⟶ X} {snd : P ⟶ Y} {f : X ⟶ Z} {g : Y ⟶ Z}
lemma flip (h : is_pullback fst snd f g) : is_pullback snd fst g f :=
of_is_limit (@pullback_cone.flip_is_limit _ _ _ _ _ _ _ _ _ _ h.w.symm h.is_limit)
lemma flip_iff : is_pullback fst snd f g ↔ is_pullback snd fst g f :=
⟨flip, flip⟩
section
variables [has_zero_object C] [has_zero_morphisms C]
open_locale zero_object
/-- The square with `0 : 0 ⟶ 0` on the left and `𝟙 X` on the right is a pullback square. -/
@[simp] lemma zero_left (X : C) : is_pullback (0 : 0 ⟶ X) (0 : 0 ⟶ 0) (𝟙 X) (0 : 0 ⟶ X) :=
{ w := by simp,
is_limit' :=
⟨{ lift := λ s, 0,
fac' := λ s, by simpa using @pullback_cone.equalizer_ext _ _ _ _ _ _ _ s _ 0 (𝟙 _)
(by simpa using (pullback_cone.condition s).symm), }⟩ }
/-- The square with `0 : 0 ⟶ 0` on the top and `𝟙 X` on the bottom is a pullback square. -/
@[simp] lemma zero_top (X : C) : is_pullback (0 : 0 ⟶ 0) (0 : 0 ⟶ X) (0 : 0 ⟶ X) (𝟙 X) :=
(zero_left X).flip
/-- The square with `0 : 0 ⟶ 0` on the right and `𝟙 X` on the left is a pullback square. -/
@[simp] lemma zero_right (X : C) : is_pullback (0 : X ⟶ 0) (𝟙 X) (0 : 0 ⟶ 0) (0 : X ⟶ 0) :=
of_iso_pullback (by simp) ((zero_prod_iso X).symm ≪≫ (pullback_zero_zero_iso _ _).symm)
(by simp) (by simp)
/-- The square with `0 : 0 ⟶ 0` on the bottom and `𝟙 X` on the top is a pullback square. -/
@[simp] lemma zero_bot (X : C) : is_pullback (𝟙 X) (0 : X ⟶ 0) (0 : X ⟶ 0) (0 : 0 ⟶ 0) :=
(zero_right X).flip
end
/-- Paste two pullback squares "vertically" to obtain another pullback square. -/
-- Objects here are arranged in a 3x2 grid, and indexed by their xy coordinates.
-- Morphisms are named `hᵢⱼ` for a horizontal morphism starting at `(i,j)`,
-- and `vᵢⱼ` for a vertical morphism starting at `(i,j)`.
lemma paste_vert {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂}
(s : is_pullback h₁₁ v₁₁ v₁₂ h₂₁) (t : is_pullback h₂₁ v₂₁ v₂₂ h₃₁) :
is_pullback h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁ :=
(of_is_limit
(big_square_is_pullback _ _ _ _ _ _ _ s.w t.w t.is_limit s.is_limit))
/-- Paste two pullback squares "horizontally" to obtain another pullback square. -/
lemma paste_horiz {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃}
(s : is_pullback h₁₁ v₁₁ v₁₂ h₂₁) (t : is_pullback h₁₂ v₁₂ v₁₃ h₂₂) :
is_pullback (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂) :=
(paste_vert s.flip t.flip).flip
/-- Given a pullback square assembled from a commuting square on the top and
a pullback square on the bottom, the top square is a pullback square. -/
lemma of_bot {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂}
(s : is_pullback h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁) (p : h₁₁ ≫ v₁₂ = v₁₁ ≫ h₂₁)
(t : is_pullback h₂₁ v₂₁ v₂₂ h₃₁) :
is_pullback h₁₁ v₁₁ v₁₂ h₂₁ :=
of_is_limit (left_square_is_pullback _ _ _ _ _ _ _ p _ t.is_limit s.is_limit)
/-- Given a pullback square assembled from a commuting square on the left and
a pullback square on the right, the left square is a pullback square. -/
lemma of_right {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃}
(s : is_pullback (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂)) (p : h₁₁ ≫ v₁₂ = v₁₁ ≫ h₂₁)
(t : is_pullback h₁₂ v₁₂ v₁₃ h₂₂) :
is_pullback h₁₁ v₁₁ v₁₂ h₂₁ :=
(of_bot s.flip p.symm t.flip).flip
lemma paste_vert_iff {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂}
(s : is_pullback h₂₁ v₂₁ v₂₂ h₃₁) (e : h₁₁ ≫ v₁₂ = v₁₁ ≫ h₂₁) :
is_pullback h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁ ↔ is_pullback h₁₁ v₁₁ v₁₂ h₂₁ :=
⟨λ h, h.of_bot e s, λ h, h.paste_vert s⟩
lemma paste_horiz_iff {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃}
(s : is_pullback h₁₂ v₁₂ v₁₃ h₂₂) (e : h₁₁ ≫ v₁₂ = v₁₁ ≫ h₂₁) :
is_pullback (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂) ↔ is_pullback h₁₁ v₁₁ v₁₂ h₂₁ :=
⟨λ h, h.of_right e s, λ h, h.paste_horiz s⟩
section
variables [has_zero_object C] [has_zero_morphisms C]
open_locale zero_object
lemma of_is_bilimit {b : binary_bicone X Y} (h : b.is_bilimit) :
is_pullback b.fst b.snd (0 : X ⟶ 0) (0 : Y ⟶ 0) :=
by convert is_pullback.of_is_product' h.is_limit has_zero_object.zero_is_terminal
@[simp] lemma of_has_biproduct (X Y : C) [has_binary_biproduct X Y] :
is_pullback biprod.fst biprod.snd (0 : X ⟶ 0) (0 : Y ⟶ 0) :=
of_is_bilimit (binary_biproduct.is_bilimit X Y)
lemma inl_snd' {b : binary_bicone X Y} (h : b.is_bilimit) :
is_pullback b.inl (0 : X ⟶ 0) b.snd (0 : 0 ⟶ Y) :=
by { refine of_right _ (by simp) (of_is_bilimit h), simp, }
/--
The square
```
X --inl--> X ⊞ Y
| |
0 snd
| |
v v
0 ---0-----> Y
```
is a pullback square.
-/
@[simp] lemma inl_snd (X Y : C) [has_binary_biproduct X Y] :
is_pullback biprod.inl (0 : X ⟶ 0) biprod.snd (0 : 0 ⟶ Y) :=
inl_snd' (binary_biproduct.is_bilimit X Y)
lemma inr_fst' {b : binary_bicone X Y} (h : b.is_bilimit) :
is_pullback b.inr (0 : Y ⟶ 0) b.fst (0 : 0 ⟶ X) :=
by { apply flip, refine of_bot _ (by simp) (of_is_bilimit h), simp, }
/--
The square
```
Y --inr--> X ⊞ Y
| |
0 fst
| |
v v
0 ---0-----> X
```
is a pullback square.
-/
@[simp] lemma inr_fst (X Y : C) [has_binary_biproduct X Y] :
is_pullback biprod.inr (0 : Y ⟶ 0) biprod.fst (0 : 0 ⟶ X) :=
inr_fst' (binary_biproduct.is_bilimit X Y)
lemma of_is_bilimit' {b : binary_bicone X Y} (h : b.is_bilimit) :
is_pullback (0 : 0 ⟶ X) (0 : 0 ⟶ Y) b.inl b.inr :=
by { refine is_pullback.of_right _ (by simp) (is_pullback.inl_snd' h).flip, simp, }
lemma of_has_binary_biproduct (X Y : C) [has_binary_biproduct X Y] :
is_pullback (0 : 0 ⟶ X) (0 : 0 ⟶ Y) biprod.inl biprod.inr :=
of_is_bilimit' (binary_biproduct.is_bilimit X Y)
instance has_pullback_biprod_fst_biprod_snd [has_binary_biproduct X Y] :
has_pullback (biprod.inl : X ⟶ _) (biprod.inr : Y ⟶ _) :=
has_limit.mk ⟨_, (of_has_binary_biproduct X Y).is_limit⟩
/-- The pullback of `biprod.inl` and `biprod.inr` is the zero object. -/
def pullback_biprod_inl_biprod_inr [has_binary_biproduct X Y] :
pullback (biprod.inl : X ⟶ _) (biprod.inr : Y ⟶ _) ≅ 0 :=
limit.iso_limit_cone ⟨_, (of_has_binary_biproduct X Y).is_limit⟩
end
lemma op (h : is_pullback fst snd f g) : is_pushout g.op f.op snd.op fst.op :=
is_pushout.of_is_colimit (is_colimit.of_iso_colimit
(limits.pullback_cone.is_limit_equiv_is_colimit_op h.flip.cone h.flip.is_limit)
h.to_comm_sq.flip.cone_op)
lemma unop {P X Y Z : Cᵒᵖ} {fst : P ⟶ X} {snd : P ⟶ Y} {f : X ⟶ Z} {g : Y ⟶ Z}
(h : is_pullback fst snd f g) : is_pushout g.unop f.unop snd.unop fst.unop :=
is_pushout.of_is_colimit (is_colimit.of_iso_colimit
(limits.pullback_cone.is_limit_equiv_is_colimit_unop h.flip.cone h.flip.is_limit)
h.to_comm_sq.flip.cone_unop)
lemma of_vert_is_iso [is_iso snd] [is_iso f] (sq : comm_sq fst snd f g) :
is_pullback fst snd f g := is_pullback.flip (of_horiz_is_iso sq.flip)
end is_pullback
namespace is_pushout
variables {Z X Y P : C} {f : Z ⟶ X} {g : Z ⟶ Y} {inl : X ⟶ P} {inr : Y ⟶ P}
lemma flip (h : is_pushout f g inl inr) : is_pushout g f inr inl :=
of_is_colimit (@pushout_cocone.flip_is_colimit _ _ _ _ _ _ _ _ _ _ h.w.symm h.is_colimit)
lemma flip_iff : is_pushout f g inl inr ↔ is_pushout g f inr inl :=
⟨flip, flip⟩
section
variables [has_zero_object C] [has_zero_morphisms C]
open_locale zero_object
/-- The square with `0 : 0 ⟶ 0` on the right and `𝟙 X` on the left is a pushout square. -/
@[simp] lemma zero_right (X : C) : is_pushout (0 : X ⟶ 0) (𝟙 X) (0 : 0 ⟶ 0) (0 : X ⟶ 0) :=
{ w := by simp,
is_colimit' :=
⟨{ desc := λ s, 0,
fac' := λ s, begin
have c := @pushout_cocone.coequalizer_ext _ _ _ _ _ _ _ s _ 0 (𝟙 _) (by simp)
(by simpa using (pushout_cocone.condition s)),
dsimp at c,
simpa using c,
end }⟩ }
/-- The square with `0 : 0 ⟶ 0` on the bottom and `𝟙 X` on the top is a pushout square. -/
@[simp] lemma zero_bot (X : C) : is_pushout (𝟙 X) (0 : X ⟶ 0) (0 : X ⟶ 0) (0 : 0 ⟶ 0) :=
(zero_right X).flip
/-- The square with `0 : 0 ⟶ 0` on the right left `𝟙 X` on the right is a pushout square. -/
@[simp] lemma zero_left (X : C) : is_pushout (0 : 0 ⟶ X) (0 : 0 ⟶ 0) (𝟙 X) (0 : 0 ⟶ X) :=
of_iso_pushout (by simp) ((coprod_zero_iso X).symm ≪≫ (pushout_zero_zero_iso _ _).symm)
(by simp) (by simp)
/-- The square with `0 : 0 ⟶ 0` on the top and `𝟙 X` on the bottom is a pushout square. -/
@[simp] lemma zero_top (X : C) : is_pushout (0 : 0 ⟶ 0) (0 : 0 ⟶ X) (0 : 0 ⟶ X) (𝟙 X) :=
(zero_left X).flip
end
/-- Paste two pushout squares "vertically" to obtain another pushout square. -/
-- Objects here are arranged in a 3x2 grid, and indexed by their xy coordinates.
-- Morphisms are named `hᵢⱼ` for a horizontal morphism starting at `(i,j)`,
-- and `vᵢⱼ` for a vertical morphism starting at `(i,j)`.
lemma paste_vert {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂}
(s : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) (t : is_pushout h₂₁ v₂₁ v₂₂ h₃₁) :
is_pushout h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁ :=
(of_is_colimit
(big_square_is_pushout _ _ _ _ _ _ _ s.w t.w t.is_colimit s.is_colimit))
/-- Paste two pushout squares "horizontally" to obtain another pushout square. -/
lemma paste_horiz {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃}
(s : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) (t : is_pushout h₁₂ v₁₂ v₁₃ h₂₂) :
is_pushout (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂) :=
(paste_vert s.flip t.flip).flip
/-- Given a pushout square assembled from a pushout square on the top and
a commuting square on the bottom, the bottom square is a pushout square. -/
lemma of_bot {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂}
(s : is_pushout h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁) (p : h₂₁ ≫ v₂₂ = v₂₁ ≫ h₃₁)
(t : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) :
is_pushout h₂₁ v₂₁ v₂₂ h₃₁ :=
of_is_colimit (right_square_is_pushout _ _ _ _ _ _ _ _ p t.is_colimit s.is_colimit)
/-- Given a pushout square assembled from a pushout square on the left and
a commuting square on the right, the right square is a pushout square. -/
lemma of_right {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃}
(s : is_pushout (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂)) (p : h₁₂ ≫ v₁₃ = v₁₂ ≫ h₂₂)
(t : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) :
is_pushout h₁₂ v₁₂ v₁₃ h₂₂ :=
(of_bot s.flip p.symm t.flip).flip
lemma paste_vert_iff {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂}
(s : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) (e : h₂₁ ≫ v₂₂ = v₂₁ ≫ h₃₁) :
is_pushout h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁ ↔ is_pushout h₂₁ v₂₁ v₂₂ h₃₁ :=
⟨λ h, h.of_bot e s, s.paste_vert⟩
lemma paste_horiz_iff {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃}
(s : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) (e : h₁₂ ≫ v₁₃ = v₁₂ ≫ h₂₂) :
is_pushout (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂) ↔ is_pushout h₁₂ v₁₂ v₁₃ h₂₂ :=
⟨λ h, h.of_right e s, s.paste_horiz⟩
section
variables [has_zero_object C] [has_zero_morphisms C]
open_locale zero_object
lemma of_is_bilimit {b : binary_bicone X Y} (h : b.is_bilimit) :
is_pushout (0 : 0 ⟶ X) (0 : 0 ⟶ Y) b.inl b.inr :=
by convert is_pushout.of_is_coproduct' h.is_colimit has_zero_object.zero_is_initial
@[simp] lemma of_has_biproduct (X Y : C) [has_binary_biproduct X Y] :
is_pushout (0 : 0 ⟶ X) (0 : 0 ⟶ Y) biprod.inl biprod.inr :=
of_is_bilimit (binary_biproduct.is_bilimit X Y)
lemma inl_snd' {b : binary_bicone X Y} (h : b.is_bilimit) :
is_pushout b.inl (0 : X ⟶ 0) b.snd (0 : 0 ⟶ Y) :=
by { apply flip, refine of_right _ (by simp) (of_is_bilimit h), simp, }
/--
The square
```
X --inl--> X ⊞ Y
| |
0 snd
| |
v v
0 ---0-----> Y
```
is a pushout square.
-/
lemma inl_snd (X Y : C) [has_binary_biproduct X Y] :
is_pushout biprod.inl (0 : X ⟶ 0) biprod.snd (0 : 0 ⟶ Y) :=
inl_snd' (binary_biproduct.is_bilimit X Y)
lemma inr_fst' {b : binary_bicone X Y} (h : b.is_bilimit) :
is_pushout b.inr (0 : Y ⟶ 0) b.fst (0 : 0 ⟶ X) :=
by { refine of_bot _ (by simp) (of_is_bilimit h), simp, }
/--
The square
```
Y --inr--> X ⊞ Y
| |
0 fst
| |
v v
0 ---0-----> X
```
is a pushout square.
-/
lemma inr_fst (X Y : C) [has_binary_biproduct X Y] :
is_pushout biprod.inr (0 : Y ⟶ 0) biprod.fst (0 : 0 ⟶ X) :=
inr_fst' (binary_biproduct.is_bilimit X Y)
lemma of_is_bilimit' {b : binary_bicone X Y} (h : b.is_bilimit) :
is_pushout b.fst b.snd (0 : X ⟶ 0) (0 : Y ⟶ 0) :=
by { refine is_pushout.of_right _ (by simp) (is_pushout.inl_snd' h), simp, }
lemma of_has_binary_biproduct (X Y : C) [has_binary_biproduct X Y] :
is_pushout biprod.fst biprod.snd (0 : X ⟶ 0) (0 : Y ⟶ 0) :=
of_is_bilimit' (binary_biproduct.is_bilimit X Y)
instance has_pushout_biprod_fst_biprod_snd [has_binary_biproduct X Y] :
has_pushout (biprod.fst : _ ⟶ X) (biprod.snd : _ ⟶ Y) :=
has_colimit.mk ⟨_, (of_has_binary_biproduct X Y).is_colimit⟩
/-- The pushout of `biprod.fst` and `biprod.snd` is the zero object. -/
def pushout_biprod_fst_biprod_snd [has_binary_biproduct X Y] :
pushout (biprod.fst : _ ⟶ X) (biprod.snd : _ ⟶ Y) ≅ 0 :=
colimit.iso_colimit_cocone ⟨_, (of_has_binary_biproduct X Y).is_colimit⟩
end
lemma op (h : is_pushout f g inl inr) : is_pullback inr.op inl.op g.op f.op :=
is_pullback.of_is_limit (is_limit.of_iso_limit
(limits.pushout_cocone.is_colimit_equiv_is_limit_op h.flip.cocone h.flip.is_colimit)
h.to_comm_sq.flip.cocone_op)
lemma unop {Z X Y P : Cᵒᵖ} {f : Z ⟶ X} {g : Z ⟶ Y} {inl : X ⟶ P} {inr : Y ⟶ P}
(h : is_pushout f g inl inr) : is_pullback inr.unop inl.unop g.unop f.unop :=
is_pullback.of_is_limit (is_limit.of_iso_limit
(limits.pushout_cocone.is_colimit_equiv_is_limit_unop h.flip.cocone h.flip.is_colimit)
h.to_comm_sq.flip.cocone_unop)
lemma of_horiz_is_iso [is_iso f] [is_iso inr] (sq : comm_sq f g inl inr) :
is_pushout f g inl inr := of_is_colimit' sq
begin
refine pushout_cocone.is_colimit.mk _ (λ s, inv inr ≫ s.inr) (λ s, _) (by tidy) (by tidy),
simp only [← cancel_epi f, s.condition, sq.w_assoc, is_iso.hom_inv_id_assoc],
end
lemma of_vert_is_iso [is_iso g] [is_iso inl] (sq : comm_sq f g inl inr) :
is_pushout f g inl inr := (of_horiz_is_iso sq.flip).flip
end is_pushout
section equalizer
variables {X Y Z : C} {f f' : X ⟶ Y} {g g' : Y ⟶ Z}
/-- If `f : X ⟶ Y`, `g g' : Y ⟶ Z` forms a pullback square, then `f` is the equalizer of
`g` and `g'`. -/
noncomputable
def is_pullback.is_limit_fork (H : is_pullback f f g g') :
is_limit (fork.of_ι f H.w) :=
begin
fapply fork.is_limit.mk,
{ exact λ s, H.is_limit.lift (pullback_cone.mk s.ι s.ι s.condition) },
{ exact λ s, H.is_limit.fac _ walking_cospan.left },
{ intros s m e, apply pullback_cone.is_limit.hom_ext H.is_limit; refine e.trans _;
symmetry; exact H.is_limit.fac _ _ }
end
/-- If `f f' : X ⟶ Y`, `g : Y ⟶ Z` forms a pushout square, then `g` is the coequalizer of
`f` and `f'`. -/
noncomputable
def is_pushout.is_limit_fork (H : is_pushout f f' g g) :
is_colimit (cofork.of_π g H.w) :=
begin
fapply cofork.is_colimit.mk,
{ exact λ s, H.is_colimit.desc (pushout_cocone.mk s.π s.π s.condition) },
{ exact λ s, H.is_colimit.fac _ walking_span.left },
{ intros s m e, apply pushout_cocone.is_colimit.hom_ext H.is_colimit; refine e.trans _;
symmetry; exact H.is_colimit.fac _ _ }
end
end equalizer
namespace bicartesian_sq
variables {W X Y Z : C} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {i : Y ⟶ Z}
lemma of_is_pullback_is_pushout (p₁ : is_pullback f g h i) (p₂ : is_pushout f g h i) :
bicartesian_sq f g h i :=
bicartesian_sq.mk p₁.to_comm_sq ⟨p₁.is_limit⟩ ⟨p₂.is_colimit⟩
lemma flip (p : bicartesian_sq f g h i) : bicartesian_sq g f i h :=
of_is_pullback_is_pushout p.to_is_pullback.flip p.to_is_pushout.flip
variables [has_zero_object C] [has_zero_morphisms C]
open_locale zero_object
/--
```
X ⊞ Y --fst--> X
| |
snd 0
| |
v v
Y -----0---> 0
```
is a bicartesian square.
-/
lemma of_is_biproduct₁ {b : binary_bicone X Y} (h : b.is_bilimit) :
bicartesian_sq b.fst b.snd (0 : X ⟶ 0) (0 : Y ⟶ 0) :=
of_is_pullback_is_pushout (is_pullback.of_is_bilimit h) (is_pushout.of_is_bilimit' h)
/--
```
0 -----0---> X
| |
0 inl
| |
v v
Y --inr--> X ⊞ Y
```
is a bicartesian square.
-/
lemma of_is_biproduct₂ {b : binary_bicone X Y} (h : b.is_bilimit) :
bicartesian_sq (0 : 0 ⟶ X) (0 : 0 ⟶ Y) b.inl b.inr :=
of_is_pullback_is_pushout (is_pullback.of_is_bilimit' h) (is_pushout.of_is_bilimit h)
/--
```
X ⊞ Y --fst--> X
| |
snd 0
| |
v v
Y -----0---> 0
```
is a bicartesian square.
-/
@[simp] lemma of_has_biproduct₁ [has_binary_biproduct X Y] :
bicartesian_sq biprod.fst biprod.snd (0 : X ⟶ 0) (0 : Y ⟶ 0) :=
by convert of_is_biproduct₁ (binary_biproduct.is_bilimit X Y)
/--
```
0 -----0---> X
| |
0 inl
| |
v v
Y --inr--> X ⊞ Y
```
is a bicartesian square.
-/
@[simp] lemma of_has_biproduct₂ [has_binary_biproduct X Y] :
bicartesian_sq (0 : 0 ⟶ X) (0 : 0 ⟶ Y) biprod.inl biprod.inr :=
by convert of_is_biproduct₂ (binary_biproduct.is_bilimit X Y)
end bicartesian_sq
section functor
variables {D : Type u₂} [category.{v₂} D]
variables (F : C ⥤ D) {W X Y Z : C} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {i : Y ⟶ Z}
lemma functor.map_is_pullback [preserves_limit (cospan h i) F] (s : is_pullback f g h i) :
is_pullback (F.map f) (F.map g) (F.map h) (F.map i) :=
-- This is made slightly awkward because `C` and `D` have different universes,
-- and so the relevant `walking_cospan` diagrams live in different universes too!
begin
refine is_pullback.of_is_limit' (F.map_comm_sq s.to_comm_sq)
(is_limit.equiv_of_nat_iso_of_iso (cospan_comp_iso F h i) _ _ (walking_cospan.ext _ _ _)
(is_limit_of_preserves F s.is_limit)),
{ refl, },
{ dsimp, simp, },
{ dsimp, simp, },
end
lemma functor.map_is_pushout [preserves_colimit (span f g) F] (s : is_pushout f g h i) :
is_pushout (F.map f) (F.map g) (F.map h) (F.map i) :=
begin
refine is_pushout.of_is_colimit' (F.map_comm_sq s.to_comm_sq)
(is_colimit.equiv_of_nat_iso_of_iso (span_comp_iso F f g) _ _ (walking_span.ext _ _ _)
(is_colimit_of_preserves F s.is_colimit)),
{ refl, },
{ dsimp, simp, },
{ dsimp, simp, },
end
alias functor.map_is_pullback ← is_pullback.map
alias functor.map_is_pushout ← is_pushout.map
lemma is_pullback.of_map [reflects_limit (cospan h i) F] (e : f ≫ h = g ≫ i)
(H : is_pullback (F.map f) (F.map g) (F.map h) (F.map i)) : is_pullback f g h i :=
begin
refine ⟨⟨e⟩, ⟨is_limit_of_reflects F $ _⟩⟩,
refine (is_limit.equiv_of_nat_iso_of_iso (cospan_comp_iso F h i) _ _
(walking_cospan.ext _ _ _)).symm H.is_limit,
exacts [iso.refl _, (category.comp_id _).trans (category.id_comp _).symm,
(category.comp_id _).trans (category.id_comp _).symm]
end
lemma is_pullback.of_map_of_faithful [reflects_limit (cospan h i) F] [faithful F]
(H : is_pullback (F.map f) (F.map g) (F.map h) (F.map i)) : is_pullback f g h i :=
H.of_map F (F.map_injective $ by simpa only [F.map_comp] using H.w)
lemma is_pullback.map_iff {D : Type*} [category D] (F : C ⥤ D)
[preserves_limit (cospan h i) F] [reflects_limit (cospan h i) F] (e : f ≫ h = g ≫ i) :
is_pullback (F.map f) (F.map g) (F.map h) (F.map i) ↔ is_pullback f g h i :=
⟨λ h, h.of_map F e, λ h, h.map F⟩
lemma is_pushout.of_map [reflects_colimit (span f g) F] (e : f ≫ h = g ≫ i)
(H : is_pushout (F.map f) (F.map g) (F.map h) (F.map i)) : is_pushout f g h i :=
begin
refine ⟨⟨e⟩, ⟨is_colimit_of_reflects F $ _⟩⟩,
refine (is_colimit.equiv_of_nat_iso_of_iso (span_comp_iso F f g) _ _
(walking_span.ext _ _ _)).symm H.is_colimit,
exacts [iso.refl _, (category.comp_id _).trans (category.id_comp _),
(category.comp_id _).trans (category.id_comp _)]
end
lemma is_pushout.of_map_of_faithful [reflects_colimit (span f g) F] [faithful F]
(H : is_pushout (F.map f) (F.map g) (F.map h) (F.map i)) : is_pushout f g h i :=
H.of_map F (F.map_injective $ by simpa only [F.map_comp] using H.w)
lemma is_pushout.map_iff {D : Type*} [category D] (F : C ⥤ D)
[preserves_colimit (span f g) F] [reflects_colimit (span f g) F] (e : f ≫ h = g ≫ i) :
is_pushout (F.map f) (F.map g) (F.map h) (F.map i) ↔ is_pushout f g h i :=
⟨λ h, h.of_map F e, λ h, h.map F⟩
end functor
end category_theory
|
e5cafce6a194496989c4fac1349d9d173a3ec714 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/data/prod.lean | cdbe2711c41c9e5c876937887a04ed8f75ec13e1 | [
"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 | 4,935 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import tactic.basic
/-!
# Extra facts about `prod`
This file defines `prod.swap : α × β → β × α` and proves various simple lemmas about `prod`.
-/
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
@[simp] theorem prod.forall {p : α × β → Prop} : (∀ x, p x) ↔ (∀ a b, p (a, b)) :=
⟨assume h a b, h (a, b), assume h ⟨a, b⟩, h a b⟩
@[simp] theorem prod.exists {p : α × β → Prop} : (∃ x, p x) ↔ (∃ a b, p (a, b)) :=
⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩
@[simp] lemma prod_map (f : α → γ) (g : β → δ) (p : α × β) : prod.map f g p = (f p.1, g p.2) := rfl
namespace prod
@[simp] lemma map_mk (f : α → γ) (g : β → δ) (a : α) (b : β) : map f g (a, b) = (f a, g b) := rfl
lemma map_fst (f : α → γ) (g : β → δ) (p : α × β) : (map f g p).1 = f (p.1) := rfl
lemma map_snd (f : α → γ) (g : β → δ) (p : α × β) : (map f g p).2 = g (p.2) := rfl
lemma map_fst' (f : α → γ) (g : β → δ) : (prod.fst ∘ map f g) = f ∘ prod.fst :=
funext $ map_fst f g
lemma map_snd' (f : α → γ) (g : β → δ) : (prod.snd ∘ map f g) = g ∘ prod.snd :=
funext $ map_snd f g
@[simp] theorem mk.inj_iff {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) = (a₂, b₂) ↔ (a₁ = a₂ ∧ b₁ = b₂) :=
⟨prod.mk.inj, by cc⟩
lemma mk.inj_left {α β : Type*} (a : α) :
function.injective (prod.mk a : β → α × β) :=
by { intros b₁ b₂ h, simpa only [true_and, prod.mk.inj_iff, eq_self_iff_true] using h }
lemma mk.inj_right {α β : Type*} (b : β) :
function.injective (λ a, prod.mk a b : α → α × β) :=
by { intros b₁ b₂ h, by simpa only [and_true, eq_self_iff_true, mk.inj_iff] using h }
lemma ext_iff {p q : α × β} : p = q ↔ p.1 = q.1 ∧ p.2 = q.2 :=
by rw [← @mk.eta _ _ p, ← @mk.eta _ _ q, mk.inj_iff]
@[ext]
lemma ext {α β} {p q : α × β} (h₁ : p.1 = q.1) (h₂ : p.2 = q.2) : p = q :=
ext_iff.2 ⟨h₁, h₂⟩
lemma map_def {f : α → γ} {g : β → δ} : prod.map f g = λ (p : α × β), (f p.1, g p.2) :=
funext (λ p, ext (map_fst f g p) (map_snd f g p))
lemma id_prod : (λ (p : α × α), (p.1, p.2)) = id :=
funext $ λ ⟨a, b⟩, rfl
lemma fst_surjective [h : nonempty β] : function.surjective (@fst α β) :=
λ x, h.elim $ λ y, ⟨⟨x, y⟩, rfl⟩
lemma snd_surjective [h : nonempty α] : function.surjective (@snd α β) :=
λ y, h.elim $ λ x, ⟨⟨x, y⟩, rfl⟩
lemma fst_injective [subsingleton β] : function.injective (@fst α β) :=
λ x y h, ext h (subsingleton.elim _ _)
lemma snd_injective [subsingleton α] : function.injective (@snd α β) :=
λ x y h, ext (subsingleton.elim _ _) h
/-- Swap the factors of a product. `swap (a, b) = (b, a)` -/
def swap : α × β → β × α := λp, (p.2, p.1)
@[simp] lemma swap_swap : ∀ x : α × β, swap (swap x) = x
| ⟨a, b⟩ := rfl
@[simp] lemma fst_swap {p : α × β} : (swap p).1 = p.2 := rfl
@[simp] lemma snd_swap {p : α × β} : (swap p).2 = p.1 := rfl
@[simp] lemma swap_prod_mk {a : α} {b : β} : swap (a, b) = (b, a) := rfl
@[simp] lemma swap_swap_eq : swap ∘ swap = @id (α × β) :=
funext swap_swap
@[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap :=
swap_swap
@[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap :=
swap_swap
lemma eq_iff_fst_eq_snd_eq : ∀{p q : α × β}, p = q ↔ (p.1 = q.1 ∧ p.2 = q.2)
| ⟨p₁, p₂⟩ ⟨q₁, q₂⟩ := by simp
lemma fst_eq_iff : ∀ {p : α × β} {x : α}, p.1 = x ↔ p = (x, p.2)
| ⟨a, b⟩ x := by simp
lemma snd_eq_iff : ∀ {p : α × β} {x : β}, p.2 = x ↔ p = (p.1, x)
| ⟨a, b⟩ x := by simp
theorem lex_def (r : α → α → Prop) (s : β → β → Prop)
{p q : α × β} : prod.lex r s p q ↔ r p.1 q.1 ∨ p.1 = q.1 ∧ s p.2 q.2 :=
⟨λ h, by cases h; simp *,
λ h, match p, q, h with
| (a, b), (c, d), or.inl h := lex.left _ _ h
| (a, b), (c, d), or.inr ⟨e, h⟩ :=
by change a = c at e; subst e; exact lex.right _ h
end⟩
instance lex.decidable [decidable_eq α]
(r : α → α → Prop) (s : β → β → Prop) [decidable_rel r] [decidable_rel s] :
decidable_rel (prod.lex r s) :=
λ p q, decidable_of_decidable_of_iff (by apply_instance) (lex_def r s).symm
end prod
open function
lemma function.injective.prod_map {f : α → γ} {g : β → δ} (hf : injective f) (hg : injective g) :
injective (prod.map f g) :=
λ x y h, prod.ext (hf (prod.ext_iff.1 h).1) (hg $ (prod.ext_iff.1 h).2)
lemma function.surjective.prod_map {f : α → γ} {g : β → δ} (hf : surjective f) (hg : surjective g) :
surjective (prod.map f g) :=
λ p, let ⟨x, hx⟩ := hf p.1 in let ⟨y, hy⟩ := hg p.2 in ⟨(x, y), prod.ext hx hy⟩
|
0bfcec29af3a2bf88d8558c1d2db9113c362e052 | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /library/data/int/order.lean | 68c535820b1b2935f255025a2001c6e7d10d394c | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,426 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Jeremy Avigad
The order relation on the integers. We show that int is an instance of linear_comm_ordered_ring
and transfer the results.
-/
import .basic algebra.ordered_ring
open nat
open decidable
open int eq.ops
namespace int
private definition nonneg (a : ℤ) : Prop := int.cases_on a (take n, true) (take n, false)
definition le (a b : ℤ) : Prop := nonneg (b - a)
definition lt (a b : ℤ) : Prop := le (a + 1) b
infix [priority int.prio] - := int.sub
infix [priority int.prio] <= := int.le
infix [priority int.prio] ≤ := int.le
infix [priority int.prio] < := int.lt
local attribute nonneg [reducible]
private definition decidable_nonneg [instance] (a : ℤ) : decidable (nonneg a) := int.cases_on a _ _
definition decidable_le [instance] (a b : ℤ) : decidable (a ≤ b) := decidable_nonneg _
definition decidable_lt [instance] (a b : ℤ) : decidable (a < b) := decidable_nonneg _
private theorem nonneg.elim {a : ℤ} : nonneg a → ∃n : ℕ, a = n :=
int.cases_on a (take n H, exists.intro n rfl) (take n', false.elim)
private theorem nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) :=
int.cases_on a (take n, or.inl trivial) (take n, or.inr trivial)
theorem le.intro {a b : ℤ} {n : ℕ} (H : a + n = b) : a ≤ b :=
have n = b - a, from eq_add_neg_of_add_eq (!add.comm ▸ H),
show nonneg (b - a), from this ▸ trivial
theorem le.elim {a b : ℤ} (H : a ≤ b) : ∃n : ℕ, a + n = b :=
obtain (n : ℕ) (H1 : b - a = n), from nonneg.elim H,
exists.intro n (!add.comm ▸ iff.mpr !add_eq_iff_eq_add_neg (H1⁻¹))
theorem le.total (a b : ℤ) : a ≤ b ∨ b ≤ a :=
or.imp_right
(assume H : nonneg (-(b - a)),
have -(b - a) = a - b, from !neg_sub,
show nonneg (a - b), from this ▸ H)
(nonneg_or_nonneg_neg (b - a))
theorem of_nat_le_of_nat_of_le {m n : ℕ} (H : #nat m ≤ n) : of_nat m ≤ of_nat n :=
obtain (k : ℕ) (Hk : m + k = n), from nat.le.elim H,
le.intro (Hk ▸ (of_nat_add m k)⁻¹)
theorem le_of_of_nat_le_of_nat {m n : ℕ} (H : of_nat m ≤ of_nat n) : (#nat m ≤ n) :=
obtain (k : ℕ) (Hk : of_nat m + of_nat k = of_nat n), from le.elim H,
have m + k = n, from of_nat.inj (of_nat_add m k ⬝ Hk),
nat.le.intro this
theorem of_nat_le_of_nat_iff (m n : ℕ) : of_nat m ≤ of_nat n ↔ m ≤ n :=
iff.intro le_of_of_nat_le_of_nat of_nat_le_of_nat_of_le
theorem lt_add_succ (a : ℤ) (n : ℕ) : a < a + succ n :=
le.intro (show a + 1 + n = a + succ n, from
calc
a + 1 + n = a + (1 + n) : add.assoc
... = a + (n + 1) : nat.add.comm
... = a + succ n : rfl)
theorem lt.intro {a b : ℤ} {n : ℕ} (H : a + succ n = b) : a < b :=
H ▸ lt_add_succ a n
theorem lt.elim {a b : ℤ} (H : a < b) : ∃n : ℕ, a + succ n = b :=
obtain (n : ℕ) (Hn : a + 1 + n = b), from le.elim H,
have a + succ n = b, from
calc
a + succ n = a + 1 + n : by rewrite [add.assoc, add.comm 1 n]
... = b : Hn,
exists.intro n this
theorem of_nat_lt_of_nat_iff (n m : ℕ) : of_nat n < of_nat m ↔ n < m :=
calc
of_nat n < of_nat m ↔ of_nat n + 1 ≤ of_nat m : iff.refl
... ↔ of_nat (nat.succ n) ≤ of_nat m : of_nat_succ n ▸ !iff.refl
... ↔ nat.succ n ≤ m : of_nat_le_of_nat_iff
... ↔ n < m : iff.symm (lt_iff_succ_le _ _)
theorem lt_of_of_nat_lt_of_nat {m n : ℕ} (H : of_nat m < of_nat n) : #nat m < n :=
iff.mp !of_nat_lt_of_nat_iff H
theorem of_nat_lt_of_nat_of_lt {m n : ℕ} (H : #nat m < n) : of_nat m < of_nat n :=
iff.mpr !of_nat_lt_of_nat_iff H
/- show that the integers form an ordered additive group -/
theorem le.refl (a : ℤ) : a ≤ a :=
le.intro (add_zero a)
theorem le.trans {a b c : ℤ} (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c :=
obtain (n : ℕ) (Hn : a + n = b), from le.elim H1,
obtain (m : ℕ) (Hm : b + m = c), from le.elim H2,
have a + of_nat (n + m) = c, from
calc
a + of_nat (n + m) = a + (of_nat n + m) : {of_nat_add n m}
... = a + n + m : (add.assoc a n m)⁻¹
... = b + m : {Hn}
... = c : Hm,
le.intro this
theorem le.antisymm : ∀ {a b : ℤ}, a ≤ b → b ≤ a → a = b :=
take a b : ℤ, assume (H₁ : a ≤ b) (H₂ : b ≤ a),
obtain (n : ℕ) (Hn : a + n = b), from le.elim H₁,
obtain (m : ℕ) (Hm : b + m = a), from le.elim H₂,
have a + of_nat (n + m) = a + 0, from
calc
a + of_nat (n + m) = a + (of_nat n + m) : of_nat_add
... = a + n + m : add.assoc
... = b + m : Hn
... = a : Hm
... = a + 0 : add_zero,
have of_nat (n + m) = of_nat 0, from add.left_cancel this,
have n + m = 0, from of_nat.inj this,
have n = 0, from nat.eq_zero_of_add_eq_zero_right this,
show a = b, from
calc
a = a + 0 : add_zero
... = a + n : this
... = b : Hn
theorem lt.irrefl (a : ℤ) : ¬ a < a :=
(suppose a < a,
obtain (n : ℕ) (Hn : a + succ n = a), from lt.elim this,
have a + succ n = a + 0, from
Hn ⬝ !add_zero⁻¹,
!succ_ne_zero (of_nat.inj (add.left_cancel this)))
theorem ne_of_lt {a b : ℤ} (H : a < b) : a ≠ b :=
(suppose a = b, absurd (this ▸ H) (lt.irrefl b))
theorem le_of_lt {a b : ℤ} (H : a < b) : a ≤ b :=
obtain (n : ℕ) (Hn : a + succ n = b), from lt.elim H,
le.intro Hn
theorem lt_iff_le_and_ne (a b : ℤ) : a < b ↔ (a ≤ b ∧ a ≠ b) :=
iff.intro
(assume H, and.intro (le_of_lt H) (ne_of_lt H))
(assume H,
have a ≤ b, from and.elim_left H,
have a ≠ b, from and.elim_right H,
obtain (n : ℕ) (Hn : a + n = b), from le.elim `a ≤ b`,
have n ≠ 0, from (assume H' : n = 0, `a ≠ b` (!add_zero ▸ H' ▸ Hn)),
obtain (k : ℕ) (Hk : n = nat.succ k), from nat.exists_eq_succ_of_ne_zero this,
lt.intro (Hk ▸ Hn))
theorem le_iff_lt_or_eq (a b : ℤ) : a ≤ b ↔ (a < b ∨ a = b) :=
iff.intro
(assume H,
by_cases
(suppose a = b, or.inr this)
(suppose a ≠ b,
obtain (n : ℕ) (Hn : a + n = b), from le.elim H,
have n ≠ 0, from (assume H' : n = 0, `a ≠ b` (!add_zero ▸ H' ▸ Hn)),
obtain (k : ℕ) (Hk : n = nat.succ k), from nat.exists_eq_succ_of_ne_zero this,
or.inl (lt.intro (Hk ▸ Hn))))
(assume H,
or.elim H
(assume H1, le_of_lt H1)
(assume H1, H1 ▸ !le.refl))
theorem lt_succ (a : ℤ) : a < a + 1 :=
le.refl (a + 1)
theorem add_le_add_left {a b : ℤ} (H : a ≤ b) (c : ℤ) : c + a ≤ c + b :=
obtain (n : ℕ) (Hn : a + n = b), from le.elim H,
have H2 : c + a + n = c + b, from
calc
c + a + n = c + (a + n) : add.assoc c a n
... = c + b : {Hn},
le.intro H2
theorem add_lt_add_left {a b : ℤ} (H : a < b) (c : ℤ) : c + a < c + b :=
let H' := le_of_lt H in
(iff.mpr (lt_iff_le_and_ne _ _)) (and.intro (add_le_add_left H' _)
(take Heq, let Heq' := add_left_cancel Heq in
!lt.irrefl (Heq' ▸ H)))
theorem mul_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a * b :=
obtain (n : ℕ) (Hn : 0 + n = a), from le.elim Ha,
obtain (m : ℕ) (Hm : 0 + m = b), from le.elim Hb,
le.intro
(eq.symm
(calc
a * b = (0 + n) * b : Hn
... = n * b : nat.zero_add
... = n * (0 + m) : {Hm⁻¹}
... = n * m : nat.zero_add
... = 0 + n * m : zero_add))
theorem mul_pos {a b : ℤ} (Ha : 0 < a) (Hb : 0 < b) : 0 < a * b :=
obtain (n : ℕ) (Hn : 0 + nat.succ n = a), from lt.elim Ha,
obtain (m : ℕ) (Hm : 0 + nat.succ m = b), from lt.elim Hb,
lt.intro
(eq.symm
(calc
a * b = (0 + nat.succ n) * b : Hn
... = nat.succ n * b : nat.zero_add
... = nat.succ n * (0 + nat.succ m) : {Hm⁻¹}
... = nat.succ n * nat.succ m : nat.zero_add
... = of_nat (nat.succ n * nat.succ m) : of_nat_mul
... = of_nat (nat.succ n * m + nat.succ n) : nat.mul_succ
... = of_nat (nat.succ (nat.succ n * m + n)) : nat.add_succ
... = 0 + nat.succ (nat.succ n * m + n) : zero_add))
theorem zero_lt_one : (0 : ℤ) < 1 := trivial
theorem not_le_of_gt {a b : ℤ} (H : a < b) : ¬ b ≤ a :=
assume Hba,
let Heq := le.antisymm (le_of_lt H) Hba in
!lt.irrefl (Heq ▸ H)
theorem lt_of_lt_of_le {a b c : ℤ} (Hab : a < b) (Hbc : b ≤ c) : a < c :=
let Hab' := le_of_lt Hab in
let Hac := le.trans Hab' Hbc in
(iff.mpr !lt_iff_le_and_ne) (and.intro Hac
(assume Heq, not_le_of_gt (Heq ▸ Hab) Hbc))
theorem lt_of_le_of_lt {a b c : ℤ} (Hab : a ≤ b) (Hbc : b < c) : a < c :=
let Hbc' := le_of_lt Hbc in
let Hac := le.trans Hab Hbc' in
(iff.mpr !lt_iff_le_and_ne) (and.intro Hac
(assume Heq, not_le_of_gt (Heq⁻¹ ▸ Hbc) Hab))
section migrate_algebra
open [classes] algebra
protected definition linear_ordered_comm_ring [reducible] :
algebra.linear_ordered_comm_ring int :=
⦃algebra.linear_ordered_comm_ring, int.integral_domain,
le := le,
le_refl := le.refl,
le_trans := @le.trans,
le_antisymm := @le.antisymm,
lt := lt,
le_of_lt := @le_of_lt,
lt_irrefl := lt.irrefl,
lt_of_lt_of_le := @lt_of_lt_of_le,
lt_of_le_of_lt := @lt_of_le_of_lt,
add_le_add_left := @add_le_add_left,
mul_nonneg := @mul_nonneg,
mul_pos := @mul_pos,
le_iff_lt_or_eq := le_iff_lt_or_eq,
le_total := le.total,
zero_ne_one := zero_ne_one,
zero_lt_one := zero_lt_one,
add_lt_add_left := @add_lt_add_left⦄
protected definition decidable_linear_ordered_comm_ring [reducible] :
algebra.decidable_linear_ordered_comm_ring int :=
⦃algebra.decidable_linear_ordered_comm_ring,
int.linear_ordered_comm_ring,
decidable_lt := decidable_lt⦄
local attribute int.integral_domain [instance]
local attribute int.linear_ordered_comm_ring [instance]
local attribute int.decidable_linear_ordered_comm_ring [instance]
definition ge [reducible] (a b : ℤ) := algebra.has_le.ge a b
definition gt [reducible] (a b : ℤ) := algebra.has_lt.gt a b
infix [priority int.prio] >= := int.ge
infix [priority int.prio] ≥ := int.ge
infix [priority int.prio] > := int.gt
definition decidable_ge [instance] (a b : ℤ) : decidable (a ≥ b) :=
show decidable (b ≤ a), from _
definition decidable_gt [instance] (a b : ℤ) : decidable (a > b) :=
show decidable (b < a), from _
definition min : ℤ → ℤ → ℤ := algebra.min
definition max : ℤ → ℤ → ℤ := algebra.max
definition abs : ℤ → ℤ := algebra.abs
definition sign : ℤ → ℤ := algebra.sign
migrate from algebra with int
replacing dvd → dvd, sub → sub, has_le.ge → ge, has_lt.gt → gt, min → min, max → max,
abs → abs, sign → sign
attribute le.trans ge.trans lt.trans gt.trans [trans]
attribute lt_of_lt_of_le lt_of_le_of_lt gt_of_gt_of_ge gt_of_ge_of_gt [trans]
end migrate_algebra
/- more facts specific to int -/
theorem of_nat_nonneg (n : ℕ) : 0 ≤ of_nat n := trivial
theorem of_nat_pos {n : ℕ} (Hpos : #nat n > 0) : of_nat n > 0 :=
of_nat_lt_of_nat_of_lt Hpos
theorem of_nat_succ_pos (n : nat) : of_nat (nat.succ n) > 0 :=
of_nat_pos !nat.succ_pos
theorem exists_eq_of_nat {a : ℤ} (H : 0 ≤ a) : ∃n : ℕ, a = of_nat n :=
obtain (n : ℕ) (H1 : 0 + of_nat n = a), from le.elim H,
exists.intro n (!zero_add ▸ (H1⁻¹))
theorem exists_eq_neg_of_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -(of_nat n) :=
have -a ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos H,
obtain (n : ℕ) (Hn : -a = of_nat n), from exists_eq_of_nat this,
exists.intro n (eq_neg_of_eq_neg (Hn⁻¹))
theorem of_nat_nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : of_nat (nat_abs a) = a :=
obtain (n : ℕ) (Hn : a = of_nat n), from exists_eq_of_nat H,
Hn⁻¹ ▸ congr_arg of_nat (nat_abs_of_nat n)
theorem of_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : of_nat (nat_abs a) = -a :=
have -a ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos H,
calc
of_nat (nat_abs a) = of_nat (nat_abs (-a)) : nat_abs_neg
... = -a : of_nat_nat_abs_of_nonneg this
theorem of_nat_nat_abs (b : ℤ) : nat_abs b = abs b :=
or.elim (le.total 0 b)
(assume H : b ≥ 0, of_nat_nat_abs_of_nonneg H ⬝ (abs_of_nonneg H)⁻¹)
(assume H : b ≤ 0, of_nat_nat_abs_of_nonpos H ⬝ (abs_of_nonpos H)⁻¹)
theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a :=
abs.by_cases rfl !nat_abs_neg
theorem lt_of_add_one_le {a b : ℤ} (H : a + 1 ≤ b) : a < b :=
obtain n (H1 : a + 1 + n = b), from le.elim H,
have a + succ n = b, by rewrite [-H1, add.assoc, add.comm 1],
lt.intro this
theorem add_one_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b :=
obtain n (H1 : a + succ n = b), from lt.elim H,
have a + 1 + n = b, by rewrite [-H1, add.assoc, add.comm 1],
le.intro this
theorem lt_add_one_of_le {a b : ℤ} (H : a ≤ b) : a < b + 1 :=
lt_add_of_le_of_pos H trivial
theorem le_of_lt_add_one {a b : ℤ} (H : a < b + 1) : a ≤ b :=
have H1 : a + 1 ≤ b + 1, from add_one_le_of_lt H,
le_of_add_le_add_right H1
theorem sub_one_le_of_lt {a b : ℤ} (H : a ≤ b) : a - 1 < b :=
lt_of_add_one_le (!sub_add_cancel⁻¹ ▸ H)
theorem lt_of_sub_one_le {a b : ℤ} (H : a - 1 < b) : a ≤ b :=
!sub_add_cancel ▸ add_one_le_of_lt H
theorem le_sub_one_of_lt {a b : ℤ} (H : a < b) : a ≤ b - 1 :=
le_of_lt_add_one (!sub_add_cancel⁻¹ ▸ H)
theorem lt_of_le_sub_one {a b : ℤ} (H : a ≤ b - 1) : a < b :=
!sub_add_cancel ▸ (lt_add_one_of_le H)
theorem sign_of_succ (n : nat) : sign (nat.succ n) = 1 :=
sign_of_pos (of_nat_pos !nat.succ_pos)
theorem exists_eq_neg_succ_of_nat {a : ℤ} : a < 0 → ∃m : ℕ, a = -[1+m] :=
int.cases_on a
(take m H, absurd (of_nat_nonneg m : 0 ≤ m) (not_le_of_gt H))
(take m H, exists.intro m rfl)
theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 :=
have a * b > 0, by rewrite H'; apply trivial,
have b > 0, from pos_of_mul_pos_left this H,
have a > 0, from pos_of_mul_pos_right `a * b > 0` (le_of_lt `b > 0`),
or.elim (le_or_gt a 1)
(suppose a ≤ 1,
show a = 1, from le.antisymm this (add_one_le_of_lt `a > 0`))
(suppose a > 1,
assert a * b ≥ 2 * 1,
from mul_le_mul (add_one_le_of_lt `a > 1`) (add_one_le_of_lt `b > 0`) trivial H,
have false, by rewrite [H' at this]; exact this,
false.elim this)
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 (!mul.comm ▸ H')
theorem eq_one_of_mul_eq_self_left {a b : ℤ} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 :=
eq_of_mul_eq_mul_right Hpos (H ⬝ (one_mul a)⁻¹)
theorem eq_one_of_mul_eq_self_right {a b : ℤ} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 :=
eq_one_of_mul_eq_self_left Hpos (!mul.comm ▸ H)
theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 :=
dvd.elim H'
(take b,
suppose 1 = a * b,
eq_one_of_mul_eq_one_right H this⁻¹)
theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P]
(Hbdd : ∃ b : ℤ, ∀ z : ℤ, z ≤ b → ¬ P z)
(Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, z < lb → ¬ P z) :=
begin
cases Hbdd with [b, Hb],
cases Hinh with [elt, Helt],
existsi b + of_nat (least (λ n, P (b + of_nat n)) (nat.succ (nat_abs (elt - b)))),
have Heltb : elt > b, begin
apply int.lt_of_not_ge,
intro Hge,
apply (Hb _ Hge) Helt
end,
have H' : P (b + of_nat (nat_abs (elt - b))), begin
rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt (iff.mpr !int.sub_pos_iff_lt Heltb)),
int.add.comm, int.sub_add_cancel],
apply Helt
end,
apply and.intro,
apply least_of_lt _ !lt_succ_self H',
intros z Hz,
cases em (z ≤ b) with [Hzb, Hzb],
apply Hb _ Hzb,
let Hzb' := int.lt_of_not_ge Hzb,
let Hpos := iff.mpr !int.sub_pos_iff_lt Hzb',
have Hzbk : z = b + of_nat (nat_abs (z - b)),
by rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos), int.add.comm, int.sub_add_cancel],
have Hk : nat_abs (z - b) < least (λ n, P (b + of_nat n)) (nat.succ (nat_abs (elt - b))), begin
let Hz' := iff.mp !int.lt_add_iff_sub_lt_left Hz,
rewrite [-of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos) at Hz'],
apply lt_of_of_nat_lt_of_nat Hz'
end,
let Hk' := nat.not_le_of_gt Hk,
rewrite Hzbk,
apply λ p, mt (ge_least_of_lt _ p) Hk',
apply nat.lt.trans Hk,
apply least_lt _ !lt_succ_self H'
end
theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P]
(Hbdd : ∃ b : ℤ, ∀ z : ℤ, z ≥ b → ¬ P z)
(Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, z > ub → ¬ P z) :=
begin
cases Hbdd with [b, Hb],
cases Hinh with [elt, Helt],
existsi b - of_nat (least (λ n, P (b - of_nat n)) (nat.succ (nat_abs (b - elt)))),
have Heltb : elt < b, begin
apply int.lt_of_not_ge,
intro Hge,
apply (Hb _ Hge) Helt
end,
have H' : P (b - of_nat (nat_abs (b - elt))), begin
rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt (iff.mpr !int.sub_pos_iff_lt Heltb)),
int.sub_sub_self],
apply Helt
end,
apply and.intro,
apply least_of_lt _ !lt_succ_self H',
intros z Hz,
cases em (z ≥ b) with [Hzb, Hzb],
apply Hb _ Hzb,
let Hzb' := int.lt_of_not_ge Hzb,
let Hpos := iff.mpr !int.sub_pos_iff_lt Hzb',
have Hzbk : z = b - of_nat (nat_abs (b - z)),
by rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos), int.sub_sub_self],
have Hk : nat_abs (b - z) < least (λ n, P (b - of_nat n)) (nat.succ (nat_abs (b - elt))), begin
let Hz' := iff.mp !int.lt_add_iff_sub_lt_left (iff.mpr !int.lt_add_iff_sub_lt_right Hz),
rewrite [-of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos) at Hz'],
apply lt_of_of_nat_lt_of_nat Hz'
end,
let Hk' := nat.not_le_of_gt Hk,
rewrite Hzbk,
apply λ p, mt (ge_least_of_lt _ p) Hk',
apply nat.lt.trans Hk,
apply least_lt _ !lt_succ_self H'
end
end int
|
18cb040db229e153d17b27264c514e9daf38d74d | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/ring_theory/localization/as_subring.lean | a233c440442caf612f5d4bd56e572ddcdfc9e754 | [
"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,254 | lean | /-
Copyright (c) 2022 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz, Junyan Xu
-/
import ring_theory.localization.localization_localization
/-!
# Localizations of domains as subalgebras of the fraction field.
Given a domain `A` with fraction field `K`, and a submonoid `S` of `A` which
does not contain zero, this file constructs the localization of `A` at `S`
as a subalgebra of the field `K` over `A`.
-/
namespace localization
open_locale non_zero_divisors
variables {A : Type*} (K : Type*) [comm_ring A] (S : submonoid A) (hS : S ≤ A⁰)
section comm_ring
variables [comm_ring K] [algebra A K] [is_fraction_ring A K]
lemma map_is_unit_of_le (hS : S ≤ A⁰) (s : S) : is_unit (algebra_map A K s) :=
by apply is_localization.map_units K (⟨s.1, hS s.2⟩ : A⁰)
/-- The canonical map from a localization of `A` at `S` to the fraction ring
of `A`, given that `S ≤ A⁰`. -/
noncomputable
def map_to_fraction_ring (B : Type*) [comm_ring B] [algebra A B]
[is_localization S B] (hS : S ≤ A⁰) :
B →ₐ[A] K :=
{ commutes' := λ a, by simp,
..is_localization.lift (map_is_unit_of_le K S hS) }
@[simp]
lemma map_to_fraction_ring_apply {B : Type*} [comm_ring B] [algebra A B]
[is_localization S B] (hS : S ≤ A⁰) (b : B) :
map_to_fraction_ring K S B hS b = is_localization.lift (map_is_unit_of_le K S hS) b := rfl
lemma mem_range_map_to_fraction_ring_iff (B : Type*) [comm_ring B] [algebra A B]
[is_localization S B] (hS : S ≤ A⁰) (x : K) :
x ∈ (map_to_fraction_ring K S B hS).range ↔
∃ (a s : A) (hs : s ∈ S), x = is_localization.mk' K a ⟨s, hS hs⟩ :=
⟨ by { rintro ⟨x,rfl⟩, obtain ⟨a,s,rfl⟩ := is_localization.mk'_surjective S x,
use [a, s, s.2], apply is_localization.lift_mk' },
by { rintro ⟨a,s,hs,rfl⟩, use is_localization.mk' _ a ⟨s,hs⟩,
apply is_localization.lift_mk' } ⟩
instance is_localization_range_map_to_fraction_ring (B : Type*) [comm_ring B] [algebra A B]
[is_localization S B] (hS : S ≤ A⁰) :
is_localization S (map_to_fraction_ring K S B hS).range :=
is_localization.is_localization_of_alg_equiv S $ show B ≃ₐ[A] _, from alg_equiv.of_bijective
(map_to_fraction_ring K S B hS).range_restrict
begin
refine ⟨λ a b h, _, set.surjective_onto_range⟩,
refine (is_localization.lift_injective_iff _).2 (λ a b, _) (subtype.ext_iff.1 h),
exact ⟨λ h, congr_arg _ (is_localization.injective _ hS h),
λ h, congr_arg _ (is_fraction_ring.injective A K h)⟩,
end
instance is_fraction_ring_range_map_to_fraction_ring
(B : Type*) [comm_ring B] [algebra A B]
[is_localization S B] (hS : S ≤ A⁰) :
is_fraction_ring (map_to_fraction_ring K S B hS).range K :=
is_fraction_ring.is_fraction_ring_of_is_localization S _ _ hS
/--
Given a commutative ring `A` with fraction ring `K`, and a submonoid `S` of `A` which
contains no zero divisor, this is the localization of `A` at `S`, considered as
a subalgebra of `K` over `A`.
The carrier of this subalgebra is defined as the set of all `x : K` of the form
`is_localization.mk' K a ⟨s, _⟩`, where `s ∈ S`.
-/
noncomputable
def subalgebra (hS : S ≤ A⁰) : subalgebra A K :=
(map_to_fraction_ring K S (localization S) hS).range.copy
{ x | ∃ (a s : A) (hs : s ∈ S), x = is_localization.mk' K a ⟨s, hS hs⟩ } $
by { ext, symmetry, apply mem_range_map_to_fraction_ring_iff }
namespace subalgebra
instance is_localization_subalgebra :
is_localization S (subalgebra K S hS) :=
by { dunfold localization.subalgebra, rw subalgebra.copy_eq, apply_instance }
instance is_fraction_ring : is_fraction_ring (subalgebra K S hS) K :=
is_fraction_ring.is_fraction_ring_of_is_localization S _ _ hS
end subalgebra
end comm_ring
section field
variables [field K] [algebra A K] [is_fraction_ring A K]
namespace subalgebra
lemma mem_range_map_to_fraction_ring_iff_of_field
(B : Type*) [comm_ring B] [algebra A B] [is_localization S B] (x : K) :
x ∈ (map_to_fraction_ring K S B hS).range ↔
∃ (a s : A) (hs : s ∈ S), x = algebra_map A K a * (algebra_map A K s)⁻¹ :=
begin
rw mem_range_map_to_fraction_ring_iff,
iterate 3 { congr' with }, convert iff.rfl, rw units.coe_inv, refl,
end
/--
Given a domain `A` with fraction field `K`, and a submonoid `S` of `A` which
contains no zero divisor, this is the localization of `A` at `S`, considered as
a subalgebra of `K` over `A`.
The carrier of this subalgebra is defined as the set of all `x : K` of the form
`algebra_map A K a * (algebra_map A K s)⁻¹` where `a s : A` and `s ∈ S`.
-/
noncomputable
def of_field : _root_.subalgebra A K :=
(map_to_fraction_ring K S (localization S) hS).range.copy
{ x | ∃ (a s : A) (hs : s ∈ S), x = algebra_map A K a * (algebra_map A K s)⁻¹ } $
by { ext, symmetry, apply mem_range_map_to_fraction_ring_iff_of_field }
instance is_localization_of_field :
is_localization S (subalgebra.of_field K S hS) :=
by { dunfold localization.subalgebra.of_field, rw subalgebra.copy_eq, apply_instance }
instance is_fraction_ring_of_field : is_fraction_ring (subalgebra.of_field K S hS) K :=
is_fraction_ring.is_fraction_ring_of_is_localization S _ _ hS
end subalgebra
end field
end localization
|
7d63dba6046b69ffd51beff7a3b1a22705b3e889 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/pkg/user_opt/UserOpt.lean | 6a4ef2093cf58210a02178277116de956b21998d | [
"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 | 359 | lean | import UserOpt.Opts
open Lean
def tst1 : MetaM Unit := do
assert! !(myBoolOpt.get (← getOptions))
assert! myNatOpt.get (← getOptions) == 100
pure ()
#eval tst1
set_option myBoolOpt true
set_option myNatOpt 4
def tst2 : MetaM Unit := do
assert! myBoolOpt.get (← getOptions)
assert! myNatOpt.get (← getOptions) == 4
pure ()
#eval tst2
|
bea8ef63b6c03a9a5003930c0923f97ddbeb1d23 | 0d9b0a832bc57849732c5bd008a7a142f7e49656 | /src/listdec.lean | 38c01b51f32c837571ff66666bd9f29fc505e6cb | [] | no_license | mirefek/sokoban.lean | bb9414af67894e4d8ce75f8c8d7031df02d371d0 | 451c92308afb4d3f8e566594b9751286f93b899b | refs/heads/master | 1,681,025,245,267 | 1,618,997,832,000 | 1,618,997,832,000 | 359,491,681 | 10 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,084 | lean | import data.list.func
import .list2d
import .boolset2d
variables {α : Type} {β : Type}
variables [inhabited α] [inhabited β]
def forall1_inh_bool (P : α → bool) : list α → bool
| [] := P (default α)
| (h::t) := (P h) && (forall1_inh_bool t)
def forall2_inh_bool (P : α → β → bool) : list α → list β → bool
| [] l2 := forall1_inh_bool (P (default α)) l2
| (h::t) l2 := (P h l2.head) && (forall2_inh_bool t l2.tail)
lemma forall1_inh_bool.correct (P : α → Prop) [Hdec : Π a, decidable (P a)]
: ∀ l1 : list α,
forall1_inh_bool (λ a, to_bool (P a)) l1 ↔ ∀ n, P (list.func.get n l1)
| [] := by simp [forall1_inh_bool]
| (h::t) := begin
simp [forall1_inh_bool, forall1_inh_bool.correct],
split, assume H n, cases n, exact H.1, exact H.2 n,
assume H, split, exact H 0, assume n, exact H n.succ,
end
lemma forall2_inh_bool.correct (P : α → β → Prop) [Hdec : Π a b, decidable (P a b)]
: ∀ l1 : list α, ∀ l2 : list β,
forall2_inh_bool (λ a b, to_bool (P a b)) l1 l2
↔ ∀ n, P (list.func.get n l1) (list.func.get n l2)
| [] l2 := by simp [forall2_inh_bool, forall1_inh_bool.correct]
| (h::t) l2 := begin
simp [forall2_inh_bool, forall2_inh_bool.correct],
split, {
assume H n, cases n,
{ cases l2, exact H.1, exact H.1 },
{ cases l2, simp, simp at H, exact H.2 n, simp [list.tail] at H, exact H.2 n, },
}, {
assume H, split,
{ cases l2, exact H 0, exact H 0, },
{ assume n, cases l2, simp, simp at H, exact H n.succ, simp [list.tail], exact H n.succ, },
}
end
def forall2_inh_dec (P : α → β → Prop) [Hdec : Π a b, decidable (P a b)]
(l1 : list α) (l2 : list β)
: decidable (∀ n, P (list.func.get n l1) (list.func.get n l2))
:=
if C : forall2_inh_bool (λ a b, to_bool (P a b)) l1 l2 = tt then
is_true ((forall2_inh_bool.correct P l1 l2).mp C)
else is_false (mt (forall2_inh_bool.correct P l1 l2).mpr C)
instance equiv_decidable [decidable_eq α] : @decidable_rel (list α) list.func.equiv
:= forall2_inh_dec eq
def forall2d2_inh_dec (P : α → β → Prop) [Hdec : Π a b, decidable (P a b)]
(l1 : list2d α) (l2 : list2d β) :
decidable (∀ xy, P (list2d.get2d xy l1) (list2d.get2d xy l2))
:= begin
let P2 := λ (as : list α) (bs : list β), ∀ x, P (list.func.get x as) (list.func.get x bs),
haveI : ∀ a b, decidable (P2 a b) := forall2_inh_dec P,
haveI := forall2_inh_dec P2 l1 l2,
apply decidable_of_iff (∀ y, P2 (list.func.get y l1) (list.func.get y l2)),
split,
{ intros H xy, cases xy with x y, exact H y x, },
{ intros H y x, exact H (x,y), },
end
instance list.equiv_decidable [decidable_eq α] : @decidable_rel (list α) list.func.equiv
:= forall2_inh_dec eq
instance list2d.equiv_decidable [decidable_eq α] : @decidable_rel (list2d α) list2d.equiv
:= forall2d2_inh_dec eq
instance : decidable_rel bset1d.subset
:= forall2_inh_dec (λ a b, a = tt → b = tt)
instance : decidable_rel bset2d.subset
:= forall2d2_inh_dec (λ a b, a = tt → b = tt)
instance : decidable_rel bset2d.disjoint
:= forall2d2_inh_dec (λ a b, a = tt → b = tt → false)
|
75e73b34cf6c56ac930255d6c163db1cdf7a3c0f | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/measure_theory/integral/divergence_theorem.lean | 07d6493bc5b2a5b62d79da6d47160561e719126b | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,460 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.box_integral.divergence_theorem
import analysis.box_integral.integrability
import measure_theory.integral.interval_integral
/-!
# Divergence theorem for Bochner integral
In this file we prove the Divergence theorem for Bochner integral on a box in
`ℝⁿ⁺¹ = fin (n + 1) → ℝ`. More precisely, we prove the following theorem.
Let `E` be a complete normed space with second countably topology. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is
differentiable on a rectangular box `[a, b] : set ℝⁿ⁺¹`, `a ≤ b`, with derivative
`f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹` and the divergence `λ x, ∑ i, f' x eᵢ i` is integrable on `[a, b]`,
where `eᵢ = pi.single i 1` is the `i`-th basis vector, then its integral is equal to the sum of
integrals of `f` over the faces of `[a, b]`, taken with appropriat signs. Moreover, the same is true
if the function is not differentiable but continuous at countably many points of `[a, b]`.
## Notations
We use the following local notation to make the statement more readable. Note that the documentation
website shows the actual terms, not those abbreviated using local notations.
* `ℝⁿ`, `ℝⁿ⁺¹`, `Eⁿ⁺¹`: `fin n → ℝ`, `fin (n + 1) → ℝ`, `fin (n + 1) → E`;
* `face i`: the `i`-th face of the box `[a, b]` as a closed segment in `ℝⁿ`, namely `[a ∘
fin.succ_above i, b ∘ fin.succ_above i]`;
* `e i` : `i`-th basis vector `pi.single i 1`;
* `front_face i`, `back_face i`: embeddings `ℝⁿ → ℝⁿ⁺¹` corresponding to the front face
`{x | x i = b i}` and back face `{x | x i = a i}` of the box `[a, b]`, respectively.
They are given by `fin.insert_nth i (b i)` and `fin.insert_nth i (a i)`.
## TODO
* Deduce corollaries about integrals in `ℝ × ℝ` and interval integral.
* Add a version that assumes existence and integrability of partial derivatives.
## Tags
divergence theorem, Bochner integral
-/
open set finset topological_space function box_integral
open_locale big_operators classical
namespace measure_theory
universes u
variables {E : Type u} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[second_countable_topology E] [complete_space E]
section
variables {n : ℕ}
local notation `ℝⁿ` := fin n → ℝ
local notation `ℝⁿ⁺¹` := fin (n + 1) → ℝ
local notation `Eⁿ⁺¹` := fin (n + 1) → E
variables (a b : ℝⁿ⁺¹)
local notation `face` i := set.Icc (a ∘ fin.succ_above i) (b ∘ fin.succ_above i)
local notation `e` i := pi.single i 1
local notation `front_face` i:2000 := fin.insert_nth i (b i)
local notation `back_face` i:2000 := fin.insert_nth i (a i)
/-- **Divergence theorem** for Bochner integral. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is differentiable on a
rectangular box `[a, b] : set ℝⁿ⁺¹`, `a ≤ b`, with derivative `f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹` and the
divergence `λ x, ∑ i, f' x eᵢ i` is integrable on `[a, b]`, where `eᵢ = pi.single i 1` is the `i`-th
basis vector, then its integral is equal to the sum of integrals of `f` over the faces of `[a, b]`,
taken with appropriat signs.
Moreover, the same is true if the function is not differentiable but continuous at countably many
points of `[a, b]`.
We represent both faces `x i = a i` and `x i = b i` as the box
`face i = [a ∘ fin.succ_above i, b ∘ fin.succ_above i]` in `ℝⁿ`, where
`fin.succ_above : fin n ↪o fin (n + 1)` is the order embedding with range `{i}ᶜ`. The restrictions
of `f : ℝⁿ⁺¹ → Eⁿ⁺¹` to these faces are given by `f ∘ back_face i` and `f ∘ front_face i`, where
`back_face i = fin.insert_nth i (a i)` and `front_face i = fin.insert_nth i (b i)` are embeddings
`ℝⁿ → ℝⁿ⁺¹` that take `y : ℝⁿ` and insert `a i` (resp., `b i`) as `i`-th coordinate. -/
lemma integral_divergence_of_has_fderiv_within_at_off_countable (hle : a ≤ b) (f : ℝⁿ⁺¹ → Eⁿ⁺¹)
(f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹) (s : set ℝⁿ⁺¹) (hs : countable s)
(Hc : ∀ x ∈ s, continuous_within_at f (Icc a b) x)
(Hd : ∀ x ∈ Icc a b \ s, has_fderiv_within_at f (f' x) (Icc a b) x)
(Hi : integrable_on (λ x, ∑ i, f' x (pi.single i 1) i) (Icc a b)) :
∫ x in Icc a b, ∑ i, f' x (e i) i =
∑ i : fin (n + 1),
((∫ x in face i, f (front_face i x) i) - ∫ x in face i, f (back_face i x) i) :=
begin
simp only [volume_pi, ← set_integral_congr_set_ae measure.univ_pi_Ioc_ae_eq_Icc],
by_cases heq : ∃ i, a i = b i,
{ rcases heq with ⟨i, hi⟩,
have hi' : Ioc (a i) (b i) = ∅ := Ioc_eq_empty hi.not_lt,
have : pi set.univ (λ j, Ioc (a j) (b j)) = ∅, from univ_pi_eq_empty hi',
rw [this, integral_empty, sum_eq_zero],
rintro j -,
rcases eq_or_ne i j with rfl|hne,
{ simp [hi] },
{ rcases fin.exists_succ_above_eq hne with ⟨i, rfl⟩,
have : pi set.univ (λ k : fin n, Ioc (a $ j.succ_above k) (b $ j.succ_above k)) = ∅,
from univ_pi_eq_empty hi',
rw [this, integral_empty, integral_empty, sub_self] } },
{ push_neg at heq,
obtain ⟨I, rfl, rfl⟩ : ∃ I : box_integral.box (fin (n + 1)), I.lower = a ∧ I.upper = b,
from ⟨⟨a, b, λ i, (hle i).lt_of_ne (heq i)⟩, rfl, rfl⟩,
simp only [← box.coe_eq_pi, ← box.face_lower, ← box.face_upper],
have A := ((Hi.mono_set box.coe_subset_Icc).has_box_integral ⊥ rfl),
have B := has_integral_bot_divergence_of_forall_has_deriv_within_at I f f' s hs Hc Hd,
have Hc : continuous_on f I.Icc,
{ intros x hx,
by_cases hxs : x ∈ s,
exacts [Hc x hxs, (Hd x ⟨hx, hxs⟩).continuous_within_at] },
rw continuous_on_pi at Hc,
refine (A.unique B).trans (sum_congr rfl $ λ i hi, _),
refine congr_arg2 has_sub.sub _ _,
{ have := box.continuous_on_face_Icc (Hc i) (right_mem_Icc.2 (hle i)),
have := (this.integrable_on_compact (box.is_compact_Icc _)).mono_set box.coe_subset_Icc,
exact (this.has_box_integral ⊥ rfl).integral_eq, apply_instance },
{ have := box.continuous_on_face_Icc (Hc i) (left_mem_Icc.2 (hle i)),
have := (this.integrable_on_compact (box.is_compact_Icc _)).mono_set box.coe_subset_Icc,
exact (this.has_box_integral ⊥ rfl).integral_eq, apply_instance } }
end
end
end measure_theory
|
d4b63d5806c148f85d6cc403d7ba6b8569751cb6 | b2e508d02500f1512e1618150413e6be69d9db10 | /src/analysis/calculus/deriv.lean | f95f2151872230a9fcbfebefad34c0bbdd0133f6 | [
"Apache-2.0"
] | permissive | callum-sutton/mathlib | c3788f90216e9cd43eeffcb9f8c9f959b3b01771 | afd623825a3ac6bfbcc675a9b023edad3f069e89 | refs/heads/master | 1,591,371,888,053 | 1,560,990,690,000 | 1,560,990,690,000 | 192,476,045 | 0 | 0 | Apache-2.0 | 1,568,941,843,000 | 1,560,837,965,000 | Lean | UTF-8 | Lean | false | false | 45,528 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Sébastien Gouëzel
The Fréchet derivative.
Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[k] F` a
continuous k-linear map, where `k` is a non-discrete normed field. Then
`has_fderiv_within_at f f' s x`
says that `f` has derivative `f'` at `x`, where the domain of interest
is restricted to `s`. We also have
`has_fderiv_at f f' x := has_fderiv_within_at f f' x univ`
The derivative is defined in terms of the `is_o` relation, but also
characterized in terms of the `tendsto` relation.
We also introduce predicates `differentiable_within_at k f s x` (where `k` is the base field,
`f` the function to be differentiated, `x` the point at which the derivative is asserted to exist,
and `s` the set along which the derivative is defined), as well as `differentiable_at k f x`,
`differentiable_on k f s` and `differentiable k f` to express the existence of a derivative.
To be able to compute with derivatives, we write `fderiv_within k f s x` and `fderiv k f x`
for some choice of a derivative if it exists, and the zero function otherwise. This choice only
behaves well along sets for which the derivative is unique, i.e., those for which the tangent
directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and
`unique_diff_on s` express this property, and we prove that indeed they imply the uniqueness of the
derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness
only holds when the field is non-discrete, which we request at the very beginning:
otherwise, a derivative can be defined, but it has no interesting properties whatsoever.
In addition to the definition and basic properties of the derivative, this file contains the
usual formulas (and existence assertions) for the derivative of
* constants
* the identity
* bounded linear maps
* bounded bilinear maps
* sum of two functions
* multiplication of a function by a scalar constant
* negative of a function
* subtraction of two functions
* bounded bilinear maps
* multiplication of a function by a scalar function
* multiplication of two scalar functions
* composition of functions (the chain rule)
-/
-- import topology.sequences topology.opens
import analysis.asymptotics
import analysis.calculus.tangent_cone
open filter asymptotics continuous_linear_map set
noncomputable theory
local attribute [instance, priority 0] classical.decidable_inhabited classical.prop_decidable
set_option class.instance_max_depth 100
section
variables {k : Type*} [nondiscrete_normed_field k]
variables {E : Type*} [normed_group E] [normed_space k E]
variables {F : Type*} [normed_group F] [normed_space k F]
variables {G : Type*} [normed_group G] [normed_space k G]
def has_fderiv_at_filter (f : E → F) (f' : E →L[k] F) (x : E) (L : filter E) :=
is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L
def has_fderiv_within_at (f : E → F) (f' : E →L[k] F) (s : set E) (x : E) :=
has_fderiv_at_filter f f' x (nhds_within x s)
def has_fderiv_at (f : E → F) (f' : E →L[k] F) (x : E) :=
has_fderiv_at_filter f f' x (nhds x)
variables (k)
def differentiable_within_at (f : E → F) (s : set E) (x : E) :=
∃f' : E →L[k] F, has_fderiv_within_at f f' s x
def differentiable_at (f : E → F) (x : E) :=
∃f' : E →L[k] F, has_fderiv_at f f' x
def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[k] F :=
if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0
def fderiv (f : E → F) (x : E) : E →L[k] F :=
if h : ∃f', has_fderiv_at f f' x then classical.some h else 0
def differentiable_on (f : E → F) (s : set E) :=
∀x ∈ s, differentiable_within_at k f s x
def differentiable (f : E → F) :=
∀x, differentiable_at k f x
variables {k}
variables {f f₀ f₁ g : E → F}
variables {f' f₀' f₁' g' : E →L[k] F}
variables {x : E}
variables {s t : set E}
variables {L L₁ L₂ : filter E}
section derivative_uniqueness
/- In this section, we discuss the uniqueness of the derivative.
We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the
uniqueness of the derivative. -/
/-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/
theorem unique_diff_within_at.eq (H : unique_diff_within_at k s x)
(h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' :=
begin
have A : ∀y ∈ tangent_cone_at k s x, f' y = f₁' y,
{ assume y hy,
rcases hy with ⟨c, d, hd, hc, ylim⟩,
have at_top_is_finer : at_top ≤ comap (λ (n : ℕ), x + d n) (nhds_within (x + 0) s),
{ rw [←tendsto_iff_comap, nhds_within, tendsto_inf],
split,
{ apply tendsto_add tendsto_const_nhds (tangent_cone_at.lim_zero hc ylim) },
{ rwa tendsto_principal } },
rw add_zero at at_top_is_finer,
have : is_o (λ y, f₁' (y - x) - f' (y - x)) (λ y, y - x) (nhds_within x s),
by simpa using h.sub h₁,
have : is_o (λ n:ℕ, f₁' ((x + d n) - x) - f' ((x + d n) - x)) (λ n, (x + d n) - x)
((nhds_within x s).comap (λn, x+ d n)) := is_o.comp this _,
have L1 : is_o (λ n:ℕ, f₁' (d n) - f' (d n)) d
((nhds_within x s).comap (λn, x + d n)) := by simpa using this,
have L2 : is_o (λn:ℕ, f₁' (d n) - f' (d n)) d at_top :=
is_o.mono at_top_is_finer L1,
have L3 : is_o (λn:ℕ, c n • (f₁' (d n) - f' (d n))) (λn, c n • d n) at_top :=
is_o_smul L2,
have L4 : is_o (λn:ℕ, c n • (f₁' (d n) - f' (d n))) (λn, (1:ℝ)) at_top :=
L3.trans_is_O (is_O_one_of_tendsto ylim),
have L : tendsto (λn:ℕ, c n • (f₁' (d n) - f' (d n))) at_top (nhds 0) :=
is_o_one_iff.1 L4,
have L' : tendsto (λ (n : ℕ), c n • (f₁' (d n) - f' (d n))) at_top (nhds (f₁' y - f' y)),
{ simp only [smul_sub, (continuous_linear_map.map_smul _ _ _).symm],
apply tendsto_sub ((f₁'.continuous.tendsto _).comp ylim) ((f'.continuous.tendsto _).comp ylim) },
have : f₁' y - f' y = 0 := tendsto_nhds_unique (by simp) L' L,
exact (sub_eq_zero_iff_eq.1 this).symm },
have B : ∀y ∈ submodule.span k (tangent_cone_at k s x), f' y = f₁' y,
{ assume y hy,
apply submodule.span_induction hy,
{ exact λy hy, A y hy },
{ simp only [continuous_linear_map.map_zero] },
{ simp {contextual := tt} },
{ simp {contextual := tt} } },
have C : ∀y ∈ closure ((submodule.span k (tangent_cone_at k s x)) : set E), f' y = f₁' y,
{ assume y hy,
let K := {y | f' y = f₁' y},
have : (submodule.span k (tangent_cone_at k s x) : set E) ⊆ K := B,
have : closure (submodule.span k (tangent_cone_at k s x) : set E) ⊆ closure K :=
closure_mono this,
have : y ∈ closure K := this hy,
rwa closure_eq_of_is_closed (is_closed_eq f'.continuous f₁'.continuous) at this },
unfold unique_diff_within_at at H,
rw H at C,
ext y,
exact C y (mem_univ _)
end
theorem unique_diff_on.eq (H : unique_diff_on k s) (hx : x ∈ s)
(h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' :=
unique_diff_within_at.eq (H x hx) h h₁
end derivative_uniqueness
/- Basic properties of the derivative -/
section fderiv_properties
theorem has_fderiv_at_filter_iff_tendsto :
has_fderiv_at_filter f f' x L ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (nhds 0) :=
have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx',
by { rw [sub_eq_zero.1 ((norm_eq_zero (x' - x)).1 hx')], simp },
begin
unfold has_fderiv_at_filter,
rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h],
exact tendsto.congr'r (λ _, div_eq_inv_mul),
end
theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds_within x s) (nhds 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds x) (nhds 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) :
has_fderiv_at_filter f f' x L₁ :=
is_o.mono hst h
theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) :
has_fderiv_within_at f f' s x :=
h.mono (nhds_within_mono _ hst)
theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ nhds x) :
has_fderiv_at_filter f f' x L :=
h.mono hL
theorem has_fderiv_at.has_fderiv_within_at
(h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x :=
h.has_fderiv_at_filter lattice.inf_le_left
lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) :
differentiable_within_at k f s x :=
⟨f', h⟩
lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at k f x :=
⟨f', h⟩
lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at k f s x) :
has_fderiv_within_at f (fderiv_within k f s x) s x :=
begin
dunfold fderiv_within,
dunfold differentiable_within_at at h,
rw dif_pos h,
exact classical.some_spec h
end
lemma differentiable_at.has_fderiv_at (h : differentiable_at k f x) :
has_fderiv_at f (fderiv k f x) x :=
begin
dunfold fderiv,
dunfold differentiable_at at h,
rw dif_pos h,
exact classical.some_spec h
end
lemma differentiable_within_at.mono {t : set E} (h : s ⊆ t)
(h : differentiable_within_at k f t x) : differentiable_within_at k f s x :=
begin
rcases h with ⟨f', hf'⟩,
exact ⟨f', hf'.mono h⟩
end
lemma differentiable_within_univ_at :
differentiable_within_at k f univ x ↔ differentiable_at k f x :=
begin
unfold differentiable_within_at has_fderiv_within_at,
rw nhds_within_univ,
refl
end
@[simp] lemma has_fderiv_within_univ_at :
has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x :=
by { simp only [has_fderiv_within_at, nhds_within_univ], refl }
theorem has_fderiv_at_unique
(h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' :=
begin
rw ← has_fderiv_within_univ_at at h₀ h₁,
exact unique_diff_within_univ_at.eq h₀ h₁
end
lemma differentiable_at.differentiable_within_at
(h : differentiable_at k f x) : differentiable_within_at k f s x :=
differentiable_within_at.mono (subset_univ _) (differentiable_within_univ_at.2 h)
lemma differentiable_within_at.differentiable_at'
(h : differentiable_within_at k f s x) (hs : s ∈ nhds x) : differentiable_at k f x :=
begin
unfold differentiable_within_at has_fderiv_within_at at h,
have : nhds_within x s = nhds x := lattice.inf_of_le_left (le_principal_iff.2 hs),
rwa this at h,
end
lemma differentiable_within_at.differentiable_at
(h : differentiable_within_at k f s x) (hx : x ∈ s) (hs : is_open s) : differentiable_at k f x :=
h.differentiable_at' (mem_nhds_sets hs hx)
lemma has_fderiv_within_at.fderiv_within {f' : E →L[k] F}
(h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at k s x) :
fderiv_within k f s x = f' :=
by { ext, rw hxs.eq h h.differentiable_within_at.has_fderiv_within_at }
lemma has_fderiv_at.fderiv {f' : E →L[k] F} (h : has_fderiv_at f f' x) :
fderiv k f x = f' :=
by { ext, rw has_fderiv_at_unique h h.differentiable_at.has_fderiv_at }
lemma differentiable.fderiv_within
(h : differentiable_at k f x) (hxs : unique_diff_within_at k s x) :
fderiv_within k f s x = fderiv k f x :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
exact h.has_fderiv_at.has_fderiv_within_at
end
lemma differentiable_on.mono {f : E → F} {s t : set E}
(h : differentiable_on k f t) (st : s ⊆ t) : differentiable_on k f s :=
λx hx, (h x (st hx)).mono st
lemma differentiable_on_univ :
differentiable_on k f univ ↔ differentiable k f :=
by { simp [differentiable_on, differentiable_within_univ_at], refl }
lemma differentiable.differentiable_on
(h : differentiable k f) : differentiable_on k f s :=
(differentiable_on_univ.2 h).mono (subset_univ _)
@[simp] lemma fderiv_within_univ : fderiv_within k f univ = fderiv k f :=
begin
ext x : 1,
by_cases h : differentiable_at k f x,
{ apply has_fderiv_within_at.fderiv_within _ (is_open_univ.unique_diff_within_at (mem_univ _)),
rw has_fderiv_within_univ_at,
apply h.has_fderiv_at },
{ have : fderiv k f x = 0,
by { unfold differentiable_at at h, simp [fderiv, h] },
rw this,
have : ¬(differentiable_within_at k f univ x), by rwa differentiable_within_univ_at,
unfold differentiable_within_at at this,
simp [fderiv_within, this, -has_fderiv_within_univ_at] }
end
lemma differentiable_within_at_inter (xs : x ∈ s) (xt : x ∈ t) (ht : is_open t) :
differentiable_within_at k f (s ∩ t) x ↔ differentiable_within_at k f s x :=
by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter,
nhds_within_restrict s xt ht]
lemma differentiable_on_of_locally_differentiable_on
(h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on k f (s ∩ u)) : differentiable_on k f s :=
begin
assume x xs,
rcases h x xs with ⟨t, t_open, xt, ht⟩,
exact (differentiable_within_at_inter xs xt t_open).1 (ht x ⟨xs, xt⟩)
end
end fderiv_properties
/- Congr -/
section congr
theorem has_fderiv_at_filter_congr'
(hx : f₀ x = f₁ x) (h₀ : {x | f₀ x = f₁ x} ∈ L) (h₁ : ∀ x, f₀' x = f₁' x) :
has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L :=
by { rw (ext h₁), exact is_o_congr
(by filter_upwards [h₀] λ x (h : _ = _), by simp [h, hx])
(univ_mem_sets' $ λ _, rfl) }
theorem has_fderiv_at_filter_congr
(h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) :
has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L :=
has_fderiv_at_filter_congr' (h₀ _) (univ_mem_sets' h₀) h₁
theorem has_fderiv_at_filter.congr
(h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) :
has_fderiv_at_filter f₀ f₀' x L → has_fderiv_at_filter f₁ f₁' x L :=
(has_fderiv_at_filter_congr h₀ h₁).1
theorem has_fderiv_within_at_congr
(h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) :
has_fderiv_within_at f₀ f₀' s x ↔ has_fderiv_within_at f₁ f₁' s x :=
has_fderiv_at_filter_congr h₀ h₁
theorem has_fderiv_within_at.congr
(h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) :
has_fderiv_within_at f₀ f₀' s x → has_fderiv_within_at f₁ f₁' s x :=
(has_fderiv_within_at_congr h₀ h₁).1
theorem has_fderiv_at_congr
(h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) :
has_fderiv_at f₀ f₀' x ↔ has_fderiv_at f₁ f₁' x :=
has_fderiv_at_filter_congr h₀ h₁
theorem has_fderiv_at.congr
(h₀ : ∀ x, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) :
has_fderiv_at f₀ f₀' x → has_fderiv_at f₁ f₁' x :=
(has_fderiv_at_congr h₀ h₁).1
lemma has_fderiv_at_filter.congr' (h : has_fderiv_at_filter f f' x L)
(hL : {x | f₁ x = f x} ∈ L) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L :=
begin
refine (asymptotics.is_o_congr_left _).1 h,
convert hL,
ext,
finish [hx],
end
lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x)
(hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x :=
has_fderiv_at_filter.congr' (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx
lemma differentiable_within_at.congr_mono (h : differentiable_within_at k f s x)
(ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at k f₁ t x :=
(has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at
lemma differentiable_at.congr (h : differentiable_at k f x) (h' : ∀x, f₁ x = f x) :
differentiable_at k f₁ x :=
by { have : f₁ = f, by { ext y, exact h' y }, rwa this }
lemma differentiable_on.congr_mono (h : differentiable_on k f s) (h' : ∀x ∈ t, f₁ x = f x)
(h₁ : t ⊆ s) : differentiable_on k f₁ t :=
λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁
lemma differentiable.congr (h : differentiable k f) (h' : ∀x, f₁ x = f x) :
differentiable k f₁ :=
by { have : f₁ = f, by { ext y, exact h' y }, rwa this }
lemma differentiable.congr' (h : differentiable_at k f x)
(hL : {y | f₁ y = f y} ∈ nhds x) (hx : f₁ x = f x) :
differentiable_at k f₁ x :=
has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr' h.has_fderiv_at hL hx)
lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at k f s x)
(hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at k t x) (h₁ : t ⊆ s) :
fderiv_within k f₁ t x = fderiv_within k f s x :=
(has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt
lemma differentiable_at.fderiv_congr (h : differentiable_at k f x) (h' : ∀x, f₁ x = f x) :
fderiv k f₁ x = fderiv k f x :=
by { have : f₁ = f, by { ext y, exact h' y }, rwa this }
lemma differentiable_at.fderiv_congr' (h : differentiable_at k f x)
(hL : {y | f₁ y = f y} ∈ nhds x) (hx : f₁ x = f x) :
fderiv k f₁ x = fderiv k f x :=
has_fderiv_at.fderiv (has_fderiv_at_filter.congr' h.has_fderiv_at hL hx)
end congr
/- id -/
section id
theorem has_fderiv_at_filter_id (x : E) (L : filter E) :
has_fderiv_at_filter id (id : E →L[k] E) x L :=
(is_o_zero _ _).congr_left $ by simp
theorem has_fderiv_within_at_id (x : E) (s : set E) :
has_fderiv_within_at id (id : E →L[k] E) s x :=
has_fderiv_at_filter_id _ _
theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id : E →L[k] E) x :=
has_fderiv_at_filter_id _ _
lemma differentiable_at_id : differentiable_at k id x :=
(has_fderiv_at_id x).differentiable_at
lemma differentiable_within_at_id : differentiable_within_at k id s x :=
differentiable_at_id.differentiable_within_at
lemma differentiable_id : differentiable k (id : E → E) :=
λx, differentiable_at_id
lemma differentiable_on_id : differentiable_on k id s :=
differentiable_id.differentiable_on
lemma fderiv_id : fderiv k id x = id :=
has_fderiv_at.fderiv (has_fderiv_at_id x)
lemma fderiv_within_id (hxs : unique_diff_within_at k s x) :
fderiv_within k id s x = id :=
begin
rw differentiable.fderiv_within (differentiable_at_id) hxs,
exact fderiv_id
end
end id
/- constants -/
section const
theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) :
has_fderiv_at_filter (λ x, c) (0 : E →L[k] F) x L :=
(is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self]
theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) :
has_fderiv_within_at (λ x, c) (0 : E →L[k] F) s x :=
has_fderiv_at_filter_const _ _ _
theorem has_fderiv_at_const (c : F) (x : E) :
has_fderiv_at (λ x, c) (0 : E →L[k] F) x :=
has_fderiv_at_filter_const _ _ _
lemma differentiable_at_const (c : F) : differentiable_at k (λx, c) x :=
⟨0, has_fderiv_at_const c x⟩
lemma differentiable_within_at_const (c : F) : differentiable_within_at k (λx, c) s x :=
differentiable_at.differentiable_within_at (differentiable_at_const _)
lemma fderiv_const (c : F) : fderiv k (λy, c) x = 0 :=
has_fderiv_at.fderiv (has_fderiv_at_const c x)
lemma fderiv_within_const (c : F) (hxs : unique_diff_within_at k s x) :
fderiv_within k (λy, c) s x = 0 :=
begin
rw differentiable.fderiv_within (differentiable_at_const _) hxs,
exact fderiv_const _
end
lemma differentiable_const (c : F) : differentiable k (λx : E, c) :=
λx, differentiable_at_const _
lemma differentiable_on_const (c : F) : differentiable_on k (λx, c) s :=
(differentiable_const _).differentiable_on
end const
/- Bounded linear maps -/
section is_bounded_linear_map
lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map k f) :
has_fderiv_at_filter f h.to_continuous_linear_map x L :=
begin
have : (λ (x' : E), f x' - f x - h.to_continuous_linear_map (x' - x)) = λx', 0,
{ ext,
have : ∀a, h.to_continuous_linear_map a = f a := λa, rfl,
simp,
simp [this] },
rw [has_fderiv_at_filter, this],
exact asymptotics.is_o_zero _ _
end
lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map k f) :
has_fderiv_within_at f h.to_continuous_linear_map s x :=
h.has_fderiv_at_filter
lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map k f) :
has_fderiv_at f h.to_continuous_linear_map x :=
h.has_fderiv_at_filter
lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map k f) :
differentiable_at k f x :=
h.has_fderiv_at.differentiable_at
lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map k f) :
differentiable_within_at k f s x :=
h.differentiable_at.differentiable_within_at
lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map k f) :
fderiv k f x = h.to_continuous_linear_map :=
has_fderiv_at.fderiv (h.has_fderiv_at)
lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map k f)
(hxs : unique_diff_within_at k s x) : fderiv_within k f s x = h.to_continuous_linear_map :=
begin
rw differentiable.fderiv_within h.differentiable_at hxs,
exact h.fderiv
end
lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map k f) :
differentiable k f :=
λx, h.differentiable_at
lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map k f) :
differentiable_on k f s :=
h.differentiable.differentiable_on
end is_bounded_linear_map
/- multiplication by a constant -/
section smul_const
theorem has_fderiv_at_filter.smul (h : has_fderiv_at_filter f f' x L) (c : k) :
has_fderiv_at_filter (λ x, c • f x) (c • f') x L :=
(is_o_const_smul_left h c).congr_left $ λ x, by simp [smul_neg, smul_add]
theorem has_fderiv_within_at.smul (h : has_fderiv_within_at f f' s x) (c : k) :
has_fderiv_within_at (λ x, c • f x) (c • f') s x :=
h.smul c
theorem has_fderiv_at.smul (h : has_fderiv_at f f' x) (c : k) :
has_fderiv_at (λ x, c • f x) (c • f') x :=
h.smul c
lemma differentiable_within_at.smul (h : differentiable_within_at k f s x) (c : k) :
differentiable_within_at k (λy, c • f y) s x :=
(h.has_fderiv_within_at.smul c).differentiable_within_at
lemma differentiable_at.smul (h : differentiable_at k f x) (c : k) :
differentiable_at k (λy, c • f y) x :=
(h.has_fderiv_at.smul c).differentiable_at
lemma differentiable_on.smul (h : differentiable_on k f s) (c : k) :
differentiable_on k (λy, c • f y) s :=
λx hx, (h x hx).smul c
lemma differentiable.smul (h : differentiable k f) (c : k) :
differentiable k (λy, c • f y) :=
λx, (h x).smul c
lemma fderiv_within_smul (hxs : unique_diff_within_at k s x)
(h : differentiable_within_at k f s x) (c : k) :
fderiv_within k (λy, c • f y) s x = c • fderiv_within k f s x :=
(h.has_fderiv_within_at.smul c).fderiv_within hxs
lemma fderiv_smul (h : differentiable_at k f x) (c : k) :
fderiv k (λy, c • f y) x = c • fderiv k f x :=
(h.has_fderiv_at.smul c).fderiv
end smul_const
/- add -/
section add
theorem has_fderiv_at_filter.add
(hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) :
has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L :=
(hf.add hg).congr_left $ λ _, by simp
theorem has_fderiv_within_at.add
(hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) :
has_fderiv_within_at (λ y, f y + g y) (f' + g') s x :=
hf.add hg
theorem has_fderiv_at.add
(hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) :
has_fderiv_at (λ x, f x + g x) (f' + g') x :=
hf.add hg
lemma differentiable_within_at.add
(hf : differentiable_within_at k f s x) (hg : differentiable_within_at k g s x) :
differentiable_within_at k (λ y, f y + g y) s x :=
(hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.add
(hf : differentiable_at k f x) (hg : differentiable_at k g x) :
differentiable_at k (λ y, f y + g y) x :=
(hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at
lemma differentiable_on.add
(hf : differentiable_on k f s) (hg : differentiable_on k g s) :
differentiable_on k (λy, f y + g y) s :=
λx hx, (hf x hx).add (hg x hx)
lemma differentiable.add
(hf : differentiable k f) (hg : differentiable k g) :
differentiable k (λy, f y + g y) :=
λx, (hf x).add (hg x)
lemma fderiv_within_add (hxs : unique_diff_within_at k s x)
(hf : differentiable_within_at k f s x) (hg : differentiable_within_at k g s x) :
fderiv_within k (λy, f y + g y) s x = fderiv_within k f s x + fderiv_within k g s x :=
(hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_add
(hf : differentiable_at k f x) (hg : differentiable_at k g x) :
fderiv k (λy, f y + g y) x = fderiv k f x + fderiv k g x :=
(hf.has_fderiv_at.add hg.has_fderiv_at).fderiv
end add
/- neg -/
section neg
theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (λ x, -f x) (-f') x L :=
(h.smul (-1:k)).congr (by simp) (by simp)
theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, -f x) (-f') s x :=
h.neg
theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) :
has_fderiv_at (λ x, -f x) (-f') x :=
h.neg
lemma differentiable_within_at.neg (h : differentiable_within_at k f s x) :
differentiable_within_at k (λy, -f y) s x :=
h.has_fderiv_within_at.neg.differentiable_within_at
lemma differentiable_at.neg (h : differentiable_at k f x) :
differentiable_at k (λy, -f y) x :=
h.has_fderiv_at.neg.differentiable_at
lemma differentiable_on.neg (h : differentiable_on k f s) :
differentiable_on k (λy, -f y) s :=
λx hx, (h x hx).neg
lemma differentiable.neg (h : differentiable k f) :
differentiable k (λy, -f y) :=
λx, (h x).neg
lemma fderiv_within_neg (hxs : unique_diff_within_at k s x)
(h : differentiable_within_at k f s x) :
fderiv_within k (λy, -f y) s x = - fderiv_within k f s x :=
h.has_fderiv_within_at.neg.fderiv_within hxs
lemma fderiv_neg (h : differentiable_at k f x) :
fderiv k (λy, -f y) x = - fderiv k f x :=
h.has_fderiv_at.neg.fderiv
end neg
/- sub -/
section sub
theorem has_fderiv_at_filter.sub
(hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) :
has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L :=
hf.add hg.neg
theorem has_fderiv_within_at.sub
(hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) :
has_fderiv_within_at (λ x, f x - g x) (f' - g') s x :=
hf.sub hg
theorem has_fderiv_at.sub
(hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) :
has_fderiv_at (λ x, f x - g x) (f' - g') x :=
hf.sub hg
lemma differentiable_within_at.sub
(hf : differentiable_within_at k f s x) (hg : differentiable_within_at k g s x) :
differentiable_within_at k (λ y, f y - g y) s x :=
(hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.sub
(hf : differentiable_at k f x) (hg : differentiable_at k g x) :
differentiable_at k (λ y, f y - g y) x :=
(hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at
lemma differentiable_on.sub
(hf : differentiable_on k f s) (hg : differentiable_on k g s) :
differentiable_on k (λy, f y - g y) s :=
λx hx, (hf x hx).sub (hg x hx)
lemma differentiable.sub
(hf : differentiable k f) (hg : differentiable k g) :
differentiable k (λy, f y - g y) :=
λx, (hf x).sub (hg x)
lemma fderiv_within_sub (hxs : unique_diff_within_at k s x)
(hf : differentiable_within_at k f s x) (hg : differentiable_within_at k g s x) :
fderiv_within k (λy, f y - g y) s x = fderiv_within k f s x - fderiv_within k g s x :=
(hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_sub
(hf : differentiable_at k f x) (hg : differentiable_at k g x) :
fderiv k (λy, f y - g y) x = fderiv k f x - fderiv k g x :=
(hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv
theorem has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) :
is_O (λ x', f x' - f x) (λ x', x' - x) L :=
h.to_is_O.congr_of_sub.2 (f'.is_O_sub _ _)
end sub
/- Continuity -/
section continuous
theorem has_fderiv_at_filter.tendsto_nhds
(hL : L ≤ nhds x) (h : has_fderiv_at_filter f f' x L) :
tendsto f L (nhds (f x)) :=
begin
have : tendsto (λ x', f x' - f x) L (nhds 0),
{ refine h.is_O_sub.trans_tendsto (tendsto_le_left hL _),
rw ← sub_self x, exact tendsto_sub tendsto_id tendsto_const_nhds },
have := tendsto_add this tendsto_const_nhds,
rw zero_add (f x) at this,
exact this.congr (by simp)
end
theorem has_fderiv_within_at.continuous_within_at
(h : has_fderiv_within_at f f' s x) : continuous_within_at f s x :=
has_fderiv_at_filter.tendsto_nhds lattice.inf_le_left h
theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) :
continuous_at f x :=
has_fderiv_at_filter.tendsto_nhds (le_refl _) h
lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at k f s x) :
continuous_within_at f s x :=
let ⟨f', hf'⟩ := h in hf'.continuous_within_at
lemma differentiable_at.continuous_at (h : differentiable_at k f x) : continuous_at f x :=
let ⟨f', hf'⟩ := h in hf'.continuous_at
lemma differentiable_on.continuous_on (h : differentiable_on k f s) : continuous_on f s :=
λx hx, (h x hx).continuous_within_at
lemma differentiable.continuous (h : differentiable k f) : continuous f :=
continuous_iff_continuous_at.2 $ λx, (h x).continuous_at
end continuous
/- Bounded bilinear maps -/
section bilinear_map
variables {b : E × F → G} {u : set (E × F) }
lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map k b) (p : E × F) :
has_fderiv_at b (h.deriv p) p :=
begin
have : (λ (x : E × F), b x - b p - (h.deriv p) (x - p)) = (λx, b (x.1 - p.1, x.2 - p.2)),
{ ext x,
delta is_bounded_bilinear_map.deriv,
change b x - b p - (b (p.1, x.2-p.2) + b (x.1-p.1, p.2))
= b (x.1 - p.1, x.2 - p.2),
have : b x = b (x.1, x.2), by { cases x, refl },
rw this,
have : b p = b (p.1, p.2), by { cases p, refl },
rw this,
simp only [h.map_sub_left, h.map_sub_right],
abel },
rw [has_fderiv_at, has_fderiv_at_filter, this],
rcases h.bound with ⟨C, Cpos, hC⟩,
have A : asymptotics.is_O (λx : E × F, b (x.1 - p.1, x.2 - p.2))
(λx, ∥x - p∥ * ∥x - p∥) (nhds p) :=
⟨C, Cpos, filter.univ_mem_sets' (λx, begin
simp only [mem_set_of_eq, norm_mul, norm_norm],
calc ∥b (x.1 - p.1, x.2 - p.2)∥ ≤ C * ∥x.1 - p.1∥ * ∥x.2 - p.2∥ : hC _ _
... ≤ C * ∥x-p∥ * ∥x-p∥ : by apply_rules [mul_le_mul, le_max_left, le_max_right, norm_nonneg,
le_of_lt Cpos, le_refl, mul_nonneg, norm_nonneg, norm_nonneg]
... = C * (∥x-p∥ * ∥x-p∥) : mul_assoc _ _ _ end)⟩,
have B : asymptotics.is_o (λ (x : E × F), ∥x - p∥ * ∥x - p∥)
(λx, 1 * ∥x - p∥) (nhds p),
{ apply asymptotics.is_o_mul_right _ (asymptotics.is_O_refl _ _),
rw [asymptotics.is_o_iff_tendsto],
{ simp only [div_one],
have : 0 = ∥p - p∥, by simp,
rw this,
have : continuous (λx, ∥x-p∥) :=
continuous_norm.comp (continuous_sub continuous_id continuous_const),
exact this.tendsto p },
simp only [forall_prop_of_false, not_false_iff, one_ne_zero, forall_true_iff] },
simp only [one_mul, asymptotics.is_o_norm_right] at B,
exact A.trans_is_o B
end
lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map k b) (p : E × F) :
has_fderiv_within_at b (h.deriv p) u p :=
(h.has_fderiv_at p).has_fderiv_within_at
lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map k b) (p : E × F) :
differentiable_at k b p :=
(h.has_fderiv_at p).differentiable_at
lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map k b) (p : E × F) :
differentiable_within_at k b u p :=
(h.differentiable_at p).differentiable_within_at
lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map k b) (p : E × F) :
fderiv k b p = h.deriv p :=
has_fderiv_at.fderiv (h.has_fderiv_at p)
lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map k b) (p : E × F)
(hxs : unique_diff_within_at k u p) : fderiv_within k b u p = h.deriv p :=
begin
rw differentiable.fderiv_within (h.differentiable_at p) hxs,
exact h.fderiv p
end
lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map k b) :
differentiable k b :=
λx, h.differentiable_at x
lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map k b) :
differentiable_on k b u :=
h.differentiable.differentiable_on
lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map k b) :
continuous b :=
h.differentiable.continuous
end bilinear_map
/- Cartesian products -/
section cartesian_product
variables {f₂ : E → G} {f₂' : E →L[k] G}
lemma has_fderiv_at_filter.prod
(hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) :
has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x L :=
begin
have : (λ (x' : E), (f₁ x', f₂ x') - (f₁ x, f₂ x) - (continuous_linear_map.prod f₁' f₂') (x' -x)) =
(λ (x' : E), (f₁ x' - f₁ x - f₁' (x' - x), f₂ x' - f₂ x - f₂' (x' - x))) := rfl,
rw [has_fderiv_at_filter, this],
rw [asymptotics.is_o_prod_left],
exact ⟨hf₁, hf₂⟩
end
lemma has_fderiv_within_at.prod
(hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) :
has_fderiv_within_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') s x :=
hf₁.prod hf₂
lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) :
has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x :=
hf₁.prod hf₂
lemma differentiable_within_at.prod
(hf₁ : differentiable_within_at k f₁ s x) (hf₂ : differentiable_within_at k f₂ s x) :
differentiable_within_at k (λx:E, (f₁ x, f₂ x)) s x :=
(hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.prod (hf₁ : differentiable_at k f₁ x) (hf₂ : differentiable_at k f₂ x) :
differentiable_at k (λx:E, (f₁ x, f₂ x)) x :=
(hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at
lemma differentiable_on.prod (hf₁ : differentiable_on k f₁ s) (hf₂ : differentiable_on k f₂ s) :
differentiable_on k (λx:E, (f₁ x, f₂ x)) s :=
λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx)
lemma differentiable.prod (hf₁ : differentiable k f₁) (hf₂ : differentiable k f₂) :
differentiable k (λx:E, (f₁ x, f₂ x)) :=
λ x, differentiable_at.prod (hf₁ x) (hf₂ x)
lemma differentiable_at.fderiv_prod
(hf₁ : differentiable_at k f₁ x) (hf₂ : differentiable_at k f₂ x) :
fderiv k (λx:E, (f₁ x, f₂ x)) x =
continuous_linear_map.prod (fderiv k f₁ x) (fderiv k f₂ x) :=
has_fderiv_at.fderiv (has_fderiv_at.prod hf₁.has_fderiv_at hf₂.has_fderiv_at)
lemma differentiable_at.fderiv_within_prod
(hf₁ : differentiable_within_at k f₁ s x) (hf₂ : differentiable_within_at k f₂ s x)
(hxs : unique_diff_within_at k s x) :
fderiv_within k (λx:E, (f₁ x, f₂ x)) s x =
continuous_linear_map.prod (fderiv_within k f₁ s x) (fderiv_within k f₂ s x) :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at
end
end cartesian_product
/- Composition -/
section composition
/- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to
get confused since there are too many possibilities for composition -/
variable (x)
theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[k] G}
(hg : has_fderiv_at_filter g g' (f x) (L.map f))
(hf : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (g ∘ f) (g'.comp f') x L :=
let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in
let eq₂ := ((hg.comp f).mono le_comap_map).trans_is_O hf.is_O_sub in
by { refine eq₂.tri (eq₁.congr_left (λ x', _)), simp }
/- A readable version of the previous theorem,
a general form of the chain rule. -/
example {g : F → G} {g' : F →L[k] G}
(hg : has_fderiv_at_filter g g' (f x) (L.map f))
(hf : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (g ∘ f) (g'.comp f') x L :=
begin
unfold has_fderiv_at_filter at hg,
have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L,
from (hg.comp f).mono le_comap_map,
have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L,
from this.trans_is_O hf.is_O_sub,
have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L,
from hf,
have : is_O
(λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L,
from g'.is_O_comp _ _,
have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L,
from this.trans_is_o eq₂,
have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L,
by { refine this.congr_left _, simp},
exact eq₁.tri eq₃
end
theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[k] G}
(hg : has_fderiv_within_at g g' (f '' s) (f x))
(hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (g ∘ f) (g'.comp f') s x :=
(has_fderiv_at_filter.mono hg
hf.continuous_within_at.tendsto_nhds_within_image).comp x hf
/-- The chain rule. -/
theorem has_fderiv_at.comp {g : F → G} {g' : F →L[k] G}
(hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) :
has_fderiv_at (g ∘ f) (g'.comp f') x :=
(hg.mono hf.continuous_at).comp x hf
theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[k] G}
(hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (g ∘ f) (g'.comp f') s x :=
begin
rw ← has_fderiv_within_univ_at at hg,
exact has_fderiv_within_at.comp x (hg.mono (subset_univ _)) hf
end
lemma differentiable_within_at.comp {g : F → G} {t : set F}
(hg : differentiable_within_at k g t (f x)) (hf : differentiable_within_at k f s x)
(h : f '' s ⊆ t) : differentiable_within_at k (g ∘ f) s x :=
begin
rcases hf with ⟨f', hf'⟩,
rcases hg with ⟨g', hg'⟩,
exact ⟨continuous_linear_map.comp g' f', (hg'.mono h).comp x hf'⟩
end
lemma differentiable_at.comp {g : F → G}
(hg : differentiable_at k g (f x)) (hf : differentiable_at k f x) :
differentiable_at k (g ∘ f) x :=
(hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at
lemma fderiv_within.comp {g : F → G} {t : set F}
(hg : differentiable_within_at k g t (f x)) (hf : differentiable_within_at k f s x)
(h : f '' s ⊆ t) (hxs : unique_diff_within_at k s x) :
fderiv_within k (g ∘ f) s x =
continuous_linear_map.comp (fderiv_within k g t (f x)) (fderiv_within k f s x) :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
apply has_fderiv_within_at.comp x _ (hf.has_fderiv_within_at),
apply hg.has_fderiv_within_at.mono h
end
lemma fderiv.comp {g : F → G}
(hg : differentiable_at k g (f x)) (hf : differentiable_at k f x) :
fderiv k (g ∘ f) x = continuous_linear_map.comp (fderiv k g (f x)) (fderiv k f x) :=
begin
apply has_fderiv_at.fderiv,
exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at
end
lemma differentiable_on.comp {g : F → G} {t : set F}
(hg : differentiable_on k g t) (hf : differentiable_on k f s) (st : f '' s ⊆ t) :
differentiable_on k (g ∘ f) s :=
λx hx, differentiable_within_at.comp x (hg (f x) (st (mem_image_of_mem _ hx))) (hf x hx) st
end composition
/- Multiplication by a scalar function -/
section smul
variables {c : E → k} {c' : E →L[k] k}
theorem has_fderiv_within_at.smul'
(hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.scalar_prod_space_iso (f x)) s x :=
begin
have : is_bounded_bilinear_map k (λ (p : k × F), p.1 • p.2) := is_bounded_bilinear_map_smul,
exact has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, f x)) (hc.prod hf)
end
theorem has_fderiv_at.smul' (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ y, c y • f y) (c x • f' + c'.scalar_prod_space_iso (f x)) x :=
begin
have : is_bounded_bilinear_map k (λ (p : k × F), p.1 • p.2) := is_bounded_bilinear_map_smul,
exact has_fderiv_at.comp x (this.has_fderiv_at (c x, f x)) (hc.prod hf)
end
lemma differentiable_within_at.smul'
(hc : differentiable_within_at k c s x) (hf : differentiable_within_at k f s x) :
differentiable_within_at k (λ y, c y • f y) s x :=
(hc.has_fderiv_within_at.smul' hf.has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.smul' (hc : differentiable_at k c x) (hf : differentiable_at k f x) :
differentiable_at k (λ y, c y • f y) x :=
(hc.has_fderiv_at.smul' hf.has_fderiv_at).differentiable_at
lemma differentiable_on.smul' (hc : differentiable_on k c s) (hf : differentiable_on k f s) :
differentiable_on k (λ y, c y • f y) s :=
λx hx, (hc x hx).smul' (hf x hx)
lemma differentiable.smul' (hc : differentiable k c) (hf : differentiable k f) :
differentiable k (λ y, c y • f y) :=
λx, (hc x).smul' (hf x)
lemma fderiv_within_smul' (hxs : unique_diff_within_at k s x)
(hc : differentiable_within_at k c s x) (hf : differentiable_within_at k f s x) :
fderiv_within k (λ y, c y • f y) s x =
c x • fderiv_within k f s x + (fderiv_within k c s x).scalar_prod_space_iso (f x) :=
(hc.has_fderiv_within_at.smul' hf.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_smul' (hc : differentiable_at k c x) (hf : differentiable_at k f x) :
fderiv k (λ y, c y • f y) x =
c x • fderiv k f x + (fderiv k c x).scalar_prod_space_iso (f x) :=
(hc.has_fderiv_at.smul' hf.has_fderiv_at).fderiv
end smul
/- Multiplication of scalar functions -/
section mul
set_option class.instance_max_depth 120
variables {c d : E → k} {c' d' : E →L[k] k}
theorem has_fderiv_within_at.mul
(hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) :
has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x :=
begin
have : is_bounded_bilinear_map k (λ (p : k × k), p.1 * p.2) := is_bounded_bilinear_map_mul,
convert has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, d x)) (hc.prod hd),
ext z,
change c x * d' z + d x * c' z = c x * d' z + c' z * d x,
ring
end
theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) :
has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x :=
begin
have : is_bounded_bilinear_map k (λ (p : k × k), p.1 * p.2) := is_bounded_bilinear_map_mul,
convert has_fderiv_at.comp x (this.has_fderiv_at (c x, d x)) (hc.prod hd),
ext z,
change c x * d' z + d x * c' z = c x * d' z + c' z * d x,
ring
end
lemma differentiable_within_at.mul
(hc : differentiable_within_at k c s x) (hd : differentiable_within_at k d s x) :
differentiable_within_at k (λ y, c y * d y) s x :=
(hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.mul (hc : differentiable_at k c x) (hd : differentiable_at k d x) :
differentiable_at k (λ y, c y * d y) x :=
(hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at
lemma differentiable_on.mul (hc : differentiable_on k c s) (hd : differentiable_on k d s) :
differentiable_on k (λ y, c y * d y) s :=
λx hx, (hc x hx).mul (hd x hx)
lemma differentiable.mul (hc : differentiable k c) (hd : differentiable k d) :
differentiable k (λ y, c y * d y) :=
λx, (hc x).mul (hd x)
lemma fderiv_within_mul (hxs : unique_diff_within_at k s x)
(hc : differentiable_within_at k c s x) (hd : differentiable_within_at k d s x) :
fderiv_within k (λ y, c y * d y) s x =
c x • fderiv_within k d s x + d x • fderiv_within k c s x :=
(hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_mul (hc : differentiable_at k c x) (hd : differentiable_at k d x) :
fderiv k (λ y, c y * d y) x =
c x • fderiv k d x + d x • fderiv k c x :=
(hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv
end mul
end
/-
In the special case of a normed space over the reals,
we can use scalar multiplication in the `tendsto` characterization
of the Fréchet derivative.
-/
section
variables {E : Type*} [normed_group E] [normed_space ℝ E]
variables {F : Type*} [normed_group F] [normed_space ℝ F]
variables {G : Type*} [normed_group G] [normed_space ℝ G]
theorem has_fderiv_at_filter_real_equiv {f : E → F} {f' : E →L[ℝ] F} {x : E} {L : filter E} :
tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (nhds 0) ↔
tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (nhds 0) :=
begin
symmetry,
rw [tendsto_iff_norm_tendsto_zero], refine tendsto.congr'r (λ x', _),
have : ∥x' + -x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _),
simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this]
end
end
|
1f6da40fbb545e22e92be40e478d489445ad740d | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/bor_lazy.lean | 69d445ca0c40e609324e98fcb9a32144c5cdccb0 | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 68 | lean | open bool
vm_eval (timeit "branch1:" tt) || (timeit "branch2:" tt)
|
3c5677c5b0db46b96267527b134b38f928b4c572 | d6aa76a731f5d0a2c72a62729e52996fe8ac81b3 | /src/adjacency_matrix.lean | 3a2a054768c825d2439d91cb6205f9bba928d149 | [] | no_license | jalex-stark/friendship-theorem | 88d30d3f4b17cc275a1a4bbc747eeb41f9e1b7a1 | d0e823b0b298c3fcfffe885cd6d2064a5757ef27 | refs/heads/master | 1,668,993,481,235 | 1,595,108,750,000 | 1,595,108,777,000 | 270,936,124 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,383 | lean | import data.fintype.basic linear_algebra.matrix data.matrix.basic data.real.basic
import sym_matrix
open_locale classical
open finset matrix
noncomputable theory
lemma symm_iff {α : Type*} {r : α → α → Prop} (h : symmetric r) {a b : α} : r a b ↔ r b a :=
by { split; apply h }
variable {V : Type*}
section graph
variable (V)
structure simple_graph :=
(E : V → V → Prop)
(loopless : irreflexive E)
(undirected : symmetric E)
variables {V} (G : simple_graph V)
@[simp] lemma simple_graph.irrefl {v : V} : ¬ G.E v v := G.loopless v
@[simp] lemma foo_symmetry {v : V} : (λ w : V, G.E w v) = G.E v := by { ext, apply symm_iff G.undirected, }
variable [fintype V]
def neighbors (v : V) : finset V := univ.filter (G.E v)
@[simp] lemma neighbor_iff_adjacent (v w : V) :
w ∈ neighbors G v ↔ G.E v w := by { unfold neighbors, simp }
def degree (v : V) : ℕ := (neighbors G v).card
def regular_graph (d : ℕ) : Prop :=
∀ v : V, degree G v = d
end graph
section adjacency_matrix
variables {V} [fintype V] (R : Type*) [ring R] (G : simple_graph V) -- R can be a semiring if we generalize trace
def adjacency_matrix : matrix V V R :=
λ v w : V, ite (G.E v w) 1 0
variable {R}
@[simp] lemma adjacency_matrix_el_idem (i j : V) :
(adjacency_matrix R G i j) * (adjacency_matrix R G i j) = adjacency_matrix R G i j :=
by { unfold adjacency_matrix, by_cases G.E i j; simp [h], }
theorem adjacency_matrix_sym :
sym_matrix (adjacency_matrix R G) :=
begin
unfold sym_matrix, ext,
unfold matrix.transpose, unfold adjacency_matrix,
rw symm_iff G.undirected,
end
@[simp]
lemma adjacency_matrix_apply {v w : V} :
adjacency_matrix R G v w = ite (G.E v w) 1 0 := rfl
@[simp]
lemma adjacency_matrix_dot_product {v : V} {vec : V → R} :
dot_product (adjacency_matrix R G v) vec = (neighbors G v).sum vec :=
begin
unfold dot_product, unfold neighbors, simp [sum_filter],
end
@[simp]
lemma dot_product_adjacency_matrix {v : V} {vec : V → R} :
dot_product vec (adjacency_matrix R G v) = (neighbors G v).sum vec :=
begin
unfold dot_product, unfold neighbors, simp [sum_filter],
end
@[simp]
lemma adjacency_matrix_mul_apply {M : matrix V V R} {v w : V} : (adjacency_matrix R G * M) v w = (neighbors G v).sum M w :=
by { rw [mul_eq_mul, mul_val', adjacency_matrix_dot_product G, sum_apply] }
@[simp]
lemma mul_adjacency_matrix_apply {M : matrix V V R} {v w : V} : (M * adjacency_matrix R G) v w = (neighbors G w).sum (M v) :=
by { rw [mul_eq_mul, mul_val', ← dot_product_adjacency_matrix G], simp_rw sym_matrix_apply (adjacency_matrix_sym G) }
variable (R)
theorem adj_mat_traceless : matrix.trace V R R (adjacency_matrix R G) = 0 := by simp
variable {R}
theorem adj_mat_sq_apply_eq {i : V} :
((adjacency_matrix R G) * (adjacency_matrix R G)) i i = degree G i :=
begin
unfold degree, simp only [filter_congr_decidable, adjacency_matrix_mul_apply, sum_boole, sum_apply, adjacency_matrix_apply],
refine congr rfl (congr rfl _), ext,
simp only [mem_filter, neighbor_iff_adjacent], rw symm_iff G.undirected, tauto,
end
variable {G}
lemma adj_mat_mul_vec_ones_apply_of_regular {d : ℕ} (reg : regular_graph G d) (i : V):
(adjacency_matrix R G).mul_vec (λ j : V, 1) i = d :=
begin
unfold matrix.mul_vec, rw adjacency_matrix_dot_product, simp only [mul_one, nsmul_eq_mul, sum_const],
rw ← reg i, refl,
end
end adjacency_matrix |
ba595865943dd78425c5fecdbfbd7a9a43c4d2ef | 865bfafdd5c31c148e891f22dba45be7ae8fe9c5 | /squareover.hlean | 25afda0e0d1816f6cfb54d8a8eab99c00c94f7f2 | [
"Apache-2.0"
] | permissive | fpvandoorn/sequential_colimits | f0eaae8e87469c41e74bbac1ba32d1772ed0e7fa | e39c3bd2efc6dfb251d334cec8c76b6aa3947c31 | refs/heads/master | 1,590,752,488,347 | 1,511,385,696,000 | 1,511,385,754,000 | 43,088,713 | 0 | 0 | null | 1,443,123,449,000 | 1,443,123,449,000 | null | UTF-8 | Lean | false | false | 5,345 | hlean | import cubical.squareover
open eq sigma
/- TODO: move -/
namespace eq
/- move to various places -/
definition apd02 [unfold 8] {A : Type} {B : A → Type} (f : Πa, B a) {a a' : A} {p q : a = a'}
(r : p = q) : change_path r (apd f p) = apd f q :=
by induction r; reflexivity
definition pathover_ap_cono {A A' : Type} {a₁ a₂ a₃ : A}
{p₁ : a₁ = a₂} {p₂ : a₂ = a₃} (B' : A' → Type) (f : A → A')
{b₁ : B' (f a₁)} {b₂ : B' (f a₂)} {b₃ : B' (f a₃)}
(q₁ : b₁ =[p₁] b₂) (q₂ : b₂ =[p₂] b₃) :
pathover_ap B' f (q₁ ⬝o q₂) =
change_path !ap_con⁻¹ (pathover_ap B' f q₁ ⬝o pathover_ap B' f q₂) :=
by induction q₁; induction q₂; reflexivity
definition concato_eq_eq {A : Type} {B : A → Type} {a₁ a₂ : A} {p₁ : a₁ = a₂}
{b₁ : B a₁} {b₂ b₂' : B a₂} (r : b₁ =[p₁] b₂) (q : b₂ = b₂') :
r ⬝op q = r ⬝o pathover_idp_of_eq q :=
by induction q; reflexivity
definition ap_apd0111 {A₁ A₂ A₃ : Type} {B : A₁ → Type} {C : Π⦃a⦄, B a → Type} {a a₂ : A₁}
{b : B a} {b₂ : B a₂} {c : C b} {c₂ : C b₂}
(g : A₂ → A₃) (f : Πa b, C b → A₂) (Ha : a = a₂) (Hb : b =[Ha] b₂)
(Hc : c =[apd011 C Ha Hb] c₂) :
ap g (apd0111 f Ha Hb Hc) = apd0111 (λa b c, (g (f a b c))) Ha Hb Hc :=
by induction Hb; induction Hc using idp_rec_on; reflexivity
/- move to squareover -/
section squareover
variables {A A' : Type} {B : A → Type}
{a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ : A}
/-a₀₀-/ {p₁₀ : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/
{p₀₁ : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂}
/-a₀₂-/ {p₁₂ : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/
{p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄}
/-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/
{s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁}
{s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃}
{b : B a}
{b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₄₀ : B a₄₀}
{b₀₂ : B a₀₂} {b₂₂ : B a₂₂} {b₄₂ : B a₄₂}
{b₀₄ : B a₀₄} {b₂₄ : B a₂₄} {b₄₄ : B a₄₄}
/-b₀₀-/ {q₁₀ : b₀₀ =[p₁₀] b₂₀} /-b₂₀-/ {q₃₀ : b₂₀ =[p₃₀] b₄₀} /-b₄₀-/
/-b₀₂-/ {q₁₂ : b₀₂ =[p₁₂] b₂₂} /-b₂₂-/ {q₃₂ : b₂₂ =[p₃₂] b₄₂} /-b₄₂-/
/-b₀₄-/ {q₁₄ : b₀₄ =[p₁₄] b₂₄} /-b₂₄-/ {q₃₄ : b₂₄ =[p₃₄] b₄₄} /-b₄₄-/
{q₀₁ : b₀₀ =[p₀₁] b₀₂} /-t₁₁-/ {q₂₁ : b₂₀ =[p₂₁] b₂₂} /-t₃₁-/ {q₄₁ : b₄₀ =[p₄₁] b₄₂}
{q₀₃ : b₀₂ =[p₀₃] b₀₄} /-t₁₃-/ {q₂₃ : b₂₂ =[p₂₃] b₂₄} /-t₃₃-/ {q₄₃ : b₄₂ =[p₄₃] b₄₄}
definition move_right_of_top_over {p : a₀₀ = a} {p' : a = a₂₀}
{s : square p p₁₂ p₀₁ (p' ⬝ p₂₁)} {q : b₀₀ =[p] b} {q' : b =[p'] b₂₀}
(t : squareover B (move_top_of_right s) (q ⬝o q') q₁₂ q₀₁ q₂₁) :
squareover B s q q₁₂ q₀₁ (q' ⬝o q₂₁) :=
begin induction q', induction q, induction q₂₁, exact t end
/- TODO: replace the version in the library by this -/
definition hconcato_pathover' {p : a₂₀ = a₂₂} {sp : p = p₂₁} {s : square p₁₀ p₁₂ p₀₁ p}
{q : b₂₀ =[p] b₂₂} (t₁₁ : squareover B (s ⬝hp sp) q₁₀ q₁₂ q₀₁ q₂₁)
(r : change_path sp q = q₂₁) : squareover B s q₁₀ q₁₂ q₀₁ q :=
by induction sp; induction r; exact t₁₁
variables (s₁₁ q₀₁ q₁₀ q₂₁ q₁₂)
definition squareover_fill_t : Σ (q : b₀₀ =[p₁₀] b₂₀), squareover B s₁₁ q q₁₂ q₀₁ q₂₁ :=
begin
induction s₁₁, induction q₀₁ using idp_rec_on, induction q₂₁ using idp_rec_on,
induction q₁₂ using idp_rec_on, exact ⟨idpo, idso⟩
end
definition squareover_fill_b : Σ (q : b₀₂ =[p₁₂] b₂₂), squareover B s₁₁ q₁₀ q q₀₁ q₂₁ :=
begin
induction s₁₁, induction q₀₁ using idp_rec_on, induction q₂₁ using idp_rec_on,
induction q₁₀ using idp_rec_on, exact ⟨idpo, idso⟩
end
definition squareover_fill_l : Σ (q : b₀₀ =[p₀₁] b₀₂), squareover B s₁₁ q₁₀ q₁₂ q q₂₁ :=
begin
induction s₁₁, induction q₁₀ using idp_rec_on, induction q₂₁ using idp_rec_on,
induction q₁₂ using idp_rec_on, exact ⟨idpo, idso⟩
end
definition squareover_fill_r : Σ (q : b₂₀ =[p₂₁] b₂₂) , squareover B s₁₁ q₁₀ q₁₂ q₀₁ q :=
begin
induction s₁₁, induction q₀₁ using idp_rec_on, induction q₁₀ using idp_rec_on,
induction q₁₂ using idp_rec_on, exact ⟨idpo, idso⟩
end
end squareover
end eq
|
4234bda43fabb3577797b2972a9caec1959b1228 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/uniform_space/basic.lean | 22adcfd5e0379dd2980a737e2051e037293a9869 | [
"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 | 83,921 | 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 order.filter.small_sets
import topology.subset_properties
import topology.nhds_set
/-!
# Uniform spaces
Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly
generalize to uniform spaces, e.g.
* uniform continuity (in this file)
* completeness (in `cauchy.lean`)
* extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`)
* totally bounded sets (in `cauchy.lean`)
* totally bounded complete sets are compact (in `cauchy.lean`)
A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions
which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means
"for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages
of `X`. The two main examples are:
* If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V`
* If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V`
Those examples are generalizations in two different directions of the elementary example where
`X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological
group structure on `ℝ` and its metric space structure.
Each uniform structure on `X` induces a topology on `X` characterized by
> `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)`
where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product
constructor.
The dictionary with metric spaces includes:
* an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X`
* a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}`
for some `V ∈ 𝓤 X`, but the later is more general (it includes in
particular both open and closed balls for suitable `V`).
In particular we have:
`is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s`
The triangle inequality is abstracted to a statement involving the composition of relations in `X`.
First note that the triangle inequality in a metric space is equivalent to
`∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`.
Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is
defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`.
In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }`
then the triangle inequality, as reformulated above, says `V ○ W` is contained in
`{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`.
In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`.
Note that this discussion does not depend on any axiom imposed on the uniformity filter,
it is simply captured by the definition of composition.
The uniform space axioms ask the filter `𝓤 X` to satisfy the following:
* every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact
that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that
`x - x` belongs to every neighborhood of zero in the topological group case.
* `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x`
in a metric space, and to continuity of negation in the topological group case.
* `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds
to cutting the radius of a ball in half and applying the triangle inequality.
In the topological group case, it comes from continuity of addition at `(0, 0)`.
These three axioms are stated more abstractly in the definition below, in terms of
operations on filters, without directly manipulating entourages.
## Main definitions
* `uniform_space X` is a uniform space structure on a type `X`
* `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces
is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r`
In this file we also define a complete lattice structure on the type `uniform_space X`
of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures
coming from the pullback of filters.
Like distance functions, uniform structures cannot be pushed forward in general.
## Notations
Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`,
and `○` for composition of relations, seen as terms with type `set (X × X)`.
## Implementation notes
There is already a theory of relations in `data/rel.lean` where the main definition is
`def rel (α β : Type*) := α → β → Prop`.
The relations used in the current file involve only one type, but this is not the reason why
we don't reuse `data/rel.lean`. We use `set (α × α)`
instead of `rel α α` because we really need sets to use the filter library, and elements
of filters on `α × α` have type `set (α × α)`.
The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and
an assumption saying those are compatible. This may not seem mathematically reasonable at first,
but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance]
below.
## References
The formalization uses the books:
* [N. Bourbaki, *General Topology*][bourbaki1966]
* [I. M. James, *Topologies and Uniformities*][james1999]
But it makes a more systematic use of the filter library.
-/
open set filter classical
open_locale classical topological_space filter
set_option eqn_compiler.zeta true
universes u
/-!
### Relations, seen as `set (α × α)`
-/
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*}
/-- The identity relation, or the graph of the identity function -/
def id_rel {α : Type*} := {p : α × α | p.1 = p.2}
@[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl
@[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s :=
by simp [subset_def]; exact forall_congr (λ a, by simp)
/-- The composition of relations -/
def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂}
localized "infix (name := uniformity.comp_rel) ` ○ `:55 := comp_rel" in uniformity
@[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)}
{x y : α} : (x, y) ∈ r₁ ○ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl
@[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α :=
set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm
theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)}
(hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ○ (g x)) :=
assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩
@[mono]
lemma comp_rel_mono {f g h k: set (α×α)} (h₁ : f ⊆ h) (h₂ : g ⊆ k) : f ○ g ⊆ h ○ k :=
λ ⟨x, y⟩ ⟨z, h, h'⟩, ⟨z, h₁ h, h₂ h'⟩
lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) :
(a, b) ∈ s ○ t :=
⟨c, h₁, h₂⟩
@[simp] lemma id_comp_rel {r : set (α×α)} : id_rel ○ r = r :=
set.ext $ assume ⟨a, b⟩, by simp
lemma comp_rel_assoc {r s t : set (α×α)} :
(r ○ s) ○ t = r ○ (s ○ t) :=
by ext p; cases p; simp only [mem_comp_rel]; tauto
lemma left_subset_comp_rel {s t : set (α × α)} (h : id_rel ⊆ t) : s ⊆ s ○ t :=
λ ⟨x, y⟩ xy_in, ⟨y, xy_in, h $ by exact rfl⟩
lemma right_subset_comp_rel {s t : set (α × α)} (h : id_rel ⊆ s) : t ⊆ s ○ t :=
λ ⟨x, y⟩ xy_in, ⟨x, h $ by exact rfl, xy_in⟩
lemma subset_comp_self {s : set (α × α)} (h : id_rel ⊆ s) : s ⊆ s ○ s :=
left_subset_comp_rel h
lemma subset_iterate_comp_rel {s t : set (α × α)} (h : id_rel ⊆ s) (n : ℕ) :
t ⊆ (((○) s) ^[n] t) :=
begin
induction n with n ihn generalizing t,
exacts [subset.rfl, (right_subset_comp_rel h).trans ihn]
end
/-- The relation is invariant under swapping factors. -/
def symmetric_rel (V : set (α × α)) : Prop := prod.swap ⁻¹' V = V
/-- The maximal symmetric relation contained in a given relation. -/
def symmetrize_rel (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V
lemma symmetric_symmetrize_rel (V : set (α × α)) : symmetric_rel (symmetrize_rel V) :=
by simp [symmetric_rel, symmetrize_rel, preimage_inter, inter_comm, ← preimage_comp]
lemma symmetrize_rel_subset_self (V : set (α × α)) : symmetrize_rel V ⊆ V :=
sep_subset _ _
@[mono]
lemma symmetrize_mono {V W: set (α × α)} (h : V ⊆ W) : symmetrize_rel V ⊆ symmetrize_rel W :=
inter_subset_inter h $ preimage_mono h
lemma symmetric_rel.mk_mem_comm {V : set (α × α)} (hV : symmetric_rel V) {x y : α} :
(x, y) ∈ V ↔ (y, x) ∈ V :=
set.ext_iff.1 hV (y, x)
lemma symmetric_rel.eq {U : set (α × α)} (hU : symmetric_rel U) : prod.swap ⁻¹' U = U := hU
lemma symmetric_rel.inter {U V : set (α × α)} (hU : symmetric_rel U) (hV : symmetric_rel V) :
symmetric_rel (U ∩ V) :=
by rw [symmetric_rel, preimage_inter, hU.eq, hV.eq]
/-- This core description of a uniform space is outside of the type class hierarchy. It is useful
for constructions of uniform spaces, when the topology is derived from the uniform space. -/
structure uniform_space.core (α : Type u) :=
(uniformity : filter (α × α))
(refl : 𝓟 id_rel ≤ uniformity)
(symm : tendsto prod.swap uniformity uniformity)
(comp : uniformity.lift' (λs, s ○ s) ≤ uniformity)
/-- An alternative constructor for `uniform_space.core`. This version unfolds various
`filter`-related definitions. -/
def uniform_space.core.mk' {α : Type u} (U : filter (α × α))
(refl : ∀ (r ∈ U) x, (x, x) ∈ r)
(symm : ∀ r ∈ U, prod.swap ⁻¹' r ∈ U)
(comp : ∀ r ∈ U, ∃ t ∈ U, t ○ t ⊆ r) : uniform_space.core α :=
⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm,
begin
intros r ru,
rw [mem_lift'_sets],
exact comp _ ru,
apply monotone_comp_rel; exact monotone_id,
end⟩
/-- Defining an `uniform_space.core` from a filter basis satisfying some uniformity-like axioms. -/
def uniform_space.core.mk_of_basis {α : Type u} (B : filter_basis (α × α))
(refl : ∀ (r ∈ B) x, (x, x) ∈ r)
(symm : ∀ r ∈ B, ∃ t ∈ B, t ⊆ prod.swap ⁻¹' r)
(comp : ∀ r ∈ B, ∃ t ∈ B, t ○ t ⊆ r) : uniform_space.core α :=
{ uniformity := B.filter,
refl := B.has_basis.ge_iff.mpr (λ r ru, id_rel_subset.2 $ refl _ ru),
symm := (B.has_basis.tendsto_iff B.has_basis).mpr symm,
comp := (has_basis.le_basis_iff (B.has_basis.lift' (monotone_comp_rel monotone_id monotone_id))
B.has_basis).mpr comp }
/-- A uniform space generates a topological space -/
def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) :
topological_space α :=
{ is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity,
is_open_univ := by simp; intro; exact univ_mem,
is_open_inter :=
assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt},
is_open_sUnion :=
assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] with p ph h using ⟨t, ts, ph h⟩ }
lemma uniform_space.core_eq :
∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂
| ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := by { congr, exact h }
-- the topological structure is embedded in the uniform structure
-- to avoid instance diamond issues. See Note [forgetful inheritance].
/-- A uniform space is a generalization of the "uniform" topological aspects of a
metric space. It consists of a filter on `α × α` called the "uniformity", which
satisfies properties analogous to the reflexivity, symmetry, and triangle properties
of a metric.
A metric space has a natural uniformity, and a uniform space has a natural topology.
A topological group also has a natural uniformity, even when it is not metrizable. -/
class uniform_space (α : Type u) extends topological_space α, uniform_space.core α :=
(is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity))
/-- Alternative constructor for `uniform_space α` when a topology is already given. -/
@[pattern] def uniform_space.mk' {α} (t : topological_space α)
(c : uniform_space.core α)
(is_open_uniformity : ∀s:set α, t.is_open s ↔
(∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) :
uniform_space α := ⟨c, is_open_uniformity⟩
/-- Construct a `uniform_space` from a `uniform_space.core`. -/
def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α :=
{ to_core := u,
to_topological_space := u.to_topological_space,
is_open_uniformity := assume a, iff.rfl }
/-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure
that is equal to `u.to_topological_space`. -/
def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α)
(h : t = u.to_topological_space) : uniform_space α :=
{ to_core := u,
to_topological_space := t,
is_open_uniformity := assume a, h.symm ▸ iff.rfl }
lemma uniform_space.to_core_to_topological_space (u : uniform_space α) :
u.to_core.to_topological_space = u.to_topological_space :=
topological_space_eq $ funext $ assume s,
by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity]
@[ext]
lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂
| (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h :=
have u₁ = u₂, from uniform_space.core_eq h,
have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this],
by simp [*]
lemma uniform_space.of_core_eq_to_core
(u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) :
uniform_space.of_core_eq u.to_core t h = u :=
uniform_space_eq rfl
/-- Replace topology in a `uniform_space` instance with a propositionally (but possibly not
definitionally) equal one. -/
@[reducible] def uniform_space.replace_topology {α : Type*} [i : topological_space α]
(u : uniform_space α) (h : i = u.to_topological_space) : uniform_space α :=
uniform_space.of_core_eq u.to_core i $ h.trans u.to_core_to_topological_space.symm
lemma uniform_space.replace_topology_eq {α : Type*} [i : topological_space α] (u : uniform_space α)
(h : i = u.to_topological_space) : u.replace_topology h = u :=
u.of_core_eq_to_core _ _
section uniform_space
variables [uniform_space α]
/-- The uniformity is a filter on α × α (inferred from an ambient uniform space
structure on α). -/
def uniformity (α : Type u) [uniform_space α] : filter (α × α) :=
(@uniform_space.to_core α _).uniformity
localized "notation (name := uniformity) `𝓤` := uniformity" in uniformity
lemma is_open_uniformity {s : set α} :
is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) :=
uniform_space.is_open_uniformity s
lemma refl_le_uniformity : 𝓟 id_rel ≤ 𝓤 α :=
(@uniform_space.to_core α _).refl
instance uniformity.ne_bot [nonempty α] : ne_bot (𝓤 α) :=
begin
inhabit α,
refine (principal_ne_bot_iff.2 _).mono refl_le_uniformity,
exact ⟨(default, default), rfl⟩
end
lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) :
(x, x) ∈ s :=
refl_le_uniformity h rfl
lemma mem_uniformity_of_eq {x y : α} {s : set (α × α)} (h : s ∈ 𝓤 α) (hx : x = y) :
(x, y) ∈ s :=
hx ▸ refl_mem_uniformity h
lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) :=
(@uniform_space.to_core α _).symm
lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), s ○ s) ≤ 𝓤 α :=
(@uniform_space.to_core α _).comp
lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) :=
symm_le_uniformity
lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, t ○ t ⊆ s :=
have s ∈ (𝓤 α).lift' (λt:set (α×α), t ○ t),
from comp_le_uniformity hs,
(mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this
/-- If `s ∈ 𝓤 α`, then for any natural `n`, for a subset `t` of a sufficiently small set in `𝓤 α`,
we have `t ○ t ○ ... ○ t ⊆ s` (`n` compositions). -/
lemma eventually_uniformity_iterate_comp_subset {s : set (α × α)} (hs : s ∈ 𝓤 α) (n : ℕ) :
∀ᶠ t in (𝓤 α).small_sets, ((○) t) ^[n] t ⊆ s :=
begin
suffices : ∀ᶠ t in (𝓤 α).small_sets, t ⊆ s ∧ (((○) t) ^[n] t ⊆ s),
from (eventually_and.1 this).2,
induction n with n ihn generalizing s, { simpa },
rcases comp_mem_uniformity_sets hs with ⟨t, htU, hts⟩,
refine (ihn htU).mono (λ U hU, _),
rw [function.iterate_succ_apply'],
exact ⟨hU.1.trans $ (subset_comp_self $ refl_le_uniformity htU).trans hts,
(comp_rel_mono hU.1 hU.2).trans hts⟩
end
/-- If `s ∈ 𝓤 α`, then for any natural `n`, for a subset `t` of a sufficiently small set in `𝓤 α`,
we have `t ○ t ⊆ s`. -/
lemma eventually_uniformity_comp_subset {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∀ᶠ t in (𝓤 α).small_sets, t ○ t ⊆ s :=
eventually_uniformity_iterate_comp_subset hs 1
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/
lemma filter.tendsto.uniformity_trans {l : filter β} {f₁ f₂ f₃ : β → α}
(h₁₂ : tendsto (λ x, (f₁ x, f₂ x)) l (𝓤 α)) (h₂₃ : tendsto (λ x, (f₂ x, f₃ x)) l (𝓤 α)) :
tendsto (λ x, (f₁ x, f₃ x)) l (𝓤 α) :=
begin
refine le_trans (le_lift'.2 $ λ s hs, mem_map.2 _) comp_le_uniformity,
filter_upwards [h₁₂ hs, h₂₃ hs] with x hx₁₂ hx₂₃ using ⟨_, hx₁₂, hx₂₃⟩,
end
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/
lemma filter.tendsto.uniformity_symm {l : filter β} {f : β → α × α}
(h : tendsto f l (𝓤 α)) :
tendsto (λ x, ((f x).2, (f x).1)) l (𝓤 α) :=
tendsto_swap_uniformity.comp h
/-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/
lemma tendsto_diag_uniformity (f : β → α) (l : filter β) :
tendsto (λ x, (f x, f x)) l (𝓤 α) :=
assume s hs, mem_map.2 $ univ_mem' $ λ x, refl_mem_uniformity hs
lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) :=
tendsto_diag_uniformity (λ _, a) f
lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s :=
have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs,
⟨s ∩ preimage prod.swap s, inter_mem hs this, λ a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩
lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ t ○ t ⊆ s :=
let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in
let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in
⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩
lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α :=
by rw [map_swap_eq_comap_swap];
from map_le_iff_le_comap.1 tendsto_swap_uniformity
lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α :=
le_antisymm uniformity_le_symm symm_le_uniformity
@[simp] lemma comap_swap_uniformity : comap (@prod.swap α α) (𝓤 α) = 𝓤 α :=
(congr_arg _ uniformity_eq_symm).trans $ comap_map prod.swap_injective
lemma symmetrize_mem_uniformity {V : set (α × α)} (h : V ∈ 𝓤 α) : symmetrize_rel V ∈ 𝓤 α :=
begin
apply (𝓤 α).inter_sets h,
rw [← image_swap_eq_preimage_swap, uniformity_eq_symm],
exact image_mem_map h,
end
/-- Symmetric entourages form a basis of `𝓤 α` -/
lemma uniform_space.has_basis_symmetric :
(𝓤 α).has_basis (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) id :=
has_basis_self.2 $ λ t t_in, ⟨symmetrize_rel t, symmetrize_mem_uniformity t_in,
symmetric_symmetrize_rel t, symmetrize_rel_subset_self t⟩
theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g)
(h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f :=
calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g :
lift_mono uniformity_le_symm le_rfl
... ≤ _ :
by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h
lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) :
(𝓤 α).lift (λs, f (s ○ s)) ≤ (𝓤 α).lift f :=
calc (𝓤 α).lift (λs, f (s ○ s)) =
((𝓤 α).lift' (λs:set (α×α), s ○ s)).lift f :
begin
rw [lift_lift'_assoc],
exact monotone_comp_rel monotone_id monotone_id,
exact h
end
... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity le_rfl
lemma comp_le_uniformity3 :
(𝓤 α).lift' (λs:set (α×α), s ○ (s ○ s)) ≤ (𝓤 α) :=
calc (𝓤 α).lift' (λd, d ○ (d ○ d)) =
(𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ (t ○ t))) :
begin
rw [lift_lift'_same_eq_lift'],
exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id),
exact (assume x, monotone_comp_rel monotone_id monotone_const),
end
... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ t)) :
lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (𝓟 ∘ (○) s) $
monotone_principal.comp (monotone_comp_rel monotone_const monotone_id)
... = (𝓤 α).lift' (λs:set(α×α), s ○ s) :
lift_lift'_same_eq_lift'
(assume s, monotone_comp_rel monotone_const monotone_id)
(assume s, monotone_comp_rel monotone_id monotone_const)
... ≤ (𝓤 α) : comp_le_uniformity
/-- See also `comp_open_symm_mem_uniformity_sets`. -/
lemma comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ⊆ s :=
begin
obtain ⟨w, w_in, w_sub⟩ : ∃ w ∈ 𝓤 α, w ○ w ⊆ s := comp_mem_uniformity_sets hs,
use [symmetrize_rel w, symmetrize_mem_uniformity w_in, symmetric_symmetrize_rel w],
have : symmetrize_rel w ⊆ w := symmetrize_rel_subset_self w,
calc symmetrize_rel w ○ symmetrize_rel w ⊆ w ○ w : by mono
... ⊆ s : w_sub,
end
lemma subset_comp_self_of_mem_uniformity {s : set (α × α)} (h : s ∈ 𝓤 α) : s ⊆ s ○ s :=
subset_comp_self (refl_le_uniformity h)
lemma comp_comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ○ t ⊆ s :=
begin
rcases comp_symm_mem_uniformity_sets hs with ⟨w, w_in, w_symm, w_sub⟩,
rcases comp_symm_mem_uniformity_sets w_in with ⟨t, t_in, t_symm, t_sub⟩,
use [t, t_in, t_symm],
have : t ⊆ t ○ t := subset_comp_self_of_mem_uniformity t_in,
calc
t ○ t ○ t ⊆ w ○ t : by mono
... ⊆ w ○ (t ○ t) : by mono
... ⊆ w ○ w : by mono
... ⊆ s : w_sub,
end
/-!
### Balls in uniform spaces
-/
/-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be
used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the
notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/
def uniform_space.ball (x : β) (V : set (β × β)) : set β := (prod.mk x) ⁻¹' V
open uniform_space (ball)
lemma uniform_space.mem_ball_self (x : α) {V : set (α × α)} (hV : V ∈ 𝓤 α) :
x ∈ ball x V :=
refl_mem_uniformity hV
/-- The triangle inequality for `uniform_space.ball` -/
lemma mem_ball_comp {V W : set (β × β)} {x y z} (h : y ∈ ball x V) (h' : z ∈ ball y W) :
z ∈ ball x (V ○ W) :=
prod_mk_mem_comp_rel h h'
lemma ball_subset_of_comp_subset {V W : set (β × β)} {x y} (h : x ∈ ball y W) (h' : W ○ W ⊆ V) :
ball x W ⊆ ball y V :=
λ z z_in, h' (mem_ball_comp h z_in)
lemma ball_mono {V W : set (β × β)} (h : V ⊆ W) (x : β) : ball x V ⊆ ball x W :=
preimage_mono h
lemma ball_inter (x : β) (V W : set (β × β)) : ball x (V ∩ W) = ball x V ∩ ball x W :=
preimage_inter
lemma ball_inter_left (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x V :=
ball_mono (inter_subset_left V W) x
lemma ball_inter_right (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x W :=
ball_mono (inter_subset_right V W) x
lemma mem_ball_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x y} :
x ∈ ball y V ↔ y ∈ ball x V :=
show (x, y) ∈ prod.swap ⁻¹' V ↔ (x, y) ∈ V, by { unfold symmetric_rel at hV, rw hV }
lemma ball_eq_of_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x} :
ball x V = {y | (y, x) ∈ V} :=
by { ext y, rw mem_ball_symmetry hV, exact iff.rfl }
lemma mem_comp_of_mem_ball {V W : set (β × β)} {x y z : β} (hV : symmetric_rel V)
(hx : x ∈ ball z V) (hy : y ∈ ball z W) : (x, y) ∈ V ○ W :=
begin
rw mem_ball_symmetry hV at hx,
exact ⟨z, hx, hy⟩
end
lemma uniform_space.is_open_ball (x : α) {V : set (α × α)} (hV : is_open V) :
is_open (ball x V) :=
hV.preimage $ continuous_const.prod_mk continuous_id
lemma mem_comp_comp {V W M : set (β × β)} (hW' : symmetric_rel W) {p : β × β} :
p ∈ V ○ M ○ W ↔ ((ball p.1 V ×ˢ ball p.2 W) ∩ M).nonempty :=
begin
cases p with x y,
split,
{ rintros ⟨z, ⟨w, hpw, hwz⟩, hzy⟩,
exact ⟨(w, z), ⟨hpw, by rwa mem_ball_symmetry hW'⟩, hwz⟩, },
{ rintro ⟨⟨w, z⟩, ⟨w_in, z_in⟩, hwz⟩,
rwa mem_ball_symmetry hW' at z_in,
use [z, w] ; tauto },
end
/-!
### Neighborhoods in uniform spaces
-/
lemma mem_nhds_uniformity_iff_right {x : α} {s : set α} :
s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α :=
begin
refine ⟨_, λ hs, _⟩,
{ simp only [mem_nhds_iff, is_open_uniformity, and_imp, exists_imp_distrib],
intros t ts ht xt,
filter_upwards [ht x xt] using λ y h eq, ts (h eq) },
{ refine mem_nhds_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, _, _, hs⟩,
{ exact λ y hy, refl_mem_uniformity hy rfl },
{ refine is_open_uniformity.mpr (λ y hy, _),
rcases comp_mem_uniformity_sets hy with ⟨t, ht, tr⟩,
filter_upwards [ht], rintro ⟨a, b⟩ hp' rfl,
filter_upwards [ht], rintro ⟨a', b'⟩ hp'' rfl,
exact @tr (a, b') ⟨a', hp', hp''⟩ rfl } }
end
lemma mem_nhds_uniformity_iff_left {x : α} {s : set α} :
s ∈ 𝓝 x ↔ {p : α × α | p.2 = x → p.1 ∈ s} ∈ 𝓤 α :=
by { rw [uniformity_eq_symm, mem_nhds_uniformity_iff_right], refl }
lemma nhds_eq_comap_uniformity_aux {α : Type u} {x : α} {s : set α} {F : filter (α × α)} :
{p : α × α | p.fst = x → p.snd ∈ s} ∈ F ↔ s ∈ comap (prod.mk x) F :=
by rw mem_comap ; from iff.intro
(assume hs, ⟨_, hs, assume x hx, hx rfl⟩)
(assume ⟨t, h, ht⟩, F.sets_of_superset h $
assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp])
lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) :=
by { ext s, rw [mem_nhds_uniformity_iff_right], exact nhds_eq_comap_uniformity_aux }
/-- See also `is_open_iff_open_ball_subset`. -/
lemma is_open_iff_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, ball x V ⊆ s :=
begin
simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity],
exact iff.rfl,
end
lemma nhds_basis_uniformity' {p : ι → Prop} {s : ι → set (α × α)} (h : (𝓤 α).has_basis p s)
{x : α} :
(𝓝 x).has_basis p (λ i, ball x (s i)) :=
by { rw [nhds_eq_comap_uniformity], exact h.comap (prod.mk x) }
lemma nhds_basis_uniformity {p : ι → Prop} {s : ι → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} :
(𝓝 x).has_basis p (λ i, {y | (y, x) ∈ s i}) :=
begin
replace h := h.comap prod.swap,
rw [← map_swap_eq_comap_swap, ← uniformity_eq_symm] at h,
exact nhds_basis_uniformity' h
end
lemma uniform_space.mem_nhds_iff {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, ball x V ⊆ s :=
begin
rw [nhds_eq_comap_uniformity, mem_comap],
exact iff.rfl,
end
lemma uniform_space.ball_mem_nhds (x : α) ⦃V : set (α × α)⦄ (V_in : V ∈ 𝓤 α) : ball x V ∈ 𝓝 x :=
begin
rw uniform_space.mem_nhds_iff,
exact ⟨V, V_in, subset.refl _⟩
end
lemma uniform_space.mem_nhds_iff_symm {x : α} {s : set α} :
s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, symmetric_rel V ∧ ball x V ⊆ s :=
begin
rw uniform_space.mem_nhds_iff,
split,
{ rintros ⟨V, V_in, V_sub⟩,
use [symmetrize_rel V, symmetrize_mem_uniformity V_in, symmetric_symmetrize_rel V],
exact subset.trans (ball_mono (symmetrize_rel_subset_self V) x) V_sub },
{ rintros ⟨V, V_in, V_symm, V_sub⟩,
exact ⟨V, V_in, V_sub⟩ }
end
lemma uniform_space.has_basis_nhds (x : α) :
has_basis (𝓝 x) (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) (λ s, ball x s) :=
⟨λ t, by simp [uniform_space.mem_nhds_iff_symm, and_assoc]⟩
open uniform_space
lemma uniform_space.mem_closure_iff_symm_ball {s : set α} {x} :
x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → symmetric_rel V → (s ∩ ball x V).nonempty :=
by simp [mem_closure_iff_nhds_basis (has_basis_nhds x), set.nonempty]
lemma uniform_space.mem_closure_iff_ball {s : set α} {x} :
x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → (ball x V ∩ s).nonempty :=
by simp [mem_closure_iff_nhds_basis' (nhds_basis_uniformity' (𝓤 α).basis_sets)]
lemma uniform_space.has_basis_nhds_prod (x y : α) :
has_basis (𝓝 (x, y)) (λ s, s ∈ 𝓤 α ∧ symmetric_rel s) $ λ s, ball x s ×ˢ ball y s :=
begin
rw nhds_prod_eq,
apply (has_basis_nhds x).prod_same_index (has_basis_nhds y),
rintro U V ⟨U_in, U_symm⟩ ⟨V_in, V_symm⟩,
exact ⟨U ∩ V, ⟨(𝓤 α).inter_sets U_in V_in, U_symm.inter V_symm⟩,
ball_inter_left x U V, ball_inter_right y U V⟩,
end
lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (ball x) :=
(nhds_basis_uniformity' (𝓤 α).basis_sets).eq_binfi
lemma nhds_eq_uniformity' {x : α} : 𝓝 x = (𝓤 α).lift' (λ s, {y | (y, x) ∈ s}) :=
(nhds_basis_uniformity (𝓤 α).basis_sets).eq_binfi
lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) :
{y : α | (x, y) ∈ s} ∈ 𝓝 x :=
ball_mem_nhds x h
lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) :
{x : α | (x, y) ∈ s} ∈ 𝓝 y :=
mem_nhds_left _ (symm_le_uniformity h)
lemma is_compact.nhds_set_basis_uniformity {p : ι → Prop} {s : ι → set (α × α)}
(hU : (𝓤 α).has_basis p s) {K : set α} (hK : is_compact K) :
(𝓝ˢ K).has_basis p (λ i, ⋃ x ∈ K, ball x (s i)) :=
begin
refine ⟨λ U, _⟩,
simp only [mem_nhds_set_iff_forall, (nhds_basis_uniformity' hU).mem_iff, Union₂_subset_iff],
refine ⟨λ H, _, λ ⟨i, hpi, hi⟩ x hx, ⟨i, hpi, hi x hx⟩⟩,
replace H : ∀ x ∈ K, ∃ i : {i // p i}, ball x (s i ○ s i) ⊆ U,
{ intros x hx,
rcases H x hx with ⟨i, hpi, hi⟩,
rcases comp_mem_uniformity_sets (hU.mem_of_mem hpi) with ⟨t, ht_mem, ht⟩,
rcases hU.mem_iff.1 ht_mem with ⟨j, hpj, hj⟩,
exact ⟨⟨j, hpj⟩, subset.trans (ball_mono ((comp_rel_mono hj hj).trans ht) _) hi⟩ },
haveI : nonempty {a // p a}, from nonempty_subtype.2 hU.ex_mem,
choose! I hI using H,
rcases hK.elim_nhds_subcover (λ x, ball x $ s (I x))
(λ x hx, ball_mem_nhds _ $ hU.mem_of_mem (I x).2) with ⟨t, htK, ht⟩,
obtain ⟨i, hpi, hi⟩ : ∃ i (hpi : p i), s i ⊆ ⋂ x ∈ t, s (I x),
from hU.mem_iff.1 ((bInter_finset_mem t).2 (λ x hx, hU.mem_of_mem (I x).2)),
rw [subset_Inter₂_iff] at hi,
refine ⟨i, hpi, λ x hx, _⟩,
rcases mem_Union₂.1 (ht hx) with ⟨z, hzt : z ∈ t, hzx : x ∈ ball z (s (I z))⟩,
calc ball x (s i) ⊆ ball z (s (I z) ○ s (I z)) : λ y hy, ⟨x, hzx, hi z hzt hy⟩
... ⊆ U : hI z (htK z hzt),
end
lemma disjoint.exists_uniform_thickening {A B : set α}
(hA : is_compact A) (hB : is_closed B) (h : disjoint A B) :
∃ V ∈ 𝓤 α, disjoint (⋃ x ∈ A, ball x V) (⋃ x ∈ B, ball x V) :=
begin
have : Bᶜ ∈ 𝓝ˢ A := hB.is_open_compl.mem_nhds_set.mpr h.le_compl_right,
rw (hA.nhds_set_basis_uniformity (filter.basis_sets _)).mem_iff at this,
rcases this with ⟨U, hU, hUAB⟩,
rcases comp_symm_mem_uniformity_sets hU with ⟨V, hV, hVsymm, hVU⟩,
refine ⟨V, hV, set.disjoint_left.mpr $ λ x, _⟩,
simp only [mem_Union₂],
rintro ⟨a, ha, hxa⟩ ⟨b, hb, hxb⟩,
rw mem_ball_symmetry hVsymm at hxa hxb,
exact hUAB (mem_Union₂_of_mem ha $ hVU $ mem_comp_of_mem_ball hVsymm hxa hxb) hb
end
lemma disjoint.exists_uniform_thickening_of_basis {p : ι → Prop} {s : ι → set (α × α)}
(hU : (𝓤 α).has_basis p s) {A B : set α}
(hA : is_compact A) (hB : is_closed B) (h : disjoint A B) :
∃ i, p i ∧ disjoint (⋃ x ∈ A, ball x (s i)) (⋃ x ∈ B, ball x (s i)) :=
begin
rcases h.exists_uniform_thickening hA hB with ⟨V, hV, hVAB⟩,
rcases hU.mem_iff.1 hV with ⟨i, hi, hiV⟩,
exact ⟨i, hi, hVAB.mono
(Union₂_mono $ λ a _, ball_mono hiV a) (Union₂_mono $ λ b _, ball_mono hiV b)⟩,
end
lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) :=
assume s, mem_nhds_right a
lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) :=
assume s, mem_nhds_left a
lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) :
(𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) :=
eq.trans
begin
rw [nhds_eq_uniformity],
exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage )
end
(congr_arg _ $ funext $ assume s, filter.lift_principal hg)
lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) :
(𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) :=
calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg
... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) :
by rw [←uniformity_eq_symm]
... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) :
map_lift_eq2 $ hg.comp monotone_preimage
... = _ : by simp [image_swap_eq_preimage_swap]
lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} :
𝓝 a ×ᶠ 𝓝 b =
(𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α),
{y : α | (y, a) ∈ s} ×ˢ {y : α | (b, y) ∈ t})) :=
begin
rw [nhds_eq_uniformity', nhds_eq_uniformity, prod_lift'_lift'],
{ refl },
{ exact monotone_preimage },
{ exact monotone_preimage },
end
lemma nhds_eq_uniformity_prod {a b : α} :
𝓝 (a, b) =
(𝓤 α).lift' (λs:set (α×α), {y : α | (y, a) ∈ s} ×ˢ {y : α | (b, y) ∈ s}) :=
begin
rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'],
{ intro s, exact monotone_const.set_prod monotone_preimage },
{ intro t, exact monotone_preimage.set_prod monotone_const }
end
lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) :
∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} :=
let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in
have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from
assume ⟨x, y⟩ hp, _root_.mem_nhds_iff.mp $
show cl_d ∈ 𝓝 (x, y),
begin
rw [nhds_eq_uniformity_prod, mem_lift'_sets],
exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩,
exact monotone_preimage.set_prod monotone_preimage
end,
have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)),
∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h,
by simp [classical.skolem] at this; simp; assumption,
match this with
| ⟨t, ht⟩ :=
⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)),
is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left,
assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end,
Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩
end
/-- Entourages are neighborhoods of the diagonal. -/
lemma nhds_le_uniformity (x : α) : 𝓝 (x, x) ≤ 𝓤 α :=
begin
intros V V_in,
rcases comp_symm_mem_uniformity_sets V_in with ⟨w, w_in, w_symm, w_sub⟩,
have : ball x w ×ˢ ball x w ∈ 𝓝 (x, x),
{ rw nhds_prod_eq,
exact prod_mem_prod (ball_mem_nhds x w_in) (ball_mem_nhds x w_in) },
apply mem_of_superset this,
rintros ⟨u, v⟩ ⟨u_in, v_in⟩,
exact w_sub (mem_comp_of_mem_ball w_symm u_in v_in)
end
/-- Entourages are neighborhoods of the diagonal. -/
lemma supr_nhds_le_uniformity : (⨆ x : α, 𝓝 (x, x)) ≤ 𝓤 α :=
supr_le nhds_le_uniformity
/-- Entourages are neighborhoods of the diagonal. -/
lemma nhds_set_diagonal_le_uniformity : 𝓝ˢ (diagonal α) ≤ 𝓤 α :=
(nhds_set_diagonal α).trans_le supr_nhds_le_uniformity
/-!
### Closure and interior in uniform spaces
-/
lemma closure_eq_uniformity (s : set $ α × α) :
closure s = ⋂ V ∈ {V | V ∈ 𝓤 α ∧ symmetric_rel V}, V ○ s ○ V :=
begin
ext ⟨x, y⟩,
simp only [mem_closure_iff_nhds_basis (uniform_space.has_basis_nhds_prod x y), mem_Inter,
mem_set_of_eq, and_imp, mem_comp_comp, exists_prop, ← mem_inter_iff, inter_comm, set.nonempty]
{ contextual := tt }
end
lemma uniformity_has_basis_closed : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_closed V) id :=
begin
refine filter.has_basis_self.2 (λ t h, _),
rcases comp_comp_symm_mem_uniformity_sets h with ⟨w, w_in, w_symm, r⟩,
refine ⟨closure w, mem_of_superset w_in subset_closure, is_closed_closure, _⟩,
refine subset.trans _ r,
rw closure_eq_uniformity,
apply Inter_subset_of_subset,
apply Inter_subset,
exact ⟨w_in, w_symm⟩
end
lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure :=
eq.symm $ uniformity_has_basis_closed.lift'_closure_eq_self $ λ _, and.right
lemma filter.has_basis.uniformity_closure {p : ι → Prop} {U : ι → set (α × α)}
(h : (𝓤 α).has_basis p U) : (𝓤 α).has_basis p (λ i, closure (U i)) :=
(@uniformity_eq_uniformity_closure α _).symm ▸ h.lift'_closure
/-- Closed entourages form a basis of the uniformity filter. -/
lemma uniformity_has_basis_closure : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α) closure :=
(𝓤 α).basis_sets.uniformity_closure
lemma closure_eq_inter_uniformity {t : set (α×α)} :
closure t = (⋂ d ∈ 𝓤 α, d ○ (t ○ d)) :=
calc closure t = ⋂ V (hV : V ∈ 𝓤 α ∧ symmetric_rel V), V ○ t ○ V : closure_eq_uniformity t
... = ⋂ V ∈ 𝓤 α, V ○ t ○ V : eq.symm $ uniform_space.has_basis_symmetric.bInter_mem $
λ V₁ V₂ hV, comp_rel_mono (comp_rel_mono hV subset.rfl) hV
... = ⋂ V ∈ 𝓤 α, V ○ (t ○ V) : by simp only [comp_rel_assoc]
lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior :=
le_antisymm
(le_infi $ assume d, le_infi $ assume 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
let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in
have s ⊆ interior d, from
calc s ⊆ t : hst
... ⊆ interior d : ht.subset_interior_iff.mpr $
λ x (hx : x ∈ t), let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp hx in hs_comp ⟨x, h₁, y, h₂, h₃⟩,
have interior d ∈ 𝓤 α, by filter_upwards [hs] using this,
by simp [this])
(assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset)
lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) :
interior s ∈ 𝓤 α :=
by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs
lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) :
∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s :=
let ⟨t, ⟨ht_mem, htc⟩, hts⟩ := uniformity_has_basis_closed.mem_iff.1 h in
⟨t, ht_mem, htc, hts⟩
lemma is_open_iff_open_ball_subset {s : set α} :
is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, is_open V ∧ ball x V ⊆ s :=
begin
rw is_open_iff_ball_subset,
split; intros h x hx,
{ obtain ⟨V, hV, hV'⟩ := h x hx,
exact ⟨interior V, interior_mem_uniformity hV, is_open_interior,
(ball_mono interior_subset x).trans hV'⟩, },
{ obtain ⟨V, hV, -, hV'⟩ := h x hx,
exact ⟨V, hV, hV'⟩, },
end
/-- The uniform neighborhoods of all points of a dense set cover the whole space. -/
lemma dense.bUnion_uniformity_ball {s : set α} {U : set (α × α)} (hs : dense s) (hU : U ∈ 𝓤 α) :
(⋃ x ∈ s, ball x U) = univ :=
begin
refine Union₂_eq_univ_iff.2 (λ y, _),
rcases hs.inter_nhds_nonempty (mem_nhds_right y hU) with ⟨x, hxs, hxy : (x, y) ∈ U⟩,
exact ⟨x, hxs, hxy⟩
end
/-!
### Uniformity bases
-/
/-- Open elements of `𝓤 α` form a basis of `𝓤 α`. -/
lemma uniformity_has_basis_open : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V) id :=
has_basis_self.2 $ λ s hs,
⟨interior s, interior_mem_uniformity hs, is_open_interior, interior_subset⟩
lemma filter.has_basis.mem_uniformity_iff {p : β → Prop} {s : β → set (α×α)}
(h : (𝓤 α).has_basis p s) {t : set (α × α)} :
t ∈ 𝓤 α ↔ ∃ i (hi : p i), ∀ a b, (a, b) ∈ s i → (a, b) ∈ t :=
h.mem_iff.trans $ by simp only [prod.forall, subset_def]
/-- Open elements `s : set (α × α)` of `𝓤 α` such that `(x, y) ∈ s ↔ (y, x) ∈ s` form a basis
of `𝓤 α`. -/
lemma uniformity_has_basis_open_symmetric :
has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V ∧ symmetric_rel V) id :=
begin
simp only [← and_assoc],
refine uniformity_has_basis_open.restrict (λ s hs, ⟨symmetrize_rel s, _⟩),
exact ⟨⟨symmetrize_mem_uniformity hs.1, is_open.inter hs.2 (hs.2.preimage continuous_swap)⟩,
symmetric_symmetrize_rel s, symmetrize_rel_subset_self s⟩
end
lemma comp_open_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, is_open t ∧ symmetric_rel t ∧ t ○ t ⊆ s :=
begin
obtain ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs,
obtain ⟨u, ⟨hu₁, hu₂, hu₃⟩, hu₄ : u ⊆ t⟩ := uniformity_has_basis_open_symmetric.mem_iff.mp ht₁,
exact ⟨u, hu₁, hu₂, hu₃, (comp_rel_mono hu₄ hu₄).trans ht₂⟩,
end
section
variable (α)
lemma uniform_space.has_seq_basis [is_countably_generated $ 𝓤 α] :
∃ V : ℕ → set (α × α), has_antitone_basis (𝓤 α) V ∧ ∀ n, symmetric_rel (V n) :=
let ⟨U, hsym, hbasis⟩ := uniform_space.has_basis_symmetric.exists_antitone_subbasis
in ⟨U, hbasis, λ n, (hsym n).2⟩
end
lemma filter.has_basis.bInter_bUnion_ball {p : ι → Prop} {U : ι → set (α × α)}
(h : has_basis (𝓤 α) p U) (s : set α) :
(⋂ i (hi : p i), ⋃ x ∈ s, ball x (U i)) = closure s :=
begin
ext x,
simp [mem_closure_iff_nhds_basis (nhds_basis_uniformity h), ball]
end
/-! ### Uniform continuity -/
/-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal
as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then
`f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/
def uniform_continuous [uniform_space β] (f : α → β) :=
tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β)
/-- A function `f : α → β` is *uniformly continuous* on `s : set α` if `(f x, f y)` tends to
the diagonal as `(x, y)` tends to the diagonal while remaining in `s ×ˢ s`.
In other words, if `x` is sufficiently close to `y`, then `f x` is close to
`f y` no matter where `x` and `y` are located in `s`.-/
def uniform_continuous_on [uniform_space β] (f : α → β) (s : set α) : Prop :=
tendsto (λ x : α × α, (f x.1, f x.2)) (𝓤 α ⊓ principal (s ×ˢ s)) (𝓤 β)
theorem uniform_continuous_def [uniform_space β] {f : α → β} :
uniform_continuous f ↔ ∀ r ∈ 𝓤 β, { x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α :=
iff.rfl
theorem uniform_continuous_iff_eventually [uniform_space β] {f : α → β} :
uniform_continuous f ↔ ∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r :=
iff.rfl
theorem uniform_continuous_on_univ [uniform_space β] {f : α → β} :
uniform_continuous_on f univ ↔ uniform_continuous f :=
by rw [uniform_continuous_on, uniform_continuous, univ_prod_univ, principal_univ, inf_top_eq]
lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) :
uniform_continuous c :=
have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from
eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b,
le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem]) refl_le_uniformity
lemma uniform_continuous_id : uniform_continuous (@id α) :=
by simp [uniform_continuous]; exact tendsto_id
lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) :=
uniform_continuous_of_const $ λ _ _, rfl
lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β}
(hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) :=
hg.comp hf
lemma filter.has_basis.uniform_continuous_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)}
(ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t)
{f : α → β} :
uniform_continuous f ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y, (x, y) ∈ s j → (f x, f y) ∈ t i :=
(ha.tendsto_iff hb).trans $ by simp only [prod.forall]
lemma filter.has_basis.uniform_continuous_on_iff [uniform_space β] {p : γ → Prop}
{s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)}
(hb : (𝓤 β).has_basis q t) {f : α → β} {S : set α} :
uniform_continuous_on f S ↔
∀ i (hi : q i), ∃ j (hj : p j), ∀ x y ∈ S, (x, y) ∈ s j → (f x, f y) ∈ t i :=
((ha.inf_principal (S ×ˢ S)).tendsto_iff hb).trans $
by simp_rw [prod.forall, set.inter_comm (s _), ball_mem_comm, mem_inter_iff, mem_prod, and_imp]
end uniform_space
open_locale uniformity
section constructions
instance : partial_order (uniform_space α) :=
{ le := λt s, t.uniformity ≤ s.uniformity,
le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂,
le_refl := assume t, le_rfl,
le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ }
instance : has_Inf (uniform_space α) :=
⟨assume s, uniform_space.of_core
{ uniformity := (⨅u∈s, @uniformity α u),
refl := le_infi $ assume u, le_infi $ assume hu, u.refl,
symm := le_infi $ assume u, le_infi $ assume hu,
le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm,
comp := le_infi $ assume u, le_infi $ assume hu,
le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_rfl) u.comp }⟩
private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) :
Inf tt ≤ t :=
show (⨅u∈tt, @uniformity α u) ≤ t.uniformity,
from infi_le_of_le t $ infi_le _ h
private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') :
t ≤ Inf tt :=
show t.uniformity ≤ (⨅u∈tt, @uniformity α u),
from le_infi $ assume t', le_infi $ assume ht', h t' ht'
instance : has_top (uniform_space α) :=
⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩
instance : has_bot (uniform_space α) :=
⟨{ to_topological_space := ⊥,
uniformity := 𝓟 id_rel,
refl := le_rfl,
symm := by simp [tendsto]; apply subset.refl,
comp :=
begin
rw [lift'_principal], {simp},
exact monotone_comp_rel monotone_id monotone_id
end,
is_open_uniformity :=
assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩
instance : has_inf (uniform_space α) :=
⟨λ u₁ u₂,
@uniform_space.replace_topology _
(u₁.to_topological_space ⊓ u₂.to_topological_space) (uniform_space.of_core
{ uniformity := u₁.uniformity ⊓ u₂.uniformity,
refl := le_inf u₁.refl u₂.refl,
symm := u₁.symm.inf u₂.symm,
comp := (lift'_inf_le _ _ _).trans $ inf_le_inf u₁.comp u₂.comp }) $
eq_of_nhds_eq_nhds $ λ a,
by simpa only [nhds_inf, nhds_eq_comap_uniformity] using comap_inf.symm⟩
instance : complete_lattice (uniform_space α) :=
{ sup := λa b, Inf {x | a ≤ x ∧ b ≤ x},
le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h),
le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h),
sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩,
inf := (⊓),
le_inf := λ a b c h₁ h₂, show a.uniformity ≤ _, from le_inf h₁ h₂,
inf_le_left := λ a b, show _ ≤ a.uniformity, from inf_le_left,
inf_le_right := λ a b, show _ ≤ b.uniformity, from inf_le_right,
top := ⊤,
le_top := λ a, show a.uniformity ≤ ⊤, from le_top,
bot := ⊥,
bot_le := λ u, u.refl,
Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t},
le_Sup := λ s u h, le_Inf (λ u' h', h' u h),
Sup_le := λ s u h, Inf_le h,
Inf := Inf,
le_Inf := λ s a hs, le_Inf hs,
Inf_le := λ s a ha, Inf_le ha,
..uniform_space.partial_order }
lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} :
(infi u).uniformity = (⨅i, (u i).uniformity) :=
show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from
le_antisymm
(le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩)
(le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _)
lemma infi_uniformity' {ι : Sort*} {u : ι → uniform_space α} :
@uniformity α (infi u) = (⨅i, @uniformity α (u i)) :=
infi_uniformity
lemma inf_uniformity {u v : uniform_space α} :
(u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity :=
rfl
lemma inf_uniformity' {u v : uniform_space α} :
@uniformity α (u ⊓ v) = @uniformity α u ⊓ @uniformity α v :=
rfl
instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩
instance inhabited_uniform_space_core : inhabited (uniform_space.core α) :=
⟨@uniform_space.to_core _ default⟩
/-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f`
is the inverse image in the filter sense of the induced function `α × α → β × β`. -/
def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α :=
{ uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)),
to_topological_space := u.to_topological_space.induced f,
refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl),
symm := by simp [tendsto_comap_iff, prod.swap, (∘)];
exact tendsto_swap_uniformity.comp tendsto_comap,
comp := le_trans
begin
rw [comap_lift'_eq, comap_lift'_eq2],
exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩),
exact monotone_comp_rel monotone_id monotone_id
end
(comap_mono u.comp),
is_open_uniformity := λ s, begin
change (@is_open α (u.to_topological_space.induced f) s ↔ _),
simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff_right, filter.comap, and_comm],
refine ball_congr (λ x hx, ⟨_, _⟩),
{ rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩,
rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) },
{ rintro ⟨t, ht, hts⟩,
exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl,
mem_nhds_uniformity_iff_right.1 $ mem_nhds_left _ ht⟩ }
end }
lemma uniformity_comap [uniform_space α] [uniform_space β] {f : α → β}
(h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) :
𝓤 α = comap (prod.map f f) (𝓤 β) :=
by { rw h, refl }
lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id :=
by ext u ; dsimp only [uniform_space.comap, id] ; rw [prod.id_prod, filter.comap_id]
lemma uniform_space.comap_comap {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} :
uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) :=
by ext ; dsimp only [uniform_space.comap] ; rw filter.comap_comap
lemma uniform_space.comap_inf {α γ} {u₁ u₂ : uniform_space γ} {f : α → γ} :
(u₁ ⊓ u₂).comap f = u₁.comap f ⊓ u₂.comap f :=
uniform_space_eq comap_inf
lemma uniform_space.comap_infi {ι α γ} {u : ι → uniform_space γ} {f : α → γ} :
(⨅ i, u i).comap f = ⨅ i, (u i).comap f :=
begin
ext : 1,
change (𝓤 _) = (𝓤 _),
simp [uniformity_comap rfl, infi_uniformity']
end
lemma uniform_space.comap_mono {α γ} {f : α → γ} :
monotone (λ u : uniform_space γ, u.comap f) :=
begin
intros u₁ u₂ hu,
change (𝓤 _) ≤ (𝓤 _),
rw uniformity_comap rfl,
exact comap_mono hu
end
lemma uniform_continuous_iff {α β} {uα : uniform_space α} {uβ : uniform_space β} {f : α → β} :
uniform_continuous f ↔ uα ≤ uβ.comap f :=
filter.map_le_iff_le_comap
lemma le_iff_uniform_continuous_id {u v : uniform_space α} :
u ≤ v ↔ @uniform_continuous _ _ u v id :=
by rw [uniform_continuous_iff, uniform_space_comap_id, id]
lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] :
@uniform_continuous α β (uniform_space.comap f u) u f :=
tendsto_comap
theorem to_topological_space_comap {f : α → β} {u : uniform_space β} :
@uniform_space.to_topological_space _ (uniform_space.comap f u) =
topological_space.induced f (@uniform_space.to_topological_space β u) := rfl
lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α]
(h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g :=
tendsto_comap_iff.2 h
lemma to_nhds_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) (a : α) :
@nhds _ (@uniform_space.to_topological_space _ u₁) a ≤
@nhds _ (@uniform_space.to_topological_space _ u₂) a :=
by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h le_rfl)
lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) :
@uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ :=
le_of_nhds_le_nhds $ to_nhds_mono h
lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β}
(hf : uniform_continuous f) : continuous f :=
continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf
lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl
lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ :=
top_unique $ assume s hs, s.eq_empty_or_nonempty.elim
(assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤)
(assume ⟨x, hx⟩,
have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl,
this.symm ▸ @is_open_univ _ ⊤)
lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} :
(infi u).to_topological_space = ⨅i, (u i).to_topological_space :=
begin
refine (eq_of_nhds_eq_nhds $ assume a, _),
rw [nhds_infi, nhds_eq_uniformity],
change (infi u).uniformity.lift' (preimage $ prod.mk a) = _,
rw [infi_uniformity, lift'_infi_of_map_univ _ preimage_univ],
{ simp only [nhds_eq_uniformity], refl },
{ exact ball_inter _ }
end
lemma to_topological_space_Inf {s : set (uniform_space α)} :
(Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) :=
begin
rw [Inf_eq_infi],
simp only [← to_topological_space_infi],
end
lemma to_topological_space_inf {u v : uniform_space α} :
(u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space :=
rfl
/-- Uniform space structure on `ulift α`. -/
instance ulift.uniform_space [uniform_space α] : uniform_space (ulift α) :=
uniform_space.comap ulift.down ‹_›
section uniform_continuous_infi
lemma uniform_continuous_inf_rng {f : α → β} {u₁ : uniform_space α} {u₂ u₃ : uniform_space β}
(h₁ : @@uniform_continuous u₁ u₂ f) (h₂ : @@uniform_continuous u₁ u₃ f) :
@@uniform_continuous u₁ (u₂ ⊓ u₃) f :=
tendsto_inf.mpr ⟨h₁, h₂⟩
lemma uniform_continuous_inf_dom_left {f : α → β} {u₁ u₂ : uniform_space α} {u₃ : uniform_space β}
(hf : @@uniform_continuous u₁ u₃ f) : @@uniform_continuous (u₁ ⊓ u₂) u₃ f :=
tendsto_inf_left hf
lemma uniform_continuous_inf_dom_right {f : α → β} {u₁ u₂ : uniform_space α} {u₃ : uniform_space β}
(hf : @@uniform_continuous u₂ u₃ f) : @@uniform_continuous (u₁ ⊓ u₂) u₃ f :=
tendsto_inf_right hf
lemma uniform_continuous_Inf_dom {f : α → β} {u₁ : set (uniform_space α)} {u₂ : uniform_space β}
{u : uniform_space α} (h₁ : u ∈ u₁) (hf : @@uniform_continuous u u₂ f) :
@@uniform_continuous (Inf u₁) u₂ f :=
begin
rw [uniform_continuous, Inf_eq_infi', infi_uniformity'],
exact tendsto_infi' ⟨u, h₁⟩ hf
end
lemma uniform_continuous_Inf_rng {f : α → β} {u₁ : uniform_space α} {u₂ : set (uniform_space β)}
(h : ∀u∈u₂, @@uniform_continuous u₁ u f) : @@uniform_continuous u₁ (Inf u₂) f :=
begin
rw [uniform_continuous, Inf_eq_infi', infi_uniformity'],
exact tendsto_infi.mpr (λ ⟨u, hu⟩, h u hu)
end
lemma uniform_continuous_infi_dom {f : α → β} {u₁ : ι → uniform_space α} {u₂ : uniform_space β}
{i : ι} (hf : @@uniform_continuous (u₁ i) u₂ f) : @@uniform_continuous (infi u₁) u₂ f :=
begin
rw [uniform_continuous, infi_uniformity'],
exact tendsto_infi' i hf
end
lemma uniform_continuous_infi_rng {f : α → β} {u₁ : uniform_space α} {u₂ : ι → uniform_space β}
(h : ∀i, @@uniform_continuous u₁ (u₂ i) f) : @@uniform_continuous u₁ (infi u₂) f :=
by rwa [uniform_continuous, infi_uniformity', tendsto_infi]
end uniform_continuous_infi
/-- A uniform space with the discrete uniformity has the discrete topology. -/
lemma discrete_topology_of_discrete_uniformity [hα : uniform_space α]
(h : uniformity α = 𝓟 id_rel) :
discrete_topology α :=
⟨(uniform_space_eq h.symm : ⊥ = hα) ▸ rfl⟩
instance : uniform_space empty := ⊥
instance : uniform_space punit := ⊥
instance : uniform_space bool := ⊥
instance : uniform_space ℕ := ⊥
instance : uniform_space ℤ := ⊥
section
variables [uniform_space α]
open additive multiplicative
instance : uniform_space (additive α) := ‹uniform_space α›
instance : uniform_space (multiplicative α) := ‹uniform_space α›
lemma uniform_continuous_of_mul : uniform_continuous (of_mul : α → additive α) :=
uniform_continuous_id
lemma uniform_continuous_to_mul : uniform_continuous (to_mul : additive α → α) :=
uniform_continuous_id
lemma uniform_continuous_of_add : uniform_continuous (of_add : α → multiplicative α) :=
uniform_continuous_id
lemma uniform_continuous_to_add : uniform_continuous (to_add : multiplicative α → α) :=
uniform_continuous_id
lemma uniformity_additive : 𝓤 (additive α) = (𝓤 α).map (prod.map of_mul of_mul) :=
by { convert map_id.symm, exact prod.map_id }
lemma uniformity_multiplicative : 𝓤 (multiplicative α) = (𝓤 α).map (prod.map of_add of_add) :=
by { convert map_id.symm, exact prod.map_id }
end
instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) :=
uniform_space.comap subtype.val t
lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] :
𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) :=
rfl
lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] :
uniform_continuous (subtype.val : {a : α // p a} → α) :=
uniform_continuous_comap
lemma uniform_continuous_subtype_coe {p : α → Prop} [uniform_space α] :
uniform_continuous (coe : {a : α // p a} → α) :=
uniform_continuous_subtype_val
lemma uniform_continuous.subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β]
{f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) :
uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) :=
uniform_continuous_comap' hf
lemma uniform_continuous_on_iff_restrict [uniform_space α] [uniform_space β] {f : α → β}
{s : set α} :
uniform_continuous_on f s ↔ uniform_continuous (s.restrict f) :=
begin
unfold uniform_continuous_on set.restrict uniform_continuous tendsto,
rw [show (λ x : s × s, (f x.1, f x.2)) = prod.map f f ∘ coe, by ext x; cases x; refl,
uniformity_comap rfl,
show prod.map subtype.val subtype.val = (coe : s × s → α × α), by ext x; cases x; refl],
conv in (map _ (comap _ _)) { rw ← filter.map_map },
rw subtype_coe_map_comap_prod, refl,
end
lemma tendsto_of_uniform_continuous_subtype
[uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α}
(hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) :
tendsto f (𝓝 a) (𝓝 (f a)) :=
by rw [(@map_nhds_subtype_coe_eq α _ s a (mem_of_mem_nhds ha) ha).symm]; exact
tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _)
lemma uniform_continuous_on.continuous_on [uniform_space α] [uniform_space β] {f : α → β}
{s : set α} (h : uniform_continuous_on f s) : continuous_on f s :=
begin
rw uniform_continuous_on_iff_restrict at h,
rw continuous_on_iff_continuous_restrict,
exact h.continuous
end
@[to_additive]
instance [uniform_space α] : uniform_space (αᵐᵒᵖ) :=
uniform_space.comap mul_opposite.unop ‹_›
@[to_additive]
lemma uniformity_mul_opposite [uniform_space α] :
𝓤 (αᵐᵒᵖ) = comap (λ q : αᵐᵒᵖ × αᵐᵒᵖ, (q.1.unop, q.2.unop)) (𝓤 α) :=
rfl
@[simp, to_additive] lemma comap_uniformity_mul_opposite [uniform_space α] :
comap (λ p : α × α, (mul_opposite.op p.1, mul_opposite.op p.2)) (𝓤 αᵐᵒᵖ) = 𝓤 α :=
by simpa [uniformity_mul_opposite, comap_comap, (∘)] using comap_id
namespace mul_opposite
@[to_additive]
lemma uniform_continuous_unop [uniform_space α] : uniform_continuous (unop : αᵐᵒᵖ → α) :=
uniform_continuous_comap
@[to_additive]
lemma uniform_continuous_op [uniform_space α] : uniform_continuous (op : α → αᵐᵒᵖ) :=
uniform_continuous_comap' uniform_continuous_id
end mul_opposite
section prod
/- a similar product space is possible on the function space (uniformity of pointwise convergence),
but we want to have the uniformity of uniform convergence on function spaces -/
instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) :=
u₁.comap prod.fst ⊓ u₂.comap prod.snd
-- check the above produces no diamond
example [u₁ : uniform_space α] [u₂ : uniform_space β] :
(prod.topological_space : topological_space (α × β)) = uniform_space.to_topological_space :=
rfl
theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) =
(𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓
(𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) :=
rfl
lemma uniformity_prod_eq_comap_prod [uniform_space α] [uniform_space β] :
𝓤 (α × β) = comap (λ p : (α × β) × (α × β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ᶠ 𝓤 β) :=
by rw [uniformity_prod, filter.prod, comap_inf, comap_comap, comap_comap]
lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] :
𝓤 (α × β) = map (λ p : (α × α) × (β × β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ᶠ 𝓤 β) :=
by rw [map_swap4_eq_comap, uniformity_prod_eq_comap_prod]
lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] [uniform_space β]
{s : set (β × β)} {f : α → α → β} (hf : uniform_continuous (λ p : α × α, f p.1 p.2))
(hs : s ∈ 𝓤 β) :
∃ u ∈ 𝓤 α, ∀ a b c, (a, b) ∈ u → (f a c, f b c) ∈ s :=
begin
rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf,
rcases mem_prod_iff.1 (mem_map.1 $ hf hs) with ⟨u, hu, v, hv, huvt⟩,
exact ⟨u, hu, λ a b c hab, @huvt ((_, _), (_, _)) ⟨hab, refl_mem_uniformity hv⟩⟩
end
lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)}
{b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) :
{p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) :=
by rw [uniformity_prod]; exact inter_mem_inf (preimage_mem_comap ha) (preimage_mem_comap hb)
lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] :
tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) :=
le_trans (map_mono inf_le_left) map_comap_le
lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] :
tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) :=
le_trans (map_mono inf_le_right) map_comap_le
lemma uniform_continuous_fst [uniform_space α] [uniform_space β] :
uniform_continuous (λp:α×β, p.1) :=
tendsto_prod_uniformity_fst
lemma uniform_continuous_snd [uniform_space α] [uniform_space β] :
uniform_continuous (λp:α×β, p.2) :=
tendsto_prod_uniformity_snd
variables [uniform_space α] [uniform_space β] [uniform_space γ]
lemma uniform_continuous.prod_mk
{f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) :
uniform_continuous (λa, (f₁ a, f₂ a)) :=
by rw [uniform_continuous, uniformity_prod]; exact
tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩
lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) :
uniform_continuous (λ a, f (a,b)) :=
h.comp (uniform_continuous_id.prod_mk uniform_continuous_const)
lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) :
uniform_continuous (λ b, f (a,b)) :=
h.comp (uniform_continuous_const.prod_mk uniform_continuous_id)
lemma uniform_continuous.prod_map [uniform_space δ] {f : α → γ} {g : β → δ}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (prod.map f g) :=
(hf.comp uniform_continuous_fst).prod_mk (hg.comp uniform_continuous_snd)
lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] :
@uniform_space.to_topological_space (α × β) prod.uniform_space =
@prod.topological_space α β u.to_topological_space v.to_topological_space := rfl
/-- A version of `uniform_continuous_inf_dom_left` for binary functions -/
lemma uniform_continuous_inf_dom_left₂ {α β γ} {f : α → β → γ}
{ua1 ua2 : uniform_space α} {ub1 ub2 : uniform_space β} {uc1 : uniform_space γ}
(h : by haveI := ua1; haveI := ub1; exact uniform_continuous (λ p : α × β, f p.1 p.2)) :
by haveI := ua1 ⊓ ua2; haveI := ub1 ⊓ ub2; exact uniform_continuous (λ p : α × β, f p.1 p.2) :=
begin
-- proof essentially copied from ``continuous_inf_dom_left₂`
have ha := @uniform_continuous_inf_dom_left _ _ id ua1 ua2 ua1 (@uniform_continuous_id _ (id _)),
have hb := @uniform_continuous_inf_dom_left _ _ id ub1 ub2 ub1 (@uniform_continuous_id _ (id _)),
have h_unif_cont_id := @uniform_continuous.prod_map _ _ _ _ (
ua1 ⊓ ua2) (ub1 ⊓ ub2) ua1 ub1 _ _ ha hb,
exact @uniform_continuous.comp _ _ _ (id _) (id _) _ _ _ h h_unif_cont_id,
end
/-- A version of `uniform_continuous_inf_dom_right` for binary functions -/
lemma uniform_continuous_inf_dom_right₂ {α β γ} {f : α → β → γ}
{ua1 ua2 : uniform_space α} {ub1 ub2 : uniform_space β} {uc1 : uniform_space γ}
(h : by haveI := ua2; haveI := ub2; exact uniform_continuous (λ p : α × β, f p.1 p.2)) :
by haveI := ua1 ⊓ ua2; haveI := ub1 ⊓ ub2; exact uniform_continuous (λ p : α × β, f p.1 p.2) :=
begin
-- proof essentially copied from ``continuous_inf_dom_right₂`
have ha := @uniform_continuous_inf_dom_right _ _ id ua1 ua2 ua2 (@uniform_continuous_id _ (id _)),
have hb := @uniform_continuous_inf_dom_right _ _ id ub1 ub2 ub2 (@uniform_continuous_id _ (id _)),
have h_unif_cont_id := @uniform_continuous.prod_map _ _ _ _
(ua1 ⊓ ua2) (ub1 ⊓ ub2) ua2 ub2 _ _ ha hb,
exact @uniform_continuous.comp _ _ _ (id _) (id _) _ _ _ h h_unif_cont_id,
end
/-- A version of `uniform_continuous_Inf_dom` for binary functions -/
lemma uniform_continuous_Inf_dom₂ {α β γ} {f : α → β → γ}
{uas : set (uniform_space α)} {ubs : set (uniform_space β)}
{ua : uniform_space α} {ub : uniform_space β} {uc : uniform_space γ}
(ha : ua ∈ uas) (hb : ub ∈ ubs)
(hf : uniform_continuous (λ p : α × β, f p.1 p.2)):
by haveI := Inf uas; haveI := Inf ubs;
exact @uniform_continuous _ _ _ uc (λ p : α × β, f p.1 p.2) :=
begin
-- proof essentially copied from ``continuous_Inf_dom`
let t : uniform_space (α × β) := prod.uniform_space,
have ha := uniform_continuous_Inf_dom ha uniform_continuous_id,
have hb := uniform_continuous_Inf_dom hb uniform_continuous_id,
have h_unif_cont_id := @uniform_continuous.prod_map _ _ _ _ (Inf uas) (Inf ubs) ua ub _ _ ha hb,
exact @uniform_continuous.comp _ _ _ (id _) (id _) _ _ _ hf h_unif_cont_id,
end
end prod
section
open uniform_space function
variables {δ' : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ]
[uniform_space δ']
local notation f ` ∘₂ ` g := function.bicompr f g
/-- Uniform continuity for functions of two variables. -/
def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry f)
lemma uniform_continuous₂_def (f : α → β → γ) :
uniform_continuous₂ f ↔ uniform_continuous (uncurry f) := iff.rfl
lemma uniform_continuous₂.uniform_continuous {f : α → β → γ} (h : uniform_continuous₂ f) :
uniform_continuous (uncurry f) := h
lemma uniform_continuous₂_curry (f : α × β → γ) :
uniform_continuous₂ (function.curry f) ↔ uniform_continuous f :=
by rw [uniform_continuous₂, uncurry_curry]
lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ}
(hg : uniform_continuous g) (hf : uniform_continuous₂ f) :
uniform_continuous₂ (g ∘₂ f) :=
hg.comp hf
lemma uniform_continuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β}
(hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) :
uniform_continuous₂ (bicompl f ga gb) :=
hf.uniform_continuous.comp (hga.prod_map hgb)
end
lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} :
@uniform_space.to_topological_space (subtype p) subtype.uniform_space =
@subtype.topological_space α p u.to_topological_space := rfl
section sum
variables [uniform_space α] [uniform_space β]
open sum
/-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained
by taking independently an entourage of the diagonal in the first part, and an entourage of
the diagonal in the second part. -/
def uniform_space.core.sum : uniform_space.core (α ⊕ β) :=
uniform_space.core.mk'
(map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β))
(λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂])
(λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩)
(λ r ⟨Hrα, Hrβ⟩, begin
rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩,
rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩,
refine ⟨_,
⟨mem_map_iff_exists_image.2 ⟨tα, htα, subset_union_left _ _⟩,
mem_map_iff_exists_image.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩,
rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩,
⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩,
{ have A : (a, c) ∈ tα ○ tα := ⟨b, hab, hbc⟩,
exact Htα A },
{ have A : (a, c) ∈ tβ ○ tβ := ⟨b, hab, hbc⟩,
exact Htβ A }
end)
/-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage
of the diagonal. -/
lemma union_mem_uniformity_sum
{a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) :
((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈
(@uniform_space.core.sum α β _ _).uniformity :=
⟨mem_map_iff_exists_image.2 ⟨_, ha, subset_union_left _ _⟩,
mem_map_iff_exists_image.2 ⟨_, hb, subset_union_right _ _⟩⟩
/- To prove that the topology defined by the uniform structure on the disjoint union coincides with
the disjoint union topology, we need two lemmas saying that open sets can be characterized by
the uniform structure -/
lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) :
{ p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity :=
begin
cases x,
{ refine mem_of_superset
(union_mem_uniformity_sum (mem_nhds_uniformity_iff_right.1 (is_open.mem_nhds hs.1 xs))
univ_mem)
(union_subset _ _);
rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩,
exact h rfl },
{ refine mem_of_superset
(union_mem_uniformity_sum univ_mem (mem_nhds_uniformity_iff_right.1
(is_open.mem_nhds hs.2 xs)))
(union_subset _ _);
rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩,
exact h rfl },
end
lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)}
(hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈
(@uniform_space.core.sum α β _ _).uniformity) :
is_open s :=
begin
split,
{ refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff_right.2 _),
rcases mem_map_iff_exists_image.1 (hs _ ha).1 with ⟨t, ht, st⟩,
refine mem_of_superset ht _,
rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl },
{ refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff_right.2 _),
rcases mem_map_iff_exists_image.1 (hs _ hb).2 with ⟨t, ht, st⟩,
refine mem_of_superset ht _,
rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }
end
/- We can now define the uniform structure on the disjoint union -/
instance sum.uniform_space : uniform_space (α ⊕ β) :=
{ to_core := uniform_space.core.sum,
is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ }
lemma sum.uniformity : 𝓤 (α ⊕ β) =
map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔
map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl
end sum
end constructions
-- For a version of the Lebesgue number lemma assuming only a sequentially compact space,
-- see topology/sequences.lean
/-- Let `c : ι → set α` be an open cover of a compact set `s`. Then there exists an entourage
`n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `c i`. -/
lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α}
(hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i :=
begin
let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ m ○ n} ⊆ c i},
have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n),
{ refine λ n hn, is_open_uniformity.2 _,
rintro x ⟨i, m, hm, h⟩,
rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩,
apply (𝓤 α).sets_of_superset hm',
rintros ⟨x, y⟩ hp rfl,
refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩,
dsimp [-mem_comp_rel] at hz ⊢, rw comp_rel_assoc,
exact ⟨y, hp, hz⟩ },
have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n,
{ intros x hx,
rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩,
rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩,
exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ },
rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩,
refine ⟨_, (bInter_mem b_fin).2 bu, λ x hx, _⟩,
rcases mem_Union₂.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩,
refine ⟨i, λ y hy, h _⟩,
exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy)
end
/-- Let `c : set (set α)` be an open cover of a compact set `s`. Then there exists an entourage
`n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `t ∈ c`. -/
lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)}
(hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma hs (by simpa) hc₂
/-- A useful consequence of the Lebesgue number lemma: given any compact set `K` contained in an
open set `U`, we can find an (open) entourage `V` such that the ball of size `V` about any point of
`K` is contained in `U`. -/
lemma lebesgue_number_of_compact_open [uniform_space α]
{K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) :
∃ V ∈ 𝓤 α, is_open V ∧ ∀ x ∈ K, uniform_space.ball x V ⊆ U :=
begin
let W : K → set (α × α) := λ k, classical.some $ is_open_iff_open_ball_subset.mp hU k.1 $ hKU k.2,
have hW : ∀ k, W k ∈ 𝓤 α ∧ is_open (W k) ∧ uniform_space.ball k.1 (W k) ⊆ U,
{ intros k,
obtain ⟨h₁, h₂, h₃⟩ := classical.some_spec (is_open_iff_open_ball_subset.mp hU k.1 (hKU k.2)),
exact ⟨h₁, h₂, h₃⟩, },
let c : K → set α := λ k, uniform_space.ball k.1 (W k),
have hc₁ : ∀ k, is_open (c k), { exact λ k, uniform_space.is_open_ball k.1 (hW k).2.1, },
have hc₂ : K ⊆ ⋃ i, c i,
{ intros k hk,
simp only [mem_Union, set_coe.exists],
exact ⟨k, hk, uniform_space.mem_ball_self k (hW ⟨k, hk⟩).1⟩, },
have hc₃ : ∀ k, c k ⊆ U, { exact λ k, (hW k).2.2, },
obtain ⟨V, hV, hV'⟩ := lebesgue_number_lemma hK hc₁ hc₂,
refine ⟨interior V, interior_mem_uniformity hV, is_open_interior, _⟩,
intros k hk,
obtain ⟨k', hk'⟩ := hV' k hk,
exact ((ball_mono interior_subset k).trans hk').trans (hc₃ k'),
end
/-!
### Expressing continuity properties in uniform spaces
We reformulate the various continuity properties of functions taking values in a uniform space
in terms of the uniformity in the target. Since the same lemmas (essentially with the same names)
also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or
the edistance in the target), we put them in a namespace `uniform` here.
In the metric and emetric space setting, there are also similar lemmas where one assumes that
both the source and the target are metric spaces, reformulating things in terms of the distance
on both sides. These lemmas are generally written without primes, and the versions where only
the target is a metric space is primed. We follow the same convention here, thus giving lemmas
with primes.
-/
namespace uniform
variables [uniform_space α]
theorem tendsto_nhds_right {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ tendsto (λ x, (a, u x)) f (𝓤 α) :=
⟨λ H, tendsto_left_nhds_uniformity.comp H,
λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_right.1 hs)⟩
theorem tendsto_nhds_left {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ tendsto (λ x, (u x, a)) f (𝓤 α) :=
⟨λ H, tendsto_right_nhds_uniformity.comp H,
λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_left.1 hs)⟩
theorem continuous_at_iff'_right [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) :=
by rw [continuous_at, tendsto_nhds_right]
theorem continuous_at_iff'_left [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) :=
by rw [continuous_at, tendsto_nhds_left]
theorem continuous_at_iff_prod [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔ tendsto (λ x : β × β, (f x.1, f x.2)) (𝓝 (b, b)) (𝓤 α) :=
⟨λ H, le_trans (H.prod_map' H) (nhds_le_uniformity _),
λ H, continuous_at_iff'_left.2 $ H.comp $ tendsto_id.prod_mk_nhds tendsto_const_nhds⟩
theorem continuous_within_at_iff'_right [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔ tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) :=
by rw [continuous_within_at, tendsto_nhds_right]
theorem continuous_within_at_iff'_left [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔ tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) :=
by rw [continuous_within_at, tendsto_nhds_left]
theorem continuous_on_iff'_right [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) :=
by simp [continuous_on, continuous_within_at_iff'_right]
theorem continuous_on_iff'_left [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) :=
by simp [continuous_on, continuous_within_at_iff'_left]
theorem continuous_iff'_right [topological_space β] {f : β → α} :
continuous f ↔ ∀ b, tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_right
theorem continuous_iff'_left [topological_space β] {f : β → α} :
continuous f ↔ ∀ b, tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_left
end uniform
lemma filter.tendsto.congr_uniformity {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β}
(hf : tendsto f l (𝓝 b)) (hg : tendsto (λ x, (f x, g x)) l (𝓤 β)) :
tendsto g l (𝓝 b) :=
uniform.tendsto_nhds_right.2 $ (uniform.tendsto_nhds_right.1 hf).uniformity_trans hg
lemma uniform.tendsto_congr {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β}
(hfg : tendsto (λ x, (f x, g x)) l (𝓤 β)) :
tendsto f l (𝓝 b) ↔ tendsto g l (𝓝 b) :=
⟨λ h, h.congr_uniformity hfg, λ h, h.congr_uniformity hfg.uniformity_symm⟩
|
3afa1f2ebaacea88a2ab38b42be57fab843fab88 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/simpImpLocal.lean | ae3d91eb45ef631d0372aada13c3feb440bdd3d2 | [
"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 | 340 | lean | theorem ex [Add α]
(assoc : {a b c : α} → a + b + c = a + (b + c))
(comm : {a b : α} → a + b = b + a)
(f : α → α) (x y z : α) : f (x + (y + z)) = f (y + (x + z)) := by
let leftAssoc {a b c : α} : a + (b + c) = b + (a + c) := by
rw [← assoc, comm (a := a), assoc]
simp [leftAssoc]
|
5226869a72f77fa6d35c9dd03ceea077ce35fa67 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/int/succ_pred.lean | 0c68e9c46f7d82a37ba533076994c16657bbaa8e | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 2,369 | lean | /-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.int.order.basic
import data.nat.succ_pred
/-!
# Successors and predecessors of integers
In this file, we show that `ℤ` is both an archimedean `succ_order` and an archimedean `pred_order`.
-/
open function order
namespace int
@[reducible] -- so that Lean reads `int.succ` through `succ_order.succ`
instance : succ_order ℤ :=
{ succ := succ,
..succ_order.of_succ_le_iff succ (λ a b, iff.rfl) }
@[reducible] -- so that Lean reads `int.pred` through `pred_order.pred`
instance : pred_order ℤ :=
{ pred := pred,
pred_le := λ a, (sub_one_lt_of_le le_rfl).le,
min_of_le_pred := λ a ha, ((sub_one_lt_of_le le_rfl).not_le ha).elim,
le_pred_of_lt := λ a b, le_sub_one_of_lt,
le_of_pred_lt := λ a b, le_of_sub_one_lt }
@[simp] lemma succ_eq_succ : order.succ = succ := rfl
@[simp] lemma pred_eq_pred : order.pred = pred := rfl
lemma pos_iff_one_le {a : ℤ} : 0 < a ↔ 1 ≤ a := order.succ_le_iff.symm
lemma succ_iterate (a : ℤ) : ∀ n, succ^[n] a = a + n
| 0 := (add_zero a).symm
| (n + 1) := by { rw [function.iterate_succ', int.coe_nat_succ, ←add_assoc],
exact congr_arg _ (succ_iterate n) }
lemma pred_iterate (a : ℤ) : ∀ n, pred^[n] a = a - n
| 0 := (sub_zero a).symm
| (n + 1) := by { rw [function.iterate_succ', int.coe_nat_succ, ←sub_sub],
exact congr_arg _ (pred_iterate n) }
instance : is_succ_archimedean ℤ :=
⟨λ a b h, ⟨(b - a).to_nat,
by rw [succ_eq_succ, succ_iterate, to_nat_sub_of_le h, ←add_sub_assoc, add_sub_cancel']⟩⟩
instance : is_pred_archimedean ℤ :=
⟨λ a b h, ⟨(b - a).to_nat, by rw [pred_eq_pred, pred_iterate, to_nat_sub_of_le h, sub_sub_cancel]⟩⟩
/-! ### Covering relation -/
protected lemma covby_iff_succ_eq {m n : ℤ} : m ⋖ n ↔ m + 1 = n := succ_eq_iff_covby.symm
@[simp] lemma sub_one_covby (z : ℤ) : z - 1 ⋖ z :=
by rw [int.covby_iff_succ_eq, sub_add_cancel]
@[simp] lemma covby_add_one (z : ℤ) : z ⋖ z + 1 :=
int.covby_iff_succ_eq.mpr rfl
end int
@[simp, norm_cast] lemma nat.cast_int_covby_iff {a b : ℕ} : (a : ℤ) ⋖ b ↔ a ⋖ b :=
by { rw [nat.covby_iff_succ_eq, int.covby_iff_succ_eq], exact int.coe_nat_inj' }
alias nat.cast_int_covby_iff ↔ _ covby.cast_int
|
9dc0e83ed60c7a23d7462d94853a54cea76102ad | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Elab/Quotation.lean | 0d1603ff0272b473dc7e05b41f8a3506e6a244bd | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 32,404 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
Elaboration of syntax quotations as terms and patterns (in `match_syntax`). See also `./Hygiene.lean` for the basic
hygiene workings and data types. -/
import Lean.Syntax
import Lean.ResolveName
import Lean.Elab.Term
import Lean.Elab.Quotation.Util
import Lean.Elab.Quotation.Precheck
import Lean.Parser.Term
namespace Lean.Elab.Term.Quotation
open Lean.Parser.Term
open Lean.Syntax
open Meta
open TSyntax.Compat
/-- `C[$(e)]` ~> `let a := e; C[$a]`. Used in the implementation of antiquot splices. -/
private partial def floatOutAntiquotTerms (stx : Syntax) : StateT (Syntax → TermElabM Syntax) TermElabM Syntax :=
if isAntiquots stx && !isEscapedAntiquot (getCanonicalAntiquot stx) then
let e := getAntiquotTerm (getCanonicalAntiquot stx)
if !e.isIdent || !e.getId.isAtomic then
withFreshMacroScope do
let a ← `(a)
modify (fun _ (stx : Syntax) => (`(let $a:ident := $e; $stx) : TermElabM Syntax))
let stx := if stx.isOfKind choiceKind then
mkNullNode <| stx.getArgs.map (·.setArg 2 a)
else
stx.setArg 2 a
return stx
else
return stx
else if let Syntax.node i k args := stx then
return Syntax.node i k (← args.mapM floatOutAntiquotTerms)
else
return stx
private def getSepFromSplice (splice : Syntax) : String :=
if let Syntax.atom _ sep := getAntiquotSpliceSuffix splice then
sep.dropRight 1 -- drop trailing *
else
unreachable!
private def getSepStxFromSplice (splice : Syntax) : Syntax := Unhygienic.run do
match getSepFromSplice splice with
| "" => `(mkNullNode) -- sepByIdent uses the null node for separator-less enumerations
| sep => `(mkAtom $(Syntax.mkStrLit sep))
partial def mkTuple : Array Syntax → TermElabM Syntax
| #[] => `(Unit.unit)
| #[e] => return e
| es => do
let stx ← mkTuple (es.eraseIdx 0)
`(Prod.mk $(es[0]!) $stx)
def resolveSectionVariable (sectionVars : NameMap Name) (id : Name) : List (Name × List String) :=
-- decode macro scopes from name before recursion
let extractionResult := extractMacroScopes id
let rec loop : Name → List String → List (Name × List String)
| id@(.str p s), projs =>
-- NOTE: we assume that macro scopes always belong to the projected constant, not the projections
let id := { extractionResult with name := id }.review
match sectionVars.find? id with
| some newId => [(newId, projs)]
| none => loop p (s::projs)
| _, _ => []
loop extractionResult.name []
/-- Transform sequence of pushes and appends into acceptable code -/
def ArrayStxBuilder := Sum (Array Term) Term
namespace ArrayStxBuilder
def empty : ArrayStxBuilder := Sum.inl #[]
def build : ArrayStxBuilder → Term
| Sum.inl elems => quote elems
| Sum.inr arr => arr
def push (b : ArrayStxBuilder) (elem : Syntax) : ArrayStxBuilder :=
match b with
| Sum.inl elems => Sum.inl <| elems.push elem
| Sum.inr arr => Sum.inr <| mkCApp ``Array.push #[arr, elem]
def append (b : ArrayStxBuilder) (arr : Syntax) (appendName := ``Array.append) : ArrayStxBuilder :=
Sum.inr <| mkCApp appendName #[b.build, arr]
end ArrayStxBuilder
def tryAddSyntaxNodeKindInfo (stx : Syntax) (k : SyntaxNodeKind) : TermElabM Unit := do
if (← getEnv).contains k then
addTermInfo' stx (← mkConstWithFreshMVarLevels k)
else
-- HACK to support built in categories, which use a different naming convention
let k := ``Lean.Parser.Category ++ k
if (← getEnv).contains k then
addTermInfo' stx (← mkConstWithFreshMVarLevels k)
/-- Elaborate the content of a syntax quotation term -/
private partial def quoteSyntax : Syntax → TermElabM Term
| Syntax.ident _ rawVal val preresolved => do
if !hygiene.get (← getOptions) then
return ← `(Syntax.ident info $(quote rawVal) $(quote val) $(quote preresolved))
-- Add global scopes at compilation time (now), add macro scope at runtime (in the quotation).
-- See the paper for details.
let r ← resolveGlobalName val
-- extension of the paper algorithm: also store unique section variable names as top-level scopes
-- so they can be captured and used inside the section, but not outside
let r' := resolveSectionVariable (← read).sectionVars val
let preresolved := r ++ r' ++ preresolved
let val := quote val
-- `scp` is bound in stxQuot.expand
`(Syntax.ident info $(quote rawVal) (addMacroScope mainModule $val scp) $(quote preresolved))
-- if antiquotation, insert contents as-is, else recurse
| stx@(Syntax.node _ k _) => do
if let some (k, _) := stx.antiquotKind? then
if let some name := getAntiquotKindSpec? stx then
tryAddSyntaxNodeKindInfo name k
if isAntiquots stx && !isEscapedAntiquot (getCanonicalAntiquot stx) then
let ks := antiquotKinds stx
`(@TSyntax.raw $(quote <| ks.map (·.1)) $(getAntiquotTerm (getCanonicalAntiquot stx)))
else if isTokenAntiquot stx && !isEscapedAntiquot stx then
match stx[0] with
| Syntax.atom _ val => `(Syntax.atom (SourceInfo.fromRef $(getAntiquotTerm stx)) $(quote val))
| _ => throwErrorAt stx "expected token"
else if isAntiquotSuffixSplice stx && !isEscapedAntiquot (getCanonicalAntiquot (getAntiquotSuffixSpliceInner stx)) then
-- splices must occur in a `many` node
throwErrorAt stx "unexpected antiquotation splice"
else if isAntiquotSplice stx && !isEscapedAntiquot stx then
throwErrorAt stx "unexpected antiquotation splice"
else
-- if escaped antiquotation, decrement by one escape level
let stx := unescapeAntiquot stx
let mut args := ArrayStxBuilder.empty
let appendName := if (← getEnv).contains ``Array.append then ``Array.append else ``Array.appendCore
for arg in stx.getArgs do
if k == nullKind && isAntiquotSuffixSplice arg && !isEscapedAntiquot (getCanonicalAntiquot (getAntiquotSuffixSpliceInner arg)) then
let antiquot := getAntiquotSuffixSpliceInner arg
let ks := antiquotKinds antiquot |>.map (·.1)
let val := getAntiquotTerm (getCanonicalAntiquot antiquot)
args := args.append (appendName := appendName) <| ←
match antiquotSuffixSplice? arg with
| `optional => `(match Option.map (@TSyntax.raw $(quote ks)) $val:term with
| some x => Array.empty.push x
| none => Array.empty)
| `many => `(@TSyntaxArray.raw $(quote ks) $val)
| `sepBy =>
let sep := quote <| getSepFromSplice arg
`(@TSepArray.elemsAndSeps $(quote ks) $sep $val)
| k => throwErrorAt arg "invalid antiquotation suffix splice kind '{k}'"
else if k == nullKind && isAntiquotSplice arg && !isEscapedAntiquot arg then
let k := antiquotSpliceKind? arg
let (arg, bindLets) ← floatOutAntiquotTerms arg |>.run pure
let inner ← (getAntiquotSpliceContents arg).mapM quoteSyntax
let ids ← getAntiquotationIds arg
if ids.isEmpty then
throwErrorAt stx "antiquotation splice must contain at least one antiquotation"
let arr ← match k with
| `optional => `(match $[$ids:ident],* with
| $[some $ids:ident],* => $(quote inner)
| $[_%$ids],* => Array.empty)
| _ =>
let arr ← ids[:ids.size-1].foldrM (fun id arr => `(Array.zip $id:ident $arr)) ids.back
`(Array.map (fun $(← mkTuple ids) => $(inner[0]!)) $arr)
let arr ← if k == `sepBy then
`(mkSepArray $arr $(getSepStxFromSplice arg))
else
pure arr
let arr ← bindLets arr
args := args.append (appendName := appendName) arr
else do
let arg ← quoteSyntax arg
args := args.push arg
`(Syntax.node info $(quote k) $(args.build))
| Syntax.atom _ val =>
`(Syntax.atom info $(quote val))
| Syntax.missing => throwUnsupportedSyntax
def addNamedQuotInfo (stx : Syntax) (k : SyntaxNodeKind) : TermElabM SyntaxNodeKind := do
if stx.getNumArgs == 3 && stx[0].isAtom then
let s := stx[0].getAtomVal!
if s.length > 3 then
if let (some l, some r) := (stx[0].getPos? true, stx[0].getTailPos? true) then
-- HACK: The atom is the string "`(foo|", so chop off the edges.
-- HACK: We have to use .original here or the hover won't show up
let name := stx[0].setInfo <| .original default ⟨l.1 + 2⟩ default ⟨r.1 - 1⟩
tryAddSyntaxNodeKindInfo name k
pure k
def getQuotKind (stx : Syntax) : TermElabM SyntaxNodeKind := do
match stx.getKind with
| ``Parser.Command.quot => addNamedQuotInfo stx `command
| ``Parser.Term.quot => addNamedQuotInfo stx `term
| ``Parser.Level.quot => addNamedQuotInfo stx `level
| ``Parser.Tactic.quot => addNamedQuotInfo stx `tactic
| ``Parser.Tactic.quotSeq => addNamedQuotInfo stx `tactic.seq
| ``Parser.Term.stx.quot => addNamedQuotInfo stx `stx
| ``Parser.Term.prec.quot => addNamedQuotInfo stx `prec
| ``Parser.Term.attr.quot => addNamedQuotInfo stx `attr
| ``Parser.Term.prio.quot => addNamedQuotInfo stx `prio
| ``Parser.Term.doElem.quot => addNamedQuotInfo stx `doElem
| .str kind "quot" => addNamedQuotInfo stx kind
| ``dynamicQuot =>
match (← resolveGlobalConstWithInfos stx[1]) with
| [parser] => pure parser
| _ => throwError "unknown parser {stx[1]}"
| k => throwError "unexpected quotation kind {k}"
def stxQuot.expand (stx : Syntax) : TermElabM Syntax := do
let stx := if stx.getNumArgs == 1 then stx[0] else stx
/- Syntax quotations are monadic values depending on the current macro scope. For efficiency, we bind
the macro scope once for each quotation, then build the syntax tree in a completely pure computation
depending on this binding. Note that regular function calls do not introduce a new macro scope (i.e.
we preserve referential transparency), so we can refer to this same `scp` inside `quoteSyntax` by
including it literally in a syntax quotation. -/
let kind ← getQuotKind stx
let stx ← quoteSyntax stx.getQuotContent
`(Bind.bind MonadRef.mkInfoFromRefPos (fun info =>
Bind.bind getCurrMacroScope (fun scp =>
Bind.bind getMainModule (fun mainModule => Pure.pure (@TSyntax.mk $(quote kind) $stx)))))
/- NOTE: It may seem like the newly introduced binding `scp` may accidentally
capture identifiers in an antiquotation introduced by `quoteSyntax`. However,
note that the syntax quotation above enjoys the same hygiene guarantees as
anywhere else in Lean; that is, we implement hygienic quotations by making
use of the hygienic quotation support of the bootstrapped Lean compiler!
Aside: While this might sound "dangerous", it is in fact less reliant on a
"chain of trust" than other bootstrapping parts of Lean: because this
implementation itself never uses `scp` (or any other identifier) both inside
and outside quotations, it can actually correctly be compiled by an
unhygienic (but otherwise correct) implementation of syntax quotations. As
long as it is then compiled again with the resulting executable (i.e. up to
stage 2), the result is a correct hygienic implementation. In this sense the
implementation is "self-stabilizing". It was in fact originally compiled
by an unhygienic prototype implementation. -/
macro "elab_stx_quot" kind:ident : command =>
`(@[builtinTermElab $kind:ident] def elabQuot : TermElab := adaptExpander stxQuot.expand)
--
elab_stx_quot Parser.Level.quot
elab_stx_quot Parser.Term.quot
elab_stx_quot Parser.Term.funBinder.quot
elab_stx_quot Parser.Term.bracketedBinder.quot
elab_stx_quot Parser.Term.matchDiscr.quot
elab_stx_quot Parser.Tactic.quot
elab_stx_quot Parser.Tactic.quotSeq
elab_stx_quot Parser.Term.stx.quot
elab_stx_quot Parser.Term.prec.quot
elab_stx_quot Parser.Term.attr.quot
elab_stx_quot Parser.Term.prio.quot
elab_stx_quot Parser.Term.doElem.quot
elab_stx_quot Parser.Term.dynamicQuot
elab_stx_quot Parser.Command.quot
/-! # match -/
/-- an "alternative" of patterns plus right-hand side -/
private abbrev Alt := List Term × Term
/--
In a single match step, we match the first discriminant against the "head" of the first pattern of the first
alternative. This datatype describes what kind of check this involves, which helps other patterns decide if
they are covered by the same check and don't have to be checked again (see also `MatchResult`). -/
inductive HeadCheck where
| /-- match step that always succeeds: _, x, `($x), ... -/
unconditional
| /-- match step based on kind and, optionally, arity of discriminant
If `arity` is given, that number of new discriminants is introduced. `covered` patterns should then introduce the
same number of new patterns.
We actually check the arity at run time only in the case of `null` nodes since it should otherwise by implied by
the node kind.
without arity: `($x:k)
with arity: any quotation without an antiquotation head pattern -/
shape (k : List SyntaxNodeKind) (arity : Option Nat)
| /-- Match step that succeeds on `null` nodes of arity at least `numPrefix + numSuffix`, introducing discriminants
for the first `numPrefix` children, one `null` node for those in between, and for the `numSuffix` last children.
example: `([$x, $xs,*, $y]) is `slice 2 2` -/
slice (numPrefix numSuffix : Nat)
| /-- other, complicated match step that will probably only cover identical patterns
example: antiquotation splices `($[...]*) -/
other (pat : Syntax)
open HeadCheck
/-- Describe whether a pattern is covered by a head check (induced by the pattern itself or a different pattern). -/
inductive MatchResult where
| /-- Pattern agrees with head check, remove and transform remaining alternative.
If `exhaustive` is `false`, *also* include unchanged alternative in the "no" branch. -/
covered (f : Alt → TermElabM Alt) (exhaustive : Bool)
| /-- Pattern disagrees with head check, include in "no" branch only -/
uncovered
| /-- Pattern is not quite sure yet; include unchanged in both branches -/
undecided
open MatchResult
/-- All necessary information on a pattern head. -/
structure HeadInfo where
/-- check induced by the pattern -/
check : HeadCheck
/-- compute compatibility of pattern with given head check -/
onMatch (taken : HeadCheck) : MatchResult
/-- actually run the specified head check, with the discriminant bound to `discr` -/
doMatch (yes : (newDiscrs : List Term) → TermElabM Term) (no : TermElabM Term) : TermElabM Term
/-- Adapt alternatives that do not introduce new discriminants in `doMatch`, but are covered by those that do so. -/
private def noOpMatchAdaptPats : HeadCheck → Alt → Alt
| shape _ (some sz), (pats, rhs) => (List.replicate sz (Unhygienic.run `(_)) ++ pats, rhs)
| slice p s, (pats, rhs) => (List.replicate (p + 1 + s) (Unhygienic.run `(_)) ++ pats, rhs)
| _, alt => alt
private def adaptRhs (fn : Term → TermElabM Term) : Alt → TermElabM Alt
| (pats, rhs) => return (pats, ← fn rhs)
private partial def getHeadInfo (alt : Alt) : TermElabM HeadInfo :=
let pat := alt.fst.head!
let unconditionally rhsFn := pure {
check := unconditional,
doMatch := fun yes _ => yes [],
onMatch := fun taken => covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (taken matches unconditional)
}
-- quotation pattern
if isQuot pat then do
let quoted := getQuotContent pat
if let some (k, _) := quoted.antiquotKind? then
if let some name := getAntiquotKindSpec? quoted then
tryAddSyntaxNodeKindInfo name k
if quoted.isAtom then
-- We assume that atoms are uniquely determined by the node kind and never have to be checked
unconditionally pure
else if quoted.isTokenAntiquot then
unconditionally (`(let $(quoted.getAntiquotTerm) := discr; $(·)))
else if isAntiquots quoted && !isEscapedAntiquot (getCanonicalAntiquot quoted) then
-- quotation contains a single antiquotation
let (ks, pseudoKinds) := antiquotKinds quoted |>.unzip
let rhsFn := match getAntiquotTerm (getCanonicalAntiquot quoted) with
| `(_) => pure
| `($id:ident) => fun stx => `(let $id := @TSyntax.mk $(quote ks) discr; $(stx))
| anti => fun _ => throwErrorAt anti "unsupported antiquotation kind in pattern"
-- Antiquotation kinds like `$id:ident` influence the parser, but also need to be considered by
-- `match` (but not by quotation terms). For example, `($id:ident) and `($e) are not
-- distinguishable without checking the kind of the node to be captured. Note that some
-- antiquotations like the latter one for terms do not correspond to any actual node kind,
-- so we would only check for `ident` here.
--
-- if stx.isOfKind `ident then
-- let id := stx; let e := stx; ...
-- else
-- let e := stx; ...
if (getCanonicalAntiquot quoted)[3].isNone || pseudoKinds.all id then unconditionally rhsFn else pure {
check := shape ks none,
onMatch := fun
| other _ => undecided
| taken@(shape ks' sz) =>
if ks' == ks then
covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (exhaustive := sz.isNone)
else uncovered
| _ => uncovered,
doMatch := fun yes no => do
let cond ← ks.foldlM (fun cond k => `(or $cond (Syntax.isOfKind discr $(quote k)))) (← `(false))
`(cond $cond $(← yes []) $(← no)),
}
else if isAntiquotSuffixSplice quoted then throwErrorAt quoted "unexpected antiquotation splice"
else if isAntiquotSplice quoted then throwErrorAt quoted "unexpected antiquotation splice"
else if quoted.getArgs.size == 1 && isAntiquotSuffixSplice quoted[0] then
let inner := getAntiquotSuffixSpliceInner quoted[0]
let anti := getAntiquotTerm (getCanonicalAntiquot inner)
let ks := antiquotKinds inner |>.map (·.1)
unconditionally fun rhs => match antiquotSuffixSplice? quoted[0] with
| `optional => `(let $anti := Option.map (@TSyntax.mk $(quote ks)) (Syntax.getOptional? discr); $rhs)
| `many => `(let $anti := @TSyntaxArray.mk $(quote ks) (Syntax.getArgs discr); $rhs)
| `sepBy => `(let $anti := @TSepArray.mk $(quote ks) $(quote <| getSepFromSplice quoted[0]) (Syntax.getArgs discr); $rhs)
| k => throwErrorAt quoted "invalid antiquotation suffix splice kind '{k}'"
else if quoted.getArgs.size == 1 && isAntiquotSplice quoted[0] then pure {
check := other pat,
onMatch := fun
| other pat' => if pat' == pat then covered pure (exhaustive := true) else undecided
| _ => undecided,
doMatch := fun yes no => do
let splice := quoted[0]
let k := antiquotSpliceKind? splice
let contents := getAntiquotSpliceContents splice
let ids ← getAntiquotationIds splice
let yes ← yes []
let no ← no
match k with
| `optional =>
let nones := mkArray ids.size (← `(none))
`(let_delayed yes _ $ids* := $yes;
if discr.isNone then yes () $[ $nones]*
else match discr with
| `($(mkNullNode contents)) => yes () $[ (some $ids)]*
| _ => $no)
| _ =>
let mut discrs ← `(Syntax.getArgs discr)
if k == `sepBy then
discrs ← `(Array.getSepElems $discrs)
let tuple ← mkTuple ids
let mut yes := yes
let resId ← match ids with
| #[id] => pure id
| _ =>
for id in ids do
yes ← `(let $id := tuples.map (fun $tuple => $id); $yes)
`(tuples)
let contents := if contents.size == 1
then contents[0]!
else mkNullNode contents
-- We use `no_error_if_unused%` in auxiliary `match`-syntax to avoid spurious error messages,
-- the outer `match` is checking for unused alternatives
`(match ($(discrs).sequenceMap fun
| `($contents) => no_error_if_unused% some $tuple
| _ => no_error_if_unused% none) with
| some $resId => $yes
| none => $no)
}
else if let some idx := quoted.getArgs.findIdx? (fun arg => isAntiquotSuffixSplice arg || isAntiquotSplice arg) then do
/-
patterns of the form `match discr, ... with | `(pat_0 ... pat_(idx-1) $[...]* pat_(idx+1) ...), ...`
transform to
```
if discr.getNumArgs >= $quoted.getNumArgs - 1 then
match discr[0], ..., discr[idx-1], mkNullNode (discr.getArgs.extract idx (discr.getNumArgs - $numSuffix))), ..., discr[quoted.getNumArgs - 1] with
| `(pat_0), ... `(pat_(idx-1)), `($[...])*, `(pat_(idx+1)), ...
```
-/
let numSuffix := quoted.getNumArgs - 1 - idx
pure {
check := slice idx numSuffix
onMatch := fun
| other _ => undecided
| slice p s =>
if p == idx && s == numSuffix then
let argPats := quoted.getArgs.mapIdx fun i arg =>
let arg := if (i : Nat) == idx then mkNullNode #[arg] else arg
Unhygienic.run `(`($(arg)))
covered (fun (pats, rhs) => pure (argPats.toList ++ pats, rhs)) (exhaustive := true)
else uncovered
| _ => uncovered
doMatch := fun yes no => do
let prefixDiscrs ← (List.range idx).mapM (`(Syntax.getArg discr $(quote ·)))
let sliceDiscr ← `(mkNullNode (discr.getArgs.extract $(quote idx) (discr.getNumArgs - $(quote numSuffix))))
let suffixDiscrs ← (List.range numSuffix).mapM fun i =>
`(Syntax.getArg discr (discr.getNumArgs - $(quote (numSuffix - i))))
`(ite (GE.ge discr.getNumArgs $(quote (quoted.getNumArgs - 1)))
$(← yes (prefixDiscrs ++ sliceDiscr :: suffixDiscrs))
$(← no))
}
else
-- not an antiquotation, or an escaped antiquotation: match head shape
let quoted := unescapeAntiquot quoted
let kind := quoted.getKind
let lit := isLitKind kind
let argPats := quoted.getArgs.map fun arg => Unhygienic.run `(`($(arg)))
pure {
check :=
-- Atoms are matched only within literals because it would be a waste of time for keywords
-- such as `if` and `then` and would blow up the generated code.
-- See also `elabMatchSyntax` docstring below.
if quoted.isIdent || lit then
-- NOTE: We could make this case split more precise by refining `HeadCheck`,
-- but matching on literals is quite rare.
other quoted
else
shape [kind] argPats.size,
onMatch := fun
| other stx' =>
if (quoted.isIdent || lit) && quoted == stx' then
covered pure (exhaustive := true)
else
uncovered
| shape ks sz =>
if ks == [kind] && sz == argPats.size then
covered (fun (pats, rhs) => pure (argPats.toList ++ pats, rhs)) (exhaustive := true)
else
uncovered
| _ => uncovered,
doMatch := fun yes no => do
let (cond, newDiscrs) ← if lit then
let cond ← `(Syntax.matchesLit discr $(quote kind) $(quote (isLit? kind quoted).get!))
pure (cond, [])
else
let cond ← match kind with
| `null => `(Syntax.matchesNull discr $(quote argPats.size))
| `ident => `(Syntax.matchesIdent discr $(quote quoted.getId))
| _ => `(Syntax.isOfKind discr $(quote kind))
let newDiscrs ← (List.range argPats.size).mapM fun i => `(Syntax.getArg discr $(quote i))
pure (cond, newDiscrs)
`(ite (Eq $cond true) $(← yes newDiscrs) $(← no))
}
else match pat with
| `(_) => unconditionally pure
| `($id:ident) => unconditionally (`(let $id := discr; $(·)))
| `($id:ident@$pat) => do
let info ← getHeadInfo (pat::alt.1.tail!, alt.2)
return { info with onMatch := fun taken => match info.onMatch taken with
| covered f exh => covered (fun alt => f alt >>= adaptRhs (`(let $id := discr; $(·)))) exh
| r => r }
| _ => throwErrorAt pat "match (syntax) : unexpected pattern kind {pat}"
/-- Bind right-hand side to new `let_delayed` decl in order to prevent code duplication -/
private def deduplicate (floatedLetDecls : Array Syntax) : Alt → TermElabM (Array Syntax × Alt)
-- NOTE: new macro scope so that introduced bindings do not collide
| (pats, rhs) => do
if let `($_:ident $[ $_:ident]*) := rhs then
-- looks simple enough/created by this function, skip
return (floatedLetDecls, (pats, rhs))
withFreshMacroScope do
match (← getPatternsVars pats.toArray) with
| #[] =>
-- no antiquotations => introduce Unit parameter to preserve evaluation order
let rhs' ← `(rhs Unit.unit)
pure (floatedLetDecls.push (← `(letDecl|rhs _ := $rhs)), (pats, rhs'))
| vars =>
let rhs' ← `(rhs $vars*)
pure (floatedLetDecls.push (← `(letDecl|rhs $vars:ident* := $rhs)), (pats, rhs'))
private partial def compileStxMatch (discrs : List Term) (alts : List Alt) : TermElabM Syntax := do
trace[Elab.match_syntax] "match {discrs} with {alts}"
match discrs, alts with
| [], ([], rhs)::_ => pure rhs -- nothing left to match
| _, [] =>
logError "non-exhaustive 'match' (syntax)"
pure Syntax.missing
| discr::discrs, alt::alts => do
let info ← getHeadInfo alt
let alts ← (alt::alts).mapM fun alt => return ((← getHeadInfo alt).onMatch info.check, alt)
let mut yesAlts := #[]
let mut undecidedAlts := #[]
let mut nonExhaustiveAlts := #[]
let mut floatedLetDecls := #[]
for (x, alt') in alts do
let mut alt' := alt'
match x with
| covered f exh =>
-- we can only factor out a common check if there are no undecided patterns in between;
-- otherwise we would change the order of alternatives
if undecidedAlts.isEmpty then
yesAlts ← yesAlts.push <$> f (alt'.1.tail!, alt'.2)
if !exh then
nonExhaustiveAlts := nonExhaustiveAlts.push alt'
else
(floatedLetDecls, alt') ← deduplicate floatedLetDecls alt'
undecidedAlts := undecidedAlts.push alt'
nonExhaustiveAlts := nonExhaustiveAlts.push alt'
| undecided =>
(floatedLetDecls, alt') ← deduplicate floatedLetDecls alt'
undecidedAlts := undecidedAlts.push alt'
nonExhaustiveAlts := nonExhaustiveAlts.push alt'
| uncovered =>
nonExhaustiveAlts := nonExhaustiveAlts.push alt'
let mut stx ← info.doMatch
(yes := fun newDiscrs => do
let mut yesAlts := yesAlts
if !undecidedAlts.isEmpty then
-- group undecided alternatives in a new default case `| discr2, ... => match discr, discr2, ... with ...`
let vars ← discrs.mapM fun _ => withFreshMacroScope `(discr)
let pats := List.replicate newDiscrs.length (Unhygienic.run `(_)) ++ vars
let alts ← undecidedAlts.mapM fun alt => `(matchAltExpr| | $(alt.1.toArray),* => no_error_if_unused% $(alt.2))
let rhs ← `(match discr, $[$(vars.toArray):term],* with $alts:matchAlt*)
yesAlts := yesAlts.push (pats, rhs)
withFreshMacroScope $ compileStxMatch (newDiscrs ++ discrs) yesAlts.toList)
(no := withFreshMacroScope $ compileStxMatch (discr::discrs) nonExhaustiveAlts.toList)
for d in floatedLetDecls do
stx ← `(let_delayed $d:letDecl; $stx)
`(let discr := $discr; $stx)
| _, _ => unreachable!
abbrev IdxSet := Std.HashSet Nat
/--
Given `rhss` the right-hand-sides of a `match`-syntax notation,
We tag them with with fresh identifiers `alt_idx`. We use them to detect whether an alternative
has been used or not.
The result is a triple `(altIdxMap, ignoreIfUnused, rhssNew)` where
- `altIdxMap` is a mapping from the `alt_idx` identifiers to right-hand-side indices.
That is, the map contains the entry `alt_idx ↦ i` if `alt_idx` was used to mark `rhss[i]`.
- `i ∈ ignoreIfUnused` if `rhss[i]` is marked with `no_error_if_unused%`
- `rhssNew` is the updated array of right-hand-sides.
-/
private def markRhss (rhss : Array Term) : TermElabM (NameMap Nat × IdxSet × Array Term) := do
let mut altIdxMap : NameMap Nat := {}
let mut ignoreIfUnused : IdxSet := {}
let mut rhssNew := #[]
for rhs in rhss do
match rhs with
| `(no_error_if_unused% $_ ) => ignoreIfUnused := ignoreIfUnused.insert rhssNew.size
| _ => pure ()
let (idx, rhs) ← withFreshMacroScope do
let idx ← `(alt_idx)
let rhs ← `(alt_idx $rhs)
return (idx, rhs)
altIdxMap := altIdxMap.insert idx.getId rhssNew.size
rhssNew := rhssNew.push rhs
return (altIdxMap, ignoreIfUnused, rhssNew)
/--
Given the mapping `idxMap` built using `markRhss`, and `stx` the resulting syntax after expanding `match`-syntax,
return the pair `(stxNew, usedSet)`, where `stxNew` is `stx` after removing the `alt_idx` markers in `idxMap`,
and `i ∈ usedSet` if `stx` contains an `alt_idx` s.t. `alt_idx ↦ i` is in `idxMap`.
That is, `usedSet` contains the index of the used match-syntax right-hand-sides.
-/
private partial def findUsedAlts (stx : Syntax) (altIdxMap : NameMap Nat) : TermElabM (Syntax × IdxSet) := do
go stx |>.run {}
where
go (stx : Syntax) : StateRefT IdxSet TermElabM Syntax := do
match stx with
| `($id:ident $rhs:term) =>
if let some idx := altIdxMap.find? id.getId then
modify fun s => s.insert idx
return rhs
| _ => pure ()
match stx with
| .node info kind cs => return .node info kind (← cs.mapM go)
| _ => return stx
/--
Check whether `stx` has unused alternatives, and remove the auxiliary `alt_idx` markers from it (see `markRhss`).
The parameter `alts` provides position information for alternatives.
`altIdxMap` and `ignoreIfUnused` are the map and set built using `markRhss`.
-/
private def checkUnusedAlts (stx : Syntax) (alts : Array Syntax) (altIdxMap : NameMap Nat) (ignoreIfUnused : IdxSet) : TermElabM Syntax := do
let (stx, used) ← findUsedAlts stx altIdxMap
for i in [:alts.size] do
unless used.contains i || ignoreIfUnused.contains i do
logErrorAt alts[i]! s!"redundant alternative #{i+1}"
return stx
def match_syntax.expand (stx : Syntax) : TermElabM Syntax := do
match stx with
| `(match $[$discrs:term],* with $[|%$alt $[$patss],* => $rhss]*) => do
if !patss.any (·.any (fun
| `($_@$pat) => pat.raw.isQuot
| pat => pat.raw.isQuot)) then
-- no quotations => fall back to regular `match`
throwUnsupportedSyntax
let (altIdxMap, ignoreIfUnused, rhss) ← markRhss rhss
-- call `getQuotKind` on all the patterns, which adds
-- term info for all `(foo| ...)` as a side effect
patss.forM (·.forM fun ⟨pat⟩ => do if pat.isQuot then _ ← getQuotKind pat)
let stx ← compileStxMatch discrs.toList (patss.map (·.toList) |>.zip rhss).toList
let stx ← checkUnusedAlts stx alt altIdxMap ignoreIfUnused
trace[Elab.match_syntax.result] "{stx}"
return stx
| _ => throwUnsupportedSyntax
@[builtinTermElab «match»] def elabMatchSyntax : TermElab :=
adaptExpander match_syntax.expand
@[builtinTermElab noErrorIfUnused] def elabNoErrorIfUnused : TermElab := fun stx expectedType? =>
match stx with
| `(no_error_if_unused% $term) => elabTerm term expectedType?
| _ => throwUnsupportedSyntax
builtin_initialize
registerTraceClass `Elab.match_syntax
registerTraceClass `Elab.match_syntax.result
end Lean.Elab.Term.Quotation
|
abad205a31ba7c1f27841bb4e57842988111184e | 12dabd587ce2621d9a4eff9f16e354d02e206c8e | /world07/level06.lean | efac2acece91c32a2fe0237f4b0721bad89092c5 | [] | no_license | abdelq/natural-number-game | a1b5b8f1d52625a7addcefc97c966d3f06a48263 | bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2 | refs/heads/master | 1,668,606,478,691 | 1,594,175,058,000 | 1,594,175,058,000 | 278,673,209 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 77 | lean | example (P Q : Prop) : Q → (P ∨ Q) :=
begin
intro q,
right,
exact q,
end
|
85bebe906f3613647377b0a5802a277966bf89b8 | 367134ba5a65885e863bdc4507601606690974c1 | /src/tactic/norm_fin.lean | 0a62dd6736b5a74bf612e9a94eba4417ab3dfc3d | [
"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 | 25,225 | lean | /-
Copyright (c) 2021 Yakov Pechersky All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky, Mario Carneiro
-/
import tactic.norm_num
/-!
# `norm_fin`
This file defines functions for dealing with `fin n` numbers as expressions.
## Main definitions
* `tactic.norm_fin.eval_ineq` is a `norm_num` plugin for normalizing equalities and inequalities of
type `fin n`.
* `tactic.interactive.norm_fin` is a standalone tactic like `norm_num` for normalizing `fin n`
expressions anywhere in the goal.
-/
namespace tactic
namespace norm_fin
open norm_num
/-- `normalize_fin n a b` means that `a : fin n` is equivalent to `b : ℕ` in the modular sense -
that is, `↑a ≡ b (mod n)`. This is used for translating the algebraic operations: addition,
multiplication, zero and one, which use modulo for reduction. -/
def normalize_fin (n : ℕ) (a : fin n) (b : ℕ) := a.1 = b % n
/-- `normalize_fin_lt n a b` means that `a : fin n` is equivalent to `b : ℕ` in the embedding
sense - that is, `↑a = b`. This is used for operations that treat `fin n` as the subset
`{0, ..., n-1}` of `ℕ`. For example, `fin.succ : fin n → fin (n+1)` is thought of as the successor
function, but it does not lift to a map `zmod n → zmod (n+1)`; this addition only makes sense if
the input is strictly less than `n`.
`normalize_fin_lt n a b` is equivalent to `normalize_fin n a b ∧ b < n`. -/
def normalize_fin_lt (n : ℕ) (a : fin n) (b : ℕ) := a.1 = b
theorem normalize_fin_lt.coe {n} {a : fin n} {b : ℕ} (h : normalize_fin_lt n a b) : ↑a = b := h
theorem normalize_fin_iff {n} [fact (0 < n)] {a b} :
normalize_fin n a b ↔ a = fin.of_nat' b :=
iff.symm (fin.eq_iff_veq _ _)
theorem normalize_fin_lt.mk {n a b n'} (hn : n = n')
(h : normalize_fin n a b) (h2 : b < n') : normalize_fin_lt n a b :=
h.trans $ nat.mod_eq_of_lt $ by rw hn; exact h2
theorem normalize_fin_lt.lt {n a b} (h : normalize_fin_lt n a b) : b < n :=
by rw ← h.coe; exact a.2
theorem normalize_fin_lt.of {n a b} (h : normalize_fin_lt n a b) : normalize_fin n a b :=
h.trans $ eq.symm $ nat.mod_eq_of_lt h.lt
theorem normalize_fin.zero (n) : normalize_fin (n+1) 0 0 := refl _
theorem normalize_fin_lt.zero (n) : normalize_fin_lt (n+1) 0 0 := refl _
theorem normalize_fin.one (n) : normalize_fin (n+1) 1 1 := refl _
theorem normalize_fin.add {n} {a b : fin n} {a' b' c' : ℕ}
(ha : normalize_fin n a a') (hb : normalize_fin n b b')
(h : a' + b' = c') : normalize_fin n (a + b) c' :=
by simp only [normalize_fin, ← h] at *; rw [nat.add_mod, ← ha, ← hb, fin.add_def]
theorem normalize_fin.mul {n} {a b : fin n} {a' b' c' : ℕ}
(ha : normalize_fin n a a') (hb : normalize_fin n b b')
(h : a' * b' = c') : normalize_fin n (a * b) c' :=
by simp only [normalize_fin, ← h] at *; rw [nat.mul_mod, ← ha, ← hb, fin.mul_def]
theorem normalize_fin.bit0 {n} {a : fin n} {a' : ℕ}
(h : normalize_fin n a a') : normalize_fin n (bit0 a) (bit0 a') := h.add h rfl
theorem normalize_fin.bit1 {n} {a : fin (n+1)} {a' : ℕ}
(h : normalize_fin (n+1) a a') : normalize_fin (n+1) (bit1 a) (bit1 a') :=
h.bit0.add (normalize_fin.one _) rfl
theorem normalize_fin_lt.succ {n} {a : fin n} {a' b : ℕ}
(h : normalize_fin_lt n a a') (e : a' + 1 = b) : normalize_fin_lt n.succ (fin.succ a) b :=
by simpa [normalize_fin_lt, ← e] using h
theorem normalize_fin_lt.cast_lt {n m} {a : fin m} {ha} {a' : ℕ}
(h : normalize_fin_lt m a a') : normalize_fin_lt n (fin.cast_lt a ha) a' :=
by simpa [normalize_fin_lt] using h
theorem normalize_fin_lt.cast_le {n m} {nm} {a : fin m} {a' : ℕ}
(h : normalize_fin_lt m a a') : normalize_fin_lt n (fin.cast_le nm a) a' :=
by simpa [normalize_fin_lt] using h
theorem normalize_fin_lt.cast {n m} {nm} {a : fin m} {a' : ℕ}
(h : normalize_fin_lt m a a') : normalize_fin_lt n (fin.cast nm a) a' :=
by simpa [normalize_fin_lt] using h
theorem normalize_fin.cast {n m} {nm} {a : fin m} {a' : ℕ}
(h : normalize_fin m a a') : normalize_fin n (fin.cast nm a) a' :=
by convert ← normalize_fin_lt.cast h
theorem normalize_fin_lt.cast_add {n m} {a : fin n} {a' : ℕ}
(h : normalize_fin_lt n a a') : normalize_fin_lt (n + m) (fin.cast_add m a) a' :=
by simpa [normalize_fin_lt] using h
theorem normalize_fin_lt.cast_succ {n} {a : fin n} {a' : ℕ}
(h : normalize_fin_lt n a a') : normalize_fin_lt (n+1) (fin.cast_succ a) a' :=
normalize_fin_lt.cast_add h
theorem normalize_fin_lt.add_nat {n m m'} (hm : m = m') {a : fin n} {a' b : ℕ}
(h : normalize_fin_lt n a a') (e : a' + m' = b) :
normalize_fin_lt (n+m) (@fin.add_nat n m a) b :=
by simpa [normalize_fin_lt, ← e, ← hm] using h
theorem normalize_fin_lt.nat_add {n m n'} (hn : n = n') {a : fin m} {a' b : ℕ}
(h : normalize_fin_lt m a a') (e : n' + a' = b) :
normalize_fin_lt (n+m) (@fin.nat_add n m a) b :=
by simpa [normalize_fin_lt, ← e, ← hn] using h
theorem normalize_fin.reduce {n} {a : fin n} {n' a' b k nk : ℕ}
(hn : n = n') (h : normalize_fin n a a') (e1 : n' * k = nk) (e2 : nk + b = a') :
normalize_fin n a b :=
by rwa [← e2, ← e1, ← hn, normalize_fin, add_comm, nat.add_mul_mod_self_left] at h
theorem normalize_fin_lt.reduce {n} {a : fin n} {n' a' b k nk : ℕ}
(hn : n = n') (h : normalize_fin n a a') (e1 : n' * k = nk) (e2 : nk + b = a') (hl : b < n') :
normalize_fin_lt n a b :=
normalize_fin_lt.mk hn (h.reduce hn e1 e2) hl
theorem normalize_fin.eq {n} {a b : fin n} {c : ℕ}
(ha : normalize_fin n a c) (hb : normalize_fin n b c) : a = b := fin.eq_of_veq $ ha.trans hb.symm
theorem normalize_fin.lt {n} {a b : fin n} {a' b' : ℕ}
(ha : normalize_fin n a a') (hb : normalize_fin_lt n b b') (h : a' < b') : a < b :=
by have ha' := normalize_fin_lt.mk rfl ha (h.trans hb.lt); rwa [← hb.coe, ← ha'.coe] at h
theorem normalize_fin.le {n} {a b : fin n} {a' b' : ℕ}
(ha : normalize_fin n a a') (hb : normalize_fin_lt n b b') (h : a' ≤ b') : a ≤ b :=
by have ha' := normalize_fin_lt.mk rfl ha (h.trans_lt hb.lt); rwa [← hb.coe, ← ha'.coe] at h
/-- The monad for the `norm_fin` internal tactics. The state consists of an instance cache for `ℕ`,
and a tuple `(nn, n', p)` where `p` is a proof of `n = n'` and `nn` is `n` evaluated to a natural
number. (`n` itself is implicit.) It is in an `option` because it is lazily initialized - for many
`n` we will never need this information, and indeed eagerly computing it would make some reductions
fail spuriously if `n` is not a numeral. -/
@[derive [monad, alternative]]
meta def eval_fin_m (α : Type) : Type :=
state_t (instance_cache × option (ℕ × expr × expr)) tactic α
/-- Lifts a tactic into the `eval_fin_m` monad. -/
@[inline] meta def eval_fin_m.lift {α} (m : tactic α) : eval_fin_m α :=
⟨λ ⟨ic, r⟩, do a ← m, pure (a, ic, r)⟩
meta instance {α} : has_coe (tactic α) (eval_fin_m α) := ⟨eval_fin_m.lift⟩
/-- Lifts an `instance_cache` tactic into the `eval_fin_m` monad. -/
@[inline] meta def eval_fin_m.lift_ic {α}
(m : instance_cache → tactic (instance_cache × α)) : eval_fin_m α :=
⟨λ ⟨ic, r⟩, do (ic, a) ← m ic, pure (a, ic, r)⟩
/-- Evaluates a monadic action with a fresh `n` cache, and restore the old cache on completion of
the action. This is used when evaluating a tactic in the context of a different `n` than the parent
context. For example if we are evaluating `fin.succ a`, then `a : fin n` and
`fin.succ a : fin (n+1)`, so the parent cache will be about `n+1` and we need a separate cache for
`n`. -/
@[inline] meta def eval_fin_m.reset {α} (m : eval_fin_m α) : eval_fin_m α :=
⟨λ ⟨ic, r⟩, do (a, ic, _) ← m.run ⟨ic, none⟩, pure (a, ic, r)⟩
/-- Given `n`, returns a tuple `(nn, n', p)` where `p` is a proof of `n = n'` and `nn` is `n`
evaluated to a natural number. The result of the evaluation is cached for future references.
Future calls to this function must use the same value of `n`, unless it is in a sub-context
created by `eval_fin_m.reset`. -/
meta def eval_fin_m.eval_n (n : expr) : eval_fin_m (ℕ × expr × expr) :=
⟨λ ⟨ic, r⟩, match r with
| none := do
(n', p) ← or_refl_conv norm_num.derive n,
nn ← n'.to_nat,
let np := (nn, n', p),
pure (np, ic, some np)
| some np := pure (np, ic, some np)
end⟩
/-- Run an `eval_fin_m` action with a new cache and discard the cache after evaluation. -/
@[inline] meta def eval_fin_m.run {α} (m : eval_fin_m α) : tactic α :=
do ic ← mk_instance_cache `(ℕ), (a, _) ← state_t.run m (ic, none), pure a
/-- The expression constructors recognized by the `eval_fin` evaluator. This is used instead of a
direct expr pattern match because expr pattern matches generate very large terms under the
hood so going via an intermediate inductive type like this is more efficient. -/
meta inductive match_fin_result
| zero (n : expr) -- `(0 : fin (n+1))`
| one (n : expr) -- `(1 : fin (n+1))`
| add (n a b : expr) -- `(a + b : fin n)`
| mul (n a b : expr) -- `(a * b : fin n)`
| bit0 (n a : expr) -- `(bit0 a : fin n)`
| bit1 (n a : expr) -- `(bit1 a : fin (n+1))`
| succ (n a : expr) -- `(fin.succ a : fin n.succ)`
| cast_lt (n m i h : expr) -- `(fin.cast_lt (i : fin m) (h : i.val < n) : fin n)`
| cast_le (n m h a : expr) -- `(fin.cast_le (h : n ≤ m) (a : fin n) : fin m)`
| cast (n m h a : expr) -- `(fin.cast_le (h : n = m) (a : fin n) : fin m)`
| cast_add (n m a : expr) -- `(fin.cast_add m (a : fin n) : fin (n + m))`
| cast_succ (n a : expr) -- `(fin.cast_succ (a : fin n) : fin (n + 1))`
| add_nat (n m a : expr) -- `(fin.add_nat m (a : fin n) : fin (n + m))`
| nat_add (n m a : expr) -- `(fin.nat_add n (a : fin m) : fin (n + m))`
section
open match_fin_result
/-- Match a fin expression of the form `(coe_fn f a)` where `f` is some fin function. Several fin
functions are written this way: for example `cast_le : n ≤ m → fin n ↪o fin m` is not actually a
function but rather an order embedding with a coercion to a function. -/
meta def match_fin_coe_fn (a : expr) : expr → option match_fin_result
| `(@fin.cast_le %%n %%m %%h) := some (cast_le n m h a)
| `(@fin.cast %%m %%n %%h) := some (cast n m h a)
| `(@fin.cast_add %%n %%m) := some (cast_add n m a)
| `(@fin.cast_succ %%n) := some (cast_succ n a)
| `(@fin.add_nat %%n %%m) := some (add_nat n m a)
| `(@fin.nat_add %%n %%m) := some (nat_add n m a)
| _ := none
/-- Match a fin expression to a `match_fin_result`, for easier pattern matching in the
evaluator. -/
meta def match_fin : expr → option match_fin_result
| `(@has_zero.zero ._ (@fin.has_zero %%n)) := some (zero n)
| `(@has_one.one ._ (@fin.has_one %%n)) := some (one n)
| `(@has_add.add (fin %%n) ._ %%a %%b) := some (add n a b)
| `(@has_mul.mul (fin %%n) ._ %%a %%b) := some (mul n a b)
| `(@_root_.bit0 (fin %%n) ._ %%a) := some (bit0 n a)
| `(@_root_.bit1 ._ (@fin.has_one %%n) ._ %%a) := some (bit1 n a)
| `(@fin.succ %%n %%a) := some (succ n a)
| `(@fin.cast_lt %%n %%m %%a %%h) := some (cast_lt n m a h)
| (expr.app `(@coe_fn ._ ._ %%f) a) := match_fin_coe_fn a f
| _ := none
end
/-- `reduce_fin lt n a (a', pa)` expects that `pa : normalize_fin n a a'` where `a'`
is a natural numeral, and produces `(b, pb)` where `pb : normalize_fin n a b` if `lt` is false, or
`pb : normalize_fin_lt n a b` if `lt` is true. In either case, `b` will be chosen to be less than
`n`, but if `lt` is true then we also prove it. This requires that `n` can be evaluated to a
numeral. -/
meta def reduce_fin' : bool → expr → expr → expr × expr → eval_fin_m (expr × expr)
| lt n a (a', pa) := do
(nn, n', pn) ← eval_fin_m.eval_n n,
na ← expr.to_nat a',
if na < nn then
if lt then do
p ← eval_fin_m.lift_ic (λ ic, prove_lt_nat ic a' n'),
pure (a', `(@normalize_fin_lt.mk).mk_app [n, a, a', n', pn, pa, p])
else pure (a', pa)
else
let nb := na % nn, nk := (na - nb) / nn in
eval_fin_m.lift_ic $ λ ic, do
(ic, k) ← ic.of_nat nk,
(ic, b) ← ic.of_nat nb,
(ic, nk, pe1) ← prove_mul_nat ic n' k,
(ic, pe2) ← prove_add_nat ic nk b a',
if lt then do
(ic, p) ← prove_lt_nat ic b n',
pure (ic, b,
`(@normalize_fin_lt.reduce).mk_app [n, a, n', a', b, k, nk, pn, pa, pe1, pe2, p])
else pure (ic, b,
`(@normalize_fin.reduce).mk_app [n, a, n', a', b, k, nk, pn, pa, pe1, pe2])
/-- `eval_fin_lt' eval_fin n a` expects that `a : fin n`, and produces `(b, p)` where
`p : normalize_fin_lt n a b`. (It is mutually recursive with `eval_fin` which is why it takes the
function as an argument.) -/
meta def eval_fin_lt' (eval_fin : expr → eval_fin_m (expr × expr)) :
expr → expr → eval_fin_m (expr × expr)
| n a := do
e ← match_fin a,
match e with
| match_fin_result.succ n a := do
(a', pa) ← (eval_fin_lt' n a).reset,
(b, pb) ← eval_fin_m.lift_ic (λ ic, prove_succ' ic a'),
pure (b, `(@normalize_fin_lt.succ).mk_app [n, a, a', b, pa, pb])
| match_fin_result.cast_lt _ m a h := do
(a', pa) ← (eval_fin_lt' m a).reset,
pure (a', `(@normalize_fin_lt.cast_lt).mk_app [n, m, a, h, a', pa])
| match_fin_result.cast_le _ m nm a := do
(a', pa) ← (eval_fin_lt' m a).reset,
pure (a', `(@normalize_fin_lt.cast_le).mk_app [n, m, nm, a, a', pa])
| match_fin_result.cast m _ nm a := do
(a', pa) ← (eval_fin_lt' m a).reset,
pure (a', `(@normalize_fin_lt.cast).mk_app [n, m, nm, a, a', pa])
| match_fin_result.cast_add n m a := do
(a', pa) ← (eval_fin_lt' m a).reset,
pure (a', `(@normalize_fin_lt.cast_add).mk_app [n, m, a, a', pa])
| match_fin_result.cast_succ n a := do
(a', pa) ← (eval_fin_lt' n a).reset,
pure (a', `(@normalize_fin_lt.cast_succ).mk_app [n, a, a', pa])
| match_fin_result.add_nat n m a := do
(a', pa) ← (eval_fin_lt' n a).reset,
(m', pm) ← or_refl_conv norm_num.derive m,
(b, pb) ← eval_fin_m.lift_ic (λ ic, prove_add_nat' ic a' m'),
pure (b, `(@normalize_fin_lt.add_nat).mk_app [n, m, m', pm, a, a', b, pa, pb])
| match_fin_result.nat_add n m a := do
(a', pa) ← (eval_fin_lt' m a).reset,
(n', pn) ← or_refl_conv norm_num.derive n,
(b, pb) ← eval_fin_m.lift_ic (λ ic, prove_add_nat' ic n' a'),
pure (b, `(@normalize_fin_lt.nat_add).mk_app [n, m, n', pn, a, a', b, pa, pb])
| _ := do
(_, n', pn) ← eval_fin_m.eval_n n,
(a', pa) ← eval_fin a >>= reduce_fin' tt n a,
p ← eval_fin_m.lift_ic (λ ic, prove_lt_nat ic a' n'),
pure (a', `(@normalize_fin_lt.mk).mk_app [n, a, a', n', pn, pa, p])
end
/-- Get `n` such that `a : fin n`. -/
meta def get_fin_type (a : expr) : tactic expr := do `(fin %%n) ← infer_type a, pure n
/-- Given `a : fin n`, `eval_fin a` returns `(b, p)` where `p : normalize_fin n a b`. This function
does no reduction of the numeral `b`; for example `eval_fin (5 + 5 : fin 6)` returns `10`. It works
even if `n` is a variable, for example `eval_fin (5 + 5 : fin (n+1))` also returns `10`. -/
meta def eval_fin : expr → eval_fin_m (expr × expr)
| a := do
m ← match_fin a,
match m with
| match_fin_result.zero n := pure (`(0 : ℕ), `(normalize_fin.zero).mk_app [n])
| match_fin_result.one n := pure (`(1 : ℕ), `(normalize_fin.one).mk_app [n])
| match_fin_result.add n a b := do
(a', pa) ← eval_fin a,
(b', pb) ← eval_fin b,
(c, pc) ← eval_fin_m.lift_ic (λ ic, prove_add_nat' ic a' b'),
pure (c, `(@normalize_fin.add).mk_app [n, a, b, a', b', c, pa, pb, pc])
| match_fin_result.mul n a b := do
(a', pa) ← eval_fin a,
(b', pb) ← eval_fin b,
(c, pc) ← eval_fin_m.lift_ic (λ ic, prove_mul_nat ic a' b'),
pure (c, `(@normalize_fin.mul).mk_app [n, a, b, a', b', c, pa, pb, pc])
| match_fin_result.bit0 n a := do
(a', pa) ← eval_fin a,
pure (`(@bit0 ℕ _).mk_app [a'], `(@normalize_fin.bit0).mk_app [n, a, a', pa])
| match_fin_result.bit1 n a := do
(a', pa) ← eval_fin a,
pure (`(@bit1 ℕ _ _).mk_app [a'], `(@normalize_fin.bit1).mk_app [n, a, a', pa])
| match_fin_result.cast m n nm a := do
(a', pa) ← (eval_fin a).reset,
pure (a', `(@normalize_fin.cast).mk_app [n, m, nm, a, a', pa])
| _ := do
n ← get_fin_type a,
(a', pa) ← eval_fin_lt' eval_fin n a,
pure (a', `(@normalize_fin_lt.of).mk_app [n, a, a', pa])
end
/-- `eval_fin_lt n a` expects that `a : fin n`, and produces `(b, p)` where
`p : normalize_fin_lt n a b`. -/
meta def eval_fin_lt : expr → expr → eval_fin_m (expr × expr) := eval_fin_lt' eval_fin
/-- Given `a : fin n`, `eval_fin ff n a` returns `(b, p)` where `p : normalize_fin n a b`, and
`eval_fin tt n a` returns `p : normalize_fin_lt n a b`. Unlike `eval_fin`, this also does reduction
of the numeral `b`; for example `reduce_fin ff 6 (5 + 5 : fin 6)` returns `4`. As a result, it
fails if `n` is a variable, for example `reduce_fin ff (n+1) (5 + 5 : fin (n+1))` fails. -/
meta def reduce_fin (lt : bool) (n a : expr) : eval_fin_m (expr × expr) :=
eval_fin a >>= reduce_fin' lt n a
/-- If `a b : fin n` and `a'` and `b'` are as returned by `eval_fin`,
then `prove_lt_fin' n a b a' b'` proves `a < b`. -/
meta def prove_lt_fin' : expr → expr → expr → expr × expr → expr × expr → eval_fin_m expr
| n a b a' b' := do
(a', pa) ← reduce_fin' ff n a a',
(b', pb) ← reduce_fin' tt n b b',
p ← eval_fin_m.lift_ic (λ ic, prove_lt_nat ic a' b'),
pure (`(@normalize_fin.lt).mk_app [n, a, b, a', b', pa, pb, p])
/-- If `a b : fin n` and `a'` and `b'` are as returned by `eval_fin`,
then `prove_le_fin' n a b a' b'` proves `a ≤ b`. -/
meta def prove_le_fin' : expr → expr → expr → expr × expr → expr × expr → eval_fin_m expr
| n a b a' b' := do
(a', pa) ← reduce_fin' ff n a a',
(b', pb) ← reduce_fin' tt n b b',
p ← eval_fin_m.lift_ic (λ ic, prove_le_nat ic a' b'),
pure (`(@normalize_fin.le).mk_app [n, a, b, a', b', pa, pb, p])
/-- If `a b : fin n` and `a'` and `b'` are as returned by `eval_fin`,
then `prove_eq_fin' n a b a' b'` proves `a = b`. -/
meta def prove_eq_fin' : expr → expr → expr → expr × expr → expr × expr → eval_fin_m expr
| n a b (a', pa) (b', pb) :=
if a' =ₐ b' then do
pure (`(@normalize_fin.eq).mk_app [n, a, b, a', pa, pb])
else do
(a', pa) ← reduce_fin' ff n a (a', pa),
(b', pb) ← reduce_fin' ff n b (b', pb),
guard (a' =ₐ b'),
pure (`(@normalize_fin.eq).mk_app [n, a, b, a', pa, pb])
/-- Given a function with the type of `prove_eq_fin'`, evaluates it with the given `a` and `b`. -/
meta def eval_prove_fin
(f : expr → expr → expr → expr × expr → expr × expr → eval_fin_m expr)
(a b : expr) : tactic expr :=
do n ← get_fin_type a, eval_fin_m.run $ eval_fin a >>= λ a', eval_fin b >>= f n a b a'
/-- If `a b : fin n`, then `prove_eq_fin a b` proves `a = b`. -/
meta def prove_eq_fin : expr → expr → tactic expr := eval_prove_fin prove_eq_fin'
/-- If `a b : fin n`, then `prove_lt_fin a b` proves `a < b`. -/
meta def prove_lt_fin : expr → expr → tactic expr := eval_prove_fin prove_lt_fin'
/-- If `a b : fin n`, then `prove_le_fin a b` proves `a ≤ b`. -/
meta def prove_le_fin : expr → expr → tactic expr := eval_prove_fin prove_le_fin'
section
open norm_num.match_numeral_result
/-- Given expressions `n` and `m` such that `n` is definitionally equal to `m.succ`, and
a natural numeral `a`, proves `(b, ⊢ normalize_fin n b a)`, where `n` and `m` are both used
in the construction of the numeral `b : fin n`. -/
meta def mk_fin_numeral (n m : expr) : expr → option (expr × expr)
| a := match match_numeral a with
| zero := some (
expr.app `(@has_zero.zero (fin %%n)) `(@fin.has_zero %%m),
expr.app `(normalize_fin.zero) m)
| one := some (
expr.app `(@has_one.one (fin %%n)) `(@fin.has_one %%m),
expr.app `(normalize_fin.one) m)
| bit0 a := do
(a', p) ← mk_fin_numeral a,
some (`(bit0 %%a' : fin %%n), `(@normalize_fin.bit0).mk_app [n, a', a, p])
| bit1 a := do
(a', p) ← mk_fin_numeral a,
some (
`(@_root_.bit1 (fin %%n)).mk_app [`(@fin.has_one %%m), `(@fin.has_add %%n), a'],
`(@normalize_fin.bit1).mk_app [m, a', a, p])
| _ := none
end
end
/-- The common prep work for the cases in `eval_ineq`. Given inputs `a b : fin n`, it calls
`f n a' b' na nb` where `a'` and `b'` are the result of `eval_fin` and `na` and `nb` are
`a' % n` and `b' % n` as natural numbers. -/
meta def eval_rel {α} (a b : expr)
(f : expr → expr × expr → expr × expr → ℕ → ℕ → eval_fin_m α) : tactic α :=
do n ← get_fin_type a,
eval_fin_m.run $ do
(nn, n', pn) ← eval_fin_m.eval_n n,
(a', pa) ← eval_fin a,
(b', pb) ← eval_fin b,
na ← eval_fin_m.lift a'.to_nat,
nb ← eval_fin_m.lift b'.to_nat,
f n (a', pa) (b', pb) (na % nn) (nb % nn)
/-- Given `a b : fin n`, proves either `(n, tt, p)` where `p : a < b` or
`(n, ff, p)` where `p : b ≤ a`. -/
meta def prove_lt_ge_fin : expr → expr → tactic (expr × bool × expr)
| a b := eval_rel a b $ λ n a' b' na nb,
if na < nb then prod.mk n <$> prod.mk tt <$> prove_lt_fin' n a b a' b'
else prod.mk n <$> prod.mk ff <$> prove_le_fin' n b a b' a'
/-- Given `a b : fin n`, proves either `(n, tt, p)` where `p : a = b` or
`(n, ff, p)` where `p : a ≠ b`. -/
meta def prove_eq_ne_fin : expr → expr → tactic (expr × bool × expr)
| a b := eval_rel a b $ λ n a' b' na nb,
if na = nb then prod.mk n <$> prod.mk tt <$> prove_eq_fin' n a b a' b'
else if na < nb then do
p ← prove_lt_fin' n a b a' b',
pure (n, ff, `(@ne_of_lt (fin %%n) _).mk_app [a, b, p])
else do
p ← prove_lt_fin' n b a b' a',
pure (n, ff, `(@ne_of_gt (fin %%n) _).mk_app [a, b, p])
/-- A `norm_num` extension that evaluates equalities and inequalities on the type `fin n`.
```
example : (5 : fin 7) = fin.succ (fin.succ 3) := by norm_num
```
-/
@[norm_num] meta def eval_ineq : expr → tactic (expr × expr)
| `(%%a < %%b) := do
(n, lt, p) ← prove_lt_ge_fin a b,
if lt then true_intro p else false_intro (`(@not_lt_of_ge (fin %%n) _).mk_app [a, b, p])
| `(%%a ≤ %%b) := do
(n, lt, p) ← prove_lt_ge_fin b a,
if lt then false_intro (`(@not_le_of_gt (fin %%n) _).mk_app [a, b, p]) else true_intro p
| `(%%a = %%b) := do
(n, eq, p) ← prove_eq_ne_fin a b,
if eq then true_intro p else false_intro p
| `(%%a > %%b) := mk_app ``has_lt.lt [b, a] >>= eval_ineq
| `(%%a ≥ %%b) := mk_app ``has_le.le [b, a] >>= eval_ineq
| `(%%a ≠ %%b) := do
(n, eq, p) ← prove_eq_ne_fin a b,
if eq then false_intro `(not_not_intro (%%p : (%%a : fin %%n) = %%b)) else true_intro p
| _ := failed
/-- Evaluates `e : fin n` to a natural number less than `n`. Returns `none` if it is not a natural
number or greater than `n`. -/
meta def as_numeral (n e : expr) : eval_fin_m (option ℕ) :=
match e.to_nat with
| none := pure none
| some ne := do
(nn, _) ← eval_fin_m.eval_n n,
pure $ if ne < nn then some ne else none
end
/-- Given `a : fin n`, returns `(b, ⊢ a = b)` where `b` is a normalized fin numeral. Fails if `a`
is already normalized. -/
meta def eval_fin_num (a : expr) : tactic (expr × expr) :=
do n ← get_fin_type a,
eval_fin_m.run $ do
as_numeral n a >>= (λ o, guardb o.is_none),
(a', pa) ← eval_fin a,
(a', pa) ← reduce_fin' ff n a (a', pa) <|> pure (a', pa),
(nm + 1, _) ← eval_fin_m.eval_n n | failure,
m' ← eval_fin_m.lift_ic (λ ic, ic.of_nat nm),
n' ← eval_fin_m.lift_ic (λ ic, ic.of_nat (nm+1)),
(b, pb) ← mk_fin_numeral n' m' a',
pure (b, `(@normalize_fin.eq).mk_app [n, a, b, a', pa, pb])
end norm_fin
namespace interactive
open interactive interactive.types
/-- Rewrites occurrences of fin expressions to normal form anywhere in the goal.
The `norm_num` extension will only rewrite fin expressions if they appear in equalities and
inequalities. For example if the goal is `P (2 + 2 : fin 3)` then `norm_num` will not do anything
but `norm_fin` will reduce the goal to `P 1`.
(The reason this is not part of `norm_num` is because evaluation of fin numerals uses a top down
evaluation strategy while `norm_num` works bottom up; also determining whether a normalization
will work is expensive, meaning that unrelated uses of `norm_num` would be slowed down with this
as a plugin.) -/
meta def norm_fin (hs : parse simp_arg_list) : tactic unit :=
try (simp_top_down tactic.norm_fin.eval_fin_num) >> try (norm_num hs (loc.ns [none]))
/--
Rewrites occurrences of fin expressions to normal form anywhere in the goal.
The `norm_num` extension will only rewrite fin expressions if they appear in equalities and
inequalities. For example if the goal is `P (2 + 2 : fin 3)` then `norm_num` will not do anything
but `norm_fin` will reduce the goal to `P 1`.
```lean
example : (5 : fin 7) = fin.succ (fin.succ 3) := by norm_num
example (P : fin 7 → Prop) (h : P 5) : P (fin.succ (fin.succ 3)) := by norm_fin; exact h
```
-/
add_tactic_doc
{ name := "norm_fin",
category := doc_category.tactic,
decl_names := [`tactic.interactive.norm_fin],
tags := ["arithmetic", "decision procedure"] }
end interactive
end tactic
|
d081901c8da2449d2a4424ce7426360975bb49bb | 5719a16e23dfc08cdea7a5bf035b81690f307965 | /stage0/src/Init/Lean/Meta/WHNF.lean | e72f32e412d166b0062d8913ac4581c8e9b00674 | [
"Apache-2.0"
] | permissive | postmasters/lean4 | 488b03969a371e1507e1e8a4df9ebf63c7cbe7ac | f3976fc53a883ac7606fc59357d43f4b51016ca7 | refs/heads/master | 1,655,582,707,480 | 1,588,682,595,000 | 1,588,682,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,823 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.AuxRecursor
import Init.Lean.Util.WHNF
import Init.Lean.Meta.Basic
import Init.Lean.Meta.LevelDefEq
namespace Lean
namespace Meta
def isAuxDef? (constName : Name) : MetaM Bool := do
env ← getEnv; pure (isAuxRecursor env constName || isNoConfusion env constName)
def unfoldDefinition? (e : Expr) : MetaM (Option Expr) :=
Lean.WHNF.unfoldDefinitionAux getConstNoEx isAuxDef? whnf inferType isExprDefEq synthPending getLocalDecl getExprMVarAssignment? e
def whnfCore (e : Expr) : MetaM Expr :=
Lean.WHNF.whnfCore getConstNoEx isAuxDef? whnf inferType isExprDefEqAux getLocalDecl getExprMVarAssignment? e
unsafe def reduceNativeConst (α : Type) (typeName : Name) (constName : Name) : MetaM α := do
env ← getEnv;
match env.evalConstCheck α typeName constName with
| Except.error ex => throw $ Exception.other ex
| Except.ok v => pure v
unsafe def reduceBoolNativeUnsafe (constName : Name) : MetaM Bool := reduceNativeConst Bool `Bool constName
unsafe def reduceNatNativeUnsafe (constName : Name) : MetaM Nat := reduceNativeConst Nat `Nat constName
@[implementedBy reduceBoolNativeUnsafe] constant reduceBoolNative (constName : Name) : MetaM Bool := arbitrary _
@[implementedBy reduceNatNativeUnsafe] constant reduceNatNative (constName : Name) : MetaM Nat := arbitrary _
def reduceNative? (e : Expr) : MetaM (Option Expr) :=
match e with
| Expr.app (Expr.const fName _ _) (Expr.const argName _ _) _ =>
if fName == `Lean.reduceBool then do
b ← reduceBoolNative argName;
pure $ toExpr b
else if fName == `Lean.reduceNat then do
n ← reduceNatNative argName;
pure $ toExpr n
else
pure none
| _ => pure none
@[inline] def withNatValue {α} (a : Expr) (k : Nat → MetaM (Option α)) : MetaM (Option α) := do
a ← whnf a;
match a with
| Expr.const `Nat.zero _ _ => k 0
| Expr.lit (Literal.natVal v) _ => k v
| _ => pure none
def reduceUnaryNatOp (f : Nat → Nat) (a : Expr) : MetaM (Option Expr) :=
withNatValue a $ fun a =>
pure $ mkNatLit $ f a
def reduceBinNatOp (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Option Expr) :=
withNatValue a $ fun a =>
withNatValue b $ fun b => do
trace `Meta.isDefEq.whnf.reduceBinOp $ fun _ => toString a ++ " op " ++ toString b;
pure $ mkNatLit $ f a b
def reduceBinNatPred (f : Nat → Nat → Bool) (a b : Expr) : MetaM (Option Expr) := do
withNatValue a $ fun a =>
withNatValue b $ fun b =>
pure $ toExpr $ f a b
def reduceNat? (e : Expr) : MetaM (Option Expr) :=
if e.hasFVar || e.hasMVar then
pure none
else match e with
| Expr.app (Expr.const fn _ _) a _ =>
if fn == `Nat.succ then reduceUnaryNatOp Nat.succ a
else pure none
| Expr.app (Expr.app (Expr.const fn _ _) a1 _) a2 _ =>
if fn == `Nat.add then reduceBinNatOp Nat.add a1 a2
else if fn == `Nat.sub then reduceBinNatOp Nat.sub a1 a2
else if fn == `Nat.mul then reduceBinNatOp Nat.mul a1 a2
else if fn == `Nat.div then reduceBinNatOp Nat.div a1 a2
else if fn == `Nat.mod then reduceBinNatOp Nat.mod a1 a2
else if fn == `Nat.beq then reduceBinNatPred Nat.beq a1 a2
else if fn == `Nat.ble then reduceBinNatPred Nat.ble a1 a2
else pure none
| _ => pure none
@[inline] private def useWHNFCache (e : Expr) : MetaM Bool := do
-- We cache only consed terms
if e.hasFVar then pure false
else do
ctx ← read;
pure $ ctx.config.transparency == TransparencyMode.default
@[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do
if useCache then do
s ← get;
pure $ s.cache.whnfDefault.find? e
else
pure none
private def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do
when useCache $
modify $ fun s => { cache := { whnfDefault := s.cache.whnfDefault.insert e r, .. s.cache }, .. s };
pure r
partial def whnfImpl : Expr → MetaM Expr
| e => Lean.WHNF.whnfEasyCases getLocalDecl getExprMVarAssignment? e $ fun e => do
useCache ← useWHNFCache e;
e? ← cached? useCache e;
match e? with
| some e' => pure e'
| none => do
e' ← whnfCore e;
v? ← reduceNat? e';
match v? with
| some v => cache useCache e v
| none => do
v? ← reduceNative? e';
match v? with
| some v => cache useCache e v
| none => do
e? ← unfoldDefinition? e';
match e? with
| some e => whnfImpl e
| none => cache useCache e e'
@[init] def setWHNFRef : IO Unit :=
whnfRef.set whnfImpl
/- Given an expression `e`, compute its WHNF and if the result is a constructor, return field #i. -/
def reduceProj? (e : Expr) (i : Nat) : MetaM (Option Expr) := do
env ← getEnv;
e ← whnf e;
match e.getAppFn with
| Expr.const name _ _ =>
match env.find? name with
| some (ConstantInfo.ctorInfo ctorVal) =>
let numArgs := e.getAppNumArgs;
let idx := ctorVal.nparams + i;
if idx < numArgs then
pure (some (e.getArg! idx))
else
pure none
| _ => pure none
| _ => pure none
@[specialize] private partial def whnfHeadPredAux (pred : Expr → MetaM Bool) : Expr → MetaM Expr
| e => Lean.WHNF.whnfEasyCases getLocalDecl getExprMVarAssignment? e $ fun e => do
e ← whnfCore e;
condM (pred e)
(do
e? ← unfoldDefinition? e;
match e? with
| some e => whnfHeadPredAux e
| none => pure e)
(pure e)
def whnfHeadPred (e : Expr) (pred : Expr → MetaM Bool) : MetaM Expr :=
whnfHeadPredAux pred e
def whnfUntil (e : Expr) (declName : Name) : MetaM Expr :=
whnfHeadPredAux (fun e => pure $ !e.isAppOf declName) e
def getStuckMVar? (e : Expr) : MetaM (Option MVarId) :=
WHNF.getStuckMVar? getConst whnf e
end Meta
end Lean
|
9f6b62bbec4985b96748ef80cc43dd071712f743 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /stage0/src/Leanpkg/LeanVersion.lean | ff353b708a81666a9564252fa26c06c025f0454d | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 724 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Sebastian Ullrich
-/
namespace Leanpkg
def leanVersionStringCore :=
s!"{Lean.version.major}.{Lean.version.minor}.{Lean.version.patch}"
def leanVersionString :=
if Lean.version.isRelease then
s!"leanprover/lean4:{leanVersionStringCore}"
else if Lean.version.specialDesc ≠ "" then
Lean.version.specialDesc
else
"master"
def uiLeanVersionString :=
if Lean.version.isRelease then
leanVersionStringCore
else if Lean.version.specialDesc ≠ "" then
Lean.version.specialDesc
else
s!"master ({leanVersionStringCore})"
end Leanpkg
|
c28d126cc331c7e08ca88333b26582970ed07921 | 8c02fed42525b65813b55c064afe2484758d6d09 | /src/spec/freevar.lean | 6e54101a10427ab65b71660206de77011c76a799 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | microsoft/AliveInLean | 3eac351a34154efedd3ffc4fe2fa4ec01b219e0d | 4b739dd6e4266b26a045613849df221374119871 | refs/heads/master | 1,691,419,737,939 | 1,689,365,567,000 | 1,689,365,568,000 | 131,156,103 | 23 | 18 | NOASSERTION | 1,660,342,040,000 | 1,524,747,538,000 | Lean | UTF-8 | Lean | false | false | 43,527 | lean | -- Copyright (c) Microsoft Corporation. All rights reserved.
-- Licensed under the MIT license.
import ..smtexpr
import ..bitvector
import ..irsem
import .spec
import .lemmas
import .irstate
import smt2.syntax
import system.io
import init.meta.tactic
import init.meta.interactive
namespace spec
open irsem
def env.added2 (η:freevar.env) (n1 n2:string) (η':freevar.env):=
(∀ n, n ∉ η → n ≠ n1 ∧ n ≠ n2 → n ∉ η') ∧
(∀ n, n ∈ η ∨ n = n1 ∨ n = n2 → n ∈ η')
def env.has_only (η:freevar.env) (names:list string) :=
∀ name, name ∈ names ↔ name ∈ η
universes u v
@[reducible]
def apply {α:Type u} (f:α → α) : option α → option α
| (some x) := some (f x)
| none := none
lemma apply_none: ∀ {α:Type u} (f:α → α) o,
apply f o = none ↔ o = none
:= begin
intros,
split,
{ intros H, cases o, refl, unfold apply at H, cases H },
{ intros H, rw H }
end
lemma apply_some: ∀ {α:Type u} {f:α → α} {o} {v}
(H:apply f o = some v), ∃ v', o = some v'
:= begin
intros,
cases o with v0,
{ unfold apply at H, cases H },
{ unfold apply at H, apply exists.intro v0, refl }
end
notation η `⟦` s `⟧'` := apply (freevar.env.replace η) s
notation η `⟦` s `⟧'` := apply (freevar.env.replace_valty η) s
notation η `⟦` s `⟧'` := apply (freevar.env.replace_sbv η) s
notation η `⟦` s `⟧'` := apply (freevar.env.replace_sb η) s
-- Induction principles for sbool & sbitvec which are mutually defined
section
@[reducible]
parameters (P:sbool → Prop) (P':Π {sz:size}, sbitvec sz → Prop)
(Hbtt: P sbool.tt) (Hbff: P sbool.ff) (Hbvar: ∀ s, P (sbool.var s))
(Hband: ∀ b1 b2, P b1 → P b2 → P (sbool.and b1 b2))
(Hbor: ∀ b1 b2, P b1 → P b2 → P (sbool.or b1 b2))
(Hbxor: ∀ b1 b2, P b1 → P b2 → P (sbool.xor b1 b2))
(Hbeqb: ∀ b1 b2, P b1 → P b2 → P (sbool.eqb b1 b2))
(Hbneb: ∀ b1 b2, P b1 → P b2 → P (sbool.neb b1 b2))
(Hbite: ∀ b1 b2 b3, P b1 → P b2 → P b3 → P (sbool.ite b1 b2 b3))
(Hbnot: ∀ b, P b → P (sbool.not b))
(Hbeqbv: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P (sbool.eqbv v1 v2))
(Hbnebv: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P (sbool.nebv v1 v2))
(Hbsle: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P (sbool.sle v1 v2))
(Hbslt: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P (sbool.slt v1 v2))
(Hbule: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P (sbool.ule v1 v2))
(Hbult: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P (sbool.ult v1 v2))
(Hvconst: ∀ sz n, P' (sbitvec.const sz n))
(Hvvar: ∀ sz n, P' (sbitvec.var sz n))
(Hvadd: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.add v1 v2))
(Hvsub: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.sub v1 v2))
(Hvmul: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.mul v1 v2))
(Hvudiv: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.udiv v1 v2))
(Hvurem: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.urem v1 v2))
(Hvsdiv: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.sdiv v1 v2))
(Hvsrem: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.srem v1 v2))
(Hvand: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.and v1 v2))
(Hvor: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.or v1 v2))
(Hvxor: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.xor v1 v2))
(Hvshl: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.shl v1 v2))
(Hvlshr: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.lshr v1 v2))
(Hvashr: ∀ {sz} (v1 v2:sbitvec sz), P' v1 → P' v2 → P' (sbitvec.ashr v1 v2))
(Hvzext: ∀ {sz} (v:sbitvec sz) sz', P' v → P' (sbitvec.zext sz' v))
(Hvsext:∀ {sz} (v:sbitvec sz) sz', P' v → P' (sbitvec.sext sz' v))
(Hvtrunc: ∀ {sz} (v:sbitvec sz) sz', P' v → P' (sbitvec.trunc sz' v))
(Hvextract: ∀ {sz sz':size} (v:sbitvec sz) highbit lowbit
(H:sz'.val = highbit - lowbit + 1),
P' v → P' (sbitvec.extract highbit lowbit H v))
(Hvite: ∀ {sz} (b:sbool) (v1 v2:sbitvec sz), P b → P' v1 → P' v2 →
P' (sbitvec.ite b v1 v2))
@[reducible]
mutual def sbool.induction, sbitvec.induction
with sbool.induction : ∀ b, P b
| sbool.tt := Hbtt
| sbool.ff := Hbff
| (sbool.var b) := Hbvar b
| (sbool.and b1 b2) := Hband b1 b2 (sbool.induction b1) (sbool.induction b2)
| (sbool.or b1 b2) := Hbor b1 b2 (sbool.induction b1) (sbool.induction b2)
| (sbool.xor b1 b2) := Hbxor b1 b2 (sbool.induction b1) (sbool.induction b2)
| (sbool.eqb b1 b2) := Hbeqb b1 b2 (sbool.induction b1) (sbool.induction b2)
| (sbool.neb b1 b2) := Hbneb b1 b2 (sbool.induction b1) (sbool.induction b2)
| (sbool.ite b1 b2 b3) := Hbite b1 b2 b3 (sbool.induction b1) (sbool.induction b2) (sbool.induction b3)
| (sbool.not b) := Hbnot b (sbool.induction b)
| (@sbool.eqbv sz v1 v2) :=
have 0 < sbitvec.sizeof sz v1, by apply sbitvec.decr_sbitvec,
have 0 < sbitvec.sizeof sz v2, by apply sbitvec.decr_sbitvec,
Hbeqbv v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| (@sbool.nebv sz v1 v2) :=
have 0 < sbitvec.sizeof sz v1, by apply sbitvec.decr_sbitvec,
have 0 < sbitvec.sizeof sz v2, by apply sbitvec.decr_sbitvec,
Hbnebv v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| (@sbool.sle sz v1 v2) :=
have 0 < sbitvec.sizeof sz v1, by apply sbitvec.decr_sbitvec,
have 0 < sbitvec.sizeof sz v2, by apply sbitvec.decr_sbitvec,
Hbsle v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| (@sbool.slt sz v1 v2) :=
have 0 < sbitvec.sizeof sz v1, by apply sbitvec.decr_sbitvec,
have 0 < sbitvec.sizeof sz v2, by apply sbitvec.decr_sbitvec,
Hbslt v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| (@sbool.ule sz v1 v2) :=
have 0 < sbitvec.sizeof sz v1, by apply sbitvec.decr_sbitvec,
have 0 < sbitvec.sizeof sz v2, by apply sbitvec.decr_sbitvec,
Hbule v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| (@sbool.ult sz v1 v2) :=
have 0 < sbitvec.sizeof sz v1, by apply sbitvec.decr_sbitvec,
have 0 < sbitvec.sizeof sz v2, by apply sbitvec.decr_sbitvec,
Hbult v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
with sbitvec.induction: ∀ {sz:size} (v:sbitvec sz), P' v
| _ (sbitvec.const sz n) := Hvconst sz n
| _ (sbitvec.var sz n) := Hvvar sz n
| _ (sbitvec.add v1 v2) := Hvadd v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.sub v1 v2) := Hvsub v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.mul v1 v2) := Hvmul v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.udiv v1 v2) := Hvudiv v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.urem v1 v2) := Hvurem v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.sdiv v1 v2) := Hvsdiv v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.srem v1 v2) := Hvsrem v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.and v1 v2) := Hvand v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.or v1 v2) := Hvor v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.xor v1 v2) := Hvxor v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.shl v1 v2) := Hvshl v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.lshr v1 v2) := Hvlshr v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.ashr v1 v2) := Hvashr v1 v2 (sbitvec.induction v1) (sbitvec.induction v2)
| _ (sbitvec.zext sz' v) := Hvzext v sz' (sbitvec.induction v)
| _ (sbitvec.sext sz' v) := Hvsext v sz' (sbitvec.induction v)
| _ (sbitvec.trunc sz' v) := Hvtrunc v sz' (sbitvec.induction v)
| _ (sbitvec.extract h l H v) := Hvextract v h l H (sbitvec.induction v)
| _ (sbitvec.ite b v1 v2) := Hvite b v1 v2 (sbool.induction b)
(sbitvec.induction v1) (sbitvec.induction v2)
end
lemma env.replace_sb_and0: ∀ (b1 b2:sbool) (η:freevar.env),
η⟦sbool.and b1 b2⟧ = sbool.and (η⟦b1⟧) (η⟦b2⟧)
:= begin intros, unfold freevar.env.replace_sb end
lemma env.replace_sb_and: ∀ (b1 b2:sbool) (η:freevar.env),
η⟦b1 & b2⟧ = η⟦b1⟧ & η⟦b2⟧
:= begin intros, apply env.replace_sb_and0 end
lemma env.replace_sb_or0: ∀ (b1 b2:sbool) (η:freevar.env),
η⟦sbool.or b1 b2⟧ = sbool.or (η⟦b1⟧) (η⟦b2⟧)
:= begin intros, unfold freevar.env.replace_sb end
lemma env.replace_sb_or: ∀ (b1 b2:sbool) (η:freevar.env),
η⟦b1 |b b2⟧ = η⟦b1⟧ |b η⟦b2⟧
:= begin intros, apply env.replace_sb_or0 end
lemma env.replace_sb_not0: ∀ (b:sbool) (η:freevar.env),
η⟦sbool.not b⟧ = sbool.not (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sb end
lemma env.replace_sb_not: ∀ (b:sbool) (η:freevar.env),
η⟦~ b⟧ = ~ η⟦b⟧
:= begin intros, apply env.replace_sb_not0 end
lemma env.replace_sb_eqbv: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbool.eqbv a b⟧ = sbool.eqbv (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sb end
lemma env.replace_sb_nebv: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbool.nebv a b⟧ = sbool.nebv (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sb end
lemma env.replace_sb_sle: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbool.sle a b⟧ = sbool.sle (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sb end
lemma env.replace_sb_slt: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbool.slt a b⟧ = sbool.slt (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sb end
lemma env.replace_sb_ule: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbool.ule a b⟧ = sbool.ule (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sb end
lemma env.replace_sb_ult: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbool.ult a b⟧ = sbool.ult (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sb end
lemma env.replace_sb_ite: ∀ (c:sbool) (a b:sbool) (η:freevar.env),
η⟦sbool.ite c a b⟧ = sbool.ite (η⟦c⟧) (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sb end
lemma env.replace_b2p: ∀ (b:sbool) (η:freevar.env),
η⟦b2p irsem_smt b⟧ = b2p irsem_smt (η⟦b⟧)
:= begin
intros,
unfold b2p,
unfold has_ite.ite,
unfold freevar.env.replace_sb,
refl
end
lemma env.replace_sb_of_bool: ∀ (a:bool) (η:freevar.env),
η⟦sbool.of_bool a⟧ = sbool.of_bool a
:= begin
intros, cases a; refl
end
lemma env.replace_eq2p: ∀ {sz:size} (v1:sbitvec sz) (v2:sbitvec sz) (η:freevar.env),
η⟦irsem.eq2p irsem_smt v1 v2⟧ = (irsem.eq2p irsem_smt (η⟦v1⟧) (η⟦v2⟧))
:= begin
intros,
unfold eq2p,
unfold has_ne.ne,
unfold has_comp.ne,
have HNE: sbool.nebv (η⟦v1⟧) (η⟦v2⟧) = η⟦sbool.nebv v1 v2⟧,
{
unfold freevar.env.replace_sb
},
rw HNE,
apply env.replace_b2p,
end
lemma env.replace_neq2p: ∀ {sz:size} (v1:sbitvec sz) (v2:sbitvec sz) (η:freevar.env),
η⟦irsem.neq2p irsem_smt v1 v2⟧ = (irsem.neq2p irsem_smt (η⟦v1⟧) (η⟦v2⟧))
:= begin
intros,
unfold neq2p,
unfold has_eq.eq,
unfold has_comp.eq,
have HNE: sbool.eqbv (η⟦v1⟧) (η⟦v2⟧) = η⟦sbool.eqbv v1 v2⟧,
{
unfold freevar.env.replace_sb
},
rw HNE,
apply env.replace_b2p,
end
lemma env.replace_eq2p': ∀ {sz:size} (v1:sbitvec sz) (v2:sbitvec sz) (η:freevar.env)
(H:v2 = η⟦v2⟧),
(irsem.eq2p irsem_smt (η⟦v1⟧) v2) = η⟦irsem.eq2p irsem_smt v1 v2⟧
:= begin
intros,
have H0: irsem.eq2p irsem_smt (η⟦v1⟧) v2 = irsem.eq2p irsem_smt (η⟦v1⟧) (η⟦v2⟧),
{ rw ← H },
rw H0,
rw ← env.replace_eq2p
end
-- replace_sbv
lemma env.replace_sbv_add: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.add a b⟧ = sbitvec.add (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_sub: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.sub a b⟧ = sbitvec.sub (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_mul: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.mul a b⟧ = sbitvec.mul (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_udiv: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.udiv a b⟧ = sbitvec.udiv (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_urem: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.urem a b⟧ = sbitvec.urem (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_sdiv: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.sdiv a b⟧ = sbitvec.sdiv (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_srem: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.srem a b⟧ = sbitvec.srem (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_shl: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.shl a b⟧ = sbitvec.shl (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_lshr: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.lshr a b⟧ = sbitvec.lshr (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_ashr: ∀ {sz:size} (a b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.ashr a b⟧ = sbitvec.ashr (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_mk_zext: ∀ {sz sz2:size} (a:sbitvec sz) (η:freevar.env),
η⟦sbitvec.mk_zext sz2 a⟧ = sbitvec.mk_zext sz2 (η⟦a⟧)
:= begin intros, unfold sbitvec.mk_zext, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_mk_sext: ∀ {sz sz2:size} (a:sbitvec sz) (η:freevar.env),
η⟦sbitvec.mk_sext sz2 a⟧ = sbitvec.mk_sext sz2 (η⟦a⟧)
:= begin intros, unfold sbitvec.mk_sext, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_trunc: ∀ {sz sz':size} (b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.trunc sz' b⟧ = sbitvec.trunc sz' (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_zext: ∀ {sz sz':size} (b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.zext sz' b⟧ = sbitvec.zext sz' (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_sext: ∀ {sz sz':size} (b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.sext sz' b⟧ = sbitvec.sext sz' (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_extract: ∀ {sz sz':size} (b:sbitvec sz) (η:freevar.env) h l
(H:sz'.val = h - l + 1),
η⟦sbitvec.extract h l H b⟧ = sbitvec.extract h l H (η⟦b⟧)
:= begin
intros,
unfold freevar.env.replace_sbv
end
lemma env.replace_sbv_ite: ∀ {sz:size} (c:sbool) (a b:sbitvec sz) (η:freevar.env),
η⟦sbitvec.ite c a b⟧ = sbitvec.ite (η⟦c⟧) (η⟦a⟧) (η⟦b⟧)
:= begin intros, unfold freevar.env.replace_sbv end
lemma env.replace_sbv_of_int: ∀ sz z (η:freevar.env),
η⟦sbitvec.of_int sz z⟧ = sbitvec.of_int sz z
:= begin
intros,
cases sz,
cases z;
{
unfold sbitvec.of_int,
unfold freevar.env.replace_sbv
}
end
lemma env.replace_sbv_of_bool: ∀ (a:sbool) (η:freevar.env),
η⟦sbitvec.of_bool a⟧ = sbitvec.of_bool (η⟦a⟧)
:= begin
intros, unfold sbitvec.of_bool, rw env.replace_sbv_ite,
unfold sbitvec.zero, unfold sbitvec.one,
rw env.replace_sbv_of_int, rw env.replace_sbv_of_int
end
lemma env.replace_idemp :
(∀ (η:freevar.env) (b:sbool), η⟦η⟦b⟧⟧ = η⟦b⟧) ∧
(∀ {sz:size} (η:freevar.env) (b:sbitvec sz), η⟦η⟦b⟧⟧ = η⟦b⟧)
:= begin
split; intros; revert b,
apply (sbool.induction (λ b, η⟦η⟦b⟧⟧ = η⟦b⟧)
(λ {sz:size} (v:sbitvec sz), η⟦η⟦v⟧⟧ = η⟦v⟧)),
any_goals {
apply (sbitvec.induction (λ b, η⟦η⟦b⟧⟧ = η⟦b⟧)
(λ {sz:size} (v:sbitvec sz), η⟦η⟦v⟧⟧ = η⟦v⟧))
},
any_goals
{ refl },
-- sbool
any_goals {
intros b1 b2 H1 H2,
unfold freevar.env.replace_sb, rw [H1, H2], done
},
any_goals {
intros,
unfold freevar.env.replace_sb,
generalize Hb': η.b s = b',
cases b',
{ unfold freevar.env.replace_sb._match_1,
unfold freevar.env.replace_sb,
rw Hb', refl
},
{ unfold freevar.env.replace_sb._match_1,
cases b'; refl
}
},
any_goals { intros b1 b2 b3 H1 H2 H3,
unfold freevar.env.replace_sb, rw [H1, H2, H3], done
},
any_goals { intros b H,
unfold freevar.env.replace_sb, rw H, done
},
any_goals { intros sz v1 v2 H1 H2,
unfold freevar.env.replace_sb, rw H1, rw H2, done
},
-- sbitvec
any_goals
{ intros, unfold freevar.env.replace_sbv, done },
any_goals {
intros sz v1 v2 H1 H2,
unfold freevar.env.replace_sbv, rw [H1, H2], done
},
any_goals {
intros,
unfold freevar.env.replace_sbv,
generalize Hb': η.bv n = b',
cases b'; unfold freevar.env.replace_sbv._match_1,
{ unfold freevar.env.replace_sbv,
rw Hb', refl
},
{ rw env.replace_sbv_of_int }, done
},
any_goals {
intros sz v' sz' H,
unfold freevar.env.replace_sbv, rw H, done
},
any_goals {
intros sz sz' v highbit lowbit H H',
unfold freevar.env.replace_sbv,
rw H', done
},
any_goals {
intros sz b v1 v2 H H1 H2,
unfold freevar.env.replace_sbv,
rw [H, H1, H2]
}
end
lemma env.replace_sb_idemp: ∀ (η:freevar.env) (b:sbool), η⟦η⟦b⟧⟧ = η⟦b⟧
:= begin
apply (and.elim_left env.replace_idemp)
end
lemma env.replace_sbv_idemp: ∀ {sz} (η:freevar.env) (b:sbitvec sz), η⟦η⟦b⟧⟧ = η⟦b⟧
:= begin
intros,
apply (and.elim_right env.replace_idemp)
end
lemma env.empty_replace: (∀ (b:sbool), freevar.env.empty⟦b⟧ = b) ∧
(∀ {sz} (b:sbitvec sz), freevar.env.empty⟦b⟧ = b)
:= begin
intros,
split; intros; revert b,
apply (sbool.induction (λ b, freevar.env.empty⟦b⟧ = b)
(λ {sz:size} (v:sbitvec sz), freevar.env.empty⟦v⟧ = v)),
any_goals {
apply (sbitvec.induction (λ b, freevar.env.empty⟦b⟧ = b)
(λ {sz:size} (v:sbitvec sz), freevar.env.empty⟦v⟧ = v)),
},
any_goals { refl },
any_goals {
intros,
unfold freevar.env.replace_sb,
unfold freevar.env.empty,
simp, done
},
any_goals {
intros b H, unfold freevar.env.replace_sb, rw H
},
any_goals {
intros b1 b2 H1 H2, unfold freevar.env.replace_sb, rw [H1, H2], done
},
any_goals {
intros b b1 b2 H H1 H2, unfold freevar.env.replace_sb, rw [H, H1, H2], done
},
any_goals {
intros sz b1 b2 H1 H2, unfold freevar.env.replace_sb, rw [H1, H2], done
},
-- sbitvec
any_goals
{ intros, unfold freevar.env.replace_sbv, done },
any_goals {
intros sz v1 v2 H1 H2,
unfold freevar.env.replace_sbv, rw [H1, H2], done
},
any_goals {
intros,
unfold freevar.env.replace_sbv,
unfold freevar.env.empty,
simp, done
},
any_goals {
intros sz v' sz' H,
unfold freevar.env.replace_sbv, rw H, done
},
any_goals {
intros sz sz' v highbit lowbit H H',
unfold freevar.env.replace_sbv,
rw H', done
},
any_goals {
intros sz b v1 v2 H H1 H2,
unfold freevar.env.replace_sbv,
rw [H, H1, H2]
}
end
lemma env.empty_replace_sb: ∀ (b:sbool), freevar.env.empty⟦b⟧ = b
:= begin
apply (and.elim_left env.empty_replace)
end
lemma env.empty_replace_sbv {sz:size} : ∀ (b:sbitvec sz), freevar.env.empty⟦b⟧ = b
:= begin
apply (and.elim_right env.empty_replace)
end
lemma env.replace_sbv_cast: ∀ {sz sz':size} {H:sz = sz'} {H':sbitvec sz = sbitvec sz'}
(b:sbitvec sz) (η:freevar.env),
η⟦cast H' b⟧ = cast H' (η⟦b⟧)
:= begin
intros,
induction H,
unfold cast
end
lemma env.replace_sb_overflowchk_add: ∀
{sz1:size} (sz2:size) (v1 v2:sbitvec sz1) nsw (η:freevar.env),
η⟦sbitvec.overflow_chk @sbitvec.add sz2 nsw v1 v2⟧ =
sbitvec.overflow_chk @sbitvec.add sz2 nsw (η⟦v1⟧) (η⟦v2⟧)
:= begin
intros, unfold sbitvec.overflow_chk,
cases nsw; simp, rw env.replace_sbv_of_int
end
lemma env.replace_sb_overflowchk_sub: ∀
{sz1:size} (sz2:size) (v1 v2:sbitvec sz1) nsw (η:freevar.env),
η⟦sbitvec.overflow_chk @sbitvec.sub sz2 nsw v1 v2⟧ =
sbitvec.overflow_chk @sbitvec.sub sz2 nsw (η⟦v1⟧) (η⟦v2⟧)
:= begin
intros, unfold sbitvec.overflow_chk,
cases nsw; simp, rw env.replace_sbv_of_int
end
lemma env.replace_sb_overflowchk_mul: ∀
{sz1:size} (sz2:size) (v1 v2:sbitvec sz1) nsw (η:freevar.env),
η⟦sbitvec.overflow_chk @sbitvec.mul sz2 nsw v1 v2⟧ =
sbitvec.overflow_chk @sbitvec.mul sz2 nsw (η⟦v1⟧) (η⟦v2⟧)
:= begin
intros, unfold sbitvec.overflow_chk,
cases nsw; simp, rw env.replace_sbv_of_int
end
lemma env.replace_sb_overflowchk_shl: ∀
{sz1:size} (sz2:size) (v1 v2:sbitvec sz1) nsw (η:freevar.env),
η⟦sbitvec.shl_overflow_chk sz2 nsw v1 v2⟧ =
sbitvec.shl_overflow_chk sz2 nsw (η⟦v1⟧) (η⟦v2⟧)
:= begin
intros, unfold sbitvec.shl_overflow_chk,
unfold sbitvec.overflow_chk,
cases nsw; simp,
{ repeat { rw env.replace_sbv_of_int }, tauto },
{ rw env.replace_sbv_of_int }
end
-- irstate
lemma getreg_replace_none: ∀ ss ss' (η:freevar.env) (name name':string)
(H:irstate.getreg irsem_smt ss name = none)
(H':ss' = η⟦ss⟧),
irstate.getreg irsem_smt ss' name = none
:= begin
intros,
unfold freevar.env.replace at H',
rw H',
rw ← irstate.getreg_apply_none_smt,
assumption
end
lemma getreg_replace_none_inv: ∀ ss ss' (η:freevar.env) (name name':string)
(H:irstate.getreg irsem_smt ss' name = none)
(H':ss' = η⟦ss⟧),
irstate.getreg irsem_smt ss name = none
:= begin
intros,
unfold freevar.env.replace at H',
rw H' at H,
rw irstate.getreg_apply_none_smt,
assumption
end
lemma getreg_replace: ∀ {ss:irstate_smt} {name:string} {η:freevar.env} {ov}
(HV:irstate.getreg irsem_smt ss name = ov),
irstate.getreg irsem_smt (η⟦ss⟧) name = η⟦ov⟧'
:= begin
intros,
revert ov,
unfold irstate.getreg at *,
unfold freevar.env.replace at *,
unfold irstate.apply_to_values at *,
cases ss with ss_ub ss_rf,
apply regfile.induction ss_rf,
{
intros ov H,
unfold irstate.setub, simp at *,
rw regfile.empty_apply_empty,
rw regfile.empty_get_none at *, rw ← H
},
{
intros rf Hind n v ov H,
unfold irstate.setub at *, simp at *,
rw regfile.apply_update_comm,
have HNAME: decidable (n = name), apply_instance,
cases HNAME,
{
rw regfile.update_get_nomatch,
rw regfile.update_get_nomatch at H,
unfold irstate.setub at Hind,
simp at Hind,
rw H at Hind,
assumption,
tauto, tauto
},
{
rw regfile.update_get_match,
rw regfile.update_get_match at H,
rw ← H, rw HNAME, rw HNAME
}
}
end
lemma replace_updatereg: ∀ (ss:irstate_smt) (name:string)
(η:freevar.env) v,
η⟦irstate.updatereg irsem_smt ss name v⟧ =
irstate.updatereg irsem_smt (η⟦ss⟧) name (η⟦v⟧)
:= begin
intros,
unfold irstate.updatereg,
unfold freevar.env.replace,
unfold irstate.apply_to_values,
congr
end
lemma replace_updateub: ∀ (ss:irstate_smt) (η:freevar.env) ub,
η⟦irstate.updateub irsem_smt ss ub⟧ =
irstate.updateub irsem_smt (η⟦ss⟧) (η⟦ub⟧)
:= begin
intros,
unfold irstate.updateub,
unfold freevar.env.replace,
unfold irstate.apply_to_values,
unfold irstate.setub,
unfold irstate.getub,
simp,
rw env.replace_sb_and
end
lemma replace_getub: ∀ (ss:irstate_smt) (η:freevar.env),
η⟦irstate.getub irsem_smt ss⟧ =
irstate.getub irsem_smt (η⟦ss⟧)
:= begin
intros,
unfold irstate.getub,
cases ss, refl
end
lemma empty_replace_st: ∀ (ss:irstate_smt),
freevar.env.empty⟦ss⟧ = ss
:= begin
intros,
unfold freevar.env.replace,
cases ss,
unfold irstate.apply_to_values,
unfold irstate.setub,
unfold irstate.getub,
simp,
split,
{ rw env.empty_replace_sb },
{
revert ss_snd,
apply regfile.induction,
{ rw regfile.empty_apply_empty },
{
intros rf H,
intros,
rw regfile.apply_update_comm,
congr, assumption, cases v,
unfold freevar.env.replace_valty,
congr, rw env.empty_replace_sbv, rw env.empty_replace_sb
}
}
end
-- ∉
lemma env.not_in_split: ∀ (η:freevar.env) n,
n ∉ η ↔ η.b n = none ∧ η.bv n = none
:= begin
intros,
split; intros H,
{
unfold has_mem.mem at H,
rw decidable.not_or_iff_and_not at H,
cases H,
rw ne.def at H_left,
rw ne.def at H_right,
rw decidable.not_not_iff at H_left,
rw decidable.not_not_iff at H_right,
split; assumption
},
{
unfold has_mem.mem,
rw decidable.not_or_iff_and_not,
cases H,
rw ne.def,
rw ne.def,
rw decidable.not_not_iff,
rw decidable.not_not_iff,
split; assumption
}
end
lemma env.in_not_in: ∀ n (η:freevar.env), n ∉ η ∨ n ∈ η
:= begin
intros,
rw env.not_in_split,
unfold has_mem.mem,
generalize Hb: η.b n = b',
generalize Hb: η.bv n = bv',
cases b'; cases bv',
{
left, split; refl
},
{ right, right, intros H, cases H },
{ right, left, intros H, cases H },
{ right, left, intros H, cases H },
end
lemma env.not_in_add_bv: ∀ (η:freevar.env) n1 n2 z
(HNEQ:n1 ≠ n2)
(HNOTIN:n1 ∉ η),
n1 ∉ (η.add_bv n2 z)
:= begin
intros,
rw env.not_in_split at *,
cases HNOTIN,
unfold freevar.env.add_bv,
split,
{ simp, assumption },
{ simp, rw if_neg; assumption }
end
lemma env.not_in_add_b: ∀ (η:freevar.env) n1 n2 z
(HNEQ:n1 ≠ n2)
(HNOTIN:n1 ∉ η),
n1 ∉ (η.add_b n2 z)
:= begin
intros,
rw env.not_in_split at *,
cases HNOTIN,
unfold freevar.env.add_b,
split,
{ simp, rw if_neg; assumption },
{ simp, assumption }
end
lemma env.not_in_empty: ∀ n, n ∉ freevar.env.empty
:= begin
intros, rw env.not_in_split,
split; refl
end
-- replace_sb, repalce_sbv
lemma env.not_in_replace_sb: ∀ (η:freevar.env) n
(HNOTIN:n ∉ η),
η⟦sbool.var n⟧ = sbool.var n
:= begin
intros,
rw env.not_in_split at *,
cases HNOTIN,
unfold freevar.env.replace_sb,
generalize H:η.b n = g,
cases g,
{ refl },
{ rw HNOTIN_left at H, cases H }
end
lemma env.not_in_replace_sbv: ∀ (η:freevar.env) n sz
(HNOTIN:n ∉ η),
η⟦sbitvec.var sz n⟧ = sbitvec.var sz n
:= begin
intros,
rw env.not_in_split at *,
cases HNOTIN,
unfold freevar.env.replace_sbv,
generalize H:η.bv n = g,
cases g,
{ refl },
{ rw HNOTIN_right at H, cases H }
end
lemma env.in_replace_sbv: ∀ (η:freevar.env) n sz
(HIN:∃ z, η.bv n = some z),
∃ z, η⟦sbitvec.var sz n⟧ = sbitvec.const sz z
:= begin
intros,
cases HIN with z HIN,
unfold freevar.env.replace_sbv,
rw HIN,
unfold freevar.env.replace_sbv._match_1,
cases z; unfold sbitvec.of_int,
apply exists.intro, refl,
apply exists.intro, refl
end
lemma env.sbv_var_or_const: ∀ (η:freevar.env) sz n,
η⟦sbitvec.var sz n⟧ = sbitvec.var sz n ∨
∃ z, η⟦sbitvec.var sz n⟧ = sbitvec.const sz z
:= begin
intros,
unfold freevar.env.replace_sbv,
generalize H: (η.bv n) = b,
cases b,
{
unfold freevar.env.replace_sbv._match_1,
left, refl
},
{
unfold freevar.env.replace_sbv._match_1,
right, cases b; unfold sbitvec.of_int,
apply exists.intro, refl,
apply exists.intro, refl
}
end
lemma env.sb_var_or_const: ∀ (η:freevar.env) n,
η⟦sbool.var n⟧ = sbool.var n ∨
η⟦sbool.var n⟧ = sbool.tt ∨
η⟦sbool.var n⟧ = sbool.ff
:= begin
intros,
unfold freevar.env.replace_sb,
generalize H: (η.b n) = b,
cases b,
{
unfold freevar.env.replace_sb._match_1,
left, refl
},
{
unfold freevar.env.replace_sb._match_1,
right, cases b, right, refl, left, refl
}
end
lemma env.not_in_add_bv_replace: ∀ (η:freevar.env) n n2 sz z
(HNEQ:n ≠ n2),
(η.add_bv n2 z)⟦sbitvec.var sz n⟧ = η⟦sbitvec.var sz n⟧
:= begin
intros,
unfold freevar.env.replace_sbv,
unfold freevar.env.add_bv,
simp,
rw if_neg, assumption
end
lemma env.not_in_add_b_replace: ∀ (η:freevar.env) n n2 z
(HNEQ:n ≠ n2),
(η.add_b n2 z)⟦sbool.var n⟧ = η⟦sbool.var n⟧
:= begin
intros,
unfold freevar.env.replace_sb,
unfold freevar.env.add_b,
simp,
rw if_neg, assumption
end
lemma env.add_b_replace_match: ∀ (η:freevar.env) n b,
(freevar.env.add_b η n b)⟦sbool.var n⟧ = sbool.of_bool b
:= begin
intros,
unfold freevar.env.replace_sb,
unfold freevar.env.add_b,
simp
end
lemma env.add_bv_replace_match: ∀ (η:freevar.env) n z sz,
(freevar.env.add_bv η n z)⟦sbitvec.var sz n⟧ = sbitvec.of_int sz z
:= begin
intros,
unfold freevar.env.replace_sbv,
unfold freevar.env.add_bv,
simp
end
lemma env.add_bv_replace_sb: ∀ (η:freevar.env) n n' z,
(freevar.env.add_bv η n z)⟦sbool.var n'⟧ = η⟦sbool.var n'⟧
:= begin
intros,
unfold freevar.env.replace_sb,
unfold freevar.env.add_bv
end
lemma env.add_b_replace_sbv: ∀ (η:freevar.env) n n' b sz,
(freevar.env.add_b η n b)⟦sbitvec.var sz n'⟧ = η⟦sbitvec.var sz n'⟧
:= begin
intros,
unfold freevar.env.replace_sbv,
unfold freevar.env.add_b
end
lemma env.replace_sb_cases: ∀ s (η:freevar.env),
η⟦sbool.var s⟧ = sbool.var s ∨ η⟦sbool.var s⟧ = sbool.tt ∨ η⟦sbool.var s⟧ = sbool.ff
:= begin
intros,
unfold freevar.env.replace_sb,
generalize Hb: η.b s = b',
rw Hb at *, cases b'; unfold freevar.env.replace_sb._match_1,
{ left, refl },
{
right,
cases b'; unfold sbool.of_bool; simp
}
end
lemma env.replace_sbv_cases: ∀ sz s (η:freevar.env),
η⟦sbitvec.var sz s⟧ = sbitvec.var sz s
∨ ∃ n, η⟦sbitvec.var sz s⟧ = sbitvec.const sz n
:= begin
intros,
unfold freevar.env.replace_sbv,
generalize Hb: η.bv s = b',
rw Hb at *, cases b'; unfold freevar.env.replace_sbv._match_1,
{ left, refl },
{
right,
cases b'; unfold sbitvec.of_int,
apply exists.intro, refl, apply exists.intro, refl
}
end
lemma env.not_in_add_b_bv_bv_comm: ∀ (η:freevar.env) z,
(∀ (v:sbool) n, n ∉ η → (η.add_bv n z)⟦v⟧ =
(freevar.env.empty.add_bv n z)⟦η⟦v⟧⟧) ∧
(∀ {sz} (v:sbitvec sz) n, n ∉ η →
(η.add_bv n z)⟦v⟧ = (freevar.env.empty.add_bv n z)⟦η⟦v⟧⟧)
:= begin
intros,
split,
apply sbool.induction
(λ v, ∀ n, n ∉ η → (η.add_bv n z)⟦v⟧ = (freevar.env.empty.add_bv n z)⟦η⟦v⟧⟧)
(λ {sz} (v:sbitvec sz), ∀ n, n ∉ η →
(η.add_bv n z)⟦v⟧ = (freevar.env.empty.add_bv n z)⟦η⟦v⟧⟧),
any_goals {
apply sbitvec.induction
(λ v, ∀ n, n ∉ η → (η.add_bv n z)⟦v⟧ = (freevar.env.empty.add_bv n z)⟦η⟦v⟧⟧)
(λ {sz} (v:sbitvec sz), ∀ n, n ∉ η →
(η.add_bv n z)⟦v⟧ = (freevar.env.empty.add_bv n z)⟦η⟦v⟧⟧),
},
any_goals { intros, refl },
any_goals {
intros,
unfold freevar.env.add_bv,
unfold freevar.env.replace_sb,
simp,
unfold freevar.env.empty,
generalize HG: η.b s = b',
cases b',
{
unfold freevar.env.replace_sb._match_1,
unfold freevar.env.replace_sb,
},
{
unfold freevar.env.replace_sb._match_1,
rw env.replace_sb_of_bool, done
}
},
any_goals {
intros b1 b2 H1 H2 n' HNOTIN',
unfold freevar.env.replace_sb at *,
rw [H1, H2]; assumption
},
any_goals {
intros b1 b2 b3 H1 H2 H3 n' HNOTIN',
unfold freevar.env.replace_sb at *,
rw [H1, H2, H3]; assumption
},
any_goals {
intros b H n' HNOTIN',
unfold freevar.env.replace_sb at *,
rw [H], assumption
},
any_goals {
intros sz b1 b2 H1 H2 n' HNOTIN',
unfold freevar.env.replace_sb at *,
rw [H1, H2]; assumption
},
any_goals {
intros,
unfold freevar.env.replace_sbv at *, done
},
any_goals {
intros sz n',
intros n'' HNOTIN',
have HEQ:decidable (n' = n''), apply_instance,
cases HEQ,
{
have H:= env.sbv_var_or_const η sz n',
cases H,
{
rw env.not_in_add_bv_replace,
rw H,
rw env.not_in_add_bv_replace,
rw env.empty_replace_sbv,
assumption, assumption
},
{
cases H with z' H,
rw env.not_in_add_bv_replace,
rw H,
unfold freevar.env.replace_sbv,
assumption
}
},
{
rw HEQ,
rw env.add_bv_replace_match,
rw env.not_in_replace_sbv,
rw env.add_bv_replace_match,
assumption
}
},
any_goals {
intros sz v1 v2 H1 H2 n' HNOTIN',
unfold freevar.env.replace_sbv at *,
rw [H1, H2]; assumption
},
any_goals {
intros sz v sz' H n' HNOTIN',
unfold freevar.env.replace_sbv at *,
rw H, assumption
},
any_goals {
intros sz sz' v highbit lowbit HH H n' HNOTIN',
unfold freevar.env.replace_sbv at *,
rw H, assumption
},
any_goals {
intros sz v1 v2 v3 H1 H2 H3 n' HNOTIN',
unfold freevar.env.replace_sbv at *,
rw [H1, H2, H3]; assumption
}
end
lemma env.not_in_add_bv_b_comm: ∀ (η:freevar.env) z (v:sbool) n,
n ∉ η → (η.add_bv n z)⟦v⟧ = (freevar.env.empty.add_bv n z)⟦η⟦v⟧⟧
:= begin
intros, apply (and.elim_left (env.not_in_add_b_bv_bv_comm η z)),
assumption
end
lemma env.not_in_add_bv_bv_comm: ∀ (η:freevar.env) z {sz} (v:sbitvec sz) n,
n ∉ η → (η.add_bv n z)⟦v⟧ = (freevar.env.empty.add_bv n z)⟦η⟦v⟧⟧
:= begin
intros, apply (and.elim_right (env.not_in_add_b_bv_bv_comm η z)),
assumption
end
lemma env.not_in_add_b_bv_b_comm: ∀ (η:freevar.env) z,
(∀ (v:sbool) n, n ∉ η → (η.add_b n z)⟦v⟧ =
(freevar.env.empty.add_b n z)⟦η⟦v⟧⟧) ∧
(∀ {sz} (v:sbitvec sz) n, n ∉ η →
(η.add_b n z)⟦v⟧ = (freevar.env.empty.add_b n z)⟦η⟦v⟧⟧)
:= begin
intros,
split,
apply sbool.induction
(λ v, ∀ n, n ∉ η → (η.add_b n z)⟦v⟧ = (freevar.env.empty.add_b n z)⟦η⟦v⟧⟧)
(λ {sz} (v:sbitvec sz), ∀ n, n ∉ η →
(η.add_b n z)⟦v⟧ = (freevar.env.empty.add_b n z)⟦η⟦v⟧⟧),
any_goals {
apply sbitvec.induction
(λ v, ∀ n, n ∉ η → (η.add_b n z)⟦v⟧ = (freevar.env.empty.add_b n z)⟦η⟦v⟧⟧)
(λ {sz} (v:sbitvec sz), ∀ n, n ∉ η →
(η.add_b n z)⟦v⟧ = (freevar.env.empty.add_b n z)⟦η⟦v⟧⟧),
},
any_goals { intros, refl },
any_goals {
intros n',
intros n'' HNOTIN',
have HEQ:decidable (n' = n''), apply_instance,
cases HEQ,
{
have H:= env.sb_var_or_const η n',
cases H,
{
rw env.not_in_add_b_replace,
rw H,
rw env.not_in_add_b_replace,
rw env.empty_replace_sb,
assumption, assumption
},
{
cases H,
any_goals {rw env.not_in_add_b_replace,
rw H,
unfold freevar.env.replace_sb,
assumption }
}
},
{
rw HEQ,
rw env.add_b_replace_match,
rw env.not_in_replace_sb,
rw env.add_b_replace_match,
assumption
}
},
any_goals {
intros b1 b2 H1 H2 n' HNOTIN',
unfold freevar.env.replace_sb at *,
rw [H1, H2]; assumption
},
any_goals {
intros b1 b2 b3 H1 H2 H3 n' HNOTIN',
unfold freevar.env.replace_sb at *,
rw [H1, H2, H3]; assumption
},
any_goals {
intros b H n' HNOTIN',
unfold freevar.env.replace_sb at *,
rw [H], assumption
},
any_goals {
intros sz b1 b2 H1 H2 n' HNOTIN',
unfold freevar.env.replace_sb at *,
rw [H1, H2]; assumption
},
any_goals {
intros,
unfold freevar.env.replace_sbv at *, done
},
any_goals {
intros,
unfold freevar.env.add_b,
unfold freevar.env.replace_sbv,
simp,
unfold freevar.env.empty,
generalize HG: η.bv n = b',
cases b',
{
unfold freevar.env.replace_sbv._match_1,
unfold freevar.env.replace_sbv,
},
{
unfold freevar.env.replace_sbv._match_1,
simp,
rw env.replace_sbv_of_int, done
}
},
any_goals {
intros sz v1 v2 H1 H2 n' HNOTIN',
unfold freevar.env.replace_sbv at *,
rw [H1, H2]; assumption
},
any_goals {
intros sz v sz' H n' HNOTIN',
unfold freevar.env.replace_sbv at *,
rw H, assumption
},
any_goals {
intros sz sz' v highbit lowbit HH H n' HNOTIN',
unfold freevar.env.replace_sbv at *,
rw H, assumption
},
any_goals {
intros sz v1 v2 v3 H1 H2 H3 n' HNOTIN',
unfold freevar.env.replace_sbv at *,
rw [H1, H2, H3]; assumption
}
end
lemma env.not_in_add_b_b_comm: ∀ (η:freevar.env) z (v:sbool) n,
n ∉ η → (η.add_b n z)⟦v⟧ = (freevar.env.empty.add_b n z)⟦η⟦v⟧⟧
:= begin
intros, apply (and.elim_left (env.not_in_add_b_bv_b_comm η z)),
assumption
end
lemma env.not_in_add_b_bv_comm: ∀ (η:freevar.env) z {sz} (v:sbitvec sz) n,
n ∉ η → (η.add_b n z)⟦v⟧ = (freevar.env.empty.add_b n z)⟦η⟦v⟧⟧
:= begin
intros, apply (and.elim_right (env.not_in_add_b_bv_b_comm η z)),
assumption
end
lemma env.not_in_add_bv_valty_comm: ∀ (η:freevar.env) (vv:valty_smt) n z,
n ∉ η → (η.add_bv n z)⟦vv⟧ = (freevar.env.empty.add_bv n z)⟦η⟦vv⟧⟧
:= begin
intros,
cases vv with sz iv pv,
unfold freevar.env.replace_valty,
simp,
rw env.not_in_add_bv_bv_comm,
rw env.not_in_add_bv_b_comm,
split, refl, refl,
assumption, assumption
end
lemma env.not_in_add_b_valty_comm: ∀ (η:freevar.env) (vv:valty_smt) n z,
n ∉ η → (η.add_b n z)⟦vv⟧ = (freevar.env.empty.add_b n z)⟦η⟦vv⟧⟧
:= begin
intros,
cases vv with sz iv pv,
unfold freevar.env.replace_valty,
simp,
rw env.not_in_add_b_bv_comm,
rw env.not_in_add_b_b_comm,
split, refl, refl,
assumption, assumption
end
lemma env.not_in_add_bv_irstate_comm: ∀ (η:freevar.env) (ss:irstate irsem_smt) n z,
n ∉ η → (η.add_bv n z)⟦ss⟧ = (freevar.env.empty.add_bv n z)⟦η⟦ss⟧⟧
:= begin
intros,
cases ss,
unfold freevar.env.replace,
rw ← irstate.setub_apply_to_values,
rw ← irstate.setub_apply_to_values,
rw ← irstate.setub_apply_to_values,
rw ← irstate.setub_apply_to_values,
unfold irstate.getub,
unfold irstate.setub,
unfold irstate.apply_to_values,
unfold regfile.apply_to_values,
simp,
--rw prod_inj,
--simp,
split,
{
rw env.not_in_add_bv_b_comm, assumption
},
{
induction ss_snd,
{ refl },
{
simp,
rw ss_snd_ih,
cases ss_snd_hd with rn v,
cases v with sz iv pv,
simp,
rw env.not_in_add_bv_bv_comm,
rw env.not_in_add_bv_b_comm,
assumption, assumption
}
}
end
lemma env.not_in_add_b_irstate_comm: ∀ (η:freevar.env) (ss:irstate irsem_smt) n z,
n ∉ η → (η.add_b n z)⟦ss⟧ = (freevar.env.empty.add_b n z)⟦η⟦ss⟧⟧
:= begin
intros,
cases ss,
unfold freevar.env.replace,
rw ← irstate.setub_apply_to_values,
rw ← irstate.setub_apply_to_values,
rw ← irstate.setub_apply_to_values,
rw ← irstate.setub_apply_to_values,
unfold irstate.getub,
unfold irstate.setub,
unfold irstate.apply_to_values,
unfold regfile.apply_to_values,
simp,
--rw prod_inj,
--simp,
split,
{
rw env.not_in_add_b_b_comm, assumption
},
{
induction ss_snd,
{ refl },
{
simp,
rw ss_snd_ih,
cases ss_snd_hd with rn v,
cases v with sz iv pv,
simp,
rw env.not_in_add_b_bv_comm,
rw env.not_in_add_b_b_comm,
assumption, assumption
}
}
end
lemma env.has_only_shuffle: ∀ {η:freevar.env} (s:string) (l1 l2:list string),
env.has_only η (s::(l1 ++ l2)) ↔ env.has_only η (l1 ++ s::l2)
:= begin
intros, rw ← list.cons_append,
unfold env.has_only,
split,
{
intros, simp, simp at a,
rw or.comm, rw or.assoc,
rw @or.comm (name ∈ l2) (name ∈ l1), apply a
},
{
intros, simp, simp at a,
rw or.comm, rw or.assoc,
rw @or.comm (name ∈ l2) (name = s), apply a
}
end
lemma env.has_only_shuffle2: ∀ {η:freevar.env} (s1 s2:string) (l:list string),
env.has_only η (s1::s2::l) ↔ env.has_only η (s2::s1::l)
:= begin
intros,
unfold env.has_only,
split,
{
intros, simp, simp at a,
rw or.comm, rw or.assoc,
rw @or.comm (name ∈ l) (name = s2), apply a
},
{
intros, simp, simp at a,
rw or.comm, rw or.assoc,
rw @or.comm (name ∈ l) (name = s1), apply a
}
end
lemma env.has_only_added2: ∀ {η η':freevar.env} {n1 n2:string}
{l:list string}
(H1: env.has_only η l)
(H2: env.added2 η n1 n2 η'),
env.has_only η' (n1::n2::l)
:= begin
intros,
unfold env.added2 at H2,
cases H2,
unfold env.has_only at *,
intros,
simp,
rw H1,
split,
{ intros, apply H2_right, rw or.comm, rw or.assoc, assumption },
{
intros,
rw ← decidable.not_not_iff (name ∈ η') at a,
rw ← decidable.not_not_iff (name = n1 ∨ name = n2 ∨ name ∈ η),
intros H0,
rw decidable.not_or_iff_and_not at H0,
rw decidable.not_or_iff_and_not at H0,
cases H0, cases H0_right,
apply a,
apply H2_left, assumption, split; assumption
}
end
lemma env.has_only_not_in: ∀ {η:freevar.env} {l n}
(H:env.has_only η l) (HNOTIN:n ∉ l), n ∉ η
:= begin
intros,
unfold env.has_only at H,
intros H0,
apply HNOTIN, rw H, assumption
end
-- get_value
lemma get_value_replace: ∀ (ss:irstate_smt) (op:operand)
(η:freevar.env) (t:ty),
get_value irsem_smt (η⟦ss⟧) op t = η⟦get_value irsem_smt ss op t⟧'
:= begin
intros,
cases op,
{ -- operand.reg
cases op,
unfold get_value,
apply getreg_replace, refl
},
{
cases op,
cases t,
{
unfold get_value,
have H0: decidable (0 < t), apply_instance,
cases H0,
{ rw dif_neg, assumption },
{
rw dif_pos,
simp,
have H1: decidable (within_signed_range ⟨t, H0⟩ op), apply_instance,
cases H1,
{
rw if_neg,
{
have H2: decidable (↑(int_min_nat ⟨t, H0⟩) ≤ op ∧ op ≤ ↑(all_one_nat ⟨t, H0⟩)),
apply_instance,
cases H2,
{ rw if_neg, apply H2 },
{ rw if_pos,
unfold uint_like.from_z,
unfold apply,
unfold freevar.env.replace_valty,
generalize HCONST: op + -↑(2^t) = c,
cases c,
{ unfold sbitvec.of_int, unfold freevar.env.replace_sbv, refl },
{ unfold sbitvec.of_int, unfold freevar.env.replace_sbv, refl },
assumption
}
},
{ assumption }
},
{ rw if_pos,
unfold uint_like.from_z,
unfold apply,
unfold freevar.env.replace_valty,
cases op,
{ unfold sbitvec.of_int, unfold freevar.env.replace_sbv, refl },
{ unfold sbitvec.of_int, unfold freevar.env.replace_sbv, refl },
assumption
}
}
},
{ unfold get_value }
}
end
end spec |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.